1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) { 83 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 84 if (DC && !DC->hasAttr<UnusedAttr>()) 85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 86 } 87 } 88 } 89 90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 92 if (!OMD) 93 return false; 94 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 95 if (!OID) 96 return false; 97 98 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 99 if (ObjCMethodDecl *CatMeth = 100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 101 if (!CatMeth->hasAttr<AvailabilityAttr>()) 102 return true; 103 return false; 104 } 105 106 AvailabilityResult 107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) { 108 AvailabilityResult Result = D->getAvailability(Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(Message); 136 } 137 138 if (Result == AR_NotYetIntroduced) { 139 // Don't do this for enums, they can't be redeclared. 140 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 141 return AR_Available; 142 143 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 144 // Objective-C method declarations in categories are not modelled as 145 // redeclarations, so manually look for a redeclaration in a category 146 // if necessary. 147 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 148 Warn = false; 149 // In general, D will point to the most recent redeclaration. However, 150 // for `@class A;` decls, this isn't true -- manually go through the 151 // redecl chain in that case. 152 if (Warn && isa<ObjCInterfaceDecl>(D)) 153 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 154 Redecl = Redecl->getPreviousDecl()) 155 if (!Redecl->hasAttr<AvailabilityAttr>() || 156 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 157 Warn = false; 158 159 return Warn ? AR_NotYetIntroduced : AR_Available; 160 } 161 162 return Result; 163 } 164 165 static void 166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 167 const ObjCInterfaceDecl *UnknownObjCClass, 168 bool ObjCPropertyAccess) { 169 std::string Message; 170 // See if this declaration is unavailable, deprecated, or partial. 171 if (AvailabilityResult Result = 172 S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) { 173 174 if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) { 175 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 176 return; 177 } 178 179 const ObjCPropertyDecl *ObjCPDecl = nullptr; 180 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 181 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 182 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 183 if (PDeclResult == Result) 184 ObjCPDecl = PD; 185 } 186 } 187 188 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 189 ObjCPDecl, ObjCPropertyAccess); 190 } 191 } 192 193 /// \brief Emit a note explaining that this function is deleted. 194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 195 assert(Decl->isDeleted()); 196 197 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 198 199 if (Method && Method->isDeleted() && Method->isDefaulted()) { 200 // If the method was explicitly defaulted, point at that declaration. 201 if (!Method->isImplicit()) 202 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 203 204 // Try to diagnose why this special member function was implicitly 205 // deleted. This might fail, if that reason no longer applies. 206 CXXSpecialMember CSM = getSpecialMember(Method); 207 if (CSM != CXXInvalid) 208 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 209 210 return; 211 } 212 213 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 214 if (Ctor && Ctor->isInheritingConstructor()) 215 return NoteDeletedInheritingConstructor(Ctor); 216 217 Diag(Decl->getLocation(), diag::note_availability_specified_here) 218 << Decl << true; 219 } 220 221 /// \brief Determine whether a FunctionDecl was ever declared with an 222 /// explicit storage class. 223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 224 for (auto I : D->redecls()) { 225 if (I->getStorageClass() != SC_None) 226 return true; 227 } 228 return false; 229 } 230 231 /// \brief Check whether we're in an extern inline function and referring to a 232 /// variable or function with internal linkage (C11 6.7.4p3). 233 /// 234 /// This is only a warning because we used to silently accept this code, but 235 /// in many cases it will not behave correctly. This is not enabled in C++ mode 236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 237 /// and so while there may still be user mistakes, most of the time we can't 238 /// prove that there are errors. 239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 240 const NamedDecl *D, 241 SourceLocation Loc) { 242 // This is disabled under C++; there are too many ways for this to fire in 243 // contexts where the warning is a false positive, or where it is technically 244 // correct but benign. 245 if (S.getLangOpts().CPlusPlus) 246 return; 247 248 // Check if this is an inlined function or method. 249 FunctionDecl *Current = S.getCurFunctionDecl(); 250 if (!Current) 251 return; 252 if (!Current->isInlined()) 253 return; 254 if (!Current->isExternallyVisible()) 255 return; 256 257 // Check if the decl has internal linkage. 258 if (D->getFormalLinkage() != InternalLinkage) 259 return; 260 261 // Downgrade from ExtWarn to Extension if 262 // (1) the supposedly external inline function is in the main file, 263 // and probably won't be included anywhere else. 264 // (2) the thing we're referencing is a pure function. 265 // (3) the thing we're referencing is another inline function. 266 // This last can give us false negatives, but it's better than warning on 267 // wrappers for simple C library functions. 268 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 269 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 270 if (!DowngradeWarning && UsedFn) 271 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 272 273 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 274 : diag::ext_internal_in_extern_inline) 275 << /*IsVar=*/!UsedFn << D; 276 277 S.MaybeSuggestAddingStaticToDecl(Current); 278 279 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 280 << D; 281 } 282 283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 284 const FunctionDecl *First = Cur->getFirstDecl(); 285 286 // Suggest "static" on the function, if possible. 287 if (!hasAnyExplicitStorageClass(First)) { 288 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 289 Diag(DeclBegin, diag::note_convert_inline_to_static) 290 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 291 } 292 } 293 294 /// \brief Determine whether the use of this declaration is valid, and 295 /// emit any corresponding diagnostics. 296 /// 297 /// This routine diagnoses various problems with referencing 298 /// declarations that can occur when using a declaration. For example, 299 /// it might warn if a deprecated or unavailable declaration is being 300 /// used, or produce an error (and return true) if a C++0x deleted 301 /// function is being used. 302 /// 303 /// \returns true if there was an error (this declaration cannot be 304 /// referenced), false otherwise. 305 /// 306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 307 const ObjCInterfaceDecl *UnknownObjCClass, 308 bool ObjCPropertyAccess) { 309 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 310 // If there were any diagnostics suppressed by template argument deduction, 311 // emit them now. 312 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 313 if (Pos != SuppressedDiagnostics.end()) { 314 for (const PartialDiagnosticAt &Suppressed : Pos->second) 315 Diag(Suppressed.first, Suppressed.second); 316 317 // Clear out the list of suppressed diagnostics, so that we don't emit 318 // them again for this specialization. However, we don't obsolete this 319 // entry from the table, because we want to avoid ever emitting these 320 // diagnostics again. 321 Pos->second.clear(); 322 } 323 324 // C++ [basic.start.main]p3: 325 // The function 'main' shall not be used within a program. 326 if (cast<FunctionDecl>(D)->isMain()) 327 Diag(Loc, diag::ext_main_used); 328 } 329 330 // See if this is an auto-typed variable whose initializer we are parsing. 331 if (ParsingInitForAutoVars.count(D)) { 332 if (isa<BindingDecl>(D)) { 333 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 334 << D->getDeclName(); 335 } else { 336 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 337 338 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 339 << D->getDeclName() << (unsigned)AT->getKeyword(); 340 } 341 return true; 342 } 343 344 // See if this is a deleted function. 345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 346 if (FD->isDeleted()) { 347 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 348 if (Ctor && Ctor->isInheritingConstructor()) 349 Diag(Loc, diag::err_deleted_inherited_ctor_use) 350 << Ctor->getParent() 351 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 352 else 353 Diag(Loc, diag::err_deleted_function_use); 354 NoteDeletedFunction(FD); 355 return true; 356 } 357 358 // If the function has a deduced return type, and we can't deduce it, 359 // then we can't use it either. 360 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 361 DeduceReturnType(FD, Loc)) 362 return true; 363 364 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 365 return true; 366 } 367 368 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 369 // Only the variables omp_in and omp_out are allowed in the combiner. 370 // Only the variables omp_priv and omp_orig are allowed in the 371 // initializer-clause. 372 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 373 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 374 isa<VarDecl>(D)) { 375 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 376 << getCurFunction()->HasOMPDeclareReductionCombiner; 377 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 378 return true; 379 } 380 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 381 ObjCPropertyAccess); 382 383 DiagnoseUnusedOfDecl(*this, D, Loc); 384 385 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 386 387 return false; 388 } 389 390 /// \brief Retrieve the message suffix that should be added to a 391 /// diagnostic complaining about the given function being deleted or 392 /// unavailable. 393 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 394 std::string Message; 395 if (FD->getAvailability(&Message)) 396 return ": " + Message; 397 398 return std::string(); 399 } 400 401 /// DiagnoseSentinelCalls - This routine checks whether a call or 402 /// message-send is to a declaration with the sentinel attribute, and 403 /// if so, it checks that the requirements of the sentinel are 404 /// satisfied. 405 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 406 ArrayRef<Expr *> Args) { 407 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 408 if (!attr) 409 return; 410 411 // The number of formal parameters of the declaration. 412 unsigned numFormalParams; 413 414 // The kind of declaration. This is also an index into a %select in 415 // the diagnostic. 416 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 417 418 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 419 numFormalParams = MD->param_size(); 420 calleeType = CT_Method; 421 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 422 numFormalParams = FD->param_size(); 423 calleeType = CT_Function; 424 } else if (isa<VarDecl>(D)) { 425 QualType type = cast<ValueDecl>(D)->getType(); 426 const FunctionType *fn = nullptr; 427 if (const PointerType *ptr = type->getAs<PointerType>()) { 428 fn = ptr->getPointeeType()->getAs<FunctionType>(); 429 if (!fn) return; 430 calleeType = CT_Function; 431 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 432 fn = ptr->getPointeeType()->castAs<FunctionType>(); 433 calleeType = CT_Block; 434 } else { 435 return; 436 } 437 438 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 439 numFormalParams = proto->getNumParams(); 440 } else { 441 numFormalParams = 0; 442 } 443 } else { 444 return; 445 } 446 447 // "nullPos" is the number of formal parameters at the end which 448 // effectively count as part of the variadic arguments. This is 449 // useful if you would prefer to not have *any* formal parameters, 450 // but the language forces you to have at least one. 451 unsigned nullPos = attr->getNullPos(); 452 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 453 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 454 455 // The number of arguments which should follow the sentinel. 456 unsigned numArgsAfterSentinel = attr->getSentinel(); 457 458 // If there aren't enough arguments for all the formal parameters, 459 // the sentinel, and the args after the sentinel, complain. 460 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 462 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 463 return; 464 } 465 466 // Otherwise, find the sentinel expression. 467 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 468 if (!sentinelExpr) return; 469 if (sentinelExpr->isValueDependent()) return; 470 if (Context.isSentinelNullExpr(sentinelExpr)) return; 471 472 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 473 // or 'NULL' if those are actually defined in the context. Only use 474 // 'nil' for ObjC methods, where it's much more likely that the 475 // variadic arguments form a list of object pointers. 476 SourceLocation MissingNilLoc 477 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 478 std::string NullValue; 479 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 480 NullValue = "nil"; 481 else if (getLangOpts().CPlusPlus11) 482 NullValue = "nullptr"; 483 else if (PP.isMacroDefined("NULL")) 484 NullValue = "NULL"; 485 else 486 NullValue = "(void*) 0"; 487 488 if (MissingNilLoc.isInvalid()) 489 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 490 else 491 Diag(MissingNilLoc, diag::warn_missing_sentinel) 492 << int(calleeType) 493 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 494 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 495 } 496 497 SourceRange Sema::getExprRange(Expr *E) const { 498 return E ? E->getSourceRange() : SourceRange(); 499 } 500 501 //===----------------------------------------------------------------------===// 502 // Standard Promotions and Conversions 503 //===----------------------------------------------------------------------===// 504 505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 506 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 507 // Handle any placeholder expressions which made it here. 508 if (E->getType()->isPlaceholderType()) { 509 ExprResult result = CheckPlaceholderExpr(E); 510 if (result.isInvalid()) return ExprError(); 511 E = result.get(); 512 } 513 514 QualType Ty = E->getType(); 515 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 516 517 if (Ty->isFunctionType()) { 518 // If we are here, we are not calling a function but taking 519 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 520 if (getLangOpts().OpenCL) { 521 if (Diagnose) 522 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 523 return ExprError(); 524 } 525 526 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 527 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 528 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 529 return ExprError(); 530 531 E = ImpCastExprToType(E, Context.getPointerType(Ty), 532 CK_FunctionToPointerDecay).get(); 533 } else if (Ty->isArrayType()) { 534 // In C90 mode, arrays only promote to pointers if the array expression is 535 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 536 // type 'array of type' is converted to an expression that has type 'pointer 537 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 538 // that has type 'array of type' ...". The relevant change is "an lvalue" 539 // (C90) to "an expression" (C99). 540 // 541 // C++ 4.2p1: 542 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 543 // T" can be converted to an rvalue of type "pointer to T". 544 // 545 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 546 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 547 CK_ArrayToPointerDecay).get(); 548 } 549 return E; 550 } 551 552 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 553 // Check to see if we are dereferencing a null pointer. If so, 554 // and if not volatile-qualified, this is undefined behavior that the 555 // optimizer will delete, so warn about it. People sometimes try to use this 556 // to get a deterministic trap and are surprised by clang's behavior. This 557 // only handles the pattern "*null", which is a very syntactic check. 558 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 559 if (UO->getOpcode() == UO_Deref && 560 UO->getSubExpr()->IgnoreParenCasts()-> 561 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 562 !UO->getType().isVolatileQualified()) { 563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 564 S.PDiag(diag::warn_indirection_through_null) 565 << UO->getSubExpr()->getSourceRange()); 566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 567 S.PDiag(diag::note_indirection_through_null)); 568 } 569 } 570 571 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 572 SourceLocation AssignLoc, 573 const Expr* RHS) { 574 const ObjCIvarDecl *IV = OIRE->getDecl(); 575 if (!IV) 576 return; 577 578 DeclarationName MemberName = IV->getDeclName(); 579 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 580 if (!Member || !Member->isStr("isa")) 581 return; 582 583 const Expr *Base = OIRE->getBase(); 584 QualType BaseType = Base->getType(); 585 if (OIRE->isArrow()) 586 BaseType = BaseType->getPointeeType(); 587 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 588 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 589 ObjCInterfaceDecl *ClassDeclared = nullptr; 590 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 591 if (!ClassDeclared->getSuperClass() 592 && (*ClassDeclared->ivar_begin()) == IV) { 593 if (RHS) { 594 NamedDecl *ObjectSetClass = 595 S.LookupSingleName(S.TUScope, 596 &S.Context.Idents.get("object_setClass"), 597 SourceLocation(), S.LookupOrdinaryName); 598 if (ObjectSetClass) { 599 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 600 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 601 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 602 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 603 AssignLoc), ",") << 604 FixItHint::CreateInsertion(RHSLocEnd, ")"); 605 } 606 else 607 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 608 } else { 609 NamedDecl *ObjectGetClass = 610 S.LookupSingleName(S.TUScope, 611 &S.Context.Idents.get("object_getClass"), 612 SourceLocation(), S.LookupOrdinaryName); 613 if (ObjectGetClass) 614 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 615 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 616 FixItHint::CreateReplacement( 617 SourceRange(OIRE->getOpLoc(), 618 OIRE->getLocEnd()), ")"); 619 else 620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 621 } 622 S.Diag(IV->getLocation(), diag::note_ivar_decl); 623 } 624 } 625 } 626 627 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 628 // Handle any placeholder expressions which made it here. 629 if (E->getType()->isPlaceholderType()) { 630 ExprResult result = CheckPlaceholderExpr(E); 631 if (result.isInvalid()) return ExprError(); 632 E = result.get(); 633 } 634 635 // C++ [conv.lval]p1: 636 // A glvalue of a non-function, non-array type T can be 637 // converted to a prvalue. 638 if (!E->isGLValue()) return E; 639 640 QualType T = E->getType(); 641 assert(!T.isNull() && "r-value conversion on typeless expression?"); 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 674 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 675 FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 UpdateMarkingForLValueToRValue(E); 702 703 // Loading a __weak object implicitly retains the value, so we need a cleanup to 704 // balance that. 705 if (getLangOpts().ObjCAutoRefCount && 706 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 707 Cleanup.setExprNeedsCleanups(true); 708 709 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 710 nullptr, VK_RValue); 711 712 // C11 6.3.2.1p2: 713 // ... if the lvalue has atomic type, the value has the non-atomic version 714 // of the type of the lvalue ... 715 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 716 T = Atomic->getValueType().getUnqualifiedType(); 717 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 718 nullptr, VK_RValue); 719 } 720 721 return Res; 722 } 723 724 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 725 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 726 if (Res.isInvalid()) 727 return ExprError(); 728 Res = DefaultLvalueConversion(Res.get()); 729 if (Res.isInvalid()) 730 return ExprError(); 731 return Res; 732 } 733 734 /// CallExprUnaryConversions - a special case of an unary conversion 735 /// performed on a function designator of a call expression. 736 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 737 QualType Ty = E->getType(); 738 ExprResult Res = E; 739 // Only do implicit cast for a function type, but not for a pointer 740 // to function type. 741 if (Ty->isFunctionType()) { 742 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 743 CK_FunctionToPointerDecay).get(); 744 if (Res.isInvalid()) 745 return ExprError(); 746 } 747 Res = DefaultLvalueConversion(Res.get()); 748 if (Res.isInvalid()) 749 return ExprError(); 750 return Res.get(); 751 } 752 753 /// UsualUnaryConversions - Performs various conversions that are common to most 754 /// operators (C99 6.3). The conversions of array and function types are 755 /// sometimes suppressed. For example, the array->pointer conversion doesn't 756 /// apply if the array is an argument to the sizeof or address (&) operators. 757 /// In these instances, this routine should *not* be called. 758 ExprResult Sema::UsualUnaryConversions(Expr *E) { 759 // First, convert to an r-value. 760 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 761 if (Res.isInvalid()) 762 return ExprError(); 763 E = Res.get(); 764 765 QualType Ty = E->getType(); 766 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 767 768 // Half FP have to be promoted to float unless it is natively supported 769 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 770 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 771 772 // Try to perform integral promotions if the object has a theoretically 773 // promotable type. 774 if (Ty->isIntegralOrUnscopedEnumerationType()) { 775 // C99 6.3.1.1p2: 776 // 777 // The following may be used in an expression wherever an int or 778 // unsigned int may be used: 779 // - an object or expression with an integer type whose integer 780 // conversion rank is less than or equal to the rank of int 781 // and unsigned int. 782 // - A bit-field of type _Bool, int, signed int, or unsigned int. 783 // 784 // If an int can represent all values of the original type, the 785 // value is converted to an int; otherwise, it is converted to an 786 // unsigned int. These are called the integer promotions. All 787 // other types are unchanged by the integer promotions. 788 789 QualType PTy = Context.isPromotableBitField(E); 790 if (!PTy.isNull()) { 791 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 792 return E; 793 } 794 if (Ty->isPromotableIntegerType()) { 795 QualType PT = Context.getPromotedIntegerType(Ty); 796 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 797 return E; 798 } 799 } 800 return E; 801 } 802 803 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 804 /// do not have a prototype. Arguments that have type float or __fp16 805 /// are promoted to double. All other argument types are converted by 806 /// UsualUnaryConversions(). 807 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 808 QualType Ty = E->getType(); 809 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 810 811 ExprResult Res = UsualUnaryConversions(E); 812 if (Res.isInvalid()) 813 return ExprError(); 814 E = Res.get(); 815 816 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 817 // double. 818 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 819 if (BTy && (BTy->getKind() == BuiltinType::Half || 820 BTy->getKind() == BuiltinType::Float)) 821 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 822 823 // C++ performs lvalue-to-rvalue conversion as a default argument 824 // promotion, even on class types, but note: 825 // C++11 [conv.lval]p2: 826 // When an lvalue-to-rvalue conversion occurs in an unevaluated 827 // operand or a subexpression thereof the value contained in the 828 // referenced object is not accessed. Otherwise, if the glvalue 829 // has a class type, the conversion copy-initializes a temporary 830 // of type T from the glvalue and the result of the conversion 831 // is a prvalue for the temporary. 832 // FIXME: add some way to gate this entire thing for correctness in 833 // potentially potentially evaluated contexts. 834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 835 ExprResult Temp = PerformCopyInitialization( 836 InitializedEntity::InitializeTemporary(E->getType()), 837 E->getExprLoc(), E); 838 if (Temp.isInvalid()) 839 return ExprError(); 840 E = Temp.get(); 841 } 842 843 return E; 844 } 845 846 /// Determine the degree of POD-ness for an expression. 847 /// Incomplete types are considered POD, since this check can be performed 848 /// when we're in an unevaluated context. 849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 850 if (Ty->isIncompleteType()) { 851 // C++11 [expr.call]p7: 852 // After these conversions, if the argument does not have arithmetic, 853 // enumeration, pointer, pointer to member, or class type, the program 854 // is ill-formed. 855 // 856 // Since we've already performed array-to-pointer and function-to-pointer 857 // decay, the only such type in C++ is cv void. This also handles 858 // initializer lists as variadic arguments. 859 if (Ty->isVoidType()) 860 return VAK_Invalid; 861 862 if (Ty->isObjCObjectType()) 863 return VAK_Invalid; 864 return VAK_Valid; 865 } 866 867 if (Ty.isCXX98PODType(Context)) 868 return VAK_Valid; 869 870 // C++11 [expr.call]p7: 871 // Passing a potentially-evaluated argument of class type (Clause 9) 872 // having a non-trivial copy constructor, a non-trivial move constructor, 873 // or a non-trivial destructor, with no corresponding parameter, 874 // is conditionally-supported with implementation-defined semantics. 875 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 876 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 877 if (!Record->hasNonTrivialCopyConstructor() && 878 !Record->hasNonTrivialMoveConstructor() && 879 !Record->hasNonTrivialDestructor()) 880 return VAK_ValidInCXX11; 881 882 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 883 return VAK_Valid; 884 885 if (Ty->isObjCObjectType()) 886 return VAK_Invalid; 887 888 if (getLangOpts().MSVCCompat) 889 return VAK_MSVCUndefined; 890 891 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 892 // permitted to reject them. We should consider doing so. 893 return VAK_Undefined; 894 } 895 896 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 897 // Don't allow one to pass an Objective-C interface to a vararg. 898 const QualType &Ty = E->getType(); 899 VarArgKind VAK = isValidVarArgType(Ty); 900 901 // Complain about passing non-POD types through varargs. 902 switch (VAK) { 903 case VAK_ValidInCXX11: 904 DiagRuntimeBehavior( 905 E->getLocStart(), nullptr, 906 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 907 << Ty << CT); 908 // Fall through. 909 case VAK_Valid: 910 if (Ty->isRecordType()) { 911 // This is unlikely to be what the user intended. If the class has a 912 // 'c_str' member function, the user probably meant to call that. 913 DiagRuntimeBehavior(E->getLocStart(), nullptr, 914 PDiag(diag::warn_pass_class_arg_to_vararg) 915 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 916 } 917 break; 918 919 case VAK_Undefined: 920 case VAK_MSVCUndefined: 921 DiagRuntimeBehavior( 922 E->getLocStart(), nullptr, 923 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 924 << getLangOpts().CPlusPlus11 << Ty << CT); 925 break; 926 927 case VAK_Invalid: 928 if (Ty->isObjCObjectType()) 929 DiagRuntimeBehavior( 930 E->getLocStart(), nullptr, 931 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 932 << Ty << CT); 933 else 934 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 935 << isa<InitListExpr>(E) << Ty << CT; 936 break; 937 } 938 } 939 940 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 941 /// will create a trap if the resulting type is not a POD type. 942 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 943 FunctionDecl *FDecl) { 944 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 945 // Strip the unbridged-cast placeholder expression off, if applicable. 946 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 947 (CT == VariadicMethod || 948 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 949 E = stripARCUnbridgedCast(E); 950 951 // Otherwise, do normal placeholder checking. 952 } else { 953 ExprResult ExprRes = CheckPlaceholderExpr(E); 954 if (ExprRes.isInvalid()) 955 return ExprError(); 956 E = ExprRes.get(); 957 } 958 } 959 960 ExprResult ExprRes = DefaultArgumentPromotion(E); 961 if (ExprRes.isInvalid()) 962 return ExprError(); 963 E = ExprRes.get(); 964 965 // Diagnostics regarding non-POD argument types are 966 // emitted along with format string checking in Sema::CheckFunctionCall(). 967 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 968 // Turn this into a trap. 969 CXXScopeSpec SS; 970 SourceLocation TemplateKWLoc; 971 UnqualifiedId Name; 972 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 973 E->getLocStart()); 974 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 975 Name, true, false); 976 if (TrapFn.isInvalid()) 977 return ExprError(); 978 979 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 980 E->getLocStart(), None, 981 E->getLocEnd()); 982 if (Call.isInvalid()) 983 return ExprError(); 984 985 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 986 Call.get(), E); 987 if (Comma.isInvalid()) 988 return ExprError(); 989 return Comma.get(); 990 } 991 992 if (!getLangOpts().CPlusPlus && 993 RequireCompleteType(E->getExprLoc(), E->getType(), 994 diag::err_call_incomplete_argument)) 995 return ExprError(); 996 997 return E; 998 } 999 1000 /// \brief Converts an integer to complex float type. Helper function of 1001 /// UsualArithmeticConversions() 1002 /// 1003 /// \return false if the integer expression is an integer type and is 1004 /// successfully converted to the complex type. 1005 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1006 ExprResult &ComplexExpr, 1007 QualType IntTy, 1008 QualType ComplexTy, 1009 bool SkipCast) { 1010 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1011 if (SkipCast) return false; 1012 if (IntTy->isIntegerType()) { 1013 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1014 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1015 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1016 CK_FloatingRealToComplex); 1017 } else { 1018 assert(IntTy->isComplexIntegerType()); 1019 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1020 CK_IntegralComplexToFloatingComplex); 1021 } 1022 return false; 1023 } 1024 1025 /// \brief Handle arithmetic conversion with complex types. Helper function of 1026 /// UsualArithmeticConversions() 1027 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1028 ExprResult &RHS, QualType LHSType, 1029 QualType RHSType, 1030 bool IsCompAssign) { 1031 // if we have an integer operand, the result is the complex type. 1032 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1033 /*skipCast*/false)) 1034 return LHSType; 1035 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1036 /*skipCast*/IsCompAssign)) 1037 return RHSType; 1038 1039 // This handles complex/complex, complex/float, or float/complex. 1040 // When both operands are complex, the shorter operand is converted to the 1041 // type of the longer, and that is the type of the result. This corresponds 1042 // to what is done when combining two real floating-point operands. 1043 // The fun begins when size promotion occur across type domains. 1044 // From H&S 6.3.4: When one operand is complex and the other is a real 1045 // floating-point type, the less precise type is converted, within it's 1046 // real or complex domain, to the precision of the other type. For example, 1047 // when combining a "long double" with a "double _Complex", the 1048 // "double _Complex" is promoted to "long double _Complex". 1049 1050 // Compute the rank of the two types, regardless of whether they are complex. 1051 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1052 1053 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1054 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1055 QualType LHSElementType = 1056 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1057 QualType RHSElementType = 1058 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1059 1060 QualType ResultType = S.Context.getComplexType(LHSElementType); 1061 if (Order < 0) { 1062 // Promote the precision of the LHS if not an assignment. 1063 ResultType = S.Context.getComplexType(RHSElementType); 1064 if (!IsCompAssign) { 1065 if (LHSComplexType) 1066 LHS = 1067 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1068 else 1069 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1070 } 1071 } else if (Order > 0) { 1072 // Promote the precision of the RHS. 1073 if (RHSComplexType) 1074 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1075 else 1076 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1077 } 1078 return ResultType; 1079 } 1080 1081 /// \brief Hande arithmetic conversion from integer to float. Helper function 1082 /// of UsualArithmeticConversions() 1083 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1084 ExprResult &IntExpr, 1085 QualType FloatTy, QualType IntTy, 1086 bool ConvertFloat, bool ConvertInt) { 1087 if (IntTy->isIntegerType()) { 1088 if (ConvertInt) 1089 // Convert intExpr to the lhs floating point type. 1090 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1091 CK_IntegralToFloating); 1092 return FloatTy; 1093 } 1094 1095 // Convert both sides to the appropriate complex float. 1096 assert(IntTy->isComplexIntegerType()); 1097 QualType result = S.Context.getComplexType(FloatTy); 1098 1099 // _Complex int -> _Complex float 1100 if (ConvertInt) 1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1102 CK_IntegralComplexToFloatingComplex); 1103 1104 // float -> _Complex float 1105 if (ConvertFloat) 1106 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1107 CK_FloatingRealToComplex); 1108 1109 return result; 1110 } 1111 1112 /// \brief Handle arithmethic conversion with floating point types. Helper 1113 /// function of UsualArithmeticConversions() 1114 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1115 ExprResult &RHS, QualType LHSType, 1116 QualType RHSType, bool IsCompAssign) { 1117 bool LHSFloat = LHSType->isRealFloatingType(); 1118 bool RHSFloat = RHSType->isRealFloatingType(); 1119 1120 // If we have two real floating types, convert the smaller operand 1121 // to the bigger result. 1122 if (LHSFloat && RHSFloat) { 1123 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1124 if (order > 0) { 1125 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1126 return LHSType; 1127 } 1128 1129 assert(order < 0 && "illegal float comparison"); 1130 if (!IsCompAssign) 1131 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1132 return RHSType; 1133 } 1134 1135 if (LHSFloat) { 1136 // Half FP has to be promoted to float unless it is natively supported 1137 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1138 LHSType = S.Context.FloatTy; 1139 1140 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1141 /*convertFloat=*/!IsCompAssign, 1142 /*convertInt=*/ true); 1143 } 1144 assert(RHSFloat); 1145 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1146 /*convertInt=*/ true, 1147 /*convertFloat=*/!IsCompAssign); 1148 } 1149 1150 /// \brief Diagnose attempts to convert between __float128 and long double if 1151 /// there is no support for such conversion. Helper function of 1152 /// UsualArithmeticConversions(). 1153 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1154 QualType RHSType) { 1155 /* No issue converting if at least one of the types is not a floating point 1156 type or the two types have the same rank. 1157 */ 1158 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1159 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1160 return false; 1161 1162 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1163 "The remaining types must be floating point types."); 1164 1165 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1166 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1167 1168 QualType LHSElemType = LHSComplex ? 1169 LHSComplex->getElementType() : LHSType; 1170 QualType RHSElemType = RHSComplex ? 1171 RHSComplex->getElementType() : RHSType; 1172 1173 // No issue if the two types have the same representation 1174 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1175 &S.Context.getFloatTypeSemantics(RHSElemType)) 1176 return false; 1177 1178 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1179 RHSElemType == S.Context.LongDoubleTy); 1180 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1181 RHSElemType == S.Context.Float128Ty); 1182 1183 /* We've handled the situation where __float128 and long double have the same 1184 representation. The only other allowable conversion is if long double is 1185 really just double. 1186 */ 1187 return Float128AndLongDouble && 1188 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1189 &llvm::APFloat::IEEEdouble); 1190 } 1191 1192 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1193 1194 namespace { 1195 /// These helper callbacks are placed in an anonymous namespace to 1196 /// permit their use as function template parameters. 1197 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1198 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1199 } 1200 1201 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1202 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1203 CK_IntegralComplexCast); 1204 } 1205 } 1206 1207 /// \brief Handle integer arithmetic conversions. Helper function of 1208 /// UsualArithmeticConversions() 1209 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1210 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1211 ExprResult &RHS, QualType LHSType, 1212 QualType RHSType, bool IsCompAssign) { 1213 // The rules for this case are in C99 6.3.1.8 1214 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1215 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1216 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1217 if (LHSSigned == RHSSigned) { 1218 // Same signedness; use the higher-ranked type 1219 if (order >= 0) { 1220 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1221 return LHSType; 1222 } else if (!IsCompAssign) 1223 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1224 return RHSType; 1225 } else if (order != (LHSSigned ? 1 : -1)) { 1226 // The unsigned type has greater than or equal rank to the 1227 // signed type, so use the unsigned type 1228 if (RHSSigned) { 1229 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1230 return LHSType; 1231 } else if (!IsCompAssign) 1232 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1233 return RHSType; 1234 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1235 // The two types are different widths; if we are here, that 1236 // means the signed type is larger than the unsigned type, so 1237 // use the signed type. 1238 if (LHSSigned) { 1239 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1240 return LHSType; 1241 } else if (!IsCompAssign) 1242 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1243 return RHSType; 1244 } else { 1245 // The signed type is higher-ranked than the unsigned type, 1246 // but isn't actually any bigger (like unsigned int and long 1247 // on most 32-bit systems). Use the unsigned type corresponding 1248 // to the signed type. 1249 QualType result = 1250 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1251 RHS = (*doRHSCast)(S, RHS.get(), result); 1252 if (!IsCompAssign) 1253 LHS = (*doLHSCast)(S, LHS.get(), result); 1254 return result; 1255 } 1256 } 1257 1258 /// \brief Handle conversions with GCC complex int extension. Helper function 1259 /// of UsualArithmeticConversions() 1260 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1261 ExprResult &RHS, QualType LHSType, 1262 QualType RHSType, 1263 bool IsCompAssign) { 1264 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1265 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1266 1267 if (LHSComplexInt && RHSComplexInt) { 1268 QualType LHSEltType = LHSComplexInt->getElementType(); 1269 QualType RHSEltType = RHSComplexInt->getElementType(); 1270 QualType ScalarType = 1271 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1272 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1273 1274 return S.Context.getComplexType(ScalarType); 1275 } 1276 1277 if (LHSComplexInt) { 1278 QualType LHSEltType = LHSComplexInt->getElementType(); 1279 QualType ScalarType = 1280 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1281 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1282 QualType ComplexType = S.Context.getComplexType(ScalarType); 1283 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1284 CK_IntegralRealToComplex); 1285 1286 return ComplexType; 1287 } 1288 1289 assert(RHSComplexInt); 1290 1291 QualType RHSEltType = RHSComplexInt->getElementType(); 1292 QualType ScalarType = 1293 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1294 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1295 QualType ComplexType = S.Context.getComplexType(ScalarType); 1296 1297 if (!IsCompAssign) 1298 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1299 CK_IntegralRealToComplex); 1300 return ComplexType; 1301 } 1302 1303 /// UsualArithmeticConversions - Performs various conversions that are common to 1304 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1305 /// routine returns the first non-arithmetic type found. The client is 1306 /// responsible for emitting appropriate error diagnostics. 1307 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1308 bool IsCompAssign) { 1309 if (!IsCompAssign) { 1310 LHS = UsualUnaryConversions(LHS.get()); 1311 if (LHS.isInvalid()) 1312 return QualType(); 1313 } 1314 1315 RHS = UsualUnaryConversions(RHS.get()); 1316 if (RHS.isInvalid()) 1317 return QualType(); 1318 1319 // For conversion purposes, we ignore any qualifiers. 1320 // For example, "const float" and "float" are equivalent. 1321 QualType LHSType = 1322 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1323 QualType RHSType = 1324 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1325 1326 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1327 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1328 LHSType = AtomicLHS->getValueType(); 1329 1330 // If both types are identical, no conversion is needed. 1331 if (LHSType == RHSType) 1332 return LHSType; 1333 1334 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1335 // The caller can deal with this (e.g. pointer + int). 1336 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1337 return QualType(); 1338 1339 // Apply unary and bitfield promotions to the LHS's type. 1340 QualType LHSUnpromotedType = LHSType; 1341 if (LHSType->isPromotableIntegerType()) 1342 LHSType = Context.getPromotedIntegerType(LHSType); 1343 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1344 if (!LHSBitfieldPromoteTy.isNull()) 1345 LHSType = LHSBitfieldPromoteTy; 1346 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1347 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1348 1349 // If both types are identical, no conversion is needed. 1350 if (LHSType == RHSType) 1351 return LHSType; 1352 1353 // At this point, we have two different arithmetic types. 1354 1355 // Diagnose attempts to convert between __float128 and long double where 1356 // such conversions currently can't be handled. 1357 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1358 return QualType(); 1359 1360 // Handle complex types first (C99 6.3.1.8p1). 1361 if (LHSType->isComplexType() || RHSType->isComplexType()) 1362 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1363 IsCompAssign); 1364 1365 // Now handle "real" floating types (i.e. float, double, long double). 1366 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1367 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1368 IsCompAssign); 1369 1370 // Handle GCC complex int extension. 1371 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1372 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1373 IsCompAssign); 1374 1375 // Finally, we have two differing integer types. 1376 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1377 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1378 } 1379 1380 1381 //===----------------------------------------------------------------------===// 1382 // Semantic Analysis for various Expression Types 1383 //===----------------------------------------------------------------------===// 1384 1385 1386 ExprResult 1387 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1388 SourceLocation DefaultLoc, 1389 SourceLocation RParenLoc, 1390 Expr *ControllingExpr, 1391 ArrayRef<ParsedType> ArgTypes, 1392 ArrayRef<Expr *> ArgExprs) { 1393 unsigned NumAssocs = ArgTypes.size(); 1394 assert(NumAssocs == ArgExprs.size()); 1395 1396 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1397 for (unsigned i = 0; i < NumAssocs; ++i) { 1398 if (ArgTypes[i]) 1399 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1400 else 1401 Types[i] = nullptr; 1402 } 1403 1404 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1405 ControllingExpr, 1406 llvm::makeArrayRef(Types, NumAssocs), 1407 ArgExprs); 1408 delete [] Types; 1409 return ER; 1410 } 1411 1412 ExprResult 1413 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1414 SourceLocation DefaultLoc, 1415 SourceLocation RParenLoc, 1416 Expr *ControllingExpr, 1417 ArrayRef<TypeSourceInfo *> Types, 1418 ArrayRef<Expr *> Exprs) { 1419 unsigned NumAssocs = Types.size(); 1420 assert(NumAssocs == Exprs.size()); 1421 1422 // Decay and strip qualifiers for the controlling expression type, and handle 1423 // placeholder type replacement. See committee discussion from WG14 DR423. 1424 { 1425 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1426 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1427 if (R.isInvalid()) 1428 return ExprError(); 1429 ControllingExpr = R.get(); 1430 } 1431 1432 // The controlling expression is an unevaluated operand, so side effects are 1433 // likely unintended. 1434 if (ActiveTemplateInstantiations.empty() && 1435 ControllingExpr->HasSideEffects(Context, false)) 1436 Diag(ControllingExpr->getExprLoc(), 1437 diag::warn_side_effects_unevaluated_context); 1438 1439 bool TypeErrorFound = false, 1440 IsResultDependent = ControllingExpr->isTypeDependent(), 1441 ContainsUnexpandedParameterPack 1442 = ControllingExpr->containsUnexpandedParameterPack(); 1443 1444 for (unsigned i = 0; i < NumAssocs; ++i) { 1445 if (Exprs[i]->containsUnexpandedParameterPack()) 1446 ContainsUnexpandedParameterPack = true; 1447 1448 if (Types[i]) { 1449 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1450 ContainsUnexpandedParameterPack = true; 1451 1452 if (Types[i]->getType()->isDependentType()) { 1453 IsResultDependent = true; 1454 } else { 1455 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1456 // complete object type other than a variably modified type." 1457 unsigned D = 0; 1458 if (Types[i]->getType()->isIncompleteType()) 1459 D = diag::err_assoc_type_incomplete; 1460 else if (!Types[i]->getType()->isObjectType()) 1461 D = diag::err_assoc_type_nonobject; 1462 else if (Types[i]->getType()->isVariablyModifiedType()) 1463 D = diag::err_assoc_type_variably_modified; 1464 1465 if (D != 0) { 1466 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1467 << Types[i]->getTypeLoc().getSourceRange() 1468 << Types[i]->getType(); 1469 TypeErrorFound = true; 1470 } 1471 1472 // C11 6.5.1.1p2 "No two generic associations in the same generic 1473 // selection shall specify compatible types." 1474 for (unsigned j = i+1; j < NumAssocs; ++j) 1475 if (Types[j] && !Types[j]->getType()->isDependentType() && 1476 Context.typesAreCompatible(Types[i]->getType(), 1477 Types[j]->getType())) { 1478 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1479 diag::err_assoc_compatible_types) 1480 << Types[j]->getTypeLoc().getSourceRange() 1481 << Types[j]->getType() 1482 << Types[i]->getType(); 1483 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1484 diag::note_compat_assoc) 1485 << Types[i]->getTypeLoc().getSourceRange() 1486 << Types[i]->getType(); 1487 TypeErrorFound = true; 1488 } 1489 } 1490 } 1491 } 1492 if (TypeErrorFound) 1493 return ExprError(); 1494 1495 // If we determined that the generic selection is result-dependent, don't 1496 // try to compute the result expression. 1497 if (IsResultDependent) 1498 return new (Context) GenericSelectionExpr( 1499 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1500 ContainsUnexpandedParameterPack); 1501 1502 SmallVector<unsigned, 1> CompatIndices; 1503 unsigned DefaultIndex = -1U; 1504 for (unsigned i = 0; i < NumAssocs; ++i) { 1505 if (!Types[i]) 1506 DefaultIndex = i; 1507 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1508 Types[i]->getType())) 1509 CompatIndices.push_back(i); 1510 } 1511 1512 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1513 // type compatible with at most one of the types named in its generic 1514 // association list." 1515 if (CompatIndices.size() > 1) { 1516 // We strip parens here because the controlling expression is typically 1517 // parenthesized in macro definitions. 1518 ControllingExpr = ControllingExpr->IgnoreParens(); 1519 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1520 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1521 << (unsigned) CompatIndices.size(); 1522 for (unsigned I : CompatIndices) { 1523 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1524 diag::note_compat_assoc) 1525 << Types[I]->getTypeLoc().getSourceRange() 1526 << Types[I]->getType(); 1527 } 1528 return ExprError(); 1529 } 1530 1531 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1532 // its controlling expression shall have type compatible with exactly one of 1533 // the types named in its generic association list." 1534 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1535 // We strip parens here because the controlling expression is typically 1536 // parenthesized in macro definitions. 1537 ControllingExpr = ControllingExpr->IgnoreParens(); 1538 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1539 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1540 return ExprError(); 1541 } 1542 1543 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1544 // type name that is compatible with the type of the controlling expression, 1545 // then the result expression of the generic selection is the expression 1546 // in that generic association. Otherwise, the result expression of the 1547 // generic selection is the expression in the default generic association." 1548 unsigned ResultIndex = 1549 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1550 1551 return new (Context) GenericSelectionExpr( 1552 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1553 ContainsUnexpandedParameterPack, ResultIndex); 1554 } 1555 1556 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1557 /// location of the token and the offset of the ud-suffix within it. 1558 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1559 unsigned Offset) { 1560 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1561 S.getLangOpts()); 1562 } 1563 1564 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1565 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1566 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1567 IdentifierInfo *UDSuffix, 1568 SourceLocation UDSuffixLoc, 1569 ArrayRef<Expr*> Args, 1570 SourceLocation LitEndLoc) { 1571 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1572 1573 QualType ArgTy[2]; 1574 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1575 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1576 if (ArgTy[ArgIdx]->isArrayType()) 1577 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1578 } 1579 1580 DeclarationName OpName = 1581 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1582 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1583 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1584 1585 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1586 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1587 /*AllowRaw*/false, /*AllowTemplate*/false, 1588 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1589 return ExprError(); 1590 1591 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1592 } 1593 1594 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1595 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1596 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1597 /// multiple tokens. However, the common case is that StringToks points to one 1598 /// string. 1599 /// 1600 ExprResult 1601 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1602 assert(!StringToks.empty() && "Must have at least one string!"); 1603 1604 StringLiteralParser Literal(StringToks, PP); 1605 if (Literal.hadError) 1606 return ExprError(); 1607 1608 SmallVector<SourceLocation, 4> StringTokLocs; 1609 for (const Token &Tok : StringToks) 1610 StringTokLocs.push_back(Tok.getLocation()); 1611 1612 QualType CharTy = Context.CharTy; 1613 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1614 if (Literal.isWide()) { 1615 CharTy = Context.getWideCharType(); 1616 Kind = StringLiteral::Wide; 1617 } else if (Literal.isUTF8()) { 1618 Kind = StringLiteral::UTF8; 1619 } else if (Literal.isUTF16()) { 1620 CharTy = Context.Char16Ty; 1621 Kind = StringLiteral::UTF16; 1622 } else if (Literal.isUTF32()) { 1623 CharTy = Context.Char32Ty; 1624 Kind = StringLiteral::UTF32; 1625 } else if (Literal.isPascal()) { 1626 CharTy = Context.UnsignedCharTy; 1627 } 1628 1629 QualType CharTyConst = CharTy; 1630 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1631 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1632 CharTyConst.addConst(); 1633 1634 // Get an array type for the string, according to C99 6.4.5. This includes 1635 // the nul terminator character as well as the string length for pascal 1636 // strings. 1637 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1638 llvm::APInt(32, Literal.GetNumStringChars()+1), 1639 ArrayType::Normal, 0); 1640 1641 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1642 if (getLangOpts().OpenCL) { 1643 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1644 } 1645 1646 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1647 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1648 Kind, Literal.Pascal, StrTy, 1649 &StringTokLocs[0], 1650 StringTokLocs.size()); 1651 if (Literal.getUDSuffix().empty()) 1652 return Lit; 1653 1654 // We're building a user-defined literal. 1655 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1656 SourceLocation UDSuffixLoc = 1657 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1658 Literal.getUDSuffixOffset()); 1659 1660 // Make sure we're allowed user-defined literals here. 1661 if (!UDLScope) 1662 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1663 1664 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1665 // operator "" X (str, len) 1666 QualType SizeType = Context.getSizeType(); 1667 1668 DeclarationName OpName = 1669 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1670 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1671 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1672 1673 QualType ArgTy[] = { 1674 Context.getArrayDecayedType(StrTy), SizeType 1675 }; 1676 1677 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1678 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1679 /*AllowRaw*/false, /*AllowTemplate*/false, 1680 /*AllowStringTemplate*/true)) { 1681 1682 case LOLR_Cooked: { 1683 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1684 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1685 StringTokLocs[0]); 1686 Expr *Args[] = { Lit, LenArg }; 1687 1688 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1689 } 1690 1691 case LOLR_StringTemplate: { 1692 TemplateArgumentListInfo ExplicitArgs; 1693 1694 unsigned CharBits = Context.getIntWidth(CharTy); 1695 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1696 llvm::APSInt Value(CharBits, CharIsUnsigned); 1697 1698 TemplateArgument TypeArg(CharTy); 1699 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1700 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1701 1702 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1703 Value = Lit->getCodeUnit(I); 1704 TemplateArgument Arg(Context, Value, CharTy); 1705 TemplateArgumentLocInfo ArgInfo; 1706 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1707 } 1708 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1709 &ExplicitArgs); 1710 } 1711 case LOLR_Raw: 1712 case LOLR_Template: 1713 llvm_unreachable("unexpected literal operator lookup result"); 1714 case LOLR_Error: 1715 return ExprError(); 1716 } 1717 llvm_unreachable("unexpected literal operator lookup result"); 1718 } 1719 1720 ExprResult 1721 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1722 SourceLocation Loc, 1723 const CXXScopeSpec *SS) { 1724 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1725 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1726 } 1727 1728 /// BuildDeclRefExpr - Build an expression that references a 1729 /// declaration that does not require a closure capture. 1730 ExprResult 1731 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1732 const DeclarationNameInfo &NameInfo, 1733 const CXXScopeSpec *SS, NamedDecl *FoundD, 1734 const TemplateArgumentListInfo *TemplateArgs) { 1735 bool RefersToCapturedVariable = 1736 isa<VarDecl>(D) && 1737 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1738 1739 DeclRefExpr *E; 1740 if (isa<VarTemplateSpecializationDecl>(D)) { 1741 VarTemplateSpecializationDecl *VarSpec = 1742 cast<VarTemplateSpecializationDecl>(D); 1743 1744 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1745 : NestedNameSpecifierLoc(), 1746 VarSpec->getTemplateKeywordLoc(), D, 1747 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1748 FoundD, TemplateArgs); 1749 } else { 1750 assert(!TemplateArgs && "No template arguments for non-variable" 1751 " template specialization references"); 1752 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1753 : NestedNameSpecifierLoc(), 1754 SourceLocation(), D, RefersToCapturedVariable, 1755 NameInfo, Ty, VK, FoundD); 1756 } 1757 1758 MarkDeclRefReferenced(E); 1759 1760 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1761 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1762 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1763 recordUseOfEvaluatedWeak(E); 1764 1765 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1766 UnusedPrivateFields.remove(FD); 1767 // Just in case we're building an illegal pointer-to-member. 1768 if (FD->isBitField()) 1769 E->setObjectKind(OK_BitField); 1770 } 1771 1772 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1773 // designates a bit-field. 1774 if (auto *BD = dyn_cast<BindingDecl>(D)) 1775 if (auto *BE = BD->getBinding()) 1776 E->setObjectKind(BE->getObjectKind()); 1777 1778 return E; 1779 } 1780 1781 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1782 /// possibly a list of template arguments. 1783 /// 1784 /// If this produces template arguments, it is permitted to call 1785 /// DecomposeTemplateName. 1786 /// 1787 /// This actually loses a lot of source location information for 1788 /// non-standard name kinds; we should consider preserving that in 1789 /// some way. 1790 void 1791 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1792 TemplateArgumentListInfo &Buffer, 1793 DeclarationNameInfo &NameInfo, 1794 const TemplateArgumentListInfo *&TemplateArgs) { 1795 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1796 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1797 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1798 1799 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1800 Id.TemplateId->NumArgs); 1801 translateTemplateArguments(TemplateArgsPtr, Buffer); 1802 1803 TemplateName TName = Id.TemplateId->Template.get(); 1804 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1805 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1806 TemplateArgs = &Buffer; 1807 } else { 1808 NameInfo = GetNameFromUnqualifiedId(Id); 1809 TemplateArgs = nullptr; 1810 } 1811 } 1812 1813 static void emitEmptyLookupTypoDiagnostic( 1814 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1815 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1816 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1817 DeclContext *Ctx = 1818 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1819 if (!TC) { 1820 // Emit a special diagnostic for failed member lookups. 1821 // FIXME: computing the declaration context might fail here (?) 1822 if (Ctx) 1823 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1824 << SS.getRange(); 1825 else 1826 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1827 return; 1828 } 1829 1830 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1831 bool DroppedSpecifier = 1832 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1833 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1834 ? diag::note_implicit_param_decl 1835 : diag::note_previous_decl; 1836 if (!Ctx) 1837 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1838 SemaRef.PDiag(NoteID)); 1839 else 1840 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1841 << Typo << Ctx << DroppedSpecifier 1842 << SS.getRange(), 1843 SemaRef.PDiag(NoteID)); 1844 } 1845 1846 /// Diagnose an empty lookup. 1847 /// 1848 /// \return false if new lookup candidates were found 1849 bool 1850 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1851 std::unique_ptr<CorrectionCandidateCallback> CCC, 1852 TemplateArgumentListInfo *ExplicitTemplateArgs, 1853 ArrayRef<Expr *> Args, TypoExpr **Out) { 1854 DeclarationName Name = R.getLookupName(); 1855 1856 unsigned diagnostic = diag::err_undeclared_var_use; 1857 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1858 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1859 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1860 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1861 diagnostic = diag::err_undeclared_use; 1862 diagnostic_suggest = diag::err_undeclared_use_suggest; 1863 } 1864 1865 // If the original lookup was an unqualified lookup, fake an 1866 // unqualified lookup. This is useful when (for example) the 1867 // original lookup would not have found something because it was a 1868 // dependent name. 1869 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1870 while (DC) { 1871 if (isa<CXXRecordDecl>(DC)) { 1872 LookupQualifiedName(R, DC); 1873 1874 if (!R.empty()) { 1875 // Don't give errors about ambiguities in this lookup. 1876 R.suppressDiagnostics(); 1877 1878 // During a default argument instantiation the CurContext points 1879 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1880 // function parameter list, hence add an explicit check. 1881 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1882 ActiveTemplateInstantiations.back().Kind == 1883 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1884 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1885 bool isInstance = CurMethod && 1886 CurMethod->isInstance() && 1887 DC == CurMethod->getParent() && !isDefaultArgument; 1888 1889 // Give a code modification hint to insert 'this->'. 1890 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1891 // Actually quite difficult! 1892 if (getLangOpts().MSVCCompat) 1893 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1894 if (isInstance) { 1895 Diag(R.getNameLoc(), diagnostic) << Name 1896 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1897 CheckCXXThisCapture(R.getNameLoc()); 1898 } else { 1899 Diag(R.getNameLoc(), diagnostic) << Name; 1900 } 1901 1902 // Do we really want to note all of these? 1903 for (NamedDecl *D : R) 1904 Diag(D->getLocation(), diag::note_dependent_var_use); 1905 1906 // Return true if we are inside a default argument instantiation 1907 // and the found name refers to an instance member function, otherwise 1908 // the function calling DiagnoseEmptyLookup will try to create an 1909 // implicit member call and this is wrong for default argument. 1910 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1911 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1912 return true; 1913 } 1914 1915 // Tell the callee to try to recover. 1916 return false; 1917 } 1918 1919 R.clear(); 1920 } 1921 1922 // In Microsoft mode, if we are performing lookup from within a friend 1923 // function definition declared at class scope then we must set 1924 // DC to the lexical parent to be able to search into the parent 1925 // class. 1926 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1927 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1928 DC->getLexicalParent()->isRecord()) 1929 DC = DC->getLexicalParent(); 1930 else 1931 DC = DC->getParent(); 1932 } 1933 1934 // We didn't find anything, so try to correct for a typo. 1935 TypoCorrection Corrected; 1936 if (S && Out) { 1937 SourceLocation TypoLoc = R.getNameLoc(); 1938 assert(!ExplicitTemplateArgs && 1939 "Diagnosing an empty lookup with explicit template args!"); 1940 *Out = CorrectTypoDelayed( 1941 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1942 [=](const TypoCorrection &TC) { 1943 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1944 diagnostic, diagnostic_suggest); 1945 }, 1946 nullptr, CTK_ErrorRecovery); 1947 if (*Out) 1948 return true; 1949 } else if (S && (Corrected = 1950 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1951 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1952 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1953 bool DroppedSpecifier = 1954 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1955 R.setLookupName(Corrected.getCorrection()); 1956 1957 bool AcceptableWithRecovery = false; 1958 bool AcceptableWithoutRecovery = false; 1959 NamedDecl *ND = Corrected.getFoundDecl(); 1960 if (ND) { 1961 if (Corrected.isOverloaded()) { 1962 OverloadCandidateSet OCS(R.getNameLoc(), 1963 OverloadCandidateSet::CSK_Normal); 1964 OverloadCandidateSet::iterator Best; 1965 for (NamedDecl *CD : Corrected) { 1966 if (FunctionTemplateDecl *FTD = 1967 dyn_cast<FunctionTemplateDecl>(CD)) 1968 AddTemplateOverloadCandidate( 1969 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1970 Args, OCS); 1971 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1972 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1973 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1974 Args, OCS); 1975 } 1976 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1977 case OR_Success: 1978 ND = Best->FoundDecl; 1979 Corrected.setCorrectionDecl(ND); 1980 break; 1981 default: 1982 // FIXME: Arbitrarily pick the first declaration for the note. 1983 Corrected.setCorrectionDecl(ND); 1984 break; 1985 } 1986 } 1987 R.addDecl(ND); 1988 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1989 CXXRecordDecl *Record = nullptr; 1990 if (Corrected.getCorrectionSpecifier()) { 1991 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1992 Record = Ty->getAsCXXRecordDecl(); 1993 } 1994 if (!Record) 1995 Record = cast<CXXRecordDecl>( 1996 ND->getDeclContext()->getRedeclContext()); 1997 R.setNamingClass(Record); 1998 } 1999 2000 auto *UnderlyingND = ND->getUnderlyingDecl(); 2001 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2002 isa<FunctionTemplateDecl>(UnderlyingND); 2003 // FIXME: If we ended up with a typo for a type name or 2004 // Objective-C class name, we're in trouble because the parser 2005 // is in the wrong place to recover. Suggest the typo 2006 // correction, but don't make it a fix-it since we're not going 2007 // to recover well anyway. 2008 AcceptableWithoutRecovery = 2009 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2010 } else { 2011 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2012 // because we aren't able to recover. 2013 AcceptableWithoutRecovery = true; 2014 } 2015 2016 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2017 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2018 ? diag::note_implicit_param_decl 2019 : diag::note_previous_decl; 2020 if (SS.isEmpty()) 2021 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2022 PDiag(NoteID), AcceptableWithRecovery); 2023 else 2024 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2025 << Name << computeDeclContext(SS, false) 2026 << DroppedSpecifier << SS.getRange(), 2027 PDiag(NoteID), AcceptableWithRecovery); 2028 2029 // Tell the callee whether to try to recover. 2030 return !AcceptableWithRecovery; 2031 } 2032 } 2033 R.clear(); 2034 2035 // Emit a special diagnostic for failed member lookups. 2036 // FIXME: computing the declaration context might fail here (?) 2037 if (!SS.isEmpty()) { 2038 Diag(R.getNameLoc(), diag::err_no_member) 2039 << Name << computeDeclContext(SS, false) 2040 << SS.getRange(); 2041 return true; 2042 } 2043 2044 // Give up, we can't recover. 2045 Diag(R.getNameLoc(), diagnostic) << Name; 2046 return true; 2047 } 2048 2049 /// In Microsoft mode, if we are inside a template class whose parent class has 2050 /// dependent base classes, and we can't resolve an unqualified identifier, then 2051 /// assume the identifier is a member of a dependent base class. We can only 2052 /// recover successfully in static methods, instance methods, and other contexts 2053 /// where 'this' is available. This doesn't precisely match MSVC's 2054 /// instantiation model, but it's close enough. 2055 static Expr * 2056 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2057 DeclarationNameInfo &NameInfo, 2058 SourceLocation TemplateKWLoc, 2059 const TemplateArgumentListInfo *TemplateArgs) { 2060 // Only try to recover from lookup into dependent bases in static methods or 2061 // contexts where 'this' is available. 2062 QualType ThisType = S.getCurrentThisType(); 2063 const CXXRecordDecl *RD = nullptr; 2064 if (!ThisType.isNull()) 2065 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2066 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2067 RD = MD->getParent(); 2068 if (!RD || !RD->hasAnyDependentBases()) 2069 return nullptr; 2070 2071 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2072 // is available, suggest inserting 'this->' as a fixit. 2073 SourceLocation Loc = NameInfo.getLoc(); 2074 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2075 DB << NameInfo.getName() << RD; 2076 2077 if (!ThisType.isNull()) { 2078 DB << FixItHint::CreateInsertion(Loc, "this->"); 2079 return CXXDependentScopeMemberExpr::Create( 2080 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2081 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2082 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2083 } 2084 2085 // Synthesize a fake NNS that points to the derived class. This will 2086 // perform name lookup during template instantiation. 2087 CXXScopeSpec SS; 2088 auto *NNS = 2089 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2090 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2091 return DependentScopeDeclRefExpr::Create( 2092 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2093 TemplateArgs); 2094 } 2095 2096 ExprResult 2097 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2098 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2099 bool HasTrailingLParen, bool IsAddressOfOperand, 2100 std::unique_ptr<CorrectionCandidateCallback> CCC, 2101 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2102 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2103 "cannot be direct & operand and have a trailing lparen"); 2104 if (SS.isInvalid()) 2105 return ExprError(); 2106 2107 TemplateArgumentListInfo TemplateArgsBuffer; 2108 2109 // Decompose the UnqualifiedId into the following data. 2110 DeclarationNameInfo NameInfo; 2111 const TemplateArgumentListInfo *TemplateArgs; 2112 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2113 2114 DeclarationName Name = NameInfo.getName(); 2115 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2116 SourceLocation NameLoc = NameInfo.getLoc(); 2117 2118 // C++ [temp.dep.expr]p3: 2119 // An id-expression is type-dependent if it contains: 2120 // -- an identifier that was declared with a dependent type, 2121 // (note: handled after lookup) 2122 // -- a template-id that is dependent, 2123 // (note: handled in BuildTemplateIdExpr) 2124 // -- a conversion-function-id that specifies a dependent type, 2125 // -- a nested-name-specifier that contains a class-name that 2126 // names a dependent type. 2127 // Determine whether this is a member of an unknown specialization; 2128 // we need to handle these differently. 2129 bool DependentID = false; 2130 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2131 Name.getCXXNameType()->isDependentType()) { 2132 DependentID = true; 2133 } else if (SS.isSet()) { 2134 if (DeclContext *DC = computeDeclContext(SS, false)) { 2135 if (RequireCompleteDeclContext(SS, DC)) 2136 return ExprError(); 2137 } else { 2138 DependentID = true; 2139 } 2140 } 2141 2142 if (DependentID) 2143 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2144 IsAddressOfOperand, TemplateArgs); 2145 2146 // Perform the required lookup. 2147 LookupResult R(*this, NameInfo, 2148 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2149 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2150 if (TemplateArgs) { 2151 // Lookup the template name again to correctly establish the context in 2152 // which it was found. This is really unfortunate as we already did the 2153 // lookup to determine that it was a template name in the first place. If 2154 // this becomes a performance hit, we can work harder to preserve those 2155 // results until we get here but it's likely not worth it. 2156 bool MemberOfUnknownSpecialization; 2157 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2158 MemberOfUnknownSpecialization); 2159 2160 if (MemberOfUnknownSpecialization || 2161 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2162 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2163 IsAddressOfOperand, TemplateArgs); 2164 } else { 2165 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2166 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2167 2168 // If the result might be in a dependent base class, this is a dependent 2169 // id-expression. 2170 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2171 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2172 IsAddressOfOperand, TemplateArgs); 2173 2174 // If this reference is in an Objective-C method, then we need to do 2175 // some special Objective-C lookup, too. 2176 if (IvarLookupFollowUp) { 2177 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2178 if (E.isInvalid()) 2179 return ExprError(); 2180 2181 if (Expr *Ex = E.getAs<Expr>()) 2182 return Ex; 2183 } 2184 } 2185 2186 if (R.isAmbiguous()) 2187 return ExprError(); 2188 2189 // This could be an implicitly declared function reference (legal in C90, 2190 // extension in C99, forbidden in C++). 2191 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2192 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2193 if (D) R.addDecl(D); 2194 } 2195 2196 // Determine whether this name might be a candidate for 2197 // argument-dependent lookup. 2198 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2199 2200 if (R.empty() && !ADL) { 2201 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2202 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2203 TemplateKWLoc, TemplateArgs)) 2204 return E; 2205 } 2206 2207 // Don't diagnose an empty lookup for inline assembly. 2208 if (IsInlineAsmIdentifier) 2209 return ExprError(); 2210 2211 // If this name wasn't predeclared and if this is not a function 2212 // call, diagnose the problem. 2213 TypoExpr *TE = nullptr; 2214 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2215 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2216 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2217 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2218 "Typo correction callback misconfigured"); 2219 if (CCC) { 2220 // Make sure the callback knows what the typo being diagnosed is. 2221 CCC->setTypoName(II); 2222 if (SS.isValid()) 2223 CCC->setTypoNNS(SS.getScopeRep()); 2224 } 2225 if (DiagnoseEmptyLookup(S, SS, R, 2226 CCC ? std::move(CCC) : std::move(DefaultValidator), 2227 nullptr, None, &TE)) { 2228 if (TE && KeywordReplacement) { 2229 auto &State = getTypoExprState(TE); 2230 auto BestTC = State.Consumer->getNextCorrection(); 2231 if (BestTC.isKeyword()) { 2232 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2233 if (State.DiagHandler) 2234 State.DiagHandler(BestTC); 2235 KeywordReplacement->startToken(); 2236 KeywordReplacement->setKind(II->getTokenID()); 2237 KeywordReplacement->setIdentifierInfo(II); 2238 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2239 // Clean up the state associated with the TypoExpr, since it has 2240 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2241 clearDelayedTypo(TE); 2242 // Signal that a correction to a keyword was performed by returning a 2243 // valid-but-null ExprResult. 2244 return (Expr*)nullptr; 2245 } 2246 State.Consumer->resetCorrectionStream(); 2247 } 2248 return TE ? TE : ExprError(); 2249 } 2250 2251 assert(!R.empty() && 2252 "DiagnoseEmptyLookup returned false but added no results"); 2253 2254 // If we found an Objective-C instance variable, let 2255 // LookupInObjCMethod build the appropriate expression to 2256 // reference the ivar. 2257 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2258 R.clear(); 2259 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2260 // In a hopelessly buggy code, Objective-C instance variable 2261 // lookup fails and no expression will be built to reference it. 2262 if (!E.isInvalid() && !E.get()) 2263 return ExprError(); 2264 return E; 2265 } 2266 } 2267 2268 // This is guaranteed from this point on. 2269 assert(!R.empty() || ADL); 2270 2271 // Check whether this might be a C++ implicit instance member access. 2272 // C++ [class.mfct.non-static]p3: 2273 // When an id-expression that is not part of a class member access 2274 // syntax and not used to form a pointer to member is used in the 2275 // body of a non-static member function of class X, if name lookup 2276 // resolves the name in the id-expression to a non-static non-type 2277 // member of some class C, the id-expression is transformed into a 2278 // class member access expression using (*this) as the 2279 // postfix-expression to the left of the . operator. 2280 // 2281 // But we don't actually need to do this for '&' operands if R 2282 // resolved to a function or overloaded function set, because the 2283 // expression is ill-formed if it actually works out to be a 2284 // non-static member function: 2285 // 2286 // C++ [expr.ref]p4: 2287 // Otherwise, if E1.E2 refers to a non-static member function. . . 2288 // [t]he expression can be used only as the left-hand operand of a 2289 // member function call. 2290 // 2291 // There are other safeguards against such uses, but it's important 2292 // to get this right here so that we don't end up making a 2293 // spuriously dependent expression if we're inside a dependent 2294 // instance method. 2295 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2296 bool MightBeImplicitMember; 2297 if (!IsAddressOfOperand) 2298 MightBeImplicitMember = true; 2299 else if (!SS.isEmpty()) 2300 MightBeImplicitMember = false; 2301 else if (R.isOverloadedResult()) 2302 MightBeImplicitMember = false; 2303 else if (R.isUnresolvableResult()) 2304 MightBeImplicitMember = true; 2305 else 2306 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2307 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2308 isa<MSPropertyDecl>(R.getFoundDecl()); 2309 2310 if (MightBeImplicitMember) 2311 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2312 R, TemplateArgs, S); 2313 } 2314 2315 if (TemplateArgs || TemplateKWLoc.isValid()) { 2316 2317 // In C++1y, if this is a variable template id, then check it 2318 // in BuildTemplateIdExpr(). 2319 // The single lookup result must be a variable template declaration. 2320 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2321 Id.TemplateId->Kind == TNK_Var_template) { 2322 assert(R.getAsSingle<VarTemplateDecl>() && 2323 "There should only be one declaration found."); 2324 } 2325 2326 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2327 } 2328 2329 return BuildDeclarationNameExpr(SS, R, ADL); 2330 } 2331 2332 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2333 /// declaration name, generally during template instantiation. 2334 /// There's a large number of things which don't need to be done along 2335 /// this path. 2336 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2337 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2338 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2339 DeclContext *DC = computeDeclContext(SS, false); 2340 if (!DC) 2341 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2342 NameInfo, /*TemplateArgs=*/nullptr); 2343 2344 if (RequireCompleteDeclContext(SS, DC)) 2345 return ExprError(); 2346 2347 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2348 LookupQualifiedName(R, DC); 2349 2350 if (R.isAmbiguous()) 2351 return ExprError(); 2352 2353 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2354 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2355 NameInfo, /*TemplateArgs=*/nullptr); 2356 2357 if (R.empty()) { 2358 Diag(NameInfo.getLoc(), diag::err_no_member) 2359 << NameInfo.getName() << DC << SS.getRange(); 2360 return ExprError(); 2361 } 2362 2363 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2364 // Diagnose a missing typename if this resolved unambiguously to a type in 2365 // a dependent context. If we can recover with a type, downgrade this to 2366 // a warning in Microsoft compatibility mode. 2367 unsigned DiagID = diag::err_typename_missing; 2368 if (RecoveryTSI && getLangOpts().MSVCCompat) 2369 DiagID = diag::ext_typename_missing; 2370 SourceLocation Loc = SS.getBeginLoc(); 2371 auto D = Diag(Loc, DiagID); 2372 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2373 << SourceRange(Loc, NameInfo.getEndLoc()); 2374 2375 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2376 // context. 2377 if (!RecoveryTSI) 2378 return ExprError(); 2379 2380 // Only issue the fixit if we're prepared to recover. 2381 D << FixItHint::CreateInsertion(Loc, "typename "); 2382 2383 // Recover by pretending this was an elaborated type. 2384 QualType Ty = Context.getTypeDeclType(TD); 2385 TypeLocBuilder TLB; 2386 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2387 2388 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2389 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2390 QTL.setElaboratedKeywordLoc(SourceLocation()); 2391 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2392 2393 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2394 2395 return ExprEmpty(); 2396 } 2397 2398 // Defend against this resolving to an implicit member access. We usually 2399 // won't get here if this might be a legitimate a class member (we end up in 2400 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2401 // a pointer-to-member or in an unevaluated context in C++11. 2402 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2403 return BuildPossibleImplicitMemberExpr(SS, 2404 /*TemplateKWLoc=*/SourceLocation(), 2405 R, /*TemplateArgs=*/nullptr, S); 2406 2407 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2408 } 2409 2410 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2411 /// detected that we're currently inside an ObjC method. Perform some 2412 /// additional lookup. 2413 /// 2414 /// Ideally, most of this would be done by lookup, but there's 2415 /// actually quite a lot of extra work involved. 2416 /// 2417 /// Returns a null sentinel to indicate trivial success. 2418 ExprResult 2419 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2420 IdentifierInfo *II, bool AllowBuiltinCreation) { 2421 SourceLocation Loc = Lookup.getNameLoc(); 2422 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2423 2424 // Check for error condition which is already reported. 2425 if (!CurMethod) 2426 return ExprError(); 2427 2428 // There are two cases to handle here. 1) scoped lookup could have failed, 2429 // in which case we should look for an ivar. 2) scoped lookup could have 2430 // found a decl, but that decl is outside the current instance method (i.e. 2431 // a global variable). In these two cases, we do a lookup for an ivar with 2432 // this name, if the lookup sucedes, we replace it our current decl. 2433 2434 // If we're in a class method, we don't normally want to look for 2435 // ivars. But if we don't find anything else, and there's an 2436 // ivar, that's an error. 2437 bool IsClassMethod = CurMethod->isClassMethod(); 2438 2439 bool LookForIvars; 2440 if (Lookup.empty()) 2441 LookForIvars = true; 2442 else if (IsClassMethod) 2443 LookForIvars = false; 2444 else 2445 LookForIvars = (Lookup.isSingleResult() && 2446 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2447 ObjCInterfaceDecl *IFace = nullptr; 2448 if (LookForIvars) { 2449 IFace = CurMethod->getClassInterface(); 2450 ObjCInterfaceDecl *ClassDeclared; 2451 ObjCIvarDecl *IV = nullptr; 2452 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2453 // Diagnose using an ivar in a class method. 2454 if (IsClassMethod) 2455 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2456 << IV->getDeclName()); 2457 2458 // If we're referencing an invalid decl, just return this as a silent 2459 // error node. The error diagnostic was already emitted on the decl. 2460 if (IV->isInvalidDecl()) 2461 return ExprError(); 2462 2463 // Check if referencing a field with __attribute__((deprecated)). 2464 if (DiagnoseUseOfDecl(IV, Loc)) 2465 return ExprError(); 2466 2467 // Diagnose the use of an ivar outside of the declaring class. 2468 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2469 !declaresSameEntity(ClassDeclared, IFace) && 2470 !getLangOpts().DebuggerSupport) 2471 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2472 2473 // FIXME: This should use a new expr for a direct reference, don't 2474 // turn this into Self->ivar, just return a BareIVarExpr or something. 2475 IdentifierInfo &II = Context.Idents.get("self"); 2476 UnqualifiedId SelfName; 2477 SelfName.setIdentifier(&II, SourceLocation()); 2478 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2479 CXXScopeSpec SelfScopeSpec; 2480 SourceLocation TemplateKWLoc; 2481 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2482 SelfName, false, false); 2483 if (SelfExpr.isInvalid()) 2484 return ExprError(); 2485 2486 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2487 if (SelfExpr.isInvalid()) 2488 return ExprError(); 2489 2490 MarkAnyDeclReferenced(Loc, IV, true); 2491 2492 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2493 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2494 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2495 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2496 2497 ObjCIvarRefExpr *Result = new (Context) 2498 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2499 IV->getLocation(), SelfExpr.get(), true, true); 2500 2501 if (getLangOpts().ObjCAutoRefCount) { 2502 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2503 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2504 recordUseOfEvaluatedWeak(Result); 2505 } 2506 if (CurContext->isClosure()) 2507 Diag(Loc, diag::warn_implicitly_retains_self) 2508 << FixItHint::CreateInsertion(Loc, "self->"); 2509 } 2510 2511 return Result; 2512 } 2513 } else if (CurMethod->isInstanceMethod()) { 2514 // We should warn if a local variable hides an ivar. 2515 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2516 ObjCInterfaceDecl *ClassDeclared; 2517 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2518 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2519 declaresSameEntity(IFace, ClassDeclared)) 2520 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2521 } 2522 } 2523 } else if (Lookup.isSingleResult() && 2524 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2525 // If accessing a stand-alone ivar in a class method, this is an error. 2526 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2527 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2528 << IV->getDeclName()); 2529 } 2530 2531 if (Lookup.empty() && II && AllowBuiltinCreation) { 2532 // FIXME. Consolidate this with similar code in LookupName. 2533 if (unsigned BuiltinID = II->getBuiltinID()) { 2534 if (!(getLangOpts().CPlusPlus && 2535 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2536 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2537 S, Lookup.isForRedeclaration(), 2538 Lookup.getNameLoc()); 2539 if (D) Lookup.addDecl(D); 2540 } 2541 } 2542 } 2543 // Sentinel value saying that we didn't do anything special. 2544 return ExprResult((Expr *)nullptr); 2545 } 2546 2547 /// \brief Cast a base object to a member's actual type. 2548 /// 2549 /// Logically this happens in three phases: 2550 /// 2551 /// * First we cast from the base type to the naming class. 2552 /// The naming class is the class into which we were looking 2553 /// when we found the member; it's the qualifier type if a 2554 /// qualifier was provided, and otherwise it's the base type. 2555 /// 2556 /// * Next we cast from the naming class to the declaring class. 2557 /// If the member we found was brought into a class's scope by 2558 /// a using declaration, this is that class; otherwise it's 2559 /// the class declaring the member. 2560 /// 2561 /// * Finally we cast from the declaring class to the "true" 2562 /// declaring class of the member. This conversion does not 2563 /// obey access control. 2564 ExprResult 2565 Sema::PerformObjectMemberConversion(Expr *From, 2566 NestedNameSpecifier *Qualifier, 2567 NamedDecl *FoundDecl, 2568 NamedDecl *Member) { 2569 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2570 if (!RD) 2571 return From; 2572 2573 QualType DestRecordType; 2574 QualType DestType; 2575 QualType FromRecordType; 2576 QualType FromType = From->getType(); 2577 bool PointerConversions = false; 2578 if (isa<FieldDecl>(Member)) { 2579 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2580 2581 if (FromType->getAs<PointerType>()) { 2582 DestType = Context.getPointerType(DestRecordType); 2583 FromRecordType = FromType->getPointeeType(); 2584 PointerConversions = true; 2585 } else { 2586 DestType = DestRecordType; 2587 FromRecordType = FromType; 2588 } 2589 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2590 if (Method->isStatic()) 2591 return From; 2592 2593 DestType = Method->getThisType(Context); 2594 DestRecordType = DestType->getPointeeType(); 2595 2596 if (FromType->getAs<PointerType>()) { 2597 FromRecordType = FromType->getPointeeType(); 2598 PointerConversions = true; 2599 } else { 2600 FromRecordType = FromType; 2601 DestType = DestRecordType; 2602 } 2603 } else { 2604 // No conversion necessary. 2605 return From; 2606 } 2607 2608 if (DestType->isDependentType() || FromType->isDependentType()) 2609 return From; 2610 2611 // If the unqualified types are the same, no conversion is necessary. 2612 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2613 return From; 2614 2615 SourceRange FromRange = From->getSourceRange(); 2616 SourceLocation FromLoc = FromRange.getBegin(); 2617 2618 ExprValueKind VK = From->getValueKind(); 2619 2620 // C++ [class.member.lookup]p8: 2621 // [...] Ambiguities can often be resolved by qualifying a name with its 2622 // class name. 2623 // 2624 // If the member was a qualified name and the qualified referred to a 2625 // specific base subobject type, we'll cast to that intermediate type 2626 // first and then to the object in which the member is declared. That allows 2627 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2628 // 2629 // class Base { public: int x; }; 2630 // class Derived1 : public Base { }; 2631 // class Derived2 : public Base { }; 2632 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2633 // 2634 // void VeryDerived::f() { 2635 // x = 17; // error: ambiguous base subobjects 2636 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2637 // } 2638 if (Qualifier && Qualifier->getAsType()) { 2639 QualType QType = QualType(Qualifier->getAsType(), 0); 2640 assert(QType->isRecordType() && "lookup done with non-record type"); 2641 2642 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2643 2644 // In C++98, the qualifier type doesn't actually have to be a base 2645 // type of the object type, in which case we just ignore it. 2646 // Otherwise build the appropriate casts. 2647 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2648 CXXCastPath BasePath; 2649 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2650 FromLoc, FromRange, &BasePath)) 2651 return ExprError(); 2652 2653 if (PointerConversions) 2654 QType = Context.getPointerType(QType); 2655 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2656 VK, &BasePath).get(); 2657 2658 FromType = QType; 2659 FromRecordType = QRecordType; 2660 2661 // If the qualifier type was the same as the destination type, 2662 // we're done. 2663 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2664 return From; 2665 } 2666 } 2667 2668 bool IgnoreAccess = false; 2669 2670 // If we actually found the member through a using declaration, cast 2671 // down to the using declaration's type. 2672 // 2673 // Pointer equality is fine here because only one declaration of a 2674 // class ever has member declarations. 2675 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2676 assert(isa<UsingShadowDecl>(FoundDecl)); 2677 QualType URecordType = Context.getTypeDeclType( 2678 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2679 2680 // We only need to do this if the naming-class to declaring-class 2681 // conversion is non-trivial. 2682 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2683 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2684 CXXCastPath BasePath; 2685 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2686 FromLoc, FromRange, &BasePath)) 2687 return ExprError(); 2688 2689 QualType UType = URecordType; 2690 if (PointerConversions) 2691 UType = Context.getPointerType(UType); 2692 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2693 VK, &BasePath).get(); 2694 FromType = UType; 2695 FromRecordType = URecordType; 2696 } 2697 2698 // We don't do access control for the conversion from the 2699 // declaring class to the true declaring class. 2700 IgnoreAccess = true; 2701 } 2702 2703 CXXCastPath BasePath; 2704 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2705 FromLoc, FromRange, &BasePath, 2706 IgnoreAccess)) 2707 return ExprError(); 2708 2709 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2710 VK, &BasePath); 2711 } 2712 2713 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2714 const LookupResult &R, 2715 bool HasTrailingLParen) { 2716 // Only when used directly as the postfix-expression of a call. 2717 if (!HasTrailingLParen) 2718 return false; 2719 2720 // Never if a scope specifier was provided. 2721 if (SS.isSet()) 2722 return false; 2723 2724 // Only in C++ or ObjC++. 2725 if (!getLangOpts().CPlusPlus) 2726 return false; 2727 2728 // Turn off ADL when we find certain kinds of declarations during 2729 // normal lookup: 2730 for (NamedDecl *D : R) { 2731 // C++0x [basic.lookup.argdep]p3: 2732 // -- a declaration of a class member 2733 // Since using decls preserve this property, we check this on the 2734 // original decl. 2735 if (D->isCXXClassMember()) 2736 return false; 2737 2738 // C++0x [basic.lookup.argdep]p3: 2739 // -- a block-scope function declaration that is not a 2740 // using-declaration 2741 // NOTE: we also trigger this for function templates (in fact, we 2742 // don't check the decl type at all, since all other decl types 2743 // turn off ADL anyway). 2744 if (isa<UsingShadowDecl>(D)) 2745 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2746 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2747 return false; 2748 2749 // C++0x [basic.lookup.argdep]p3: 2750 // -- a declaration that is neither a function or a function 2751 // template 2752 // And also for builtin functions. 2753 if (isa<FunctionDecl>(D)) { 2754 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2755 2756 // But also builtin functions. 2757 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2758 return false; 2759 } else if (!isa<FunctionTemplateDecl>(D)) 2760 return false; 2761 } 2762 2763 return true; 2764 } 2765 2766 2767 /// Diagnoses obvious problems with the use of the given declaration 2768 /// as an expression. This is only actually called for lookups that 2769 /// were not overloaded, and it doesn't promise that the declaration 2770 /// will in fact be used. 2771 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2772 if (isa<TypedefNameDecl>(D)) { 2773 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2774 return true; 2775 } 2776 2777 if (isa<ObjCInterfaceDecl>(D)) { 2778 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2779 return true; 2780 } 2781 2782 if (isa<NamespaceDecl>(D)) { 2783 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2784 return true; 2785 } 2786 2787 return false; 2788 } 2789 2790 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2791 LookupResult &R, bool NeedsADL, 2792 bool AcceptInvalidDecl) { 2793 // If this is a single, fully-resolved result and we don't need ADL, 2794 // just build an ordinary singleton decl ref. 2795 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2796 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2797 R.getRepresentativeDecl(), nullptr, 2798 AcceptInvalidDecl); 2799 2800 // We only need to check the declaration if there's exactly one 2801 // result, because in the overloaded case the results can only be 2802 // functions and function templates. 2803 if (R.isSingleResult() && 2804 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2805 return ExprError(); 2806 2807 // Otherwise, just build an unresolved lookup expression. Suppress 2808 // any lookup-related diagnostics; we'll hash these out later, when 2809 // we've picked a target. 2810 R.suppressDiagnostics(); 2811 2812 UnresolvedLookupExpr *ULE 2813 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2814 SS.getWithLocInContext(Context), 2815 R.getLookupNameInfo(), 2816 NeedsADL, R.isOverloadedResult(), 2817 R.begin(), R.end()); 2818 2819 return ULE; 2820 } 2821 2822 static void 2823 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2824 ValueDecl *var, DeclContext *DC); 2825 2826 /// \brief Complete semantic analysis for a reference to the given declaration. 2827 ExprResult Sema::BuildDeclarationNameExpr( 2828 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2829 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2830 bool AcceptInvalidDecl) { 2831 assert(D && "Cannot refer to a NULL declaration"); 2832 assert(!isa<FunctionTemplateDecl>(D) && 2833 "Cannot refer unambiguously to a function template"); 2834 2835 SourceLocation Loc = NameInfo.getLoc(); 2836 if (CheckDeclInExpr(*this, Loc, D)) 2837 return ExprError(); 2838 2839 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2840 // Specifically diagnose references to class templates that are missing 2841 // a template argument list. 2842 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2843 << Template << SS.getRange(); 2844 Diag(Template->getLocation(), diag::note_template_decl_here); 2845 return ExprError(); 2846 } 2847 2848 // Make sure that we're referring to a value. 2849 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2850 if (!VD) { 2851 Diag(Loc, diag::err_ref_non_value) 2852 << D << SS.getRange(); 2853 Diag(D->getLocation(), diag::note_declared_at); 2854 return ExprError(); 2855 } 2856 2857 // Check whether this declaration can be used. Note that we suppress 2858 // this check when we're going to perform argument-dependent lookup 2859 // on this function name, because this might not be the function 2860 // that overload resolution actually selects. 2861 if (DiagnoseUseOfDecl(VD, Loc)) 2862 return ExprError(); 2863 2864 // Only create DeclRefExpr's for valid Decl's. 2865 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2866 return ExprError(); 2867 2868 // Handle members of anonymous structs and unions. If we got here, 2869 // and the reference is to a class member indirect field, then this 2870 // must be the subject of a pointer-to-member expression. 2871 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2872 if (!indirectField->isCXXClassMember()) 2873 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2874 indirectField); 2875 2876 { 2877 QualType type = VD->getType(); 2878 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2879 // C++ [except.spec]p17: 2880 // An exception-specification is considered to be needed when: 2881 // - in an expression, the function is the unique lookup result or 2882 // the selected member of a set of overloaded functions. 2883 ResolveExceptionSpec(Loc, FPT); 2884 type = VD->getType(); 2885 } 2886 ExprValueKind valueKind = VK_RValue; 2887 2888 switch (D->getKind()) { 2889 // Ignore all the non-ValueDecl kinds. 2890 #define ABSTRACT_DECL(kind) 2891 #define VALUE(type, base) 2892 #define DECL(type, base) \ 2893 case Decl::type: 2894 #include "clang/AST/DeclNodes.inc" 2895 llvm_unreachable("invalid value decl kind"); 2896 2897 // These shouldn't make it here. 2898 case Decl::ObjCAtDefsField: 2899 case Decl::ObjCIvar: 2900 llvm_unreachable("forming non-member reference to ivar?"); 2901 2902 // Enum constants are always r-values and never references. 2903 // Unresolved using declarations are dependent. 2904 case Decl::EnumConstant: 2905 case Decl::UnresolvedUsingValue: 2906 case Decl::OMPDeclareReduction: 2907 valueKind = VK_RValue; 2908 break; 2909 2910 // Fields and indirect fields that got here must be for 2911 // pointer-to-member expressions; we just call them l-values for 2912 // internal consistency, because this subexpression doesn't really 2913 // exist in the high-level semantics. 2914 case Decl::Field: 2915 case Decl::IndirectField: 2916 assert(getLangOpts().CPlusPlus && 2917 "building reference to field in C?"); 2918 2919 // These can't have reference type in well-formed programs, but 2920 // for internal consistency we do this anyway. 2921 type = type.getNonReferenceType(); 2922 valueKind = VK_LValue; 2923 break; 2924 2925 // Non-type template parameters are either l-values or r-values 2926 // depending on the type. 2927 case Decl::NonTypeTemplateParm: { 2928 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2929 type = reftype->getPointeeType(); 2930 valueKind = VK_LValue; // even if the parameter is an r-value reference 2931 break; 2932 } 2933 2934 // For non-references, we need to strip qualifiers just in case 2935 // the template parameter was declared as 'const int' or whatever. 2936 valueKind = VK_RValue; 2937 type = type.getUnqualifiedType(); 2938 break; 2939 } 2940 2941 case Decl::Var: 2942 case Decl::VarTemplateSpecialization: 2943 case Decl::VarTemplatePartialSpecialization: 2944 case Decl::Decomposition: 2945 case Decl::OMPCapturedExpr: 2946 // In C, "extern void blah;" is valid and is an r-value. 2947 if (!getLangOpts().CPlusPlus && 2948 !type.hasQualifiers() && 2949 type->isVoidType()) { 2950 valueKind = VK_RValue; 2951 break; 2952 } 2953 // fallthrough 2954 2955 case Decl::ImplicitParam: 2956 case Decl::ParmVar: { 2957 // These are always l-values. 2958 valueKind = VK_LValue; 2959 type = type.getNonReferenceType(); 2960 2961 // FIXME: Does the addition of const really only apply in 2962 // potentially-evaluated contexts? Since the variable isn't actually 2963 // captured in an unevaluated context, it seems that the answer is no. 2964 if (!isUnevaluatedContext()) { 2965 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2966 if (!CapturedType.isNull()) 2967 type = CapturedType; 2968 } 2969 2970 break; 2971 } 2972 2973 case Decl::Binding: { 2974 // These are always lvalues. 2975 valueKind = VK_LValue; 2976 type = type.getNonReferenceType(); 2977 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2978 // decides how that's supposed to work. 2979 auto *BD = cast<BindingDecl>(VD); 2980 if (BD->getDeclContext()->isFunctionOrMethod() && 2981 BD->getDeclContext() != CurContext) 2982 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2983 break; 2984 } 2985 2986 case Decl::Function: { 2987 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2988 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2989 type = Context.BuiltinFnTy; 2990 valueKind = VK_RValue; 2991 break; 2992 } 2993 } 2994 2995 const FunctionType *fty = type->castAs<FunctionType>(); 2996 2997 // If we're referring to a function with an __unknown_anytype 2998 // result type, make the entire expression __unknown_anytype. 2999 if (fty->getReturnType() == Context.UnknownAnyTy) { 3000 type = Context.UnknownAnyTy; 3001 valueKind = VK_RValue; 3002 break; 3003 } 3004 3005 // Functions are l-values in C++. 3006 if (getLangOpts().CPlusPlus) { 3007 valueKind = VK_LValue; 3008 break; 3009 } 3010 3011 // C99 DR 316 says that, if a function type comes from a 3012 // function definition (without a prototype), that type is only 3013 // used for checking compatibility. Therefore, when referencing 3014 // the function, we pretend that we don't have the full function 3015 // type. 3016 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3017 isa<FunctionProtoType>(fty)) 3018 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3019 fty->getExtInfo()); 3020 3021 // Functions are r-values in C. 3022 valueKind = VK_RValue; 3023 break; 3024 } 3025 3026 case Decl::MSProperty: 3027 valueKind = VK_LValue; 3028 break; 3029 3030 case Decl::CXXMethod: 3031 // If we're referring to a method with an __unknown_anytype 3032 // result type, make the entire expression __unknown_anytype. 3033 // This should only be possible with a type written directly. 3034 if (const FunctionProtoType *proto 3035 = dyn_cast<FunctionProtoType>(VD->getType())) 3036 if (proto->getReturnType() == Context.UnknownAnyTy) { 3037 type = Context.UnknownAnyTy; 3038 valueKind = VK_RValue; 3039 break; 3040 } 3041 3042 // C++ methods are l-values if static, r-values if non-static. 3043 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3044 valueKind = VK_LValue; 3045 break; 3046 } 3047 // fallthrough 3048 3049 case Decl::CXXConversion: 3050 case Decl::CXXDestructor: 3051 case Decl::CXXConstructor: 3052 valueKind = VK_RValue; 3053 break; 3054 } 3055 3056 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3057 TemplateArgs); 3058 } 3059 } 3060 3061 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3062 SmallString<32> &Target) { 3063 Target.resize(CharByteWidth * (Source.size() + 1)); 3064 char *ResultPtr = &Target[0]; 3065 const llvm::UTF8 *ErrorPtr; 3066 bool success = 3067 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3068 (void)success; 3069 assert(success); 3070 Target.resize(ResultPtr - &Target[0]); 3071 } 3072 3073 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3074 PredefinedExpr::IdentType IT) { 3075 // Pick the current block, lambda, captured statement or function. 3076 Decl *currentDecl = nullptr; 3077 if (const BlockScopeInfo *BSI = getCurBlock()) 3078 currentDecl = BSI->TheDecl; 3079 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3080 currentDecl = LSI->CallOperator; 3081 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3082 currentDecl = CSI->TheCapturedDecl; 3083 else 3084 currentDecl = getCurFunctionOrMethodDecl(); 3085 3086 if (!currentDecl) { 3087 Diag(Loc, diag::ext_predef_outside_function); 3088 currentDecl = Context.getTranslationUnitDecl(); 3089 } 3090 3091 QualType ResTy; 3092 StringLiteral *SL = nullptr; 3093 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3094 ResTy = Context.DependentTy; 3095 else { 3096 // Pre-defined identifiers are of type char[x], where x is the length of 3097 // the string. 3098 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3099 unsigned Length = Str.length(); 3100 3101 llvm::APInt LengthI(32, Length + 1); 3102 if (IT == PredefinedExpr::LFunction) { 3103 ResTy = Context.WideCharTy.withConst(); 3104 SmallString<32> RawChars; 3105 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3106 Str, RawChars); 3107 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3108 /*IndexTypeQuals*/ 0); 3109 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3110 /*Pascal*/ false, ResTy, Loc); 3111 } else { 3112 ResTy = Context.CharTy.withConst(); 3113 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3114 /*IndexTypeQuals*/ 0); 3115 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3116 /*Pascal*/ false, ResTy, Loc); 3117 } 3118 } 3119 3120 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3121 } 3122 3123 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3124 PredefinedExpr::IdentType IT; 3125 3126 switch (Kind) { 3127 default: llvm_unreachable("Unknown simple primary expr!"); 3128 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3129 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3130 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3131 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3132 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3133 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3134 } 3135 3136 return BuildPredefinedExpr(Loc, IT); 3137 } 3138 3139 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3140 SmallString<16> CharBuffer; 3141 bool Invalid = false; 3142 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3143 if (Invalid) 3144 return ExprError(); 3145 3146 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3147 PP, Tok.getKind()); 3148 if (Literal.hadError()) 3149 return ExprError(); 3150 3151 QualType Ty; 3152 if (Literal.isWide()) 3153 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3154 else if (Literal.isUTF16()) 3155 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3156 else if (Literal.isUTF32()) 3157 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3158 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3159 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3160 else 3161 Ty = Context.CharTy; // 'x' -> char in C++ 3162 3163 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3164 if (Literal.isWide()) 3165 Kind = CharacterLiteral::Wide; 3166 else if (Literal.isUTF16()) 3167 Kind = CharacterLiteral::UTF16; 3168 else if (Literal.isUTF32()) 3169 Kind = CharacterLiteral::UTF32; 3170 else if (Literal.isUTF8()) 3171 Kind = CharacterLiteral::UTF8; 3172 3173 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3174 Tok.getLocation()); 3175 3176 if (Literal.getUDSuffix().empty()) 3177 return Lit; 3178 3179 // We're building a user-defined literal. 3180 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3181 SourceLocation UDSuffixLoc = 3182 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3183 3184 // Make sure we're allowed user-defined literals here. 3185 if (!UDLScope) 3186 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3187 3188 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3189 // operator "" X (ch) 3190 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3191 Lit, Tok.getLocation()); 3192 } 3193 3194 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3195 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3196 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3197 Context.IntTy, Loc); 3198 } 3199 3200 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3201 QualType Ty, SourceLocation Loc) { 3202 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3203 3204 using llvm::APFloat; 3205 APFloat Val(Format); 3206 3207 APFloat::opStatus result = Literal.GetFloatValue(Val); 3208 3209 // Overflow is always an error, but underflow is only an error if 3210 // we underflowed to zero (APFloat reports denormals as underflow). 3211 if ((result & APFloat::opOverflow) || 3212 ((result & APFloat::opUnderflow) && Val.isZero())) { 3213 unsigned diagnostic; 3214 SmallString<20> buffer; 3215 if (result & APFloat::opOverflow) { 3216 diagnostic = diag::warn_float_overflow; 3217 APFloat::getLargest(Format).toString(buffer); 3218 } else { 3219 diagnostic = diag::warn_float_underflow; 3220 APFloat::getSmallest(Format).toString(buffer); 3221 } 3222 3223 S.Diag(Loc, diagnostic) 3224 << Ty 3225 << StringRef(buffer.data(), buffer.size()); 3226 } 3227 3228 bool isExact = (result == APFloat::opOK); 3229 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3230 } 3231 3232 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3233 assert(E && "Invalid expression"); 3234 3235 if (E->isValueDependent()) 3236 return false; 3237 3238 QualType QT = E->getType(); 3239 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3240 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3241 return true; 3242 } 3243 3244 llvm::APSInt ValueAPS; 3245 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3246 3247 if (R.isInvalid()) 3248 return true; 3249 3250 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3251 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3252 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3253 << ValueAPS.toString(10) << ValueIsPositive; 3254 return true; 3255 } 3256 3257 return false; 3258 } 3259 3260 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3261 // Fast path for a single digit (which is quite common). A single digit 3262 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3263 if (Tok.getLength() == 1) { 3264 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3265 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3266 } 3267 3268 SmallString<128> SpellingBuffer; 3269 // NumericLiteralParser wants to overread by one character. Add padding to 3270 // the buffer in case the token is copied to the buffer. If getSpelling() 3271 // returns a StringRef to the memory buffer, it should have a null char at 3272 // the EOF, so it is also safe. 3273 SpellingBuffer.resize(Tok.getLength() + 1); 3274 3275 // Get the spelling of the token, which eliminates trigraphs, etc. 3276 bool Invalid = false; 3277 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3278 if (Invalid) 3279 return ExprError(); 3280 3281 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3282 if (Literal.hadError) 3283 return ExprError(); 3284 3285 if (Literal.hasUDSuffix()) { 3286 // We're building a user-defined literal. 3287 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3288 SourceLocation UDSuffixLoc = 3289 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3290 3291 // Make sure we're allowed user-defined literals here. 3292 if (!UDLScope) 3293 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3294 3295 QualType CookedTy; 3296 if (Literal.isFloatingLiteral()) { 3297 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3298 // long double, the literal is treated as a call of the form 3299 // operator "" X (f L) 3300 CookedTy = Context.LongDoubleTy; 3301 } else { 3302 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3303 // unsigned long long, the literal is treated as a call of the form 3304 // operator "" X (n ULL) 3305 CookedTy = Context.UnsignedLongLongTy; 3306 } 3307 3308 DeclarationName OpName = 3309 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3310 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3311 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3312 3313 SourceLocation TokLoc = Tok.getLocation(); 3314 3315 // Perform literal operator lookup to determine if we're building a raw 3316 // literal or a cooked one. 3317 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3318 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3319 /*AllowRaw*/true, /*AllowTemplate*/true, 3320 /*AllowStringTemplate*/false)) { 3321 case LOLR_Error: 3322 return ExprError(); 3323 3324 case LOLR_Cooked: { 3325 Expr *Lit; 3326 if (Literal.isFloatingLiteral()) { 3327 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3328 } else { 3329 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3330 if (Literal.GetIntegerValue(ResultVal)) 3331 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3332 << /* Unsigned */ 1; 3333 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3334 Tok.getLocation()); 3335 } 3336 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3337 } 3338 3339 case LOLR_Raw: { 3340 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3341 // literal is treated as a call of the form 3342 // operator "" X ("n") 3343 unsigned Length = Literal.getUDSuffixOffset(); 3344 QualType StrTy = Context.getConstantArrayType( 3345 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3346 ArrayType::Normal, 0); 3347 Expr *Lit = StringLiteral::Create( 3348 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3349 /*Pascal*/false, StrTy, &TokLoc, 1); 3350 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3351 } 3352 3353 case LOLR_Template: { 3354 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3355 // template), L is treated as a call fo the form 3356 // operator "" X <'c1', 'c2', ... 'ck'>() 3357 // where n is the source character sequence c1 c2 ... ck. 3358 TemplateArgumentListInfo ExplicitArgs; 3359 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3360 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3361 llvm::APSInt Value(CharBits, CharIsUnsigned); 3362 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3363 Value = TokSpelling[I]; 3364 TemplateArgument Arg(Context, Value, Context.CharTy); 3365 TemplateArgumentLocInfo ArgInfo; 3366 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3367 } 3368 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3369 &ExplicitArgs); 3370 } 3371 case LOLR_StringTemplate: 3372 llvm_unreachable("unexpected literal operator lookup result"); 3373 } 3374 } 3375 3376 Expr *Res; 3377 3378 if (Literal.isFloatingLiteral()) { 3379 QualType Ty; 3380 if (Literal.isHalf){ 3381 if (getOpenCLOptions().cl_khr_fp16) 3382 Ty = Context.HalfTy; 3383 else { 3384 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3385 return ExprError(); 3386 } 3387 } else if (Literal.isFloat) 3388 Ty = Context.FloatTy; 3389 else if (Literal.isLong) 3390 Ty = Context.LongDoubleTy; 3391 else if (Literal.isFloat128) 3392 Ty = Context.Float128Ty; 3393 else 3394 Ty = Context.DoubleTy; 3395 3396 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3397 3398 if (Ty == Context.DoubleTy) { 3399 if (getLangOpts().SinglePrecisionConstants) { 3400 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3401 } else if (getLangOpts().OpenCL && 3402 !((getLangOpts().OpenCLVersion >= 120) || 3403 getOpenCLOptions().cl_khr_fp64)) { 3404 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3405 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3406 } 3407 } 3408 } else if (!Literal.isIntegerLiteral()) { 3409 return ExprError(); 3410 } else { 3411 QualType Ty; 3412 3413 // 'long long' is a C99 or C++11 feature. 3414 if (!getLangOpts().C99 && Literal.isLongLong) { 3415 if (getLangOpts().CPlusPlus) 3416 Diag(Tok.getLocation(), 3417 getLangOpts().CPlusPlus11 ? 3418 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3419 else 3420 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3421 } 3422 3423 // Get the value in the widest-possible width. 3424 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3425 llvm::APInt ResultVal(MaxWidth, 0); 3426 3427 if (Literal.GetIntegerValue(ResultVal)) { 3428 // If this value didn't fit into uintmax_t, error and force to ull. 3429 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3430 << /* Unsigned */ 1; 3431 Ty = Context.UnsignedLongLongTy; 3432 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3433 "long long is not intmax_t?"); 3434 } else { 3435 // If this value fits into a ULL, try to figure out what else it fits into 3436 // according to the rules of C99 6.4.4.1p5. 3437 3438 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3439 // be an unsigned int. 3440 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3441 3442 // Check from smallest to largest, picking the smallest type we can. 3443 unsigned Width = 0; 3444 3445 // Microsoft specific integer suffixes are explicitly sized. 3446 if (Literal.MicrosoftInteger) { 3447 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3448 Width = 8; 3449 Ty = Context.CharTy; 3450 } else { 3451 Width = Literal.MicrosoftInteger; 3452 Ty = Context.getIntTypeForBitwidth(Width, 3453 /*Signed=*/!Literal.isUnsigned); 3454 } 3455 } 3456 3457 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3458 // Are int/unsigned possibilities? 3459 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3460 3461 // Does it fit in a unsigned int? 3462 if (ResultVal.isIntN(IntSize)) { 3463 // Does it fit in a signed int? 3464 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3465 Ty = Context.IntTy; 3466 else if (AllowUnsigned) 3467 Ty = Context.UnsignedIntTy; 3468 Width = IntSize; 3469 } 3470 } 3471 3472 // Are long/unsigned long possibilities? 3473 if (Ty.isNull() && !Literal.isLongLong) { 3474 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3475 3476 // Does it fit in a unsigned long? 3477 if (ResultVal.isIntN(LongSize)) { 3478 // Does it fit in a signed long? 3479 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3480 Ty = Context.LongTy; 3481 else if (AllowUnsigned) 3482 Ty = Context.UnsignedLongTy; 3483 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3484 // is compatible. 3485 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3486 const unsigned LongLongSize = 3487 Context.getTargetInfo().getLongLongWidth(); 3488 Diag(Tok.getLocation(), 3489 getLangOpts().CPlusPlus 3490 ? Literal.isLong 3491 ? diag::warn_old_implicitly_unsigned_long_cxx 3492 : /*C++98 UB*/ diag:: 3493 ext_old_implicitly_unsigned_long_cxx 3494 : diag::warn_old_implicitly_unsigned_long) 3495 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3496 : /*will be ill-formed*/ 1); 3497 Ty = Context.UnsignedLongTy; 3498 } 3499 Width = LongSize; 3500 } 3501 } 3502 3503 // Check long long if needed. 3504 if (Ty.isNull()) { 3505 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3506 3507 // Does it fit in a unsigned long long? 3508 if (ResultVal.isIntN(LongLongSize)) { 3509 // Does it fit in a signed long long? 3510 // To be compatible with MSVC, hex integer literals ending with the 3511 // LL or i64 suffix are always signed in Microsoft mode. 3512 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3513 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3514 Ty = Context.LongLongTy; 3515 else if (AllowUnsigned) 3516 Ty = Context.UnsignedLongLongTy; 3517 Width = LongLongSize; 3518 } 3519 } 3520 3521 // If we still couldn't decide a type, we probably have something that 3522 // does not fit in a signed long long, but has no U suffix. 3523 if (Ty.isNull()) { 3524 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3525 Ty = Context.UnsignedLongLongTy; 3526 Width = Context.getTargetInfo().getLongLongWidth(); 3527 } 3528 3529 if (ResultVal.getBitWidth() != Width) 3530 ResultVal = ResultVal.trunc(Width); 3531 } 3532 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3533 } 3534 3535 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3536 if (Literal.isImaginary) 3537 Res = new (Context) ImaginaryLiteral(Res, 3538 Context.getComplexType(Res->getType())); 3539 3540 return Res; 3541 } 3542 3543 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3544 assert(E && "ActOnParenExpr() missing expr"); 3545 return new (Context) ParenExpr(L, R, E); 3546 } 3547 3548 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3549 SourceLocation Loc, 3550 SourceRange ArgRange) { 3551 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3552 // scalar or vector data type argument..." 3553 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3554 // type (C99 6.2.5p18) or void. 3555 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3556 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3557 << T << ArgRange; 3558 return true; 3559 } 3560 3561 assert((T->isVoidType() || !T->isIncompleteType()) && 3562 "Scalar types should always be complete"); 3563 return false; 3564 } 3565 3566 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3567 SourceLocation Loc, 3568 SourceRange ArgRange, 3569 UnaryExprOrTypeTrait TraitKind) { 3570 // Invalid types must be hard errors for SFINAE in C++. 3571 if (S.LangOpts.CPlusPlus) 3572 return true; 3573 3574 // C99 6.5.3.4p1: 3575 if (T->isFunctionType() && 3576 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3577 // sizeof(function)/alignof(function) is allowed as an extension. 3578 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3579 << TraitKind << ArgRange; 3580 return false; 3581 } 3582 3583 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3584 // this is an error (OpenCL v1.1 s6.3.k) 3585 if (T->isVoidType()) { 3586 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3587 : diag::ext_sizeof_alignof_void_type; 3588 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3589 return false; 3590 } 3591 3592 return true; 3593 } 3594 3595 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3596 SourceLocation Loc, 3597 SourceRange ArgRange, 3598 UnaryExprOrTypeTrait TraitKind) { 3599 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3600 // runtime doesn't allow it. 3601 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3602 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3603 << T << (TraitKind == UETT_SizeOf) 3604 << ArgRange; 3605 return true; 3606 } 3607 3608 return false; 3609 } 3610 3611 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3612 /// pointer type is equal to T) and emit a warning if it is. 3613 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3614 Expr *E) { 3615 // Don't warn if the operation changed the type. 3616 if (T != E->getType()) 3617 return; 3618 3619 // Now look for array decays. 3620 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3621 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3622 return; 3623 3624 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3625 << ICE->getType() 3626 << ICE->getSubExpr()->getType(); 3627 } 3628 3629 /// \brief Check the constraints on expression operands to unary type expression 3630 /// and type traits. 3631 /// 3632 /// Completes any types necessary and validates the constraints on the operand 3633 /// expression. The logic mostly mirrors the type-based overload, but may modify 3634 /// the expression as it completes the type for that expression through template 3635 /// instantiation, etc. 3636 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3637 UnaryExprOrTypeTrait ExprKind) { 3638 QualType ExprTy = E->getType(); 3639 assert(!ExprTy->isReferenceType()); 3640 3641 if (ExprKind == UETT_VecStep) 3642 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3643 E->getSourceRange()); 3644 3645 // Whitelist some types as extensions 3646 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3647 E->getSourceRange(), ExprKind)) 3648 return false; 3649 3650 // 'alignof' applied to an expression only requires the base element type of 3651 // the expression to be complete. 'sizeof' requires the expression's type to 3652 // be complete (and will attempt to complete it if it's an array of unknown 3653 // bound). 3654 if (ExprKind == UETT_AlignOf) { 3655 if (RequireCompleteType(E->getExprLoc(), 3656 Context.getBaseElementType(E->getType()), 3657 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3658 E->getSourceRange())) 3659 return true; 3660 } else { 3661 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3662 ExprKind, E->getSourceRange())) 3663 return true; 3664 } 3665 3666 // Completing the expression's type may have changed it. 3667 ExprTy = E->getType(); 3668 assert(!ExprTy->isReferenceType()); 3669 3670 if (ExprTy->isFunctionType()) { 3671 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3672 << ExprKind << E->getSourceRange(); 3673 return true; 3674 } 3675 3676 // The operand for sizeof and alignof is in an unevaluated expression context, 3677 // so side effects could result in unintended consequences. 3678 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3679 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3680 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3681 3682 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3683 E->getSourceRange(), ExprKind)) 3684 return true; 3685 3686 if (ExprKind == UETT_SizeOf) { 3687 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3688 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3689 QualType OType = PVD->getOriginalType(); 3690 QualType Type = PVD->getType(); 3691 if (Type->isPointerType() && OType->isArrayType()) { 3692 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3693 << Type << OType; 3694 Diag(PVD->getLocation(), diag::note_declared_at); 3695 } 3696 } 3697 } 3698 3699 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3700 // decays into a pointer and returns an unintended result. This is most 3701 // likely a typo for "sizeof(array) op x". 3702 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3703 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3704 BO->getLHS()); 3705 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3706 BO->getRHS()); 3707 } 3708 } 3709 3710 return false; 3711 } 3712 3713 /// \brief Check the constraints on operands to unary expression and type 3714 /// traits. 3715 /// 3716 /// This will complete any types necessary, and validate the various constraints 3717 /// on those operands. 3718 /// 3719 /// The UsualUnaryConversions() function is *not* called by this routine. 3720 /// C99 6.3.2.1p[2-4] all state: 3721 /// Except when it is the operand of the sizeof operator ... 3722 /// 3723 /// C++ [expr.sizeof]p4 3724 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3725 /// standard conversions are not applied to the operand of sizeof. 3726 /// 3727 /// This policy is followed for all of the unary trait expressions. 3728 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3729 SourceLocation OpLoc, 3730 SourceRange ExprRange, 3731 UnaryExprOrTypeTrait ExprKind) { 3732 if (ExprType->isDependentType()) 3733 return false; 3734 3735 // C++ [expr.sizeof]p2: 3736 // When applied to a reference or a reference type, the result 3737 // is the size of the referenced type. 3738 // C++11 [expr.alignof]p3: 3739 // When alignof is applied to a reference type, the result 3740 // shall be the alignment of the referenced type. 3741 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3742 ExprType = Ref->getPointeeType(); 3743 3744 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3745 // When alignof or _Alignof is applied to an array type, the result 3746 // is the alignment of the element type. 3747 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3748 ExprType = Context.getBaseElementType(ExprType); 3749 3750 if (ExprKind == UETT_VecStep) 3751 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3752 3753 // Whitelist some types as extensions 3754 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3755 ExprKind)) 3756 return false; 3757 3758 if (RequireCompleteType(OpLoc, ExprType, 3759 diag::err_sizeof_alignof_incomplete_type, 3760 ExprKind, ExprRange)) 3761 return true; 3762 3763 if (ExprType->isFunctionType()) { 3764 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3765 << ExprKind << ExprRange; 3766 return true; 3767 } 3768 3769 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3770 ExprKind)) 3771 return true; 3772 3773 return false; 3774 } 3775 3776 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3777 E = E->IgnoreParens(); 3778 3779 // Cannot know anything else if the expression is dependent. 3780 if (E->isTypeDependent()) 3781 return false; 3782 3783 if (E->getObjectKind() == OK_BitField) { 3784 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3785 << 1 << E->getSourceRange(); 3786 return true; 3787 } 3788 3789 ValueDecl *D = nullptr; 3790 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3791 D = DRE->getDecl(); 3792 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3793 D = ME->getMemberDecl(); 3794 } 3795 3796 // If it's a field, require the containing struct to have a 3797 // complete definition so that we can compute the layout. 3798 // 3799 // This can happen in C++11 onwards, either by naming the member 3800 // in a way that is not transformed into a member access expression 3801 // (in an unevaluated operand, for instance), or by naming the member 3802 // in a trailing-return-type. 3803 // 3804 // For the record, since __alignof__ on expressions is a GCC 3805 // extension, GCC seems to permit this but always gives the 3806 // nonsensical answer 0. 3807 // 3808 // We don't really need the layout here --- we could instead just 3809 // directly check for all the appropriate alignment-lowing 3810 // attributes --- but that would require duplicating a lot of 3811 // logic that just isn't worth duplicating for such a marginal 3812 // use-case. 3813 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3814 // Fast path this check, since we at least know the record has a 3815 // definition if we can find a member of it. 3816 if (!FD->getParent()->isCompleteDefinition()) { 3817 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3818 << E->getSourceRange(); 3819 return true; 3820 } 3821 3822 // Otherwise, if it's a field, and the field doesn't have 3823 // reference type, then it must have a complete type (or be a 3824 // flexible array member, which we explicitly want to 3825 // white-list anyway), which makes the following checks trivial. 3826 if (!FD->getType()->isReferenceType()) 3827 return false; 3828 } 3829 3830 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3831 } 3832 3833 bool Sema::CheckVecStepExpr(Expr *E) { 3834 E = E->IgnoreParens(); 3835 3836 // Cannot know anything else if the expression is dependent. 3837 if (E->isTypeDependent()) 3838 return false; 3839 3840 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3841 } 3842 3843 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3844 CapturingScopeInfo *CSI) { 3845 assert(T->isVariablyModifiedType()); 3846 assert(CSI != nullptr); 3847 3848 // We're going to walk down into the type and look for VLA expressions. 3849 do { 3850 const Type *Ty = T.getTypePtr(); 3851 switch (Ty->getTypeClass()) { 3852 #define TYPE(Class, Base) 3853 #define ABSTRACT_TYPE(Class, Base) 3854 #define NON_CANONICAL_TYPE(Class, Base) 3855 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3856 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3857 #include "clang/AST/TypeNodes.def" 3858 T = QualType(); 3859 break; 3860 // These types are never variably-modified. 3861 case Type::Builtin: 3862 case Type::Complex: 3863 case Type::Vector: 3864 case Type::ExtVector: 3865 case Type::Record: 3866 case Type::Enum: 3867 case Type::Elaborated: 3868 case Type::TemplateSpecialization: 3869 case Type::ObjCObject: 3870 case Type::ObjCInterface: 3871 case Type::ObjCObjectPointer: 3872 case Type::ObjCTypeParam: 3873 case Type::Pipe: 3874 llvm_unreachable("type class is never variably-modified!"); 3875 case Type::Adjusted: 3876 T = cast<AdjustedType>(Ty)->getOriginalType(); 3877 break; 3878 case Type::Decayed: 3879 T = cast<DecayedType>(Ty)->getPointeeType(); 3880 break; 3881 case Type::Pointer: 3882 T = cast<PointerType>(Ty)->getPointeeType(); 3883 break; 3884 case Type::BlockPointer: 3885 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3886 break; 3887 case Type::LValueReference: 3888 case Type::RValueReference: 3889 T = cast<ReferenceType>(Ty)->getPointeeType(); 3890 break; 3891 case Type::MemberPointer: 3892 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3893 break; 3894 case Type::ConstantArray: 3895 case Type::IncompleteArray: 3896 // Losing element qualification here is fine. 3897 T = cast<ArrayType>(Ty)->getElementType(); 3898 break; 3899 case Type::VariableArray: { 3900 // Losing element qualification here is fine. 3901 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3902 3903 // Unknown size indication requires no size computation. 3904 // Otherwise, evaluate and record it. 3905 if (auto Size = VAT->getSizeExpr()) { 3906 if (!CSI->isVLATypeCaptured(VAT)) { 3907 RecordDecl *CapRecord = nullptr; 3908 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3909 CapRecord = LSI->Lambda; 3910 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3911 CapRecord = CRSI->TheRecordDecl; 3912 } 3913 if (CapRecord) { 3914 auto ExprLoc = Size->getExprLoc(); 3915 auto SizeType = Context.getSizeType(); 3916 // Build the non-static data member. 3917 auto Field = 3918 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3919 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3920 /*BW*/ nullptr, /*Mutable*/ false, 3921 /*InitStyle*/ ICIS_NoInit); 3922 Field->setImplicit(true); 3923 Field->setAccess(AS_private); 3924 Field->setCapturedVLAType(VAT); 3925 CapRecord->addDecl(Field); 3926 3927 CSI->addVLATypeCapture(ExprLoc, SizeType); 3928 } 3929 } 3930 } 3931 T = VAT->getElementType(); 3932 break; 3933 } 3934 case Type::FunctionProto: 3935 case Type::FunctionNoProto: 3936 T = cast<FunctionType>(Ty)->getReturnType(); 3937 break; 3938 case Type::Paren: 3939 case Type::TypeOf: 3940 case Type::UnaryTransform: 3941 case Type::Attributed: 3942 case Type::SubstTemplateTypeParm: 3943 case Type::PackExpansion: 3944 // Keep walking after single level desugaring. 3945 T = T.getSingleStepDesugaredType(Context); 3946 break; 3947 case Type::Typedef: 3948 T = cast<TypedefType>(Ty)->desugar(); 3949 break; 3950 case Type::Decltype: 3951 T = cast<DecltypeType>(Ty)->desugar(); 3952 break; 3953 case Type::Auto: 3954 T = cast<AutoType>(Ty)->getDeducedType(); 3955 break; 3956 case Type::TypeOfExpr: 3957 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3958 break; 3959 case Type::Atomic: 3960 T = cast<AtomicType>(Ty)->getValueType(); 3961 break; 3962 } 3963 } while (!T.isNull() && T->isVariablyModifiedType()); 3964 } 3965 3966 /// \brief Build a sizeof or alignof expression given a type operand. 3967 ExprResult 3968 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3969 SourceLocation OpLoc, 3970 UnaryExprOrTypeTrait ExprKind, 3971 SourceRange R) { 3972 if (!TInfo) 3973 return ExprError(); 3974 3975 QualType T = TInfo->getType(); 3976 3977 if (!T->isDependentType() && 3978 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3979 return ExprError(); 3980 3981 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3982 if (auto *TT = T->getAs<TypedefType>()) { 3983 for (auto I = FunctionScopes.rbegin(), 3984 E = std::prev(FunctionScopes.rend()); 3985 I != E; ++I) { 3986 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3987 if (CSI == nullptr) 3988 break; 3989 DeclContext *DC = nullptr; 3990 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3991 DC = LSI->CallOperator; 3992 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3993 DC = CRSI->TheCapturedDecl; 3994 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3995 DC = BSI->TheDecl; 3996 if (DC) { 3997 if (DC->containsDecl(TT->getDecl())) 3998 break; 3999 captureVariablyModifiedType(Context, T, CSI); 4000 } 4001 } 4002 } 4003 } 4004 4005 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4006 return new (Context) UnaryExprOrTypeTraitExpr( 4007 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4008 } 4009 4010 /// \brief Build a sizeof or alignof expression given an expression 4011 /// operand. 4012 ExprResult 4013 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4014 UnaryExprOrTypeTrait ExprKind) { 4015 ExprResult PE = CheckPlaceholderExpr(E); 4016 if (PE.isInvalid()) 4017 return ExprError(); 4018 4019 E = PE.get(); 4020 4021 // Verify that the operand is valid. 4022 bool isInvalid = false; 4023 if (E->isTypeDependent()) { 4024 // Delay type-checking for type-dependent expressions. 4025 } else if (ExprKind == UETT_AlignOf) { 4026 isInvalid = CheckAlignOfExpr(*this, E); 4027 } else if (ExprKind == UETT_VecStep) { 4028 isInvalid = CheckVecStepExpr(E); 4029 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4030 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4031 isInvalid = true; 4032 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4033 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4034 isInvalid = true; 4035 } else { 4036 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4037 } 4038 4039 if (isInvalid) 4040 return ExprError(); 4041 4042 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4043 PE = TransformToPotentiallyEvaluated(E); 4044 if (PE.isInvalid()) return ExprError(); 4045 E = PE.get(); 4046 } 4047 4048 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4049 return new (Context) UnaryExprOrTypeTraitExpr( 4050 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4051 } 4052 4053 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4054 /// expr and the same for @c alignof and @c __alignof 4055 /// Note that the ArgRange is invalid if isType is false. 4056 ExprResult 4057 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4058 UnaryExprOrTypeTrait ExprKind, bool IsType, 4059 void *TyOrEx, SourceRange ArgRange) { 4060 // If error parsing type, ignore. 4061 if (!TyOrEx) return ExprError(); 4062 4063 if (IsType) { 4064 TypeSourceInfo *TInfo; 4065 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4066 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4067 } 4068 4069 Expr *ArgEx = (Expr *)TyOrEx; 4070 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4071 return Result; 4072 } 4073 4074 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4075 bool IsReal) { 4076 if (V.get()->isTypeDependent()) 4077 return S.Context.DependentTy; 4078 4079 // _Real and _Imag are only l-values for normal l-values. 4080 if (V.get()->getObjectKind() != OK_Ordinary) { 4081 V = S.DefaultLvalueConversion(V.get()); 4082 if (V.isInvalid()) 4083 return QualType(); 4084 } 4085 4086 // These operators return the element type of a complex type. 4087 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4088 return CT->getElementType(); 4089 4090 // Otherwise they pass through real integer and floating point types here. 4091 if (V.get()->getType()->isArithmeticType()) 4092 return V.get()->getType(); 4093 4094 // Test for placeholders. 4095 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4096 if (PR.isInvalid()) return QualType(); 4097 if (PR.get() != V.get()) { 4098 V = PR; 4099 return CheckRealImagOperand(S, V, Loc, IsReal); 4100 } 4101 4102 // Reject anything else. 4103 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4104 << (IsReal ? "__real" : "__imag"); 4105 return QualType(); 4106 } 4107 4108 4109 4110 ExprResult 4111 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4112 tok::TokenKind Kind, Expr *Input) { 4113 UnaryOperatorKind Opc; 4114 switch (Kind) { 4115 default: llvm_unreachable("Unknown unary op!"); 4116 case tok::plusplus: Opc = UO_PostInc; break; 4117 case tok::minusminus: Opc = UO_PostDec; break; 4118 } 4119 4120 // Since this might is a postfix expression, get rid of ParenListExprs. 4121 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4122 if (Result.isInvalid()) return ExprError(); 4123 Input = Result.get(); 4124 4125 return BuildUnaryOp(S, OpLoc, Opc, Input); 4126 } 4127 4128 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4129 /// 4130 /// \return true on error 4131 static bool checkArithmeticOnObjCPointer(Sema &S, 4132 SourceLocation opLoc, 4133 Expr *op) { 4134 assert(op->getType()->isObjCObjectPointerType()); 4135 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4136 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4137 return false; 4138 4139 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4140 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4141 << op->getSourceRange(); 4142 return true; 4143 } 4144 4145 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4146 auto *BaseNoParens = Base->IgnoreParens(); 4147 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4148 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4149 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4150 } 4151 4152 ExprResult 4153 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4154 Expr *idx, SourceLocation rbLoc) { 4155 if (base && !base->getType().isNull() && 4156 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4157 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4158 /*Length=*/nullptr, rbLoc); 4159 4160 // Since this might be a postfix expression, get rid of ParenListExprs. 4161 if (isa<ParenListExpr>(base)) { 4162 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4163 if (result.isInvalid()) return ExprError(); 4164 base = result.get(); 4165 } 4166 4167 // Handle any non-overload placeholder types in the base and index 4168 // expressions. We can't handle overloads here because the other 4169 // operand might be an overloadable type, in which case the overload 4170 // resolution for the operator overload should get the first crack 4171 // at the overload. 4172 bool IsMSPropertySubscript = false; 4173 if (base->getType()->isNonOverloadPlaceholderType()) { 4174 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4175 if (!IsMSPropertySubscript) { 4176 ExprResult result = CheckPlaceholderExpr(base); 4177 if (result.isInvalid()) 4178 return ExprError(); 4179 base = result.get(); 4180 } 4181 } 4182 if (idx->getType()->isNonOverloadPlaceholderType()) { 4183 ExprResult result = CheckPlaceholderExpr(idx); 4184 if (result.isInvalid()) return ExprError(); 4185 idx = result.get(); 4186 } 4187 4188 // Build an unanalyzed expression if either operand is type-dependent. 4189 if (getLangOpts().CPlusPlus && 4190 (base->isTypeDependent() || idx->isTypeDependent())) { 4191 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4192 VK_LValue, OK_Ordinary, rbLoc); 4193 } 4194 4195 // MSDN, property (C++) 4196 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4197 // This attribute can also be used in the declaration of an empty array in a 4198 // class or structure definition. For example: 4199 // __declspec(property(get=GetX, put=PutX)) int x[]; 4200 // The above statement indicates that x[] can be used with one or more array 4201 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4202 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4203 if (IsMSPropertySubscript) { 4204 // Build MS property subscript expression if base is MS property reference 4205 // or MS property subscript. 4206 return new (Context) MSPropertySubscriptExpr( 4207 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4208 } 4209 4210 // Use C++ overloaded-operator rules if either operand has record 4211 // type. The spec says to do this if either type is *overloadable*, 4212 // but enum types can't declare subscript operators or conversion 4213 // operators, so there's nothing interesting for overload resolution 4214 // to do if there aren't any record types involved. 4215 // 4216 // ObjC pointers have their own subscripting logic that is not tied 4217 // to overload resolution and so should not take this path. 4218 if (getLangOpts().CPlusPlus && 4219 (base->getType()->isRecordType() || 4220 (!base->getType()->isObjCObjectPointerType() && 4221 idx->getType()->isRecordType()))) { 4222 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4223 } 4224 4225 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4226 } 4227 4228 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4229 Expr *LowerBound, 4230 SourceLocation ColonLoc, Expr *Length, 4231 SourceLocation RBLoc) { 4232 if (Base->getType()->isPlaceholderType() && 4233 !Base->getType()->isSpecificPlaceholderType( 4234 BuiltinType::OMPArraySection)) { 4235 ExprResult Result = CheckPlaceholderExpr(Base); 4236 if (Result.isInvalid()) 4237 return ExprError(); 4238 Base = Result.get(); 4239 } 4240 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4241 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4242 if (Result.isInvalid()) 4243 return ExprError(); 4244 Result = DefaultLvalueConversion(Result.get()); 4245 if (Result.isInvalid()) 4246 return ExprError(); 4247 LowerBound = Result.get(); 4248 } 4249 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4250 ExprResult Result = CheckPlaceholderExpr(Length); 4251 if (Result.isInvalid()) 4252 return ExprError(); 4253 Result = DefaultLvalueConversion(Result.get()); 4254 if (Result.isInvalid()) 4255 return ExprError(); 4256 Length = Result.get(); 4257 } 4258 4259 // Build an unanalyzed expression if either operand is type-dependent. 4260 if (Base->isTypeDependent() || 4261 (LowerBound && 4262 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4263 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4264 return new (Context) 4265 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4266 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4267 } 4268 4269 // Perform default conversions. 4270 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4271 QualType ResultTy; 4272 if (OriginalTy->isAnyPointerType()) { 4273 ResultTy = OriginalTy->getPointeeType(); 4274 } else if (OriginalTy->isArrayType()) { 4275 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4276 } else { 4277 return ExprError( 4278 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4279 << Base->getSourceRange()); 4280 } 4281 // C99 6.5.2.1p1 4282 if (LowerBound) { 4283 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4284 LowerBound); 4285 if (Res.isInvalid()) 4286 return ExprError(Diag(LowerBound->getExprLoc(), 4287 diag::err_omp_typecheck_section_not_integer) 4288 << 0 << LowerBound->getSourceRange()); 4289 LowerBound = Res.get(); 4290 4291 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4292 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4293 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4294 << 0 << LowerBound->getSourceRange(); 4295 } 4296 if (Length) { 4297 auto Res = 4298 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4299 if (Res.isInvalid()) 4300 return ExprError(Diag(Length->getExprLoc(), 4301 diag::err_omp_typecheck_section_not_integer) 4302 << 1 << Length->getSourceRange()); 4303 Length = Res.get(); 4304 4305 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4306 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4307 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4308 << 1 << Length->getSourceRange(); 4309 } 4310 4311 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4312 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4313 // type. Note that functions are not objects, and that (in C99 parlance) 4314 // incomplete types are not object types. 4315 if (ResultTy->isFunctionType()) { 4316 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4317 << ResultTy << Base->getSourceRange(); 4318 return ExprError(); 4319 } 4320 4321 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4322 diag::err_omp_section_incomplete_type, Base)) 4323 return ExprError(); 4324 4325 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4326 llvm::APSInt LowerBoundValue; 4327 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4328 // OpenMP 4.5, [2.4 Array Sections] 4329 // The array section must be a subset of the original array. 4330 if (LowerBoundValue.isNegative()) { 4331 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4332 << LowerBound->getSourceRange(); 4333 return ExprError(); 4334 } 4335 } 4336 } 4337 4338 if (Length) { 4339 llvm::APSInt LengthValue; 4340 if (Length->EvaluateAsInt(LengthValue, Context)) { 4341 // OpenMP 4.5, [2.4 Array Sections] 4342 // The length must evaluate to non-negative integers. 4343 if (LengthValue.isNegative()) { 4344 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4345 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4346 << Length->getSourceRange(); 4347 return ExprError(); 4348 } 4349 } 4350 } else if (ColonLoc.isValid() && 4351 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4352 !OriginalTy->isVariableArrayType()))) { 4353 // OpenMP 4.5, [2.4 Array Sections] 4354 // When the size of the array dimension is not known, the length must be 4355 // specified explicitly. 4356 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4357 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4358 return ExprError(); 4359 } 4360 4361 if (!Base->getType()->isSpecificPlaceholderType( 4362 BuiltinType::OMPArraySection)) { 4363 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4364 if (Result.isInvalid()) 4365 return ExprError(); 4366 Base = Result.get(); 4367 } 4368 return new (Context) 4369 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4370 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4371 } 4372 4373 ExprResult 4374 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4375 Expr *Idx, SourceLocation RLoc) { 4376 Expr *LHSExp = Base; 4377 Expr *RHSExp = Idx; 4378 4379 ExprValueKind VK = VK_LValue; 4380 ExprObjectKind OK = OK_Ordinary; 4381 4382 // Per C++ core issue 1213, the result is an xvalue if either operand is 4383 // a non-lvalue array, and an lvalue otherwise. 4384 if (getLangOpts().CPlusPlus11 && 4385 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4386 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4387 VK = VK_XValue; 4388 4389 // Perform default conversions. 4390 if (!LHSExp->getType()->getAs<VectorType>()) { 4391 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4392 if (Result.isInvalid()) 4393 return ExprError(); 4394 LHSExp = Result.get(); 4395 } 4396 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4397 if (Result.isInvalid()) 4398 return ExprError(); 4399 RHSExp = Result.get(); 4400 4401 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4402 4403 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4404 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4405 // in the subscript position. As a result, we need to derive the array base 4406 // and index from the expression types. 4407 Expr *BaseExpr, *IndexExpr; 4408 QualType ResultType; 4409 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4410 BaseExpr = LHSExp; 4411 IndexExpr = RHSExp; 4412 ResultType = Context.DependentTy; 4413 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4414 BaseExpr = LHSExp; 4415 IndexExpr = RHSExp; 4416 ResultType = PTy->getPointeeType(); 4417 } else if (const ObjCObjectPointerType *PTy = 4418 LHSTy->getAs<ObjCObjectPointerType>()) { 4419 BaseExpr = LHSExp; 4420 IndexExpr = RHSExp; 4421 4422 // Use custom logic if this should be the pseudo-object subscript 4423 // expression. 4424 if (!LangOpts.isSubscriptPointerArithmetic()) 4425 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4426 nullptr); 4427 4428 ResultType = PTy->getPointeeType(); 4429 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4430 // Handle the uncommon case of "123[Ptr]". 4431 BaseExpr = RHSExp; 4432 IndexExpr = LHSExp; 4433 ResultType = PTy->getPointeeType(); 4434 } else if (const ObjCObjectPointerType *PTy = 4435 RHSTy->getAs<ObjCObjectPointerType>()) { 4436 // Handle the uncommon case of "123[Ptr]". 4437 BaseExpr = RHSExp; 4438 IndexExpr = LHSExp; 4439 ResultType = PTy->getPointeeType(); 4440 if (!LangOpts.isSubscriptPointerArithmetic()) { 4441 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4442 << ResultType << BaseExpr->getSourceRange(); 4443 return ExprError(); 4444 } 4445 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4446 BaseExpr = LHSExp; // vectors: V[123] 4447 IndexExpr = RHSExp; 4448 VK = LHSExp->getValueKind(); 4449 if (VK != VK_RValue) 4450 OK = OK_VectorComponent; 4451 4452 // FIXME: need to deal with const... 4453 ResultType = VTy->getElementType(); 4454 } else if (LHSTy->isArrayType()) { 4455 // If we see an array that wasn't promoted by 4456 // DefaultFunctionArrayLvalueConversion, it must be an array that 4457 // wasn't promoted because of the C90 rule that doesn't 4458 // allow promoting non-lvalue arrays. Warn, then 4459 // force the promotion here. 4460 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4461 LHSExp->getSourceRange(); 4462 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4463 CK_ArrayToPointerDecay).get(); 4464 LHSTy = LHSExp->getType(); 4465 4466 BaseExpr = LHSExp; 4467 IndexExpr = RHSExp; 4468 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4469 } else if (RHSTy->isArrayType()) { 4470 // Same as previous, except for 123[f().a] case 4471 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4472 RHSExp->getSourceRange(); 4473 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4474 CK_ArrayToPointerDecay).get(); 4475 RHSTy = RHSExp->getType(); 4476 4477 BaseExpr = RHSExp; 4478 IndexExpr = LHSExp; 4479 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4480 } else { 4481 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4482 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4483 } 4484 // C99 6.5.2.1p1 4485 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4486 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4487 << IndexExpr->getSourceRange()); 4488 4489 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4490 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4491 && !IndexExpr->isTypeDependent()) 4492 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4493 4494 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4495 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4496 // type. Note that Functions are not objects, and that (in C99 parlance) 4497 // incomplete types are not object types. 4498 if (ResultType->isFunctionType()) { 4499 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4500 << ResultType << BaseExpr->getSourceRange(); 4501 return ExprError(); 4502 } 4503 4504 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4505 // GNU extension: subscripting on pointer to void 4506 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4507 << BaseExpr->getSourceRange(); 4508 4509 // C forbids expressions of unqualified void type from being l-values. 4510 // See IsCForbiddenLValueType. 4511 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4512 } else if (!ResultType->isDependentType() && 4513 RequireCompleteType(LLoc, ResultType, 4514 diag::err_subscript_incomplete_type, BaseExpr)) 4515 return ExprError(); 4516 4517 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4518 !ResultType.isCForbiddenLValueType()); 4519 4520 return new (Context) 4521 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4522 } 4523 4524 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4525 ParmVarDecl *Param) { 4526 if (Param->hasUnparsedDefaultArg()) { 4527 Diag(CallLoc, 4528 diag::err_use_of_default_argument_to_function_declared_later) << 4529 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4530 Diag(UnparsedDefaultArgLocs[Param], 4531 diag::note_default_argument_declared_here); 4532 return true; 4533 } 4534 4535 if (Param->hasUninstantiatedDefaultArg()) { 4536 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4537 4538 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4539 Param); 4540 4541 // Instantiate the expression. 4542 MultiLevelTemplateArgumentList MutiLevelArgList 4543 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4544 4545 InstantiatingTemplate Inst(*this, CallLoc, Param, 4546 MutiLevelArgList.getInnermost()); 4547 if (Inst.isInvalid()) 4548 return true; 4549 if (Inst.isAlreadyInstantiating()) { 4550 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4551 Param->setInvalidDecl(); 4552 return true; 4553 } 4554 4555 ExprResult Result; 4556 { 4557 // C++ [dcl.fct.default]p5: 4558 // The names in the [default argument] expression are bound, and 4559 // the semantic constraints are checked, at the point where the 4560 // default argument expression appears. 4561 ContextRAII SavedContext(*this, FD); 4562 LocalInstantiationScope Local(*this); 4563 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4564 /*DirectInit*/false); 4565 } 4566 if (Result.isInvalid()) 4567 return true; 4568 4569 // Check the expression as an initializer for the parameter. 4570 InitializedEntity Entity 4571 = InitializedEntity::InitializeParameter(Context, Param); 4572 InitializationKind Kind 4573 = InitializationKind::CreateCopy(Param->getLocation(), 4574 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4575 Expr *ResultE = Result.getAs<Expr>(); 4576 4577 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4578 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4579 if (Result.isInvalid()) 4580 return true; 4581 4582 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4583 Param->getOuterLocStart()); 4584 if (Result.isInvalid()) 4585 return true; 4586 4587 // Remember the instantiated default argument. 4588 Param->setDefaultArg(Result.getAs<Expr>()); 4589 if (ASTMutationListener *L = getASTMutationListener()) { 4590 L->DefaultArgumentInstantiated(Param); 4591 } 4592 } 4593 4594 // If the default argument expression is not set yet, we are building it now. 4595 if (!Param->hasInit()) { 4596 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4597 Param->setInvalidDecl(); 4598 return true; 4599 } 4600 4601 // If the default expression creates temporaries, we need to 4602 // push them to the current stack of expression temporaries so they'll 4603 // be properly destroyed. 4604 // FIXME: We should really be rebuilding the default argument with new 4605 // bound temporaries; see the comment in PR5810. 4606 // We don't need to do that with block decls, though, because 4607 // blocks in default argument expression can never capture anything. 4608 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4609 // Set the "needs cleanups" bit regardless of whether there are 4610 // any explicit objects. 4611 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4612 4613 // Append all the objects to the cleanup list. Right now, this 4614 // should always be a no-op, because blocks in default argument 4615 // expressions should never be able to capture anything. 4616 assert(!Init->getNumObjects() && 4617 "default argument expression has capturing blocks?"); 4618 } 4619 4620 // We already type-checked the argument, so we know it works. 4621 // Just mark all of the declarations in this potentially-evaluated expression 4622 // as being "referenced". 4623 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4624 /*SkipLocalVariables=*/true); 4625 return false; 4626 } 4627 4628 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4629 FunctionDecl *FD, ParmVarDecl *Param) { 4630 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4631 return ExprError(); 4632 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4633 } 4634 4635 Sema::VariadicCallType 4636 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4637 Expr *Fn) { 4638 if (Proto && Proto->isVariadic()) { 4639 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4640 return VariadicConstructor; 4641 else if (Fn && Fn->getType()->isBlockPointerType()) 4642 return VariadicBlock; 4643 else if (FDecl) { 4644 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4645 if (Method->isInstance()) 4646 return VariadicMethod; 4647 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4648 return VariadicMethod; 4649 return VariadicFunction; 4650 } 4651 return VariadicDoesNotApply; 4652 } 4653 4654 namespace { 4655 class FunctionCallCCC : public FunctionCallFilterCCC { 4656 public: 4657 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4658 unsigned NumArgs, MemberExpr *ME) 4659 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4660 FunctionName(FuncName) {} 4661 4662 bool ValidateCandidate(const TypoCorrection &candidate) override { 4663 if (!candidate.getCorrectionSpecifier() || 4664 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4665 return false; 4666 } 4667 4668 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4669 } 4670 4671 private: 4672 const IdentifierInfo *const FunctionName; 4673 }; 4674 } 4675 4676 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4677 FunctionDecl *FDecl, 4678 ArrayRef<Expr *> Args) { 4679 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4680 DeclarationName FuncName = FDecl->getDeclName(); 4681 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4682 4683 if (TypoCorrection Corrected = S.CorrectTypo( 4684 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4685 S.getScopeForContext(S.CurContext), nullptr, 4686 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4687 Args.size(), ME), 4688 Sema::CTK_ErrorRecovery)) { 4689 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4690 if (Corrected.isOverloaded()) { 4691 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4692 OverloadCandidateSet::iterator Best; 4693 for (NamedDecl *CD : Corrected) { 4694 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4695 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4696 OCS); 4697 } 4698 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4699 case OR_Success: 4700 ND = Best->FoundDecl; 4701 Corrected.setCorrectionDecl(ND); 4702 break; 4703 default: 4704 break; 4705 } 4706 } 4707 ND = ND->getUnderlyingDecl(); 4708 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4709 return Corrected; 4710 } 4711 } 4712 return TypoCorrection(); 4713 } 4714 4715 /// ConvertArgumentsForCall - Converts the arguments specified in 4716 /// Args/NumArgs to the parameter types of the function FDecl with 4717 /// function prototype Proto. Call is the call expression itself, and 4718 /// Fn is the function expression. For a C++ member function, this 4719 /// routine does not attempt to convert the object argument. Returns 4720 /// true if the call is ill-formed. 4721 bool 4722 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4723 FunctionDecl *FDecl, 4724 const FunctionProtoType *Proto, 4725 ArrayRef<Expr *> Args, 4726 SourceLocation RParenLoc, 4727 bool IsExecConfig) { 4728 // Bail out early if calling a builtin with custom typechecking. 4729 if (FDecl) 4730 if (unsigned ID = FDecl->getBuiltinID()) 4731 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4732 return false; 4733 4734 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4735 // assignment, to the types of the corresponding parameter, ... 4736 unsigned NumParams = Proto->getNumParams(); 4737 bool Invalid = false; 4738 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4739 unsigned FnKind = Fn->getType()->isBlockPointerType() 4740 ? 1 /* block */ 4741 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4742 : 0 /* function */); 4743 4744 // If too few arguments are available (and we don't have default 4745 // arguments for the remaining parameters), don't make the call. 4746 if (Args.size() < NumParams) { 4747 if (Args.size() < MinArgs) { 4748 TypoCorrection TC; 4749 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4750 unsigned diag_id = 4751 MinArgs == NumParams && !Proto->isVariadic() 4752 ? diag::err_typecheck_call_too_few_args_suggest 4753 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4754 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4755 << static_cast<unsigned>(Args.size()) 4756 << TC.getCorrectionRange()); 4757 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4758 Diag(RParenLoc, 4759 MinArgs == NumParams && !Proto->isVariadic() 4760 ? diag::err_typecheck_call_too_few_args_one 4761 : diag::err_typecheck_call_too_few_args_at_least_one) 4762 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4763 else 4764 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4765 ? diag::err_typecheck_call_too_few_args 4766 : diag::err_typecheck_call_too_few_args_at_least) 4767 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4768 << Fn->getSourceRange(); 4769 4770 // Emit the location of the prototype. 4771 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4772 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4773 << FDecl; 4774 4775 return true; 4776 } 4777 Call->setNumArgs(Context, NumParams); 4778 } 4779 4780 // If too many are passed and not variadic, error on the extras and drop 4781 // them. 4782 if (Args.size() > NumParams) { 4783 if (!Proto->isVariadic()) { 4784 TypoCorrection TC; 4785 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4786 unsigned diag_id = 4787 MinArgs == NumParams && !Proto->isVariadic() 4788 ? diag::err_typecheck_call_too_many_args_suggest 4789 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4790 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4791 << static_cast<unsigned>(Args.size()) 4792 << TC.getCorrectionRange()); 4793 } else if (NumParams == 1 && FDecl && 4794 FDecl->getParamDecl(0)->getDeclName()) 4795 Diag(Args[NumParams]->getLocStart(), 4796 MinArgs == NumParams 4797 ? diag::err_typecheck_call_too_many_args_one 4798 : diag::err_typecheck_call_too_many_args_at_most_one) 4799 << FnKind << FDecl->getParamDecl(0) 4800 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4801 << SourceRange(Args[NumParams]->getLocStart(), 4802 Args.back()->getLocEnd()); 4803 else 4804 Diag(Args[NumParams]->getLocStart(), 4805 MinArgs == NumParams 4806 ? diag::err_typecheck_call_too_many_args 4807 : diag::err_typecheck_call_too_many_args_at_most) 4808 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4809 << Fn->getSourceRange() 4810 << SourceRange(Args[NumParams]->getLocStart(), 4811 Args.back()->getLocEnd()); 4812 4813 // Emit the location of the prototype. 4814 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4815 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4816 << FDecl; 4817 4818 // This deletes the extra arguments. 4819 Call->setNumArgs(Context, NumParams); 4820 return true; 4821 } 4822 } 4823 SmallVector<Expr *, 8> AllArgs; 4824 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4825 4826 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4827 Proto, 0, Args, AllArgs, CallType); 4828 if (Invalid) 4829 return true; 4830 unsigned TotalNumArgs = AllArgs.size(); 4831 for (unsigned i = 0; i < TotalNumArgs; ++i) 4832 Call->setArg(i, AllArgs[i]); 4833 4834 return false; 4835 } 4836 4837 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4838 const FunctionProtoType *Proto, 4839 unsigned FirstParam, ArrayRef<Expr *> Args, 4840 SmallVectorImpl<Expr *> &AllArgs, 4841 VariadicCallType CallType, bool AllowExplicit, 4842 bool IsListInitialization) { 4843 unsigned NumParams = Proto->getNumParams(); 4844 bool Invalid = false; 4845 size_t ArgIx = 0; 4846 // Continue to check argument types (even if we have too few/many args). 4847 for (unsigned i = FirstParam; i < NumParams; i++) { 4848 QualType ProtoArgType = Proto->getParamType(i); 4849 4850 Expr *Arg; 4851 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4852 if (ArgIx < Args.size()) { 4853 Arg = Args[ArgIx++]; 4854 4855 if (RequireCompleteType(Arg->getLocStart(), 4856 ProtoArgType, 4857 diag::err_call_incomplete_argument, Arg)) 4858 return true; 4859 4860 // Strip the unbridged-cast placeholder expression off, if applicable. 4861 bool CFAudited = false; 4862 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4863 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4864 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4865 Arg = stripARCUnbridgedCast(Arg); 4866 else if (getLangOpts().ObjCAutoRefCount && 4867 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4868 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4869 CFAudited = true; 4870 4871 InitializedEntity Entity = 4872 Param ? InitializedEntity::InitializeParameter(Context, Param, 4873 ProtoArgType) 4874 : InitializedEntity::InitializeParameter( 4875 Context, ProtoArgType, Proto->isParamConsumed(i)); 4876 4877 // Remember that parameter belongs to a CF audited API. 4878 if (CFAudited) 4879 Entity.setParameterCFAudited(); 4880 4881 ExprResult ArgE = PerformCopyInitialization( 4882 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4883 if (ArgE.isInvalid()) 4884 return true; 4885 4886 Arg = ArgE.getAs<Expr>(); 4887 } else { 4888 assert(Param && "can't use default arguments without a known callee"); 4889 4890 ExprResult ArgExpr = 4891 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4892 if (ArgExpr.isInvalid()) 4893 return true; 4894 4895 Arg = ArgExpr.getAs<Expr>(); 4896 } 4897 4898 // Check for array bounds violations for each argument to the call. This 4899 // check only triggers warnings when the argument isn't a more complex Expr 4900 // with its own checking, such as a BinaryOperator. 4901 CheckArrayAccess(Arg); 4902 4903 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4904 CheckStaticArrayArgument(CallLoc, Param, Arg); 4905 4906 AllArgs.push_back(Arg); 4907 } 4908 4909 // If this is a variadic call, handle args passed through "...". 4910 if (CallType != VariadicDoesNotApply) { 4911 // Assume that extern "C" functions with variadic arguments that 4912 // return __unknown_anytype aren't *really* variadic. 4913 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4914 FDecl->isExternC()) { 4915 for (Expr *A : Args.slice(ArgIx)) { 4916 QualType paramType; // ignored 4917 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4918 Invalid |= arg.isInvalid(); 4919 AllArgs.push_back(arg.get()); 4920 } 4921 4922 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4923 } else { 4924 for (Expr *A : Args.slice(ArgIx)) { 4925 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4926 Invalid |= Arg.isInvalid(); 4927 AllArgs.push_back(Arg.get()); 4928 } 4929 } 4930 4931 // Check for array bounds violations. 4932 for (Expr *A : Args.slice(ArgIx)) 4933 CheckArrayAccess(A); 4934 } 4935 return Invalid; 4936 } 4937 4938 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4939 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4940 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4941 TL = DTL.getOriginalLoc(); 4942 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4943 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4944 << ATL.getLocalSourceRange(); 4945 } 4946 4947 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4948 /// array parameter, check that it is non-null, and that if it is formed by 4949 /// array-to-pointer decay, the underlying array is sufficiently large. 4950 /// 4951 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4952 /// array type derivation, then for each call to the function, the value of the 4953 /// corresponding actual argument shall provide access to the first element of 4954 /// an array with at least as many elements as specified by the size expression. 4955 void 4956 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4957 ParmVarDecl *Param, 4958 const Expr *ArgExpr) { 4959 // Static array parameters are not supported in C++. 4960 if (!Param || getLangOpts().CPlusPlus) 4961 return; 4962 4963 QualType OrigTy = Param->getOriginalType(); 4964 4965 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4966 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4967 return; 4968 4969 if (ArgExpr->isNullPointerConstant(Context, 4970 Expr::NPC_NeverValueDependent)) { 4971 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4972 DiagnoseCalleeStaticArrayParam(*this, Param); 4973 return; 4974 } 4975 4976 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4977 if (!CAT) 4978 return; 4979 4980 const ConstantArrayType *ArgCAT = 4981 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4982 if (!ArgCAT) 4983 return; 4984 4985 if (ArgCAT->getSize().ult(CAT->getSize())) { 4986 Diag(CallLoc, diag::warn_static_array_too_small) 4987 << ArgExpr->getSourceRange() 4988 << (unsigned) ArgCAT->getSize().getZExtValue() 4989 << (unsigned) CAT->getSize().getZExtValue(); 4990 DiagnoseCalleeStaticArrayParam(*this, Param); 4991 } 4992 } 4993 4994 /// Given a function expression of unknown-any type, try to rebuild it 4995 /// to have a function type. 4996 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4997 4998 /// Is the given type a placeholder that we need to lower out 4999 /// immediately during argument processing? 5000 static bool isPlaceholderToRemoveAsArg(QualType type) { 5001 // Placeholders are never sugared. 5002 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5003 if (!placeholder) return false; 5004 5005 switch (placeholder->getKind()) { 5006 // Ignore all the non-placeholder types. 5007 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5008 case BuiltinType::Id: 5009 #include "clang/Basic/OpenCLImageTypes.def" 5010 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5011 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5012 #include "clang/AST/BuiltinTypes.def" 5013 return false; 5014 5015 // We cannot lower out overload sets; they might validly be resolved 5016 // by the call machinery. 5017 case BuiltinType::Overload: 5018 return false; 5019 5020 // Unbridged casts in ARC can be handled in some call positions and 5021 // should be left in place. 5022 case BuiltinType::ARCUnbridgedCast: 5023 return false; 5024 5025 // Pseudo-objects should be converted as soon as possible. 5026 case BuiltinType::PseudoObject: 5027 return true; 5028 5029 // The debugger mode could theoretically but currently does not try 5030 // to resolve unknown-typed arguments based on known parameter types. 5031 case BuiltinType::UnknownAny: 5032 return true; 5033 5034 // These are always invalid as call arguments and should be reported. 5035 case BuiltinType::BoundMember: 5036 case BuiltinType::BuiltinFn: 5037 case BuiltinType::OMPArraySection: 5038 return true; 5039 5040 } 5041 llvm_unreachable("bad builtin type kind"); 5042 } 5043 5044 /// Check an argument list for placeholders that we won't try to 5045 /// handle later. 5046 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5047 // Apply this processing to all the arguments at once instead of 5048 // dying at the first failure. 5049 bool hasInvalid = false; 5050 for (size_t i = 0, e = args.size(); i != e; i++) { 5051 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5052 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5053 if (result.isInvalid()) hasInvalid = true; 5054 else args[i] = result.get(); 5055 } else if (hasInvalid) { 5056 (void)S.CorrectDelayedTyposInExpr(args[i]); 5057 } 5058 } 5059 return hasInvalid; 5060 } 5061 5062 /// If a builtin function has a pointer argument with no explicit address 5063 /// space, then it should be able to accept a pointer to any address 5064 /// space as input. In order to do this, we need to replace the 5065 /// standard builtin declaration with one that uses the same address space 5066 /// as the call. 5067 /// 5068 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5069 /// it does not contain any pointer arguments without 5070 /// an address space qualifer. Otherwise the rewritten 5071 /// FunctionDecl is returned. 5072 /// TODO: Handle pointer return types. 5073 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5074 const FunctionDecl *FDecl, 5075 MultiExprArg ArgExprs) { 5076 5077 QualType DeclType = FDecl->getType(); 5078 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5079 5080 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5081 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5082 return nullptr; 5083 5084 bool NeedsNewDecl = false; 5085 unsigned i = 0; 5086 SmallVector<QualType, 8> OverloadParams; 5087 5088 for (QualType ParamType : FT->param_types()) { 5089 5090 // Convert array arguments to pointer to simplify type lookup. 5091 ExprResult ArgRes = 5092 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5093 if (ArgRes.isInvalid()) 5094 return nullptr; 5095 Expr *Arg = ArgRes.get(); 5096 QualType ArgType = Arg->getType(); 5097 if (!ParamType->isPointerType() || 5098 ParamType.getQualifiers().hasAddressSpace() || 5099 !ArgType->isPointerType() || 5100 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5101 OverloadParams.push_back(ParamType); 5102 continue; 5103 } 5104 5105 NeedsNewDecl = true; 5106 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5107 5108 QualType PointeeType = ParamType->getPointeeType(); 5109 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5110 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5111 } 5112 5113 if (!NeedsNewDecl) 5114 return nullptr; 5115 5116 FunctionProtoType::ExtProtoInfo EPI; 5117 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5118 OverloadParams, EPI); 5119 DeclContext *Parent = Context.getTranslationUnitDecl(); 5120 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5121 FDecl->getLocation(), 5122 FDecl->getLocation(), 5123 FDecl->getIdentifier(), 5124 OverloadTy, 5125 /*TInfo=*/nullptr, 5126 SC_Extern, false, 5127 /*hasPrototype=*/true); 5128 SmallVector<ParmVarDecl*, 16> Params; 5129 FT = cast<FunctionProtoType>(OverloadTy); 5130 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5131 QualType ParamType = FT->getParamType(i); 5132 ParmVarDecl *Parm = 5133 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5134 SourceLocation(), nullptr, ParamType, 5135 /*TInfo=*/nullptr, SC_None, nullptr); 5136 Parm->setScopeInfo(0, i); 5137 Params.push_back(Parm); 5138 } 5139 OverloadDecl->setParams(Params); 5140 return OverloadDecl; 5141 } 5142 5143 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5144 std::size_t NumArgs) { 5145 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5146 /*PartialOverloading=*/false)) 5147 return Callee->isVariadic(); 5148 return Callee->getMinRequiredArguments() <= NumArgs; 5149 } 5150 5151 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5152 /// This provides the location of the left/right parens and a list of comma 5153 /// locations. 5154 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5155 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5156 Expr *ExecConfig, bool IsExecConfig) { 5157 // Since this might be a postfix expression, get rid of ParenListExprs. 5158 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5159 if (Result.isInvalid()) return ExprError(); 5160 Fn = Result.get(); 5161 5162 if (checkArgsForPlaceholders(*this, ArgExprs)) 5163 return ExprError(); 5164 5165 if (getLangOpts().CPlusPlus) { 5166 // If this is a pseudo-destructor expression, build the call immediately. 5167 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5168 if (!ArgExprs.empty()) { 5169 // Pseudo-destructor calls should not have any arguments. 5170 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5171 << FixItHint::CreateRemoval( 5172 SourceRange(ArgExprs.front()->getLocStart(), 5173 ArgExprs.back()->getLocEnd())); 5174 } 5175 5176 return new (Context) 5177 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5178 } 5179 if (Fn->getType() == Context.PseudoObjectTy) { 5180 ExprResult result = CheckPlaceholderExpr(Fn); 5181 if (result.isInvalid()) return ExprError(); 5182 Fn = result.get(); 5183 } 5184 5185 // Determine whether this is a dependent call inside a C++ template, 5186 // in which case we won't do any semantic analysis now. 5187 bool Dependent = false; 5188 if (Fn->isTypeDependent()) 5189 Dependent = true; 5190 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5191 Dependent = true; 5192 5193 if (Dependent) { 5194 if (ExecConfig) { 5195 return new (Context) CUDAKernelCallExpr( 5196 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5197 Context.DependentTy, VK_RValue, RParenLoc); 5198 } else { 5199 return new (Context) CallExpr( 5200 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5201 } 5202 } 5203 5204 // Determine whether this is a call to an object (C++ [over.call.object]). 5205 if (Fn->getType()->isRecordType()) 5206 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5207 RParenLoc); 5208 5209 if (Fn->getType() == Context.UnknownAnyTy) { 5210 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5211 if (result.isInvalid()) return ExprError(); 5212 Fn = result.get(); 5213 } 5214 5215 if (Fn->getType() == Context.BoundMemberTy) { 5216 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5217 RParenLoc); 5218 } 5219 } 5220 5221 // Check for overloaded calls. This can happen even in C due to extensions. 5222 if (Fn->getType() == Context.OverloadTy) { 5223 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5224 5225 // We aren't supposed to apply this logic for if there'Scope an '&' 5226 // involved. 5227 if (!find.HasFormOfMemberPointer) { 5228 OverloadExpr *ovl = find.Expression; 5229 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5230 return BuildOverloadedCallExpr( 5231 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5232 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5233 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5234 RParenLoc); 5235 } 5236 } 5237 5238 // If we're directly calling a function, get the appropriate declaration. 5239 if (Fn->getType() == Context.UnknownAnyTy) { 5240 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5241 if (result.isInvalid()) return ExprError(); 5242 Fn = result.get(); 5243 } 5244 5245 Expr *NakedFn = Fn->IgnoreParens(); 5246 5247 bool CallingNDeclIndirectly = false; 5248 NamedDecl *NDecl = nullptr; 5249 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5250 if (UnOp->getOpcode() == UO_AddrOf) { 5251 CallingNDeclIndirectly = true; 5252 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5253 } 5254 } 5255 5256 if (isa<DeclRefExpr>(NakedFn)) { 5257 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5258 5259 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5260 if (FDecl && FDecl->getBuiltinID()) { 5261 // Rewrite the function decl for this builtin by replacing parameters 5262 // with no explicit address space with the address space of the arguments 5263 // in ArgExprs. 5264 if ((FDecl = 5265 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5266 NDecl = FDecl; 5267 Fn = DeclRefExpr::Create( 5268 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5269 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5270 } 5271 } 5272 } else if (isa<MemberExpr>(NakedFn)) 5273 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5274 5275 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5276 if (CallingNDeclIndirectly && 5277 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5278 Fn->getLocStart())) 5279 return ExprError(); 5280 5281 // CheckEnableIf assumes that the we're passing in a sane number of args for 5282 // FD, but that doesn't always hold true here. This is because, in some 5283 // cases, we'll emit a diag about an ill-formed function call, but then 5284 // we'll continue on as if the function call wasn't ill-formed. So, if the 5285 // number of args looks incorrect, don't do enable_if checks; we should've 5286 // already emitted an error about the bad call. 5287 if (FD->hasAttr<EnableIfAttr>() && 5288 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5289 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5290 Diag(Fn->getLocStart(), 5291 isa<CXXMethodDecl>(FD) 5292 ? diag::err_ovl_no_viable_member_function_in_call 5293 : diag::err_ovl_no_viable_function_in_call) 5294 << FD << FD->getSourceRange(); 5295 Diag(FD->getLocation(), 5296 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5297 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5298 } 5299 } 5300 } 5301 5302 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5303 ExecConfig, IsExecConfig); 5304 } 5305 5306 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5307 /// 5308 /// __builtin_astype( value, dst type ) 5309 /// 5310 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5311 SourceLocation BuiltinLoc, 5312 SourceLocation RParenLoc) { 5313 ExprValueKind VK = VK_RValue; 5314 ExprObjectKind OK = OK_Ordinary; 5315 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5316 QualType SrcTy = E->getType(); 5317 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5318 return ExprError(Diag(BuiltinLoc, 5319 diag::err_invalid_astype_of_different_size) 5320 << DstTy 5321 << SrcTy 5322 << E->getSourceRange()); 5323 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5324 } 5325 5326 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5327 /// provided arguments. 5328 /// 5329 /// __builtin_convertvector( value, dst type ) 5330 /// 5331 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5332 SourceLocation BuiltinLoc, 5333 SourceLocation RParenLoc) { 5334 TypeSourceInfo *TInfo; 5335 GetTypeFromParser(ParsedDestTy, &TInfo); 5336 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5337 } 5338 5339 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5340 /// i.e. an expression not of \p OverloadTy. The expression should 5341 /// unary-convert to an expression of function-pointer or 5342 /// block-pointer type. 5343 /// 5344 /// \param NDecl the declaration being called, if available 5345 ExprResult 5346 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5347 SourceLocation LParenLoc, 5348 ArrayRef<Expr *> Args, 5349 SourceLocation RParenLoc, 5350 Expr *Config, bool IsExecConfig) { 5351 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5352 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5353 5354 // Functions with 'interrupt' attribute cannot be called directly. 5355 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5356 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5357 return ExprError(); 5358 } 5359 5360 // Promote the function operand. 5361 // We special-case function promotion here because we only allow promoting 5362 // builtin functions to function pointers in the callee of a call. 5363 ExprResult Result; 5364 if (BuiltinID && 5365 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5366 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5367 CK_BuiltinFnToFnPtr).get(); 5368 } else { 5369 Result = CallExprUnaryConversions(Fn); 5370 } 5371 if (Result.isInvalid()) 5372 return ExprError(); 5373 Fn = Result.get(); 5374 5375 // Make the call expr early, before semantic checks. This guarantees cleanup 5376 // of arguments and function on error. 5377 CallExpr *TheCall; 5378 if (Config) 5379 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5380 cast<CallExpr>(Config), Args, 5381 Context.BoolTy, VK_RValue, 5382 RParenLoc); 5383 else 5384 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5385 VK_RValue, RParenLoc); 5386 5387 if (!getLangOpts().CPlusPlus) { 5388 // C cannot always handle TypoExpr nodes in builtin calls and direct 5389 // function calls as their argument checking don't necessarily handle 5390 // dependent types properly, so make sure any TypoExprs have been 5391 // dealt with. 5392 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5393 if (!Result.isUsable()) return ExprError(); 5394 TheCall = dyn_cast<CallExpr>(Result.get()); 5395 if (!TheCall) return Result; 5396 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5397 } 5398 5399 // Bail out early if calling a builtin with custom typechecking. 5400 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5401 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5402 5403 retry: 5404 const FunctionType *FuncT; 5405 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5406 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5407 // have type pointer to function". 5408 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5409 if (!FuncT) 5410 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5411 << Fn->getType() << Fn->getSourceRange()); 5412 } else if (const BlockPointerType *BPT = 5413 Fn->getType()->getAs<BlockPointerType>()) { 5414 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5415 } else { 5416 // Handle calls to expressions of unknown-any type. 5417 if (Fn->getType() == Context.UnknownAnyTy) { 5418 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5419 if (rewrite.isInvalid()) return ExprError(); 5420 Fn = rewrite.get(); 5421 TheCall->setCallee(Fn); 5422 goto retry; 5423 } 5424 5425 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5426 << Fn->getType() << Fn->getSourceRange()); 5427 } 5428 5429 if (getLangOpts().CUDA) { 5430 if (Config) { 5431 // CUDA: Kernel calls must be to global functions 5432 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5433 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5434 << FDecl->getName() << Fn->getSourceRange()); 5435 5436 // CUDA: Kernel function must have 'void' return type 5437 if (!FuncT->getReturnType()->isVoidType()) 5438 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5439 << Fn->getType() << Fn->getSourceRange()); 5440 } else { 5441 // CUDA: Calls to global functions must be configured 5442 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5443 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5444 << FDecl->getName() << Fn->getSourceRange()); 5445 } 5446 } 5447 5448 // Check for a valid return type 5449 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5450 FDecl)) 5451 return ExprError(); 5452 5453 // We know the result type of the call, set it. 5454 TheCall->setType(FuncT->getCallResultType(Context)); 5455 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5456 5457 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5458 if (Proto) { 5459 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5460 IsExecConfig)) 5461 return ExprError(); 5462 } else { 5463 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5464 5465 if (FDecl) { 5466 // Check if we have too few/too many template arguments, based 5467 // on our knowledge of the function definition. 5468 const FunctionDecl *Def = nullptr; 5469 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5470 Proto = Def->getType()->getAs<FunctionProtoType>(); 5471 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5472 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5473 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5474 } 5475 5476 // If the function we're calling isn't a function prototype, but we have 5477 // a function prototype from a prior declaratiom, use that prototype. 5478 if (!FDecl->hasPrototype()) 5479 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5480 } 5481 5482 // Promote the arguments (C99 6.5.2.2p6). 5483 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5484 Expr *Arg = Args[i]; 5485 5486 if (Proto && i < Proto->getNumParams()) { 5487 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5488 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5489 ExprResult ArgE = 5490 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5491 if (ArgE.isInvalid()) 5492 return true; 5493 5494 Arg = ArgE.getAs<Expr>(); 5495 5496 } else { 5497 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5498 5499 if (ArgE.isInvalid()) 5500 return true; 5501 5502 Arg = ArgE.getAs<Expr>(); 5503 } 5504 5505 if (RequireCompleteType(Arg->getLocStart(), 5506 Arg->getType(), 5507 diag::err_call_incomplete_argument, Arg)) 5508 return ExprError(); 5509 5510 TheCall->setArg(i, Arg); 5511 } 5512 } 5513 5514 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5515 if (!Method->isStatic()) 5516 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5517 << Fn->getSourceRange()); 5518 5519 // Check for sentinels 5520 if (NDecl) 5521 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5522 5523 // Do special checking on direct calls to functions. 5524 if (FDecl) { 5525 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5526 return ExprError(); 5527 5528 if (BuiltinID) 5529 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5530 } else if (NDecl) { 5531 if (CheckPointerCall(NDecl, TheCall, Proto)) 5532 return ExprError(); 5533 } else { 5534 if (CheckOtherCall(TheCall, Proto)) 5535 return ExprError(); 5536 } 5537 5538 return MaybeBindToTemporary(TheCall); 5539 } 5540 5541 ExprResult 5542 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5543 SourceLocation RParenLoc, Expr *InitExpr) { 5544 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5545 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5546 5547 TypeSourceInfo *TInfo; 5548 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5549 if (!TInfo) 5550 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5551 5552 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5553 } 5554 5555 ExprResult 5556 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5557 SourceLocation RParenLoc, Expr *LiteralExpr) { 5558 QualType literalType = TInfo->getType(); 5559 5560 if (literalType->isArrayType()) { 5561 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5562 diag::err_illegal_decl_array_incomplete_type, 5563 SourceRange(LParenLoc, 5564 LiteralExpr->getSourceRange().getEnd()))) 5565 return ExprError(); 5566 if (literalType->isVariableArrayType()) 5567 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5568 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5569 } else if (!literalType->isDependentType() && 5570 RequireCompleteType(LParenLoc, literalType, 5571 diag::err_typecheck_decl_incomplete_type, 5572 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5573 return ExprError(); 5574 5575 InitializedEntity Entity 5576 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5577 InitializationKind Kind 5578 = InitializationKind::CreateCStyleCast(LParenLoc, 5579 SourceRange(LParenLoc, RParenLoc), 5580 /*InitList=*/true); 5581 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5582 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5583 &literalType); 5584 if (Result.isInvalid()) 5585 return ExprError(); 5586 LiteralExpr = Result.get(); 5587 5588 bool isFileScope = !CurContext->isFunctionOrMethod(); 5589 if (isFileScope && 5590 !LiteralExpr->isTypeDependent() && 5591 !LiteralExpr->isValueDependent() && 5592 !literalType->isDependentType()) { // 6.5.2.5p3 5593 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5594 return ExprError(); 5595 } 5596 5597 // In C, compound literals are l-values for some reason. 5598 // For GCC compatibility, in C++, file-scope array compound literals with 5599 // constant initializers are also l-values, and compound literals are 5600 // otherwise prvalues. 5601 // 5602 // (GCC also treats C++ list-initialized file-scope array prvalues with 5603 // constant initializers as l-values, but that's non-conforming, so we don't 5604 // follow it there.) 5605 // 5606 // FIXME: It would be better to handle the lvalue cases as materializing and 5607 // lifetime-extending a temporary object, but our materialized temporaries 5608 // representation only supports lifetime extension from a variable, not "out 5609 // of thin air". 5610 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5611 // is bound to the result of applying array-to-pointer decay to the compound 5612 // literal. 5613 // FIXME: GCC supports compound literals of reference type, which should 5614 // obviously have a value kind derived from the kind of reference involved. 5615 ExprValueKind VK = 5616 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5617 ? VK_RValue 5618 : VK_LValue; 5619 5620 return MaybeBindToTemporary( 5621 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5622 VK, LiteralExpr, isFileScope)); 5623 } 5624 5625 ExprResult 5626 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5627 SourceLocation RBraceLoc) { 5628 // Immediately handle non-overload placeholders. Overloads can be 5629 // resolved contextually, but everything else here can't. 5630 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5631 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5632 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5633 5634 // Ignore failures; dropping the entire initializer list because 5635 // of one failure would be terrible for indexing/etc. 5636 if (result.isInvalid()) continue; 5637 5638 InitArgList[I] = result.get(); 5639 } 5640 } 5641 5642 // Semantic analysis for initializers is done by ActOnDeclarator() and 5643 // CheckInitializer() - it requires knowledge of the object being intialized. 5644 5645 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5646 RBraceLoc); 5647 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5648 return E; 5649 } 5650 5651 /// Do an explicit extend of the given block pointer if we're in ARC. 5652 void Sema::maybeExtendBlockObject(ExprResult &E) { 5653 assert(E.get()->getType()->isBlockPointerType()); 5654 assert(E.get()->isRValue()); 5655 5656 // Only do this in an r-value context. 5657 if (!getLangOpts().ObjCAutoRefCount) return; 5658 5659 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5660 CK_ARCExtendBlockObject, E.get(), 5661 /*base path*/ nullptr, VK_RValue); 5662 Cleanup.setExprNeedsCleanups(true); 5663 } 5664 5665 /// Prepare a conversion of the given expression to an ObjC object 5666 /// pointer type. 5667 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5668 QualType type = E.get()->getType(); 5669 if (type->isObjCObjectPointerType()) { 5670 return CK_BitCast; 5671 } else if (type->isBlockPointerType()) { 5672 maybeExtendBlockObject(E); 5673 return CK_BlockPointerToObjCPointerCast; 5674 } else { 5675 assert(type->isPointerType()); 5676 return CK_CPointerToObjCPointerCast; 5677 } 5678 } 5679 5680 /// Prepares for a scalar cast, performing all the necessary stages 5681 /// except the final cast and returning the kind required. 5682 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5683 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5684 // Also, callers should have filtered out the invalid cases with 5685 // pointers. Everything else should be possible. 5686 5687 QualType SrcTy = Src.get()->getType(); 5688 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5689 return CK_NoOp; 5690 5691 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5692 case Type::STK_MemberPointer: 5693 llvm_unreachable("member pointer type in C"); 5694 5695 case Type::STK_CPointer: 5696 case Type::STK_BlockPointer: 5697 case Type::STK_ObjCObjectPointer: 5698 switch (DestTy->getScalarTypeKind()) { 5699 case Type::STK_CPointer: { 5700 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5701 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5702 if (SrcAS != DestAS) 5703 return CK_AddressSpaceConversion; 5704 return CK_BitCast; 5705 } 5706 case Type::STK_BlockPointer: 5707 return (SrcKind == Type::STK_BlockPointer 5708 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5709 case Type::STK_ObjCObjectPointer: 5710 if (SrcKind == Type::STK_ObjCObjectPointer) 5711 return CK_BitCast; 5712 if (SrcKind == Type::STK_CPointer) 5713 return CK_CPointerToObjCPointerCast; 5714 maybeExtendBlockObject(Src); 5715 return CK_BlockPointerToObjCPointerCast; 5716 case Type::STK_Bool: 5717 return CK_PointerToBoolean; 5718 case Type::STK_Integral: 5719 return CK_PointerToIntegral; 5720 case Type::STK_Floating: 5721 case Type::STK_FloatingComplex: 5722 case Type::STK_IntegralComplex: 5723 case Type::STK_MemberPointer: 5724 llvm_unreachable("illegal cast from pointer"); 5725 } 5726 llvm_unreachable("Should have returned before this"); 5727 5728 case Type::STK_Bool: // casting from bool is like casting from an integer 5729 case Type::STK_Integral: 5730 switch (DestTy->getScalarTypeKind()) { 5731 case Type::STK_CPointer: 5732 case Type::STK_ObjCObjectPointer: 5733 case Type::STK_BlockPointer: 5734 if (Src.get()->isNullPointerConstant(Context, 5735 Expr::NPC_ValueDependentIsNull)) 5736 return CK_NullToPointer; 5737 return CK_IntegralToPointer; 5738 case Type::STK_Bool: 5739 return CK_IntegralToBoolean; 5740 case Type::STK_Integral: 5741 return CK_IntegralCast; 5742 case Type::STK_Floating: 5743 return CK_IntegralToFloating; 5744 case Type::STK_IntegralComplex: 5745 Src = ImpCastExprToType(Src.get(), 5746 DestTy->castAs<ComplexType>()->getElementType(), 5747 CK_IntegralCast); 5748 return CK_IntegralRealToComplex; 5749 case Type::STK_FloatingComplex: 5750 Src = ImpCastExprToType(Src.get(), 5751 DestTy->castAs<ComplexType>()->getElementType(), 5752 CK_IntegralToFloating); 5753 return CK_FloatingRealToComplex; 5754 case Type::STK_MemberPointer: 5755 llvm_unreachable("member pointer type in C"); 5756 } 5757 llvm_unreachable("Should have returned before this"); 5758 5759 case Type::STK_Floating: 5760 switch (DestTy->getScalarTypeKind()) { 5761 case Type::STK_Floating: 5762 return CK_FloatingCast; 5763 case Type::STK_Bool: 5764 return CK_FloatingToBoolean; 5765 case Type::STK_Integral: 5766 return CK_FloatingToIntegral; 5767 case Type::STK_FloatingComplex: 5768 Src = ImpCastExprToType(Src.get(), 5769 DestTy->castAs<ComplexType>()->getElementType(), 5770 CK_FloatingCast); 5771 return CK_FloatingRealToComplex; 5772 case Type::STK_IntegralComplex: 5773 Src = ImpCastExprToType(Src.get(), 5774 DestTy->castAs<ComplexType>()->getElementType(), 5775 CK_FloatingToIntegral); 5776 return CK_IntegralRealToComplex; 5777 case Type::STK_CPointer: 5778 case Type::STK_ObjCObjectPointer: 5779 case Type::STK_BlockPointer: 5780 llvm_unreachable("valid float->pointer cast?"); 5781 case Type::STK_MemberPointer: 5782 llvm_unreachable("member pointer type in C"); 5783 } 5784 llvm_unreachable("Should have returned before this"); 5785 5786 case Type::STK_FloatingComplex: 5787 switch (DestTy->getScalarTypeKind()) { 5788 case Type::STK_FloatingComplex: 5789 return CK_FloatingComplexCast; 5790 case Type::STK_IntegralComplex: 5791 return CK_FloatingComplexToIntegralComplex; 5792 case Type::STK_Floating: { 5793 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5794 if (Context.hasSameType(ET, DestTy)) 5795 return CK_FloatingComplexToReal; 5796 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5797 return CK_FloatingCast; 5798 } 5799 case Type::STK_Bool: 5800 return CK_FloatingComplexToBoolean; 5801 case Type::STK_Integral: 5802 Src = ImpCastExprToType(Src.get(), 5803 SrcTy->castAs<ComplexType>()->getElementType(), 5804 CK_FloatingComplexToReal); 5805 return CK_FloatingToIntegral; 5806 case Type::STK_CPointer: 5807 case Type::STK_ObjCObjectPointer: 5808 case Type::STK_BlockPointer: 5809 llvm_unreachable("valid complex float->pointer cast?"); 5810 case Type::STK_MemberPointer: 5811 llvm_unreachable("member pointer type in C"); 5812 } 5813 llvm_unreachable("Should have returned before this"); 5814 5815 case Type::STK_IntegralComplex: 5816 switch (DestTy->getScalarTypeKind()) { 5817 case Type::STK_FloatingComplex: 5818 return CK_IntegralComplexToFloatingComplex; 5819 case Type::STK_IntegralComplex: 5820 return CK_IntegralComplexCast; 5821 case Type::STK_Integral: { 5822 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5823 if (Context.hasSameType(ET, DestTy)) 5824 return CK_IntegralComplexToReal; 5825 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5826 return CK_IntegralCast; 5827 } 5828 case Type::STK_Bool: 5829 return CK_IntegralComplexToBoolean; 5830 case Type::STK_Floating: 5831 Src = ImpCastExprToType(Src.get(), 5832 SrcTy->castAs<ComplexType>()->getElementType(), 5833 CK_IntegralComplexToReal); 5834 return CK_IntegralToFloating; 5835 case Type::STK_CPointer: 5836 case Type::STK_ObjCObjectPointer: 5837 case Type::STK_BlockPointer: 5838 llvm_unreachable("valid complex int->pointer cast?"); 5839 case Type::STK_MemberPointer: 5840 llvm_unreachable("member pointer type in C"); 5841 } 5842 llvm_unreachable("Should have returned before this"); 5843 } 5844 5845 llvm_unreachable("Unhandled scalar cast"); 5846 } 5847 5848 static bool breakDownVectorType(QualType type, uint64_t &len, 5849 QualType &eltType) { 5850 // Vectors are simple. 5851 if (const VectorType *vecType = type->getAs<VectorType>()) { 5852 len = vecType->getNumElements(); 5853 eltType = vecType->getElementType(); 5854 assert(eltType->isScalarType()); 5855 return true; 5856 } 5857 5858 // We allow lax conversion to and from non-vector types, but only if 5859 // they're real types (i.e. non-complex, non-pointer scalar types). 5860 if (!type->isRealType()) return false; 5861 5862 len = 1; 5863 eltType = type; 5864 return true; 5865 } 5866 5867 /// Are the two types lax-compatible vector types? That is, given 5868 /// that one of them is a vector, do they have equal storage sizes, 5869 /// where the storage size is the number of elements times the element 5870 /// size? 5871 /// 5872 /// This will also return false if either of the types is neither a 5873 /// vector nor a real type. 5874 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5875 assert(destTy->isVectorType() || srcTy->isVectorType()); 5876 5877 // Disallow lax conversions between scalars and ExtVectors (these 5878 // conversions are allowed for other vector types because common headers 5879 // depend on them). Most scalar OP ExtVector cases are handled by the 5880 // splat path anyway, which does what we want (convert, not bitcast). 5881 // What this rules out for ExtVectors is crazy things like char4*float. 5882 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5883 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5884 5885 uint64_t srcLen, destLen; 5886 QualType srcEltTy, destEltTy; 5887 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5888 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5889 5890 // ASTContext::getTypeSize will return the size rounded up to a 5891 // power of 2, so instead of using that, we need to use the raw 5892 // element size multiplied by the element count. 5893 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5894 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5895 5896 return (srcLen * srcEltSize == destLen * destEltSize); 5897 } 5898 5899 /// Is this a legal conversion between two types, one of which is 5900 /// known to be a vector type? 5901 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5902 assert(destTy->isVectorType() || srcTy->isVectorType()); 5903 5904 if (!Context.getLangOpts().LaxVectorConversions) 5905 return false; 5906 return areLaxCompatibleVectorTypes(srcTy, destTy); 5907 } 5908 5909 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5910 CastKind &Kind) { 5911 assert(VectorTy->isVectorType() && "Not a vector type!"); 5912 5913 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5914 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5915 return Diag(R.getBegin(), 5916 Ty->isVectorType() ? 5917 diag::err_invalid_conversion_between_vectors : 5918 diag::err_invalid_conversion_between_vector_and_integer) 5919 << VectorTy << Ty << R; 5920 } else 5921 return Diag(R.getBegin(), 5922 diag::err_invalid_conversion_between_vector_and_scalar) 5923 << VectorTy << Ty << R; 5924 5925 Kind = CK_BitCast; 5926 return false; 5927 } 5928 5929 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5930 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5931 5932 if (DestElemTy == SplattedExpr->getType()) 5933 return SplattedExpr; 5934 5935 assert(DestElemTy->isFloatingType() || 5936 DestElemTy->isIntegralOrEnumerationType()); 5937 5938 CastKind CK; 5939 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5940 // OpenCL requires that we convert `true` boolean expressions to -1, but 5941 // only when splatting vectors. 5942 if (DestElemTy->isFloatingType()) { 5943 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5944 // in two steps: boolean to signed integral, then to floating. 5945 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5946 CK_BooleanToSignedIntegral); 5947 SplattedExpr = CastExprRes.get(); 5948 CK = CK_IntegralToFloating; 5949 } else { 5950 CK = CK_BooleanToSignedIntegral; 5951 } 5952 } else { 5953 ExprResult CastExprRes = SplattedExpr; 5954 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5955 if (CastExprRes.isInvalid()) 5956 return ExprError(); 5957 SplattedExpr = CastExprRes.get(); 5958 } 5959 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5960 } 5961 5962 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5963 Expr *CastExpr, CastKind &Kind) { 5964 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5965 5966 QualType SrcTy = CastExpr->getType(); 5967 5968 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5969 // an ExtVectorType. 5970 // In OpenCL, casts between vectors of different types are not allowed. 5971 // (See OpenCL 6.2). 5972 if (SrcTy->isVectorType()) { 5973 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5974 || (getLangOpts().OpenCL && 5975 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5976 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5977 << DestTy << SrcTy << R; 5978 return ExprError(); 5979 } 5980 Kind = CK_BitCast; 5981 return CastExpr; 5982 } 5983 5984 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5985 // conversion will take place first from scalar to elt type, and then 5986 // splat from elt type to vector. 5987 if (SrcTy->isPointerType()) 5988 return Diag(R.getBegin(), 5989 diag::err_invalid_conversion_between_vector_and_scalar) 5990 << DestTy << SrcTy << R; 5991 5992 Kind = CK_VectorSplat; 5993 return prepareVectorSplat(DestTy, CastExpr); 5994 } 5995 5996 ExprResult 5997 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5998 Declarator &D, ParsedType &Ty, 5999 SourceLocation RParenLoc, Expr *CastExpr) { 6000 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6001 "ActOnCastExpr(): missing type or expr"); 6002 6003 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6004 if (D.isInvalidType()) 6005 return ExprError(); 6006 6007 if (getLangOpts().CPlusPlus) { 6008 // Check that there are no default arguments (C++ only). 6009 CheckExtraCXXDefaultArguments(D); 6010 } else { 6011 // Make sure any TypoExprs have been dealt with. 6012 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6013 if (!Res.isUsable()) 6014 return ExprError(); 6015 CastExpr = Res.get(); 6016 } 6017 6018 checkUnusedDeclAttributes(D); 6019 6020 QualType castType = castTInfo->getType(); 6021 Ty = CreateParsedType(castType, castTInfo); 6022 6023 bool isVectorLiteral = false; 6024 6025 // Check for an altivec or OpenCL literal, 6026 // i.e. all the elements are integer constants. 6027 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6028 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6029 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6030 && castType->isVectorType() && (PE || PLE)) { 6031 if (PLE && PLE->getNumExprs() == 0) { 6032 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6033 return ExprError(); 6034 } 6035 if (PE || PLE->getNumExprs() == 1) { 6036 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6037 if (!E->getType()->isVectorType()) 6038 isVectorLiteral = true; 6039 } 6040 else 6041 isVectorLiteral = true; 6042 } 6043 6044 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6045 // then handle it as such. 6046 if (isVectorLiteral) 6047 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6048 6049 // If the Expr being casted is a ParenListExpr, handle it specially. 6050 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6051 // sequence of BinOp comma operators. 6052 if (isa<ParenListExpr>(CastExpr)) { 6053 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6054 if (Result.isInvalid()) return ExprError(); 6055 CastExpr = Result.get(); 6056 } 6057 6058 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6059 !getSourceManager().isInSystemMacro(LParenLoc)) 6060 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6061 6062 CheckTollFreeBridgeCast(castType, CastExpr); 6063 6064 CheckObjCBridgeRelatedCast(castType, CastExpr); 6065 6066 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6067 6068 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6069 } 6070 6071 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6072 SourceLocation RParenLoc, Expr *E, 6073 TypeSourceInfo *TInfo) { 6074 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6075 "Expected paren or paren list expression"); 6076 6077 Expr **exprs; 6078 unsigned numExprs; 6079 Expr *subExpr; 6080 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6081 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6082 LiteralLParenLoc = PE->getLParenLoc(); 6083 LiteralRParenLoc = PE->getRParenLoc(); 6084 exprs = PE->getExprs(); 6085 numExprs = PE->getNumExprs(); 6086 } else { // isa<ParenExpr> by assertion at function entrance 6087 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6088 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6089 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6090 exprs = &subExpr; 6091 numExprs = 1; 6092 } 6093 6094 QualType Ty = TInfo->getType(); 6095 assert(Ty->isVectorType() && "Expected vector type"); 6096 6097 SmallVector<Expr *, 8> initExprs; 6098 const VectorType *VTy = Ty->getAs<VectorType>(); 6099 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6100 6101 // '(...)' form of vector initialization in AltiVec: the number of 6102 // initializers must be one or must match the size of the vector. 6103 // If a single value is specified in the initializer then it will be 6104 // replicated to all the components of the vector 6105 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6106 // The number of initializers must be one or must match the size of the 6107 // vector. If a single value is specified in the initializer then it will 6108 // be replicated to all the components of the vector 6109 if (numExprs == 1) { 6110 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6111 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6112 if (Literal.isInvalid()) 6113 return ExprError(); 6114 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6115 PrepareScalarCast(Literal, ElemTy)); 6116 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6117 } 6118 else if (numExprs < numElems) { 6119 Diag(E->getExprLoc(), 6120 diag::err_incorrect_number_of_vector_initializers); 6121 return ExprError(); 6122 } 6123 else 6124 initExprs.append(exprs, exprs + numExprs); 6125 } 6126 else { 6127 // For OpenCL, when the number of initializers is a single value, 6128 // it will be replicated to all components of the vector. 6129 if (getLangOpts().OpenCL && 6130 VTy->getVectorKind() == VectorType::GenericVector && 6131 numExprs == 1) { 6132 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6133 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6134 if (Literal.isInvalid()) 6135 return ExprError(); 6136 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6137 PrepareScalarCast(Literal, ElemTy)); 6138 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6139 } 6140 6141 initExprs.append(exprs, exprs + numExprs); 6142 } 6143 // FIXME: This means that pretty-printing the final AST will produce curly 6144 // braces instead of the original commas. 6145 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6146 initExprs, LiteralRParenLoc); 6147 initE->setType(Ty); 6148 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6149 } 6150 6151 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6152 /// the ParenListExpr into a sequence of comma binary operators. 6153 ExprResult 6154 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6155 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6156 if (!E) 6157 return OrigExpr; 6158 6159 ExprResult Result(E->getExpr(0)); 6160 6161 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6162 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6163 E->getExpr(i)); 6164 6165 if (Result.isInvalid()) return ExprError(); 6166 6167 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6168 } 6169 6170 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6171 SourceLocation R, 6172 MultiExprArg Val) { 6173 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6174 return expr; 6175 } 6176 6177 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6178 /// constant and the other is not a pointer. Returns true if a diagnostic is 6179 /// emitted. 6180 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6181 SourceLocation QuestionLoc) { 6182 Expr *NullExpr = LHSExpr; 6183 Expr *NonPointerExpr = RHSExpr; 6184 Expr::NullPointerConstantKind NullKind = 6185 NullExpr->isNullPointerConstant(Context, 6186 Expr::NPC_ValueDependentIsNotNull); 6187 6188 if (NullKind == Expr::NPCK_NotNull) { 6189 NullExpr = RHSExpr; 6190 NonPointerExpr = LHSExpr; 6191 NullKind = 6192 NullExpr->isNullPointerConstant(Context, 6193 Expr::NPC_ValueDependentIsNotNull); 6194 } 6195 6196 if (NullKind == Expr::NPCK_NotNull) 6197 return false; 6198 6199 if (NullKind == Expr::NPCK_ZeroExpression) 6200 return false; 6201 6202 if (NullKind == Expr::NPCK_ZeroLiteral) { 6203 // In this case, check to make sure that we got here from a "NULL" 6204 // string in the source code. 6205 NullExpr = NullExpr->IgnoreParenImpCasts(); 6206 SourceLocation loc = NullExpr->getExprLoc(); 6207 if (!findMacroSpelling(loc, "NULL")) 6208 return false; 6209 } 6210 6211 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6212 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6213 << NonPointerExpr->getType() << DiagType 6214 << NonPointerExpr->getSourceRange(); 6215 return true; 6216 } 6217 6218 /// \brief Return false if the condition expression is valid, true otherwise. 6219 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6220 QualType CondTy = Cond->getType(); 6221 6222 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6223 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6224 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6225 << CondTy << Cond->getSourceRange(); 6226 return true; 6227 } 6228 6229 // C99 6.5.15p2 6230 if (CondTy->isScalarType()) return false; 6231 6232 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6233 << CondTy << Cond->getSourceRange(); 6234 return true; 6235 } 6236 6237 /// \brief Handle when one or both operands are void type. 6238 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6239 ExprResult &RHS) { 6240 Expr *LHSExpr = LHS.get(); 6241 Expr *RHSExpr = RHS.get(); 6242 6243 if (!LHSExpr->getType()->isVoidType()) 6244 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6245 << RHSExpr->getSourceRange(); 6246 if (!RHSExpr->getType()->isVoidType()) 6247 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6248 << LHSExpr->getSourceRange(); 6249 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6250 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6251 return S.Context.VoidTy; 6252 } 6253 6254 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6255 /// true otherwise. 6256 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6257 QualType PointerTy) { 6258 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6259 !NullExpr.get()->isNullPointerConstant(S.Context, 6260 Expr::NPC_ValueDependentIsNull)) 6261 return true; 6262 6263 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6264 return false; 6265 } 6266 6267 /// \brief Checks compatibility between two pointers and return the resulting 6268 /// type. 6269 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6270 ExprResult &RHS, 6271 SourceLocation Loc) { 6272 QualType LHSTy = LHS.get()->getType(); 6273 QualType RHSTy = RHS.get()->getType(); 6274 6275 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6276 // Two identical pointers types are always compatible. 6277 return LHSTy; 6278 } 6279 6280 QualType lhptee, rhptee; 6281 6282 // Get the pointee types. 6283 bool IsBlockPointer = false; 6284 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6285 lhptee = LHSBTy->getPointeeType(); 6286 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6287 IsBlockPointer = true; 6288 } else { 6289 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6290 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6291 } 6292 6293 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6294 // differently qualified versions of compatible types, the result type is 6295 // a pointer to an appropriately qualified version of the composite 6296 // type. 6297 6298 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6299 // clause doesn't make sense for our extensions. E.g. address space 2 should 6300 // be incompatible with address space 3: they may live on different devices or 6301 // anything. 6302 Qualifiers lhQual = lhptee.getQualifiers(); 6303 Qualifiers rhQual = rhptee.getQualifiers(); 6304 6305 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6306 lhQual.removeCVRQualifiers(); 6307 rhQual.removeCVRQualifiers(); 6308 6309 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6310 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6311 6312 // For OpenCL: 6313 // 1. If LHS and RHS types match exactly and: 6314 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6315 // (b) AS overlap => generate addrspacecast 6316 // (c) AS don't overlap => give an error 6317 // 2. if LHS and RHS types don't match: 6318 // (a) AS match => use standard C rules, generate bitcast 6319 // (b) AS overlap => generate addrspacecast instead of bitcast 6320 // (c) AS don't overlap => give an error 6321 6322 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6323 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6324 6325 // OpenCL cases 1c, 2a, 2b, and 2c. 6326 if (CompositeTy.isNull()) { 6327 // In this situation, we assume void* type. No especially good 6328 // reason, but this is what gcc does, and we do have to pick 6329 // to get a consistent AST. 6330 QualType incompatTy; 6331 if (S.getLangOpts().OpenCL) { 6332 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6333 // spaces is disallowed. 6334 unsigned ResultAddrSpace; 6335 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6336 // Cases 2a and 2b. 6337 ResultAddrSpace = lhQual.getAddressSpace(); 6338 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6339 // Cases 2a and 2b. 6340 ResultAddrSpace = rhQual.getAddressSpace(); 6341 } else { 6342 // Cases 1c and 2c. 6343 S.Diag(Loc, 6344 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6345 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6346 << RHS.get()->getSourceRange(); 6347 return QualType(); 6348 } 6349 6350 // Continue handling cases 2a and 2b. 6351 incompatTy = S.Context.getPointerType( 6352 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6353 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6354 (lhQual.getAddressSpace() != ResultAddrSpace) 6355 ? CK_AddressSpaceConversion /* 2b */ 6356 : CK_BitCast /* 2a */); 6357 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6358 (rhQual.getAddressSpace() != ResultAddrSpace) 6359 ? CK_AddressSpaceConversion /* 2b */ 6360 : CK_BitCast /* 2a */); 6361 } else { 6362 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6363 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6364 << RHS.get()->getSourceRange(); 6365 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6366 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6367 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6368 } 6369 return incompatTy; 6370 } 6371 6372 // The pointer types are compatible. 6373 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6374 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6375 if (IsBlockPointer) 6376 ResultTy = S.Context.getBlockPointerType(ResultTy); 6377 else { 6378 // Cases 1a and 1b for OpenCL. 6379 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6380 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6381 ? CK_BitCast /* 1a */ 6382 : CK_AddressSpaceConversion /* 1b */; 6383 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6384 ? CK_BitCast /* 1a */ 6385 : CK_AddressSpaceConversion /* 1b */; 6386 ResultTy = S.Context.getPointerType(ResultTy); 6387 } 6388 6389 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6390 // if the target type does not change. 6391 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6392 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6393 return ResultTy; 6394 } 6395 6396 /// \brief Return the resulting type when the operands are both block pointers. 6397 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6398 ExprResult &LHS, 6399 ExprResult &RHS, 6400 SourceLocation Loc) { 6401 QualType LHSTy = LHS.get()->getType(); 6402 QualType RHSTy = RHS.get()->getType(); 6403 6404 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6405 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6406 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6407 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6408 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6409 return destType; 6410 } 6411 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6412 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6413 << RHS.get()->getSourceRange(); 6414 return QualType(); 6415 } 6416 6417 // We have 2 block pointer types. 6418 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6419 } 6420 6421 /// \brief Return the resulting type when the operands are both pointers. 6422 static QualType 6423 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6424 ExprResult &RHS, 6425 SourceLocation Loc) { 6426 // get the pointer types 6427 QualType LHSTy = LHS.get()->getType(); 6428 QualType RHSTy = RHS.get()->getType(); 6429 6430 // get the "pointed to" types 6431 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6432 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6433 6434 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6435 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6436 // Figure out necessary qualifiers (C99 6.5.15p6) 6437 QualType destPointee 6438 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6439 QualType destType = S.Context.getPointerType(destPointee); 6440 // Add qualifiers if necessary. 6441 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6442 // Promote to void*. 6443 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6444 return destType; 6445 } 6446 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6447 QualType destPointee 6448 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6449 QualType destType = S.Context.getPointerType(destPointee); 6450 // Add qualifiers if necessary. 6451 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6452 // Promote to void*. 6453 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6454 return destType; 6455 } 6456 6457 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6458 } 6459 6460 /// \brief Return false if the first expression is not an integer and the second 6461 /// expression is not a pointer, true otherwise. 6462 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6463 Expr* PointerExpr, SourceLocation Loc, 6464 bool IsIntFirstExpr) { 6465 if (!PointerExpr->getType()->isPointerType() || 6466 !Int.get()->getType()->isIntegerType()) 6467 return false; 6468 6469 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6470 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6471 6472 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6473 << Expr1->getType() << Expr2->getType() 6474 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6475 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6476 CK_IntegralToPointer); 6477 return true; 6478 } 6479 6480 /// \brief Simple conversion between integer and floating point types. 6481 /// 6482 /// Used when handling the OpenCL conditional operator where the 6483 /// condition is a vector while the other operands are scalar. 6484 /// 6485 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6486 /// types are either integer or floating type. Between the two 6487 /// operands, the type with the higher rank is defined as the "result 6488 /// type". The other operand needs to be promoted to the same type. No 6489 /// other type promotion is allowed. We cannot use 6490 /// UsualArithmeticConversions() for this purpose, since it always 6491 /// promotes promotable types. 6492 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6493 ExprResult &RHS, 6494 SourceLocation QuestionLoc) { 6495 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6496 if (LHS.isInvalid()) 6497 return QualType(); 6498 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6499 if (RHS.isInvalid()) 6500 return QualType(); 6501 6502 // For conversion purposes, we ignore any qualifiers. 6503 // For example, "const float" and "float" are equivalent. 6504 QualType LHSType = 6505 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6506 QualType RHSType = 6507 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6508 6509 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6510 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6511 << LHSType << LHS.get()->getSourceRange(); 6512 return QualType(); 6513 } 6514 6515 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6516 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6517 << RHSType << RHS.get()->getSourceRange(); 6518 return QualType(); 6519 } 6520 6521 // If both types are identical, no conversion is needed. 6522 if (LHSType == RHSType) 6523 return LHSType; 6524 6525 // Now handle "real" floating types (i.e. float, double, long double). 6526 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6527 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6528 /*IsCompAssign = */ false); 6529 6530 // Finally, we have two differing integer types. 6531 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6532 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6533 } 6534 6535 /// \brief Convert scalar operands to a vector that matches the 6536 /// condition in length. 6537 /// 6538 /// Used when handling the OpenCL conditional operator where the 6539 /// condition is a vector while the other operands are scalar. 6540 /// 6541 /// We first compute the "result type" for the scalar operands 6542 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6543 /// into a vector of that type where the length matches the condition 6544 /// vector type. s6.11.6 requires that the element types of the result 6545 /// and the condition must have the same number of bits. 6546 static QualType 6547 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6548 QualType CondTy, SourceLocation QuestionLoc) { 6549 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6550 if (ResTy.isNull()) return QualType(); 6551 6552 const VectorType *CV = CondTy->getAs<VectorType>(); 6553 assert(CV); 6554 6555 // Determine the vector result type 6556 unsigned NumElements = CV->getNumElements(); 6557 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6558 6559 // Ensure that all types have the same number of bits 6560 if (S.Context.getTypeSize(CV->getElementType()) 6561 != S.Context.getTypeSize(ResTy)) { 6562 // Since VectorTy is created internally, it does not pretty print 6563 // with an OpenCL name. Instead, we just print a description. 6564 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6565 SmallString<64> Str; 6566 llvm::raw_svector_ostream OS(Str); 6567 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6568 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6569 << CondTy << OS.str(); 6570 return QualType(); 6571 } 6572 6573 // Convert operands to the vector result type 6574 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6575 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6576 6577 return VectorTy; 6578 } 6579 6580 /// \brief Return false if this is a valid OpenCL condition vector 6581 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6582 SourceLocation QuestionLoc) { 6583 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6584 // integral type. 6585 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6586 assert(CondTy); 6587 QualType EleTy = CondTy->getElementType(); 6588 if (EleTy->isIntegerType()) return false; 6589 6590 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6591 << Cond->getType() << Cond->getSourceRange(); 6592 return true; 6593 } 6594 6595 /// \brief Return false if the vector condition type and the vector 6596 /// result type are compatible. 6597 /// 6598 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6599 /// number of elements, and their element types have the same number 6600 /// of bits. 6601 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6602 SourceLocation QuestionLoc) { 6603 const VectorType *CV = CondTy->getAs<VectorType>(); 6604 const VectorType *RV = VecResTy->getAs<VectorType>(); 6605 assert(CV && RV); 6606 6607 if (CV->getNumElements() != RV->getNumElements()) { 6608 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6609 << CondTy << VecResTy; 6610 return true; 6611 } 6612 6613 QualType CVE = CV->getElementType(); 6614 QualType RVE = RV->getElementType(); 6615 6616 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6617 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6618 << CondTy << VecResTy; 6619 return true; 6620 } 6621 6622 return false; 6623 } 6624 6625 /// \brief Return the resulting type for the conditional operator in 6626 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6627 /// s6.3.i) when the condition is a vector type. 6628 static QualType 6629 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6630 ExprResult &LHS, ExprResult &RHS, 6631 SourceLocation QuestionLoc) { 6632 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6633 if (Cond.isInvalid()) 6634 return QualType(); 6635 QualType CondTy = Cond.get()->getType(); 6636 6637 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6638 return QualType(); 6639 6640 // If either operand is a vector then find the vector type of the 6641 // result as specified in OpenCL v1.1 s6.3.i. 6642 if (LHS.get()->getType()->isVectorType() || 6643 RHS.get()->getType()->isVectorType()) { 6644 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6645 /*isCompAssign*/false, 6646 /*AllowBothBool*/true, 6647 /*AllowBoolConversions*/false); 6648 if (VecResTy.isNull()) return QualType(); 6649 // The result type must match the condition type as specified in 6650 // OpenCL v1.1 s6.11.6. 6651 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6652 return QualType(); 6653 return VecResTy; 6654 } 6655 6656 // Both operands are scalar. 6657 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6658 } 6659 6660 /// \brief Return true if the Expr is block type 6661 static bool checkBlockType(Sema &S, const Expr *E) { 6662 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6663 QualType Ty = CE->getCallee()->getType(); 6664 if (Ty->isBlockPointerType()) { 6665 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6666 return true; 6667 } 6668 } 6669 return false; 6670 } 6671 6672 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6673 /// In that case, LHS = cond. 6674 /// C99 6.5.15 6675 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6676 ExprResult &RHS, ExprValueKind &VK, 6677 ExprObjectKind &OK, 6678 SourceLocation QuestionLoc) { 6679 6680 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6681 if (!LHSResult.isUsable()) return QualType(); 6682 LHS = LHSResult; 6683 6684 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6685 if (!RHSResult.isUsable()) return QualType(); 6686 RHS = RHSResult; 6687 6688 // C++ is sufficiently different to merit its own checker. 6689 if (getLangOpts().CPlusPlus) 6690 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6691 6692 VK = VK_RValue; 6693 OK = OK_Ordinary; 6694 6695 // The OpenCL operator with a vector condition is sufficiently 6696 // different to merit its own checker. 6697 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6698 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6699 6700 // First, check the condition. 6701 Cond = UsualUnaryConversions(Cond.get()); 6702 if (Cond.isInvalid()) 6703 return QualType(); 6704 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6705 return QualType(); 6706 6707 // Now check the two expressions. 6708 if (LHS.get()->getType()->isVectorType() || 6709 RHS.get()->getType()->isVectorType()) 6710 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6711 /*AllowBothBool*/true, 6712 /*AllowBoolConversions*/false); 6713 6714 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6715 if (LHS.isInvalid() || RHS.isInvalid()) 6716 return QualType(); 6717 6718 QualType LHSTy = LHS.get()->getType(); 6719 QualType RHSTy = RHS.get()->getType(); 6720 6721 // Diagnose attempts to convert between __float128 and long double where 6722 // such conversions currently can't be handled. 6723 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6724 Diag(QuestionLoc, 6725 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6726 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6727 return QualType(); 6728 } 6729 6730 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6731 // selection operator (?:). 6732 if (getLangOpts().OpenCL && 6733 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6734 return QualType(); 6735 } 6736 6737 // If both operands have arithmetic type, do the usual arithmetic conversions 6738 // to find a common type: C99 6.5.15p3,5. 6739 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6740 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6741 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6742 6743 return ResTy; 6744 } 6745 6746 // If both operands are the same structure or union type, the result is that 6747 // type. 6748 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6749 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6750 if (LHSRT->getDecl() == RHSRT->getDecl()) 6751 // "If both the operands have structure or union type, the result has 6752 // that type." This implies that CV qualifiers are dropped. 6753 return LHSTy.getUnqualifiedType(); 6754 // FIXME: Type of conditional expression must be complete in C mode. 6755 } 6756 6757 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6758 // The following || allows only one side to be void (a GCC-ism). 6759 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6760 return checkConditionalVoidType(*this, LHS, RHS); 6761 } 6762 6763 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6764 // the type of the other operand." 6765 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6766 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6767 6768 // All objective-c pointer type analysis is done here. 6769 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6770 QuestionLoc); 6771 if (LHS.isInvalid() || RHS.isInvalid()) 6772 return QualType(); 6773 if (!compositeType.isNull()) 6774 return compositeType; 6775 6776 6777 // Handle block pointer types. 6778 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6779 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6780 QuestionLoc); 6781 6782 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6783 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6784 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6785 QuestionLoc); 6786 6787 // GCC compatibility: soften pointer/integer mismatch. Note that 6788 // null pointers have been filtered out by this point. 6789 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6790 /*isIntFirstExpr=*/true)) 6791 return RHSTy; 6792 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6793 /*isIntFirstExpr=*/false)) 6794 return LHSTy; 6795 6796 // Emit a better diagnostic if one of the expressions is a null pointer 6797 // constant and the other is not a pointer type. In this case, the user most 6798 // likely forgot to take the address of the other expression. 6799 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6800 return QualType(); 6801 6802 // Otherwise, the operands are not compatible. 6803 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6804 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6805 << RHS.get()->getSourceRange(); 6806 return QualType(); 6807 } 6808 6809 /// FindCompositeObjCPointerType - Helper method to find composite type of 6810 /// two objective-c pointer types of the two input expressions. 6811 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6812 SourceLocation QuestionLoc) { 6813 QualType LHSTy = LHS.get()->getType(); 6814 QualType RHSTy = RHS.get()->getType(); 6815 6816 // Handle things like Class and struct objc_class*. Here we case the result 6817 // to the pseudo-builtin, because that will be implicitly cast back to the 6818 // redefinition type if an attempt is made to access its fields. 6819 if (LHSTy->isObjCClassType() && 6820 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6821 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6822 return LHSTy; 6823 } 6824 if (RHSTy->isObjCClassType() && 6825 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6826 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6827 return RHSTy; 6828 } 6829 // And the same for struct objc_object* / id 6830 if (LHSTy->isObjCIdType() && 6831 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6832 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6833 return LHSTy; 6834 } 6835 if (RHSTy->isObjCIdType() && 6836 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6837 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6838 return RHSTy; 6839 } 6840 // And the same for struct objc_selector* / SEL 6841 if (Context.isObjCSelType(LHSTy) && 6842 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6843 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6844 return LHSTy; 6845 } 6846 if (Context.isObjCSelType(RHSTy) && 6847 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6848 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6849 return RHSTy; 6850 } 6851 // Check constraints for Objective-C object pointers types. 6852 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6853 6854 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6855 // Two identical object pointer types are always compatible. 6856 return LHSTy; 6857 } 6858 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6859 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6860 QualType compositeType = LHSTy; 6861 6862 // If both operands are interfaces and either operand can be 6863 // assigned to the other, use that type as the composite 6864 // type. This allows 6865 // xxx ? (A*) a : (B*) b 6866 // where B is a subclass of A. 6867 // 6868 // Additionally, as for assignment, if either type is 'id' 6869 // allow silent coercion. Finally, if the types are 6870 // incompatible then make sure to use 'id' as the composite 6871 // type so the result is acceptable for sending messages to. 6872 6873 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6874 // It could return the composite type. 6875 if (!(compositeType = 6876 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6877 // Nothing more to do. 6878 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6879 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6880 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6881 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6882 } else if ((LHSTy->isObjCQualifiedIdType() || 6883 RHSTy->isObjCQualifiedIdType()) && 6884 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6885 // Need to handle "id<xx>" explicitly. 6886 // GCC allows qualified id and any Objective-C type to devolve to 6887 // id. Currently localizing to here until clear this should be 6888 // part of ObjCQualifiedIdTypesAreCompatible. 6889 compositeType = Context.getObjCIdType(); 6890 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6891 compositeType = Context.getObjCIdType(); 6892 } else { 6893 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6894 << LHSTy << RHSTy 6895 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6896 QualType incompatTy = Context.getObjCIdType(); 6897 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6898 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6899 return incompatTy; 6900 } 6901 // The object pointer types are compatible. 6902 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6903 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6904 return compositeType; 6905 } 6906 // Check Objective-C object pointer types and 'void *' 6907 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6908 if (getLangOpts().ObjCAutoRefCount) { 6909 // ARC forbids the implicit conversion of object pointers to 'void *', 6910 // so these types are not compatible. 6911 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6912 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6913 LHS = RHS = true; 6914 return QualType(); 6915 } 6916 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6917 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6918 QualType destPointee 6919 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6920 QualType destType = Context.getPointerType(destPointee); 6921 // Add qualifiers if necessary. 6922 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6923 // Promote to void*. 6924 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6925 return destType; 6926 } 6927 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6928 if (getLangOpts().ObjCAutoRefCount) { 6929 // ARC forbids the implicit conversion of object pointers to 'void *', 6930 // so these types are not compatible. 6931 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6932 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6933 LHS = RHS = true; 6934 return QualType(); 6935 } 6936 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6937 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6938 QualType destPointee 6939 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6940 QualType destType = Context.getPointerType(destPointee); 6941 // Add qualifiers if necessary. 6942 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6943 // Promote to void*. 6944 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6945 return destType; 6946 } 6947 return QualType(); 6948 } 6949 6950 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6951 /// ParenRange in parentheses. 6952 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6953 const PartialDiagnostic &Note, 6954 SourceRange ParenRange) { 6955 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6956 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6957 EndLoc.isValid()) { 6958 Self.Diag(Loc, Note) 6959 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6960 << FixItHint::CreateInsertion(EndLoc, ")"); 6961 } else { 6962 // We can't display the parentheses, so just show the bare note. 6963 Self.Diag(Loc, Note) << ParenRange; 6964 } 6965 } 6966 6967 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6968 return BinaryOperator::isAdditiveOp(Opc) || 6969 BinaryOperator::isMultiplicativeOp(Opc) || 6970 BinaryOperator::isShiftOp(Opc); 6971 } 6972 6973 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6974 /// expression, either using a built-in or overloaded operator, 6975 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6976 /// expression. 6977 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6978 Expr **RHSExprs) { 6979 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6980 E = E->IgnoreImpCasts(); 6981 E = E->IgnoreConversionOperator(); 6982 E = E->IgnoreImpCasts(); 6983 6984 // Built-in binary operator. 6985 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6986 if (IsArithmeticOp(OP->getOpcode())) { 6987 *Opcode = OP->getOpcode(); 6988 *RHSExprs = OP->getRHS(); 6989 return true; 6990 } 6991 } 6992 6993 // Overloaded operator. 6994 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6995 if (Call->getNumArgs() != 2) 6996 return false; 6997 6998 // Make sure this is really a binary operator that is safe to pass into 6999 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7000 OverloadedOperatorKind OO = Call->getOperator(); 7001 if (OO < OO_Plus || OO > OO_Arrow || 7002 OO == OO_PlusPlus || OO == OO_MinusMinus) 7003 return false; 7004 7005 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7006 if (IsArithmeticOp(OpKind)) { 7007 *Opcode = OpKind; 7008 *RHSExprs = Call->getArg(1); 7009 return true; 7010 } 7011 } 7012 7013 return false; 7014 } 7015 7016 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7017 /// or is a logical expression such as (x==y) which has int type, but is 7018 /// commonly interpreted as boolean. 7019 static bool ExprLooksBoolean(Expr *E) { 7020 E = E->IgnoreParenImpCasts(); 7021 7022 if (E->getType()->isBooleanType()) 7023 return true; 7024 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7025 return OP->isComparisonOp() || OP->isLogicalOp(); 7026 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7027 return OP->getOpcode() == UO_LNot; 7028 if (E->getType()->isPointerType()) 7029 return true; 7030 7031 return false; 7032 } 7033 7034 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7035 /// and binary operator are mixed in a way that suggests the programmer assumed 7036 /// the conditional operator has higher precedence, for example: 7037 /// "int x = a + someBinaryCondition ? 1 : 2". 7038 static void DiagnoseConditionalPrecedence(Sema &Self, 7039 SourceLocation OpLoc, 7040 Expr *Condition, 7041 Expr *LHSExpr, 7042 Expr *RHSExpr) { 7043 BinaryOperatorKind CondOpcode; 7044 Expr *CondRHS; 7045 7046 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7047 return; 7048 if (!ExprLooksBoolean(CondRHS)) 7049 return; 7050 7051 // The condition is an arithmetic binary expression, with a right- 7052 // hand side that looks boolean, so warn. 7053 7054 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7055 << Condition->getSourceRange() 7056 << BinaryOperator::getOpcodeStr(CondOpcode); 7057 7058 SuggestParentheses(Self, OpLoc, 7059 Self.PDiag(diag::note_precedence_silence) 7060 << BinaryOperator::getOpcodeStr(CondOpcode), 7061 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7062 7063 SuggestParentheses(Self, OpLoc, 7064 Self.PDiag(diag::note_precedence_conditional_first), 7065 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7066 } 7067 7068 /// Compute the nullability of a conditional expression. 7069 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7070 QualType LHSTy, QualType RHSTy, 7071 ASTContext &Ctx) { 7072 if (!ResTy->isAnyPointerType()) 7073 return ResTy; 7074 7075 auto GetNullability = [&Ctx](QualType Ty) { 7076 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7077 if (Kind) 7078 return *Kind; 7079 return NullabilityKind::Unspecified; 7080 }; 7081 7082 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7083 NullabilityKind MergedKind; 7084 7085 // Compute nullability of a binary conditional expression. 7086 if (IsBin) { 7087 if (LHSKind == NullabilityKind::NonNull) 7088 MergedKind = NullabilityKind::NonNull; 7089 else 7090 MergedKind = RHSKind; 7091 // Compute nullability of a normal conditional expression. 7092 } else { 7093 if (LHSKind == NullabilityKind::Nullable || 7094 RHSKind == NullabilityKind::Nullable) 7095 MergedKind = NullabilityKind::Nullable; 7096 else if (LHSKind == NullabilityKind::NonNull) 7097 MergedKind = RHSKind; 7098 else if (RHSKind == NullabilityKind::NonNull) 7099 MergedKind = LHSKind; 7100 else 7101 MergedKind = NullabilityKind::Unspecified; 7102 } 7103 7104 // Return if ResTy already has the correct nullability. 7105 if (GetNullability(ResTy) == MergedKind) 7106 return ResTy; 7107 7108 // Strip all nullability from ResTy. 7109 while (ResTy->getNullability(Ctx)) 7110 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7111 7112 // Create a new AttributedType with the new nullability kind. 7113 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7114 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7115 } 7116 7117 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7118 /// in the case of a the GNU conditional expr extension. 7119 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7120 SourceLocation ColonLoc, 7121 Expr *CondExpr, Expr *LHSExpr, 7122 Expr *RHSExpr) { 7123 if (!getLangOpts().CPlusPlus) { 7124 // C cannot handle TypoExpr nodes in the condition because it 7125 // doesn't handle dependent types properly, so make sure any TypoExprs have 7126 // been dealt with before checking the operands. 7127 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7128 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7129 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7130 7131 if (!CondResult.isUsable()) 7132 return ExprError(); 7133 7134 if (LHSExpr) { 7135 if (!LHSResult.isUsable()) 7136 return ExprError(); 7137 } 7138 7139 if (!RHSResult.isUsable()) 7140 return ExprError(); 7141 7142 CondExpr = CondResult.get(); 7143 LHSExpr = LHSResult.get(); 7144 RHSExpr = RHSResult.get(); 7145 } 7146 7147 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7148 // was the condition. 7149 OpaqueValueExpr *opaqueValue = nullptr; 7150 Expr *commonExpr = nullptr; 7151 if (!LHSExpr) { 7152 commonExpr = CondExpr; 7153 // Lower out placeholder types first. This is important so that we don't 7154 // try to capture a placeholder. This happens in few cases in C++; such 7155 // as Objective-C++'s dictionary subscripting syntax. 7156 if (commonExpr->hasPlaceholderType()) { 7157 ExprResult result = CheckPlaceholderExpr(commonExpr); 7158 if (!result.isUsable()) return ExprError(); 7159 commonExpr = result.get(); 7160 } 7161 // We usually want to apply unary conversions *before* saving, except 7162 // in the special case of a C++ l-value conditional. 7163 if (!(getLangOpts().CPlusPlus 7164 && !commonExpr->isTypeDependent() 7165 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7166 && commonExpr->isGLValue() 7167 && commonExpr->isOrdinaryOrBitFieldObject() 7168 && RHSExpr->isOrdinaryOrBitFieldObject() 7169 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7170 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7171 if (commonRes.isInvalid()) 7172 return ExprError(); 7173 commonExpr = commonRes.get(); 7174 } 7175 7176 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7177 commonExpr->getType(), 7178 commonExpr->getValueKind(), 7179 commonExpr->getObjectKind(), 7180 commonExpr); 7181 LHSExpr = CondExpr = opaqueValue; 7182 } 7183 7184 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7185 ExprValueKind VK = VK_RValue; 7186 ExprObjectKind OK = OK_Ordinary; 7187 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7188 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7189 VK, OK, QuestionLoc); 7190 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7191 RHS.isInvalid()) 7192 return ExprError(); 7193 7194 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7195 RHS.get()); 7196 7197 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7198 7199 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7200 Context); 7201 7202 if (!commonExpr) 7203 return new (Context) 7204 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7205 RHS.get(), result, VK, OK); 7206 7207 return new (Context) BinaryConditionalOperator( 7208 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7209 ColonLoc, result, VK, OK); 7210 } 7211 7212 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7213 // being closely modeled after the C99 spec:-). The odd characteristic of this 7214 // routine is it effectively iqnores the qualifiers on the top level pointee. 7215 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7216 // FIXME: add a couple examples in this comment. 7217 static Sema::AssignConvertType 7218 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7219 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7220 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7221 7222 // get the "pointed to" type (ignoring qualifiers at the top level) 7223 const Type *lhptee, *rhptee; 7224 Qualifiers lhq, rhq; 7225 std::tie(lhptee, lhq) = 7226 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7227 std::tie(rhptee, rhq) = 7228 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7229 7230 Sema::AssignConvertType ConvTy = Sema::Compatible; 7231 7232 // C99 6.5.16.1p1: This following citation is common to constraints 7233 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7234 // qualifiers of the type *pointed to* by the right; 7235 7236 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7237 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7238 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7239 // Ignore lifetime for further calculation. 7240 lhq.removeObjCLifetime(); 7241 rhq.removeObjCLifetime(); 7242 } 7243 7244 if (!lhq.compatiblyIncludes(rhq)) { 7245 // Treat address-space mismatches as fatal. TODO: address subspaces 7246 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7247 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7248 7249 // It's okay to add or remove GC or lifetime qualifiers when converting to 7250 // and from void*. 7251 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7252 .compatiblyIncludes( 7253 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7254 && (lhptee->isVoidType() || rhptee->isVoidType())) 7255 ; // keep old 7256 7257 // Treat lifetime mismatches as fatal. 7258 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7259 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7260 7261 // For GCC/MS compatibility, other qualifier mismatches are treated 7262 // as still compatible in C. 7263 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7264 } 7265 7266 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7267 // incomplete type and the other is a pointer to a qualified or unqualified 7268 // version of void... 7269 if (lhptee->isVoidType()) { 7270 if (rhptee->isIncompleteOrObjectType()) 7271 return ConvTy; 7272 7273 // As an extension, we allow cast to/from void* to function pointer. 7274 assert(rhptee->isFunctionType()); 7275 return Sema::FunctionVoidPointer; 7276 } 7277 7278 if (rhptee->isVoidType()) { 7279 if (lhptee->isIncompleteOrObjectType()) 7280 return ConvTy; 7281 7282 // As an extension, we allow cast to/from void* to function pointer. 7283 assert(lhptee->isFunctionType()); 7284 return Sema::FunctionVoidPointer; 7285 } 7286 7287 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7288 // unqualified versions of compatible types, ... 7289 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7290 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7291 // Check if the pointee types are compatible ignoring the sign. 7292 // We explicitly check for char so that we catch "char" vs 7293 // "unsigned char" on systems where "char" is unsigned. 7294 if (lhptee->isCharType()) 7295 ltrans = S.Context.UnsignedCharTy; 7296 else if (lhptee->hasSignedIntegerRepresentation()) 7297 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7298 7299 if (rhptee->isCharType()) 7300 rtrans = S.Context.UnsignedCharTy; 7301 else if (rhptee->hasSignedIntegerRepresentation()) 7302 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7303 7304 if (ltrans == rtrans) { 7305 // Types are compatible ignoring the sign. Qualifier incompatibility 7306 // takes priority over sign incompatibility because the sign 7307 // warning can be disabled. 7308 if (ConvTy != Sema::Compatible) 7309 return ConvTy; 7310 7311 return Sema::IncompatiblePointerSign; 7312 } 7313 7314 // If we are a multi-level pointer, it's possible that our issue is simply 7315 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7316 // the eventual target type is the same and the pointers have the same 7317 // level of indirection, this must be the issue. 7318 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7319 do { 7320 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7321 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7322 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7323 7324 if (lhptee == rhptee) 7325 return Sema::IncompatibleNestedPointerQualifiers; 7326 } 7327 7328 // General pointer incompatibility takes priority over qualifiers. 7329 return Sema::IncompatiblePointer; 7330 } 7331 if (!S.getLangOpts().CPlusPlus && 7332 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7333 return Sema::IncompatiblePointer; 7334 return ConvTy; 7335 } 7336 7337 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7338 /// block pointer types are compatible or whether a block and normal pointer 7339 /// are compatible. It is more restrict than comparing two function pointer 7340 // types. 7341 static Sema::AssignConvertType 7342 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7343 QualType RHSType) { 7344 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7345 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7346 7347 QualType lhptee, rhptee; 7348 7349 // get the "pointed to" type (ignoring qualifiers at the top level) 7350 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7351 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7352 7353 // In C++, the types have to match exactly. 7354 if (S.getLangOpts().CPlusPlus) 7355 return Sema::IncompatibleBlockPointer; 7356 7357 Sema::AssignConvertType ConvTy = Sema::Compatible; 7358 7359 // For blocks we enforce that qualifiers are identical. 7360 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7361 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7362 7363 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7364 return Sema::IncompatibleBlockPointer; 7365 7366 return ConvTy; 7367 } 7368 7369 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7370 /// for assignment compatibility. 7371 static Sema::AssignConvertType 7372 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7373 QualType RHSType) { 7374 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7375 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7376 7377 if (LHSType->isObjCBuiltinType()) { 7378 // Class is not compatible with ObjC object pointers. 7379 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7380 !RHSType->isObjCQualifiedClassType()) 7381 return Sema::IncompatiblePointer; 7382 return Sema::Compatible; 7383 } 7384 if (RHSType->isObjCBuiltinType()) { 7385 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7386 !LHSType->isObjCQualifiedClassType()) 7387 return Sema::IncompatiblePointer; 7388 return Sema::Compatible; 7389 } 7390 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7391 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7392 7393 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7394 // make an exception for id<P> 7395 !LHSType->isObjCQualifiedIdType()) 7396 return Sema::CompatiblePointerDiscardsQualifiers; 7397 7398 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7399 return Sema::Compatible; 7400 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7401 return Sema::IncompatibleObjCQualifiedId; 7402 return Sema::IncompatiblePointer; 7403 } 7404 7405 Sema::AssignConvertType 7406 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7407 QualType LHSType, QualType RHSType) { 7408 // Fake up an opaque expression. We don't actually care about what 7409 // cast operations are required, so if CheckAssignmentConstraints 7410 // adds casts to this they'll be wasted, but fortunately that doesn't 7411 // usually happen on valid code. 7412 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7413 ExprResult RHSPtr = &RHSExpr; 7414 CastKind K = CK_Invalid; 7415 7416 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7417 } 7418 7419 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7420 /// has code to accommodate several GCC extensions when type checking 7421 /// pointers. Here are some objectionable examples that GCC considers warnings: 7422 /// 7423 /// int a, *pint; 7424 /// short *pshort; 7425 /// struct foo *pfoo; 7426 /// 7427 /// pint = pshort; // warning: assignment from incompatible pointer type 7428 /// a = pint; // warning: assignment makes integer from pointer without a cast 7429 /// pint = a; // warning: assignment makes pointer from integer without a cast 7430 /// pint = pfoo; // warning: assignment from incompatible pointer type 7431 /// 7432 /// As a result, the code for dealing with pointers is more complex than the 7433 /// C99 spec dictates. 7434 /// 7435 /// Sets 'Kind' for any result kind except Incompatible. 7436 Sema::AssignConvertType 7437 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7438 CastKind &Kind, bool ConvertRHS) { 7439 QualType RHSType = RHS.get()->getType(); 7440 QualType OrigLHSType = LHSType; 7441 7442 // Get canonical types. We're not formatting these types, just comparing 7443 // them. 7444 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7445 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7446 7447 // Common case: no conversion required. 7448 if (LHSType == RHSType) { 7449 Kind = CK_NoOp; 7450 return Compatible; 7451 } 7452 7453 // If we have an atomic type, try a non-atomic assignment, then just add an 7454 // atomic qualification step. 7455 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7456 Sema::AssignConvertType result = 7457 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7458 if (result != Compatible) 7459 return result; 7460 if (Kind != CK_NoOp && ConvertRHS) 7461 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7462 Kind = CK_NonAtomicToAtomic; 7463 return Compatible; 7464 } 7465 7466 // If the left-hand side is a reference type, then we are in a 7467 // (rare!) case where we've allowed the use of references in C, 7468 // e.g., as a parameter type in a built-in function. In this case, 7469 // just make sure that the type referenced is compatible with the 7470 // right-hand side type. The caller is responsible for adjusting 7471 // LHSType so that the resulting expression does not have reference 7472 // type. 7473 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7474 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7475 Kind = CK_LValueBitCast; 7476 return Compatible; 7477 } 7478 return Incompatible; 7479 } 7480 7481 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7482 // to the same ExtVector type. 7483 if (LHSType->isExtVectorType()) { 7484 if (RHSType->isExtVectorType()) 7485 return Incompatible; 7486 if (RHSType->isArithmeticType()) { 7487 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7488 if (ConvertRHS) 7489 RHS = prepareVectorSplat(LHSType, RHS.get()); 7490 Kind = CK_VectorSplat; 7491 return Compatible; 7492 } 7493 } 7494 7495 // Conversions to or from vector type. 7496 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7497 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7498 // Allow assignments of an AltiVec vector type to an equivalent GCC 7499 // vector type and vice versa 7500 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7501 Kind = CK_BitCast; 7502 return Compatible; 7503 } 7504 7505 // If we are allowing lax vector conversions, and LHS and RHS are both 7506 // vectors, the total size only needs to be the same. This is a bitcast; 7507 // no bits are changed but the result type is different. 7508 if (isLaxVectorConversion(RHSType, LHSType)) { 7509 Kind = CK_BitCast; 7510 return IncompatibleVectors; 7511 } 7512 } 7513 7514 // When the RHS comes from another lax conversion (e.g. binops between 7515 // scalars and vectors) the result is canonicalized as a vector. When the 7516 // LHS is also a vector, the lax is allowed by the condition above. Handle 7517 // the case where LHS is a scalar. 7518 if (LHSType->isScalarType()) { 7519 const VectorType *VecType = RHSType->getAs<VectorType>(); 7520 if (VecType && VecType->getNumElements() == 1 && 7521 isLaxVectorConversion(RHSType, LHSType)) { 7522 ExprResult *VecExpr = &RHS; 7523 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7524 Kind = CK_BitCast; 7525 return Compatible; 7526 } 7527 } 7528 7529 return Incompatible; 7530 } 7531 7532 // Diagnose attempts to convert between __float128 and long double where 7533 // such conversions currently can't be handled. 7534 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7535 return Incompatible; 7536 7537 // Arithmetic conversions. 7538 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7539 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7540 if (ConvertRHS) 7541 Kind = PrepareScalarCast(RHS, LHSType); 7542 return Compatible; 7543 } 7544 7545 // Conversions to normal pointers. 7546 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7547 // U* -> T* 7548 if (isa<PointerType>(RHSType)) { 7549 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7550 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7551 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7552 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7553 } 7554 7555 // int -> T* 7556 if (RHSType->isIntegerType()) { 7557 Kind = CK_IntegralToPointer; // FIXME: null? 7558 return IntToPointer; 7559 } 7560 7561 // C pointers are not compatible with ObjC object pointers, 7562 // with two exceptions: 7563 if (isa<ObjCObjectPointerType>(RHSType)) { 7564 // - conversions to void* 7565 if (LHSPointer->getPointeeType()->isVoidType()) { 7566 Kind = CK_BitCast; 7567 return Compatible; 7568 } 7569 7570 // - conversions from 'Class' to the redefinition type 7571 if (RHSType->isObjCClassType() && 7572 Context.hasSameType(LHSType, 7573 Context.getObjCClassRedefinitionType())) { 7574 Kind = CK_BitCast; 7575 return Compatible; 7576 } 7577 7578 Kind = CK_BitCast; 7579 return IncompatiblePointer; 7580 } 7581 7582 // U^ -> void* 7583 if (RHSType->getAs<BlockPointerType>()) { 7584 if (LHSPointer->getPointeeType()->isVoidType()) { 7585 Kind = CK_BitCast; 7586 return Compatible; 7587 } 7588 } 7589 7590 return Incompatible; 7591 } 7592 7593 // Conversions to block pointers. 7594 if (isa<BlockPointerType>(LHSType)) { 7595 // U^ -> T^ 7596 if (RHSType->isBlockPointerType()) { 7597 Kind = CK_BitCast; 7598 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7599 } 7600 7601 // int or null -> T^ 7602 if (RHSType->isIntegerType()) { 7603 Kind = CK_IntegralToPointer; // FIXME: null 7604 return IntToBlockPointer; 7605 } 7606 7607 // id -> T^ 7608 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7609 Kind = CK_AnyPointerToBlockPointerCast; 7610 return Compatible; 7611 } 7612 7613 // void* -> T^ 7614 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7615 if (RHSPT->getPointeeType()->isVoidType()) { 7616 Kind = CK_AnyPointerToBlockPointerCast; 7617 return Compatible; 7618 } 7619 7620 return Incompatible; 7621 } 7622 7623 // Conversions to Objective-C pointers. 7624 if (isa<ObjCObjectPointerType>(LHSType)) { 7625 // A* -> B* 7626 if (RHSType->isObjCObjectPointerType()) { 7627 Kind = CK_BitCast; 7628 Sema::AssignConvertType result = 7629 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7630 if (getLangOpts().ObjCAutoRefCount && 7631 result == Compatible && 7632 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7633 result = IncompatibleObjCWeakRef; 7634 return result; 7635 } 7636 7637 // int or null -> A* 7638 if (RHSType->isIntegerType()) { 7639 Kind = CK_IntegralToPointer; // FIXME: null 7640 return IntToPointer; 7641 } 7642 7643 // In general, C pointers are not compatible with ObjC object pointers, 7644 // with two exceptions: 7645 if (isa<PointerType>(RHSType)) { 7646 Kind = CK_CPointerToObjCPointerCast; 7647 7648 // - conversions from 'void*' 7649 if (RHSType->isVoidPointerType()) { 7650 return Compatible; 7651 } 7652 7653 // - conversions to 'Class' from its redefinition type 7654 if (LHSType->isObjCClassType() && 7655 Context.hasSameType(RHSType, 7656 Context.getObjCClassRedefinitionType())) { 7657 return Compatible; 7658 } 7659 7660 return IncompatiblePointer; 7661 } 7662 7663 // Only under strict condition T^ is compatible with an Objective-C pointer. 7664 if (RHSType->isBlockPointerType() && 7665 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7666 if (ConvertRHS) 7667 maybeExtendBlockObject(RHS); 7668 Kind = CK_BlockPointerToObjCPointerCast; 7669 return Compatible; 7670 } 7671 7672 return Incompatible; 7673 } 7674 7675 // Conversions from pointers that are not covered by the above. 7676 if (isa<PointerType>(RHSType)) { 7677 // T* -> _Bool 7678 if (LHSType == Context.BoolTy) { 7679 Kind = CK_PointerToBoolean; 7680 return Compatible; 7681 } 7682 7683 // T* -> int 7684 if (LHSType->isIntegerType()) { 7685 Kind = CK_PointerToIntegral; 7686 return PointerToInt; 7687 } 7688 7689 return Incompatible; 7690 } 7691 7692 // Conversions from Objective-C pointers that are not covered by the above. 7693 if (isa<ObjCObjectPointerType>(RHSType)) { 7694 // T* -> _Bool 7695 if (LHSType == Context.BoolTy) { 7696 Kind = CK_PointerToBoolean; 7697 return Compatible; 7698 } 7699 7700 // T* -> int 7701 if (LHSType->isIntegerType()) { 7702 Kind = CK_PointerToIntegral; 7703 return PointerToInt; 7704 } 7705 7706 return Incompatible; 7707 } 7708 7709 // struct A -> struct B 7710 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7711 if (Context.typesAreCompatible(LHSType, RHSType)) { 7712 Kind = CK_NoOp; 7713 return Compatible; 7714 } 7715 } 7716 7717 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7718 Kind = CK_IntToOCLSampler; 7719 return Compatible; 7720 } 7721 7722 return Incompatible; 7723 } 7724 7725 /// \brief Constructs a transparent union from an expression that is 7726 /// used to initialize the transparent union. 7727 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7728 ExprResult &EResult, QualType UnionType, 7729 FieldDecl *Field) { 7730 // Build an initializer list that designates the appropriate member 7731 // of the transparent union. 7732 Expr *E = EResult.get(); 7733 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7734 E, SourceLocation()); 7735 Initializer->setType(UnionType); 7736 Initializer->setInitializedFieldInUnion(Field); 7737 7738 // Build a compound literal constructing a value of the transparent 7739 // union type from this initializer list. 7740 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7741 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7742 VK_RValue, Initializer, false); 7743 } 7744 7745 Sema::AssignConvertType 7746 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7747 ExprResult &RHS) { 7748 QualType RHSType = RHS.get()->getType(); 7749 7750 // If the ArgType is a Union type, we want to handle a potential 7751 // transparent_union GCC extension. 7752 const RecordType *UT = ArgType->getAsUnionType(); 7753 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7754 return Incompatible; 7755 7756 // The field to initialize within the transparent union. 7757 RecordDecl *UD = UT->getDecl(); 7758 FieldDecl *InitField = nullptr; 7759 // It's compatible if the expression matches any of the fields. 7760 for (auto *it : UD->fields()) { 7761 if (it->getType()->isPointerType()) { 7762 // If the transparent union contains a pointer type, we allow: 7763 // 1) void pointer 7764 // 2) null pointer constant 7765 if (RHSType->isPointerType()) 7766 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7767 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7768 InitField = it; 7769 break; 7770 } 7771 7772 if (RHS.get()->isNullPointerConstant(Context, 7773 Expr::NPC_ValueDependentIsNull)) { 7774 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7775 CK_NullToPointer); 7776 InitField = it; 7777 break; 7778 } 7779 } 7780 7781 CastKind Kind = CK_Invalid; 7782 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7783 == Compatible) { 7784 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7785 InitField = it; 7786 break; 7787 } 7788 } 7789 7790 if (!InitField) 7791 return Incompatible; 7792 7793 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7794 return Compatible; 7795 } 7796 7797 Sema::AssignConvertType 7798 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7799 bool Diagnose, 7800 bool DiagnoseCFAudited, 7801 bool ConvertRHS) { 7802 // We need to be able to tell the caller whether we diagnosed a problem, if 7803 // they ask us to issue diagnostics. 7804 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7805 7806 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7807 // we can't avoid *all* modifications at the moment, so we need some somewhere 7808 // to put the updated value. 7809 ExprResult LocalRHS = CallerRHS; 7810 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7811 7812 if (getLangOpts().CPlusPlus) { 7813 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7814 // C++ 5.17p3: If the left operand is not of class type, the 7815 // expression is implicitly converted (C++ 4) to the 7816 // cv-unqualified type of the left operand. 7817 QualType RHSType = RHS.get()->getType(); 7818 if (Diagnose) { 7819 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7820 AA_Assigning); 7821 } else { 7822 ImplicitConversionSequence ICS = 7823 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7824 /*SuppressUserConversions=*/false, 7825 /*AllowExplicit=*/false, 7826 /*InOverloadResolution=*/false, 7827 /*CStyle=*/false, 7828 /*AllowObjCWritebackConversion=*/false); 7829 if (ICS.isFailure()) 7830 return Incompatible; 7831 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7832 ICS, AA_Assigning); 7833 } 7834 if (RHS.isInvalid()) 7835 return Incompatible; 7836 Sema::AssignConvertType result = Compatible; 7837 if (getLangOpts().ObjCAutoRefCount && 7838 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7839 result = IncompatibleObjCWeakRef; 7840 return result; 7841 } 7842 7843 // FIXME: Currently, we fall through and treat C++ classes like C 7844 // structures. 7845 // FIXME: We also fall through for atomics; not sure what should 7846 // happen there, though. 7847 } else if (RHS.get()->getType() == Context.OverloadTy) { 7848 // As a set of extensions to C, we support overloading on functions. These 7849 // functions need to be resolved here. 7850 DeclAccessPair DAP; 7851 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7852 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7853 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7854 else 7855 return Incompatible; 7856 } 7857 7858 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7859 // a null pointer constant. 7860 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7861 LHSType->isBlockPointerType()) && 7862 RHS.get()->isNullPointerConstant(Context, 7863 Expr::NPC_ValueDependentIsNull)) { 7864 if (Diagnose || ConvertRHS) { 7865 CastKind Kind; 7866 CXXCastPath Path; 7867 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7868 /*IgnoreBaseAccess=*/false, Diagnose); 7869 if (ConvertRHS) 7870 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7871 } 7872 return Compatible; 7873 } 7874 7875 // This check seems unnatural, however it is necessary to ensure the proper 7876 // conversion of functions/arrays. If the conversion were done for all 7877 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7878 // expressions that suppress this implicit conversion (&, sizeof). 7879 // 7880 // Suppress this for references: C++ 8.5.3p5. 7881 if (!LHSType->isReferenceType()) { 7882 // FIXME: We potentially allocate here even if ConvertRHS is false. 7883 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7884 if (RHS.isInvalid()) 7885 return Incompatible; 7886 } 7887 7888 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7889 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7890 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7891 if (PDecl && !PDecl->hasDefinition()) { 7892 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7893 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7894 } 7895 } 7896 7897 CastKind Kind = CK_Invalid; 7898 Sema::AssignConvertType result = 7899 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7900 7901 // C99 6.5.16.1p2: The value of the right operand is converted to the 7902 // type of the assignment expression. 7903 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7904 // so that we can use references in built-in functions even in C. 7905 // The getNonReferenceType() call makes sure that the resulting expression 7906 // does not have reference type. 7907 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7908 QualType Ty = LHSType.getNonLValueExprType(Context); 7909 Expr *E = RHS.get(); 7910 7911 // Check for various Objective-C errors. If we are not reporting 7912 // diagnostics and just checking for errors, e.g., during overload 7913 // resolution, return Incompatible to indicate the failure. 7914 if (getLangOpts().ObjCAutoRefCount && 7915 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7916 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7917 if (!Diagnose) 7918 return Incompatible; 7919 } 7920 if (getLangOpts().ObjC1 && 7921 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7922 E->getType(), E, Diagnose) || 7923 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7924 if (!Diagnose) 7925 return Incompatible; 7926 // Replace the expression with a corrected version and continue so we 7927 // can find further errors. 7928 RHS = E; 7929 return Compatible; 7930 } 7931 7932 if (ConvertRHS) 7933 RHS = ImpCastExprToType(E, Ty, Kind); 7934 } 7935 return result; 7936 } 7937 7938 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7939 ExprResult &RHS) { 7940 Diag(Loc, diag::err_typecheck_invalid_operands) 7941 << LHS.get()->getType() << RHS.get()->getType() 7942 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7943 return QualType(); 7944 } 7945 7946 /// Try to convert a value of non-vector type to a vector type by converting 7947 /// the type to the element type of the vector and then performing a splat. 7948 /// If the language is OpenCL, we only use conversions that promote scalar 7949 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7950 /// for float->int. 7951 /// 7952 /// \param scalar - if non-null, actually perform the conversions 7953 /// \return true if the operation fails (but without diagnosing the failure) 7954 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7955 QualType scalarTy, 7956 QualType vectorEltTy, 7957 QualType vectorTy) { 7958 // The conversion to apply to the scalar before splatting it, 7959 // if necessary. 7960 CastKind scalarCast = CK_Invalid; 7961 7962 if (vectorEltTy->isIntegralType(S.Context)) { 7963 if (!scalarTy->isIntegralType(S.Context)) 7964 return true; 7965 if (S.getLangOpts().OpenCL && 7966 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7967 return true; 7968 scalarCast = CK_IntegralCast; 7969 } else if (vectorEltTy->isRealFloatingType()) { 7970 if (scalarTy->isRealFloatingType()) { 7971 if (S.getLangOpts().OpenCL && 7972 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7973 return true; 7974 scalarCast = CK_FloatingCast; 7975 } 7976 else if (scalarTy->isIntegralType(S.Context)) 7977 scalarCast = CK_IntegralToFloating; 7978 else 7979 return true; 7980 } else { 7981 return true; 7982 } 7983 7984 // Adjust scalar if desired. 7985 if (scalar) { 7986 if (scalarCast != CK_Invalid) 7987 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7988 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7989 } 7990 return false; 7991 } 7992 7993 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7994 SourceLocation Loc, bool IsCompAssign, 7995 bool AllowBothBool, 7996 bool AllowBoolConversions) { 7997 if (!IsCompAssign) { 7998 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7999 if (LHS.isInvalid()) 8000 return QualType(); 8001 } 8002 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8003 if (RHS.isInvalid()) 8004 return QualType(); 8005 8006 // For conversion purposes, we ignore any qualifiers. 8007 // For example, "const float" and "float" are equivalent. 8008 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8009 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8010 8011 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8012 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8013 assert(LHSVecType || RHSVecType); 8014 8015 // AltiVec-style "vector bool op vector bool" combinations are allowed 8016 // for some operators but not others. 8017 if (!AllowBothBool && 8018 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8019 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8020 return InvalidOperands(Loc, LHS, RHS); 8021 8022 // If the vector types are identical, return. 8023 if (Context.hasSameType(LHSType, RHSType)) 8024 return LHSType; 8025 8026 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8027 if (LHSVecType && RHSVecType && 8028 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8029 if (isa<ExtVectorType>(LHSVecType)) { 8030 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8031 return LHSType; 8032 } 8033 8034 if (!IsCompAssign) 8035 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8036 return RHSType; 8037 } 8038 8039 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8040 // can be mixed, with the result being the non-bool type. The non-bool 8041 // operand must have integer element type. 8042 if (AllowBoolConversions && LHSVecType && RHSVecType && 8043 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8044 (Context.getTypeSize(LHSVecType->getElementType()) == 8045 Context.getTypeSize(RHSVecType->getElementType()))) { 8046 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8047 LHSVecType->getElementType()->isIntegerType() && 8048 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8049 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8050 return LHSType; 8051 } 8052 if (!IsCompAssign && 8053 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8054 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8055 RHSVecType->getElementType()->isIntegerType()) { 8056 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8057 return RHSType; 8058 } 8059 } 8060 8061 // If there's an ext-vector type and a scalar, try to convert the scalar to 8062 // the vector element type and splat. 8063 // FIXME: this should also work for regular vector types as supported in GCC. 8064 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8065 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8066 LHSVecType->getElementType(), LHSType)) 8067 return LHSType; 8068 } 8069 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8070 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8071 LHSType, RHSVecType->getElementType(), 8072 RHSType)) 8073 return RHSType; 8074 } 8075 8076 // FIXME: The code below also handles convertion between vectors and 8077 // non-scalars, we should break this down into fine grained specific checks 8078 // and emit proper diagnostics. 8079 QualType VecType = LHSVecType ? LHSType : RHSType; 8080 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8081 QualType OtherType = LHSVecType ? RHSType : LHSType; 8082 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8083 if (isLaxVectorConversion(OtherType, VecType)) { 8084 // If we're allowing lax vector conversions, only the total (data) size 8085 // needs to be the same. For non compound assignment, if one of the types is 8086 // scalar, the result is always the vector type. 8087 if (!IsCompAssign) { 8088 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8089 return VecType; 8090 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8091 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8092 // type. Note that this is already done by non-compound assignments in 8093 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8094 // <1 x T> -> T. The result is also a vector type. 8095 } else if (OtherType->isExtVectorType() || 8096 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8097 ExprResult *RHSExpr = &RHS; 8098 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8099 return VecType; 8100 } 8101 } 8102 8103 // Okay, the expression is invalid. 8104 8105 // If there's a non-vector, non-real operand, diagnose that. 8106 if ((!RHSVecType && !RHSType->isRealType()) || 8107 (!LHSVecType && !LHSType->isRealType())) { 8108 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8109 << LHSType << RHSType 8110 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8111 return QualType(); 8112 } 8113 8114 // OpenCL V1.1 6.2.6.p1: 8115 // If the operands are of more than one vector type, then an error shall 8116 // occur. Implicit conversions between vector types are not permitted, per 8117 // section 6.2.1. 8118 if (getLangOpts().OpenCL && 8119 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8120 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8121 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8122 << RHSType; 8123 return QualType(); 8124 } 8125 8126 // Otherwise, use the generic diagnostic. 8127 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8128 << LHSType << RHSType 8129 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8130 return QualType(); 8131 } 8132 8133 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8134 // expression. These are mainly cases where the null pointer is used as an 8135 // integer instead of a pointer. 8136 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8137 SourceLocation Loc, bool IsCompare) { 8138 // The canonical way to check for a GNU null is with isNullPointerConstant, 8139 // but we use a bit of a hack here for speed; this is a relatively 8140 // hot path, and isNullPointerConstant is slow. 8141 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8142 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8143 8144 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8145 8146 // Avoid analyzing cases where the result will either be invalid (and 8147 // diagnosed as such) or entirely valid and not something to warn about. 8148 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8149 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8150 return; 8151 8152 // Comparison operations would not make sense with a null pointer no matter 8153 // what the other expression is. 8154 if (!IsCompare) { 8155 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8156 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8157 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8158 return; 8159 } 8160 8161 // The rest of the operations only make sense with a null pointer 8162 // if the other expression is a pointer. 8163 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8164 NonNullType->canDecayToPointerType()) 8165 return; 8166 8167 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8168 << LHSNull /* LHS is NULL */ << NonNullType 8169 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8170 } 8171 8172 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8173 ExprResult &RHS, 8174 SourceLocation Loc, bool IsDiv) { 8175 // Check for division/remainder by zero. 8176 llvm::APSInt RHSValue; 8177 if (!RHS.get()->isValueDependent() && 8178 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8179 S.DiagRuntimeBehavior(Loc, RHS.get(), 8180 S.PDiag(diag::warn_remainder_division_by_zero) 8181 << IsDiv << RHS.get()->getSourceRange()); 8182 } 8183 8184 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8185 SourceLocation Loc, 8186 bool IsCompAssign, bool IsDiv) { 8187 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8188 8189 if (LHS.get()->getType()->isVectorType() || 8190 RHS.get()->getType()->isVectorType()) 8191 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8192 /*AllowBothBool*/getLangOpts().AltiVec, 8193 /*AllowBoolConversions*/false); 8194 8195 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8196 if (LHS.isInvalid() || RHS.isInvalid()) 8197 return QualType(); 8198 8199 8200 if (compType.isNull() || !compType->isArithmeticType()) 8201 return InvalidOperands(Loc, LHS, RHS); 8202 if (IsDiv) 8203 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8204 return compType; 8205 } 8206 8207 QualType Sema::CheckRemainderOperands( 8208 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8209 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8210 8211 if (LHS.get()->getType()->isVectorType() || 8212 RHS.get()->getType()->isVectorType()) { 8213 if (LHS.get()->getType()->hasIntegerRepresentation() && 8214 RHS.get()->getType()->hasIntegerRepresentation()) 8215 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8216 /*AllowBothBool*/getLangOpts().AltiVec, 8217 /*AllowBoolConversions*/false); 8218 return InvalidOperands(Loc, LHS, RHS); 8219 } 8220 8221 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8222 if (LHS.isInvalid() || RHS.isInvalid()) 8223 return QualType(); 8224 8225 if (compType.isNull() || !compType->isIntegerType()) 8226 return InvalidOperands(Loc, LHS, RHS); 8227 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8228 return compType; 8229 } 8230 8231 /// \brief Diagnose invalid arithmetic on two void pointers. 8232 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8233 Expr *LHSExpr, Expr *RHSExpr) { 8234 S.Diag(Loc, S.getLangOpts().CPlusPlus 8235 ? diag::err_typecheck_pointer_arith_void_type 8236 : diag::ext_gnu_void_ptr) 8237 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8238 << RHSExpr->getSourceRange(); 8239 } 8240 8241 /// \brief Diagnose invalid arithmetic on a void pointer. 8242 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8243 Expr *Pointer) { 8244 S.Diag(Loc, S.getLangOpts().CPlusPlus 8245 ? diag::err_typecheck_pointer_arith_void_type 8246 : diag::ext_gnu_void_ptr) 8247 << 0 /* one pointer */ << Pointer->getSourceRange(); 8248 } 8249 8250 /// \brief Diagnose invalid arithmetic on two function pointers. 8251 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8252 Expr *LHS, Expr *RHS) { 8253 assert(LHS->getType()->isAnyPointerType()); 8254 assert(RHS->getType()->isAnyPointerType()); 8255 S.Diag(Loc, S.getLangOpts().CPlusPlus 8256 ? diag::err_typecheck_pointer_arith_function_type 8257 : diag::ext_gnu_ptr_func_arith) 8258 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8259 // We only show the second type if it differs from the first. 8260 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8261 RHS->getType()) 8262 << RHS->getType()->getPointeeType() 8263 << LHS->getSourceRange() << RHS->getSourceRange(); 8264 } 8265 8266 /// \brief Diagnose invalid arithmetic on a function pointer. 8267 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8268 Expr *Pointer) { 8269 assert(Pointer->getType()->isAnyPointerType()); 8270 S.Diag(Loc, S.getLangOpts().CPlusPlus 8271 ? diag::err_typecheck_pointer_arith_function_type 8272 : diag::ext_gnu_ptr_func_arith) 8273 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8274 << 0 /* one pointer, so only one type */ 8275 << Pointer->getSourceRange(); 8276 } 8277 8278 /// \brief Emit error if Operand is incomplete pointer type 8279 /// 8280 /// \returns True if pointer has incomplete type 8281 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8282 Expr *Operand) { 8283 QualType ResType = Operand->getType(); 8284 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8285 ResType = ResAtomicType->getValueType(); 8286 8287 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8288 QualType PointeeTy = ResType->getPointeeType(); 8289 return S.RequireCompleteType(Loc, PointeeTy, 8290 diag::err_typecheck_arithmetic_incomplete_type, 8291 PointeeTy, Operand->getSourceRange()); 8292 } 8293 8294 /// \brief Check the validity of an arithmetic pointer operand. 8295 /// 8296 /// If the operand has pointer type, this code will check for pointer types 8297 /// which are invalid in arithmetic operations. These will be diagnosed 8298 /// appropriately, including whether or not the use is supported as an 8299 /// extension. 8300 /// 8301 /// \returns True when the operand is valid to use (even if as an extension). 8302 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8303 Expr *Operand) { 8304 QualType ResType = Operand->getType(); 8305 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8306 ResType = ResAtomicType->getValueType(); 8307 8308 if (!ResType->isAnyPointerType()) return true; 8309 8310 QualType PointeeTy = ResType->getPointeeType(); 8311 if (PointeeTy->isVoidType()) { 8312 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8313 return !S.getLangOpts().CPlusPlus; 8314 } 8315 if (PointeeTy->isFunctionType()) { 8316 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8317 return !S.getLangOpts().CPlusPlus; 8318 } 8319 8320 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8321 8322 return true; 8323 } 8324 8325 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8326 /// operands. 8327 /// 8328 /// This routine will diagnose any invalid arithmetic on pointer operands much 8329 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8330 /// for emitting a single diagnostic even for operations where both LHS and RHS 8331 /// are (potentially problematic) pointers. 8332 /// 8333 /// \returns True when the operand is valid to use (even if as an extension). 8334 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8335 Expr *LHSExpr, Expr *RHSExpr) { 8336 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8337 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8338 if (!isLHSPointer && !isRHSPointer) return true; 8339 8340 QualType LHSPointeeTy, RHSPointeeTy; 8341 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8342 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8343 8344 // if both are pointers check if operation is valid wrt address spaces 8345 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8346 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8347 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8348 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8349 S.Diag(Loc, 8350 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8351 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8352 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8353 return false; 8354 } 8355 } 8356 8357 // Check for arithmetic on pointers to incomplete types. 8358 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8359 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8360 if (isLHSVoidPtr || isRHSVoidPtr) { 8361 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8362 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8363 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8364 8365 return !S.getLangOpts().CPlusPlus; 8366 } 8367 8368 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8369 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8370 if (isLHSFuncPtr || isRHSFuncPtr) { 8371 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8372 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8373 RHSExpr); 8374 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8375 8376 return !S.getLangOpts().CPlusPlus; 8377 } 8378 8379 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8380 return false; 8381 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8382 return false; 8383 8384 return true; 8385 } 8386 8387 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8388 /// literal. 8389 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8390 Expr *LHSExpr, Expr *RHSExpr) { 8391 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8392 Expr* IndexExpr = RHSExpr; 8393 if (!StrExpr) { 8394 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8395 IndexExpr = LHSExpr; 8396 } 8397 8398 bool IsStringPlusInt = StrExpr && 8399 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8400 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8401 return; 8402 8403 llvm::APSInt index; 8404 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8405 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8406 if (index.isNonNegative() && 8407 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8408 index.isUnsigned())) 8409 return; 8410 } 8411 8412 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8413 Self.Diag(OpLoc, diag::warn_string_plus_int) 8414 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8415 8416 // Only print a fixit for "str" + int, not for int + "str". 8417 if (IndexExpr == RHSExpr) { 8418 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8419 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8420 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8421 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8422 << FixItHint::CreateInsertion(EndLoc, "]"); 8423 } else 8424 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8425 } 8426 8427 /// \brief Emit a warning when adding a char literal to a string. 8428 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8429 Expr *LHSExpr, Expr *RHSExpr) { 8430 const Expr *StringRefExpr = LHSExpr; 8431 const CharacterLiteral *CharExpr = 8432 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8433 8434 if (!CharExpr) { 8435 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8436 StringRefExpr = RHSExpr; 8437 } 8438 8439 if (!CharExpr || !StringRefExpr) 8440 return; 8441 8442 const QualType StringType = StringRefExpr->getType(); 8443 8444 // Return if not a PointerType. 8445 if (!StringType->isAnyPointerType()) 8446 return; 8447 8448 // Return if not a CharacterType. 8449 if (!StringType->getPointeeType()->isAnyCharacterType()) 8450 return; 8451 8452 ASTContext &Ctx = Self.getASTContext(); 8453 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8454 8455 const QualType CharType = CharExpr->getType(); 8456 if (!CharType->isAnyCharacterType() && 8457 CharType->isIntegerType() && 8458 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8459 Self.Diag(OpLoc, diag::warn_string_plus_char) 8460 << DiagRange << Ctx.CharTy; 8461 } else { 8462 Self.Diag(OpLoc, diag::warn_string_plus_char) 8463 << DiagRange << CharExpr->getType(); 8464 } 8465 8466 // Only print a fixit for str + char, not for char + str. 8467 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8468 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8469 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8470 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8471 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8472 << FixItHint::CreateInsertion(EndLoc, "]"); 8473 } else { 8474 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8475 } 8476 } 8477 8478 /// \brief Emit error when two pointers are incompatible. 8479 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8480 Expr *LHSExpr, Expr *RHSExpr) { 8481 assert(LHSExpr->getType()->isAnyPointerType()); 8482 assert(RHSExpr->getType()->isAnyPointerType()); 8483 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8484 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8485 << RHSExpr->getSourceRange(); 8486 } 8487 8488 // C99 6.5.6 8489 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8490 SourceLocation Loc, BinaryOperatorKind Opc, 8491 QualType* CompLHSTy) { 8492 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8493 8494 if (LHS.get()->getType()->isVectorType() || 8495 RHS.get()->getType()->isVectorType()) { 8496 QualType compType = CheckVectorOperands( 8497 LHS, RHS, Loc, CompLHSTy, 8498 /*AllowBothBool*/getLangOpts().AltiVec, 8499 /*AllowBoolConversions*/getLangOpts().ZVector); 8500 if (CompLHSTy) *CompLHSTy = compType; 8501 return compType; 8502 } 8503 8504 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8505 if (LHS.isInvalid() || RHS.isInvalid()) 8506 return QualType(); 8507 8508 // Diagnose "string literal" '+' int and string '+' "char literal". 8509 if (Opc == BO_Add) { 8510 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8511 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8512 } 8513 8514 // handle the common case first (both operands are arithmetic). 8515 if (!compType.isNull() && compType->isArithmeticType()) { 8516 if (CompLHSTy) *CompLHSTy = compType; 8517 return compType; 8518 } 8519 8520 // Type-checking. Ultimately the pointer's going to be in PExp; 8521 // note that we bias towards the LHS being the pointer. 8522 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8523 8524 bool isObjCPointer; 8525 if (PExp->getType()->isPointerType()) { 8526 isObjCPointer = false; 8527 } else if (PExp->getType()->isObjCObjectPointerType()) { 8528 isObjCPointer = true; 8529 } else { 8530 std::swap(PExp, IExp); 8531 if (PExp->getType()->isPointerType()) { 8532 isObjCPointer = false; 8533 } else if (PExp->getType()->isObjCObjectPointerType()) { 8534 isObjCPointer = true; 8535 } else { 8536 return InvalidOperands(Loc, LHS, RHS); 8537 } 8538 } 8539 assert(PExp->getType()->isAnyPointerType()); 8540 8541 if (!IExp->getType()->isIntegerType()) 8542 return InvalidOperands(Loc, LHS, RHS); 8543 8544 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8545 return QualType(); 8546 8547 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8548 return QualType(); 8549 8550 // Check array bounds for pointer arithemtic 8551 CheckArrayAccess(PExp, IExp); 8552 8553 if (CompLHSTy) { 8554 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8555 if (LHSTy.isNull()) { 8556 LHSTy = LHS.get()->getType(); 8557 if (LHSTy->isPromotableIntegerType()) 8558 LHSTy = Context.getPromotedIntegerType(LHSTy); 8559 } 8560 *CompLHSTy = LHSTy; 8561 } 8562 8563 return PExp->getType(); 8564 } 8565 8566 // C99 6.5.6 8567 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8568 SourceLocation Loc, 8569 QualType* CompLHSTy) { 8570 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8571 8572 if (LHS.get()->getType()->isVectorType() || 8573 RHS.get()->getType()->isVectorType()) { 8574 QualType compType = CheckVectorOperands( 8575 LHS, RHS, Loc, CompLHSTy, 8576 /*AllowBothBool*/getLangOpts().AltiVec, 8577 /*AllowBoolConversions*/getLangOpts().ZVector); 8578 if (CompLHSTy) *CompLHSTy = compType; 8579 return compType; 8580 } 8581 8582 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8583 if (LHS.isInvalid() || RHS.isInvalid()) 8584 return QualType(); 8585 8586 // Enforce type constraints: C99 6.5.6p3. 8587 8588 // Handle the common case first (both operands are arithmetic). 8589 if (!compType.isNull() && compType->isArithmeticType()) { 8590 if (CompLHSTy) *CompLHSTy = compType; 8591 return compType; 8592 } 8593 8594 // Either ptr - int or ptr - ptr. 8595 if (LHS.get()->getType()->isAnyPointerType()) { 8596 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8597 8598 // Diagnose bad cases where we step over interface counts. 8599 if (LHS.get()->getType()->isObjCObjectPointerType() && 8600 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8601 return QualType(); 8602 8603 // The result type of a pointer-int computation is the pointer type. 8604 if (RHS.get()->getType()->isIntegerType()) { 8605 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8606 return QualType(); 8607 8608 // Check array bounds for pointer arithemtic 8609 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8610 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8611 8612 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8613 return LHS.get()->getType(); 8614 } 8615 8616 // Handle pointer-pointer subtractions. 8617 if (const PointerType *RHSPTy 8618 = RHS.get()->getType()->getAs<PointerType>()) { 8619 QualType rpointee = RHSPTy->getPointeeType(); 8620 8621 if (getLangOpts().CPlusPlus) { 8622 // Pointee types must be the same: C++ [expr.add] 8623 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8624 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8625 } 8626 } else { 8627 // Pointee types must be compatible C99 6.5.6p3 8628 if (!Context.typesAreCompatible( 8629 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8630 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8631 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8632 return QualType(); 8633 } 8634 } 8635 8636 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8637 LHS.get(), RHS.get())) 8638 return QualType(); 8639 8640 // The pointee type may have zero size. As an extension, a structure or 8641 // union may have zero size or an array may have zero length. In this 8642 // case subtraction does not make sense. 8643 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8644 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8645 if (ElementSize.isZero()) { 8646 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8647 << rpointee.getUnqualifiedType() 8648 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8649 } 8650 } 8651 8652 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8653 return Context.getPointerDiffType(); 8654 } 8655 } 8656 8657 return InvalidOperands(Loc, LHS, RHS); 8658 } 8659 8660 static bool isScopedEnumerationType(QualType T) { 8661 if (const EnumType *ET = T->getAs<EnumType>()) 8662 return ET->getDecl()->isScoped(); 8663 return false; 8664 } 8665 8666 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8667 SourceLocation Loc, BinaryOperatorKind Opc, 8668 QualType LHSType) { 8669 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8670 // so skip remaining warnings as we don't want to modify values within Sema. 8671 if (S.getLangOpts().OpenCL) 8672 return; 8673 8674 llvm::APSInt Right; 8675 // Check right/shifter operand 8676 if (RHS.get()->isValueDependent() || 8677 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8678 return; 8679 8680 if (Right.isNegative()) { 8681 S.DiagRuntimeBehavior(Loc, RHS.get(), 8682 S.PDiag(diag::warn_shift_negative) 8683 << RHS.get()->getSourceRange()); 8684 return; 8685 } 8686 llvm::APInt LeftBits(Right.getBitWidth(), 8687 S.Context.getTypeSize(LHS.get()->getType())); 8688 if (Right.uge(LeftBits)) { 8689 S.DiagRuntimeBehavior(Loc, RHS.get(), 8690 S.PDiag(diag::warn_shift_gt_typewidth) 8691 << RHS.get()->getSourceRange()); 8692 return; 8693 } 8694 if (Opc != BO_Shl) 8695 return; 8696 8697 // When left shifting an ICE which is signed, we can check for overflow which 8698 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8699 // integers have defined behavior modulo one more than the maximum value 8700 // representable in the result type, so never warn for those. 8701 llvm::APSInt Left; 8702 if (LHS.get()->isValueDependent() || 8703 LHSType->hasUnsignedIntegerRepresentation() || 8704 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8705 return; 8706 8707 // If LHS does not have a signed type and non-negative value 8708 // then, the behavior is undefined. Warn about it. 8709 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8710 S.DiagRuntimeBehavior(Loc, LHS.get(), 8711 S.PDiag(diag::warn_shift_lhs_negative) 8712 << LHS.get()->getSourceRange()); 8713 return; 8714 } 8715 8716 llvm::APInt ResultBits = 8717 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8718 if (LeftBits.uge(ResultBits)) 8719 return; 8720 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8721 Result = Result.shl(Right); 8722 8723 // Print the bit representation of the signed integer as an unsigned 8724 // hexadecimal number. 8725 SmallString<40> HexResult; 8726 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8727 8728 // If we are only missing a sign bit, this is less likely to result in actual 8729 // bugs -- if the result is cast back to an unsigned type, it will have the 8730 // expected value. Thus we place this behind a different warning that can be 8731 // turned off separately if needed. 8732 if (LeftBits == ResultBits - 1) { 8733 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8734 << HexResult << LHSType 8735 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8736 return; 8737 } 8738 8739 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8740 << HexResult.str() << Result.getMinSignedBits() << LHSType 8741 << Left.getBitWidth() << LHS.get()->getSourceRange() 8742 << RHS.get()->getSourceRange(); 8743 } 8744 8745 /// \brief Return the resulting type when a vector is shifted 8746 /// by a scalar or vector shift amount. 8747 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8748 SourceLocation Loc, bool IsCompAssign) { 8749 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8750 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8751 !LHS.get()->getType()->isVectorType()) { 8752 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8753 << RHS.get()->getType() << LHS.get()->getType() 8754 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8755 return QualType(); 8756 } 8757 8758 if (!IsCompAssign) { 8759 LHS = S.UsualUnaryConversions(LHS.get()); 8760 if (LHS.isInvalid()) return QualType(); 8761 } 8762 8763 RHS = S.UsualUnaryConversions(RHS.get()); 8764 if (RHS.isInvalid()) return QualType(); 8765 8766 QualType LHSType = LHS.get()->getType(); 8767 // Note that LHS might be a scalar because the routine calls not only in 8768 // OpenCL case. 8769 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8770 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8771 8772 // Note that RHS might not be a vector. 8773 QualType RHSType = RHS.get()->getType(); 8774 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8775 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8776 8777 // The operands need to be integers. 8778 if (!LHSEleType->isIntegerType()) { 8779 S.Diag(Loc, diag::err_typecheck_expect_int) 8780 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8781 return QualType(); 8782 } 8783 8784 if (!RHSEleType->isIntegerType()) { 8785 S.Diag(Loc, diag::err_typecheck_expect_int) 8786 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8787 return QualType(); 8788 } 8789 8790 if (!LHSVecTy) { 8791 assert(RHSVecTy); 8792 if (IsCompAssign) 8793 return RHSType; 8794 if (LHSEleType != RHSEleType) { 8795 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8796 LHSEleType = RHSEleType; 8797 } 8798 QualType VecTy = 8799 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8800 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8801 LHSType = VecTy; 8802 } else if (RHSVecTy) { 8803 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8804 // are applied component-wise. So if RHS is a vector, then ensure 8805 // that the number of elements is the same as LHS... 8806 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8807 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8808 << LHS.get()->getType() << RHS.get()->getType() 8809 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8810 return QualType(); 8811 } 8812 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 8813 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 8814 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 8815 if (LHSBT != RHSBT && 8816 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 8817 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 8818 << LHS.get()->getType() << RHS.get()->getType() 8819 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8820 } 8821 } 8822 } else { 8823 // ...else expand RHS to match the number of elements in LHS. 8824 QualType VecTy = 8825 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8826 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8827 } 8828 8829 return LHSType; 8830 } 8831 8832 // C99 6.5.7 8833 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8834 SourceLocation Loc, BinaryOperatorKind Opc, 8835 bool IsCompAssign) { 8836 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8837 8838 // Vector shifts promote their scalar inputs to vector type. 8839 if (LHS.get()->getType()->isVectorType() || 8840 RHS.get()->getType()->isVectorType()) { 8841 if (LangOpts.ZVector) { 8842 // The shift operators for the z vector extensions work basically 8843 // like general shifts, except that neither the LHS nor the RHS is 8844 // allowed to be a "vector bool". 8845 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8846 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8847 return InvalidOperands(Loc, LHS, RHS); 8848 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8849 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8850 return InvalidOperands(Loc, LHS, RHS); 8851 } 8852 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8853 } 8854 8855 // Shifts don't perform usual arithmetic conversions, they just do integer 8856 // promotions on each operand. C99 6.5.7p3 8857 8858 // For the LHS, do usual unary conversions, but then reset them away 8859 // if this is a compound assignment. 8860 ExprResult OldLHS = LHS; 8861 LHS = UsualUnaryConversions(LHS.get()); 8862 if (LHS.isInvalid()) 8863 return QualType(); 8864 QualType LHSType = LHS.get()->getType(); 8865 if (IsCompAssign) LHS = OldLHS; 8866 8867 // The RHS is simpler. 8868 RHS = UsualUnaryConversions(RHS.get()); 8869 if (RHS.isInvalid()) 8870 return QualType(); 8871 QualType RHSType = RHS.get()->getType(); 8872 8873 // C99 6.5.7p2: Each of the operands shall have integer type. 8874 if (!LHSType->hasIntegerRepresentation() || 8875 !RHSType->hasIntegerRepresentation()) 8876 return InvalidOperands(Loc, LHS, RHS); 8877 8878 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8879 // hasIntegerRepresentation() above instead of this. 8880 if (isScopedEnumerationType(LHSType) || 8881 isScopedEnumerationType(RHSType)) { 8882 return InvalidOperands(Loc, LHS, RHS); 8883 } 8884 // Sanity-check shift operands 8885 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8886 8887 // "The type of the result is that of the promoted left operand." 8888 return LHSType; 8889 } 8890 8891 static bool IsWithinTemplateSpecialization(Decl *D) { 8892 if (DeclContext *DC = D->getDeclContext()) { 8893 if (isa<ClassTemplateSpecializationDecl>(DC)) 8894 return true; 8895 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8896 return FD->isFunctionTemplateSpecialization(); 8897 } 8898 return false; 8899 } 8900 8901 /// If two different enums are compared, raise a warning. 8902 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8903 Expr *RHS) { 8904 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8905 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8906 8907 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8908 if (!LHSEnumType) 8909 return; 8910 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8911 if (!RHSEnumType) 8912 return; 8913 8914 // Ignore anonymous enums. 8915 if (!LHSEnumType->getDecl()->getIdentifier()) 8916 return; 8917 if (!RHSEnumType->getDecl()->getIdentifier()) 8918 return; 8919 8920 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8921 return; 8922 8923 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8924 << LHSStrippedType << RHSStrippedType 8925 << LHS->getSourceRange() << RHS->getSourceRange(); 8926 } 8927 8928 /// \brief Diagnose bad pointer comparisons. 8929 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8930 ExprResult &LHS, ExprResult &RHS, 8931 bool IsError) { 8932 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8933 : diag::ext_typecheck_comparison_of_distinct_pointers) 8934 << LHS.get()->getType() << RHS.get()->getType() 8935 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8936 } 8937 8938 /// \brief Returns false if the pointers are converted to a composite type, 8939 /// true otherwise. 8940 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8941 ExprResult &LHS, ExprResult &RHS) { 8942 // C++ [expr.rel]p2: 8943 // [...] Pointer conversions (4.10) and qualification 8944 // conversions (4.4) are performed on pointer operands (or on 8945 // a pointer operand and a null pointer constant) to bring 8946 // them to their composite pointer type. [...] 8947 // 8948 // C++ [expr.eq]p1 uses the same notion for (in)equality 8949 // comparisons of pointers. 8950 8951 QualType LHSType = LHS.get()->getType(); 8952 QualType RHSType = RHS.get()->getType(); 8953 assert(LHSType->isPointerType() || RHSType->isPointerType() || 8954 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 8955 8956 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 8957 if (T.isNull()) { 8958 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 8959 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 8960 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8961 else 8962 S.InvalidOperands(Loc, LHS, RHS); 8963 return true; 8964 } 8965 8966 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8967 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8968 return false; 8969 } 8970 8971 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8972 ExprResult &LHS, 8973 ExprResult &RHS, 8974 bool IsError) { 8975 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8976 : diag::ext_typecheck_comparison_of_fptr_to_void) 8977 << LHS.get()->getType() << RHS.get()->getType() 8978 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8979 } 8980 8981 static bool isObjCObjectLiteral(ExprResult &E) { 8982 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8983 case Stmt::ObjCArrayLiteralClass: 8984 case Stmt::ObjCDictionaryLiteralClass: 8985 case Stmt::ObjCStringLiteralClass: 8986 case Stmt::ObjCBoxedExprClass: 8987 return true; 8988 default: 8989 // Note that ObjCBoolLiteral is NOT an object literal! 8990 return false; 8991 } 8992 } 8993 8994 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8995 const ObjCObjectPointerType *Type = 8996 LHS->getType()->getAs<ObjCObjectPointerType>(); 8997 8998 // If this is not actually an Objective-C object, bail out. 8999 if (!Type) 9000 return false; 9001 9002 // Get the LHS object's interface type. 9003 QualType InterfaceType = Type->getPointeeType(); 9004 9005 // If the RHS isn't an Objective-C object, bail out. 9006 if (!RHS->getType()->isObjCObjectPointerType()) 9007 return false; 9008 9009 // Try to find the -isEqual: method. 9010 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9011 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9012 InterfaceType, 9013 /*instance=*/true); 9014 if (!Method) { 9015 if (Type->isObjCIdType()) { 9016 // For 'id', just check the global pool. 9017 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9018 /*receiverId=*/true); 9019 } else { 9020 // Check protocols. 9021 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9022 /*instance=*/true); 9023 } 9024 } 9025 9026 if (!Method) 9027 return false; 9028 9029 QualType T = Method->parameters()[0]->getType(); 9030 if (!T->isObjCObjectPointerType()) 9031 return false; 9032 9033 QualType R = Method->getReturnType(); 9034 if (!R->isScalarType()) 9035 return false; 9036 9037 return true; 9038 } 9039 9040 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9041 FromE = FromE->IgnoreParenImpCasts(); 9042 switch (FromE->getStmtClass()) { 9043 default: 9044 break; 9045 case Stmt::ObjCStringLiteralClass: 9046 // "string literal" 9047 return LK_String; 9048 case Stmt::ObjCArrayLiteralClass: 9049 // "array literal" 9050 return LK_Array; 9051 case Stmt::ObjCDictionaryLiteralClass: 9052 // "dictionary literal" 9053 return LK_Dictionary; 9054 case Stmt::BlockExprClass: 9055 return LK_Block; 9056 case Stmt::ObjCBoxedExprClass: { 9057 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9058 switch (Inner->getStmtClass()) { 9059 case Stmt::IntegerLiteralClass: 9060 case Stmt::FloatingLiteralClass: 9061 case Stmt::CharacterLiteralClass: 9062 case Stmt::ObjCBoolLiteralExprClass: 9063 case Stmt::CXXBoolLiteralExprClass: 9064 // "numeric literal" 9065 return LK_Numeric; 9066 case Stmt::ImplicitCastExprClass: { 9067 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9068 // Boolean literals can be represented by implicit casts. 9069 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9070 return LK_Numeric; 9071 break; 9072 } 9073 default: 9074 break; 9075 } 9076 return LK_Boxed; 9077 } 9078 } 9079 return LK_None; 9080 } 9081 9082 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9083 ExprResult &LHS, ExprResult &RHS, 9084 BinaryOperator::Opcode Opc){ 9085 Expr *Literal; 9086 Expr *Other; 9087 if (isObjCObjectLiteral(LHS)) { 9088 Literal = LHS.get(); 9089 Other = RHS.get(); 9090 } else { 9091 Literal = RHS.get(); 9092 Other = LHS.get(); 9093 } 9094 9095 // Don't warn on comparisons against nil. 9096 Other = Other->IgnoreParenCasts(); 9097 if (Other->isNullPointerConstant(S.getASTContext(), 9098 Expr::NPC_ValueDependentIsNotNull)) 9099 return; 9100 9101 // This should be kept in sync with warn_objc_literal_comparison. 9102 // LK_String should always be after the other literals, since it has its own 9103 // warning flag. 9104 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9105 assert(LiteralKind != Sema::LK_Block); 9106 if (LiteralKind == Sema::LK_None) { 9107 llvm_unreachable("Unknown Objective-C object literal kind"); 9108 } 9109 9110 if (LiteralKind == Sema::LK_String) 9111 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9112 << Literal->getSourceRange(); 9113 else 9114 S.Diag(Loc, diag::warn_objc_literal_comparison) 9115 << LiteralKind << Literal->getSourceRange(); 9116 9117 if (BinaryOperator::isEqualityOp(Opc) && 9118 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9119 SourceLocation Start = LHS.get()->getLocStart(); 9120 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9121 CharSourceRange OpRange = 9122 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9123 9124 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9125 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9126 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9127 << FixItHint::CreateInsertion(End, "]"); 9128 } 9129 } 9130 9131 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9132 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9133 ExprResult &RHS, SourceLocation Loc, 9134 BinaryOperatorKind Opc) { 9135 // Check that left hand side is !something. 9136 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9137 if (!UO || UO->getOpcode() != UO_LNot) return; 9138 9139 // Only check if the right hand side is non-bool arithmetic type. 9140 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9141 9142 // Make sure that the something in !something is not bool. 9143 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9144 if (SubExpr->isKnownToHaveBooleanValue()) return; 9145 9146 // Emit warning. 9147 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9148 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9149 << Loc << IsBitwiseOp; 9150 9151 // First note suggest !(x < y) 9152 SourceLocation FirstOpen = SubExpr->getLocStart(); 9153 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9154 FirstClose = S.getLocForEndOfToken(FirstClose); 9155 if (FirstClose.isInvalid()) 9156 FirstOpen = SourceLocation(); 9157 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9158 << IsBitwiseOp 9159 << FixItHint::CreateInsertion(FirstOpen, "(") 9160 << FixItHint::CreateInsertion(FirstClose, ")"); 9161 9162 // Second note suggests (!x) < y 9163 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9164 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9165 SecondClose = S.getLocForEndOfToken(SecondClose); 9166 if (SecondClose.isInvalid()) 9167 SecondOpen = SourceLocation(); 9168 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9169 << FixItHint::CreateInsertion(SecondOpen, "(") 9170 << FixItHint::CreateInsertion(SecondClose, ")"); 9171 } 9172 9173 // Get the decl for a simple expression: a reference to a variable, 9174 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9175 static ValueDecl *getCompareDecl(Expr *E) { 9176 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9177 return DR->getDecl(); 9178 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9179 if (Ivar->isFreeIvar()) 9180 return Ivar->getDecl(); 9181 } 9182 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9183 if (Mem->isImplicitAccess()) 9184 return Mem->getMemberDecl(); 9185 } 9186 return nullptr; 9187 } 9188 9189 // C99 6.5.8, C++ [expr.rel] 9190 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9191 SourceLocation Loc, BinaryOperatorKind Opc, 9192 bool IsRelational) { 9193 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9194 9195 // Handle vector comparisons separately. 9196 if (LHS.get()->getType()->isVectorType() || 9197 RHS.get()->getType()->isVectorType()) 9198 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9199 9200 QualType LHSType = LHS.get()->getType(); 9201 QualType RHSType = RHS.get()->getType(); 9202 9203 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9204 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9205 9206 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9207 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9208 9209 if (!LHSType->hasFloatingRepresentation() && 9210 !(LHSType->isBlockPointerType() && IsRelational) && 9211 !LHS.get()->getLocStart().isMacroID() && 9212 !RHS.get()->getLocStart().isMacroID() && 9213 ActiveTemplateInstantiations.empty()) { 9214 // For non-floating point types, check for self-comparisons of the form 9215 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9216 // often indicate logic errors in the program. 9217 // 9218 // NOTE: Don't warn about comparison expressions resulting from macro 9219 // expansion. Also don't warn about comparisons which are only self 9220 // comparisons within a template specialization. The warnings should catch 9221 // obvious cases in the definition of the template anyways. The idea is to 9222 // warn when the typed comparison operator will always evaluate to the same 9223 // result. 9224 ValueDecl *DL = getCompareDecl(LHSStripped); 9225 ValueDecl *DR = getCompareDecl(RHSStripped); 9226 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9227 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9228 << 0 // self- 9229 << (Opc == BO_EQ 9230 || Opc == BO_LE 9231 || Opc == BO_GE)); 9232 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9233 !DL->getType()->isReferenceType() && 9234 !DR->getType()->isReferenceType()) { 9235 // what is it always going to eval to? 9236 char always_evals_to; 9237 switch(Opc) { 9238 case BO_EQ: // e.g. array1 == array2 9239 always_evals_to = 0; // false 9240 break; 9241 case BO_NE: // e.g. array1 != array2 9242 always_evals_to = 1; // true 9243 break; 9244 default: 9245 // best we can say is 'a constant' 9246 always_evals_to = 2; // e.g. array1 <= array2 9247 break; 9248 } 9249 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9250 << 1 // array 9251 << always_evals_to); 9252 } 9253 9254 if (isa<CastExpr>(LHSStripped)) 9255 LHSStripped = LHSStripped->IgnoreParenCasts(); 9256 if (isa<CastExpr>(RHSStripped)) 9257 RHSStripped = RHSStripped->IgnoreParenCasts(); 9258 9259 // Warn about comparisons against a string constant (unless the other 9260 // operand is null), the user probably wants strcmp. 9261 Expr *literalString = nullptr; 9262 Expr *literalStringStripped = nullptr; 9263 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9264 !RHSStripped->isNullPointerConstant(Context, 9265 Expr::NPC_ValueDependentIsNull)) { 9266 literalString = LHS.get(); 9267 literalStringStripped = LHSStripped; 9268 } else if ((isa<StringLiteral>(RHSStripped) || 9269 isa<ObjCEncodeExpr>(RHSStripped)) && 9270 !LHSStripped->isNullPointerConstant(Context, 9271 Expr::NPC_ValueDependentIsNull)) { 9272 literalString = RHS.get(); 9273 literalStringStripped = RHSStripped; 9274 } 9275 9276 if (literalString) { 9277 DiagRuntimeBehavior(Loc, nullptr, 9278 PDiag(diag::warn_stringcompare) 9279 << isa<ObjCEncodeExpr>(literalStringStripped) 9280 << literalString->getSourceRange()); 9281 } 9282 } 9283 9284 // C99 6.5.8p3 / C99 6.5.9p4 9285 UsualArithmeticConversions(LHS, RHS); 9286 if (LHS.isInvalid() || RHS.isInvalid()) 9287 return QualType(); 9288 9289 LHSType = LHS.get()->getType(); 9290 RHSType = RHS.get()->getType(); 9291 9292 // The result of comparisons is 'bool' in C++, 'int' in C. 9293 QualType ResultTy = Context.getLogicalOperationType(); 9294 9295 if (IsRelational) { 9296 if (LHSType->isRealType() && RHSType->isRealType()) 9297 return ResultTy; 9298 } else { 9299 // Check for comparisons of floating point operands using != and ==. 9300 if (LHSType->hasFloatingRepresentation()) 9301 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9302 9303 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9304 return ResultTy; 9305 } 9306 9307 const Expr::NullPointerConstantKind LHSNullKind = 9308 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9309 const Expr::NullPointerConstantKind RHSNullKind = 9310 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9311 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9312 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9313 9314 if (!IsRelational && LHSIsNull != RHSIsNull) { 9315 bool IsEquality = Opc == BO_EQ; 9316 if (RHSIsNull) 9317 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9318 RHS.get()->getSourceRange()); 9319 else 9320 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9321 LHS.get()->getSourceRange()); 9322 } 9323 9324 if ((LHSType->isIntegerType() && !LHSIsNull) || 9325 (RHSType->isIntegerType() && !RHSIsNull)) { 9326 // Skip normal pointer conversion checks in this case; we have better 9327 // diagnostics for this below. 9328 } else if (getLangOpts().CPlusPlus) { 9329 // Equality comparison of a function pointer to a void pointer is invalid, 9330 // but we allow it as an extension. 9331 // FIXME: If we really want to allow this, should it be part of composite 9332 // pointer type computation so it works in conditionals too? 9333 if (!IsRelational && 9334 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9335 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9336 // This is a gcc extension compatibility comparison. 9337 // In a SFINAE context, we treat this as a hard error to maintain 9338 // conformance with the C++ standard. 9339 diagnoseFunctionPointerToVoidComparison( 9340 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9341 9342 if (isSFINAEContext()) 9343 return QualType(); 9344 9345 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9346 return ResultTy; 9347 } 9348 9349 // C++ [expr.eq]p2: 9350 // If at least one operand is a pointer [...] bring them to their 9351 // composite pointer type. 9352 // C++ [expr.rel]p2: 9353 // If both operands are pointers, [...] bring them to their composite 9354 // pointer type. 9355 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9356 (IsRelational ? 2 : 1)) { 9357 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9358 return QualType(); 9359 else 9360 return ResultTy; 9361 } 9362 } else if (LHSType->isPointerType() && 9363 RHSType->isPointerType()) { // C99 6.5.8p2 9364 // All of the following pointer-related warnings are GCC extensions, except 9365 // when handling null pointer constants. 9366 QualType LCanPointeeTy = 9367 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9368 QualType RCanPointeeTy = 9369 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9370 9371 // C99 6.5.9p2 and C99 6.5.8p2 9372 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9373 RCanPointeeTy.getUnqualifiedType())) { 9374 // Valid unless a relational comparison of function pointers 9375 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9376 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9377 << LHSType << RHSType << LHS.get()->getSourceRange() 9378 << RHS.get()->getSourceRange(); 9379 } 9380 } else if (!IsRelational && 9381 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9382 // Valid unless comparison between non-null pointer and function pointer 9383 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9384 && !LHSIsNull && !RHSIsNull) 9385 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9386 /*isError*/false); 9387 } else { 9388 // Invalid 9389 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9390 } 9391 if (LCanPointeeTy != RCanPointeeTy) { 9392 // Treat NULL constant as a special case in OpenCL. 9393 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9394 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9395 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9396 Diag(Loc, 9397 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9398 << LHSType << RHSType << 0 /* comparison */ 9399 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9400 } 9401 } 9402 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9403 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9404 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9405 : CK_BitCast; 9406 if (LHSIsNull && !RHSIsNull) 9407 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9408 else 9409 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9410 } 9411 return ResultTy; 9412 } 9413 9414 if (getLangOpts().CPlusPlus) { 9415 // C++ [expr.eq]p4: 9416 // Two operands of type std::nullptr_t or one operand of type 9417 // std::nullptr_t and the other a null pointer constant compare equal. 9418 if (!IsRelational && LHSIsNull && RHSIsNull) { 9419 if (LHSType->isNullPtrType()) { 9420 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9421 return ResultTy; 9422 } 9423 if (RHSType->isNullPtrType()) { 9424 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9425 return ResultTy; 9426 } 9427 } 9428 9429 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9430 // These aren't covered by the composite pointer type rules. 9431 if (!IsRelational && RHSType->isNullPtrType() && 9432 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9433 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9434 return ResultTy; 9435 } 9436 if (!IsRelational && LHSType->isNullPtrType() && 9437 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9438 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9439 return ResultTy; 9440 } 9441 9442 if (IsRelational && 9443 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9444 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9445 // HACK: Relational comparison of nullptr_t against a pointer type is 9446 // invalid per DR583, but we allow it within std::less<> and friends, 9447 // since otherwise common uses of it break. 9448 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9449 // friends to have std::nullptr_t overload candidates. 9450 DeclContext *DC = CurContext; 9451 if (isa<FunctionDecl>(DC)) 9452 DC = DC->getParent(); 9453 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9454 if (CTSD->isInStdNamespace() && 9455 llvm::StringSwitch<bool>(CTSD->getName()) 9456 .Cases("less", "less_equal", "greater", "greater_equal", true) 9457 .Default(false)) { 9458 if (RHSType->isNullPtrType()) 9459 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9460 else 9461 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9462 return ResultTy; 9463 } 9464 } 9465 } 9466 9467 // C++ [expr.eq]p2: 9468 // If at least one operand is a pointer to member, [...] bring them to 9469 // their composite pointer type. 9470 if (!IsRelational && 9471 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9472 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9473 return QualType(); 9474 else 9475 return ResultTy; 9476 } 9477 9478 // Handle scoped enumeration types specifically, since they don't promote 9479 // to integers. 9480 if (LHS.get()->getType()->isEnumeralType() && 9481 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9482 RHS.get()->getType())) 9483 return ResultTy; 9484 } 9485 9486 // Handle block pointer types. 9487 if (!IsRelational && LHSType->isBlockPointerType() && 9488 RHSType->isBlockPointerType()) { 9489 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9490 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9491 9492 if (!LHSIsNull && !RHSIsNull && 9493 !Context.typesAreCompatible(lpointee, rpointee)) { 9494 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9495 << LHSType << RHSType << LHS.get()->getSourceRange() 9496 << RHS.get()->getSourceRange(); 9497 } 9498 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9499 return ResultTy; 9500 } 9501 9502 // Allow block pointers to be compared with null pointer constants. 9503 if (!IsRelational 9504 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9505 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9506 if (!LHSIsNull && !RHSIsNull) { 9507 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9508 ->getPointeeType()->isVoidType()) 9509 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9510 ->getPointeeType()->isVoidType()))) 9511 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9512 << LHSType << RHSType << LHS.get()->getSourceRange() 9513 << RHS.get()->getSourceRange(); 9514 } 9515 if (LHSIsNull && !RHSIsNull) 9516 LHS = ImpCastExprToType(LHS.get(), RHSType, 9517 RHSType->isPointerType() ? CK_BitCast 9518 : CK_AnyPointerToBlockPointerCast); 9519 else 9520 RHS = ImpCastExprToType(RHS.get(), LHSType, 9521 LHSType->isPointerType() ? CK_BitCast 9522 : CK_AnyPointerToBlockPointerCast); 9523 return ResultTy; 9524 } 9525 9526 if (LHSType->isObjCObjectPointerType() || 9527 RHSType->isObjCObjectPointerType()) { 9528 const PointerType *LPT = LHSType->getAs<PointerType>(); 9529 const PointerType *RPT = RHSType->getAs<PointerType>(); 9530 if (LPT || RPT) { 9531 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9532 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9533 9534 if (!LPtrToVoid && !RPtrToVoid && 9535 !Context.typesAreCompatible(LHSType, RHSType)) { 9536 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9537 /*isError*/false); 9538 } 9539 if (LHSIsNull && !RHSIsNull) { 9540 Expr *E = LHS.get(); 9541 if (getLangOpts().ObjCAutoRefCount) 9542 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9543 LHS = ImpCastExprToType(E, RHSType, 9544 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9545 } 9546 else { 9547 Expr *E = RHS.get(); 9548 if (getLangOpts().ObjCAutoRefCount) 9549 CheckObjCARCConversion(SourceRange(), LHSType, E, 9550 CCK_ImplicitConversion, /*Diagnose=*/true, 9551 /*DiagnoseCFAudited=*/false, Opc); 9552 RHS = ImpCastExprToType(E, LHSType, 9553 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9554 } 9555 return ResultTy; 9556 } 9557 if (LHSType->isObjCObjectPointerType() && 9558 RHSType->isObjCObjectPointerType()) { 9559 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9560 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9561 /*isError*/false); 9562 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9563 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9564 9565 if (LHSIsNull && !RHSIsNull) 9566 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9567 else 9568 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9569 return ResultTy; 9570 } 9571 } 9572 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9573 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9574 unsigned DiagID = 0; 9575 bool isError = false; 9576 if (LangOpts.DebuggerSupport) { 9577 // Under a debugger, allow the comparison of pointers to integers, 9578 // since users tend to want to compare addresses. 9579 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9580 (RHSIsNull && RHSType->isIntegerType())) { 9581 if (IsRelational) { 9582 isError = getLangOpts().CPlusPlus; 9583 DiagID = 9584 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9585 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9586 } 9587 } else if (getLangOpts().CPlusPlus) { 9588 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9589 isError = true; 9590 } else if (IsRelational) 9591 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9592 else 9593 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9594 9595 if (DiagID) { 9596 Diag(Loc, DiagID) 9597 << LHSType << RHSType << LHS.get()->getSourceRange() 9598 << RHS.get()->getSourceRange(); 9599 if (isError) 9600 return QualType(); 9601 } 9602 9603 if (LHSType->isIntegerType()) 9604 LHS = ImpCastExprToType(LHS.get(), RHSType, 9605 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9606 else 9607 RHS = ImpCastExprToType(RHS.get(), LHSType, 9608 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9609 return ResultTy; 9610 } 9611 9612 // Handle block pointers. 9613 if (!IsRelational && RHSIsNull 9614 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9615 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9616 return ResultTy; 9617 } 9618 if (!IsRelational && LHSIsNull 9619 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9620 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9621 return ResultTy; 9622 } 9623 9624 return InvalidOperands(Loc, LHS, RHS); 9625 } 9626 9627 9628 // Return a signed type that is of identical size and number of elements. 9629 // For floating point vectors, return an integer type of identical size 9630 // and number of elements. 9631 QualType Sema::GetSignedVectorType(QualType V) { 9632 const VectorType *VTy = V->getAs<VectorType>(); 9633 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9634 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9635 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9636 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9637 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9638 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9639 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9640 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9641 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9642 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9643 "Unhandled vector element size in vector compare"); 9644 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9645 } 9646 9647 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9648 /// operates on extended vector types. Instead of producing an IntTy result, 9649 /// like a scalar comparison, a vector comparison produces a vector of integer 9650 /// types. 9651 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9652 SourceLocation Loc, 9653 bool IsRelational) { 9654 // Check to make sure we're operating on vectors of the same type and width, 9655 // Allowing one side to be a scalar of element type. 9656 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9657 /*AllowBothBool*/true, 9658 /*AllowBoolConversions*/getLangOpts().ZVector); 9659 if (vType.isNull()) 9660 return vType; 9661 9662 QualType LHSType = LHS.get()->getType(); 9663 9664 // If AltiVec, the comparison results in a numeric type, i.e. 9665 // bool for C++, int for C 9666 if (getLangOpts().AltiVec && 9667 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9668 return Context.getLogicalOperationType(); 9669 9670 // For non-floating point types, check for self-comparisons of the form 9671 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9672 // often indicate logic errors in the program. 9673 if (!LHSType->hasFloatingRepresentation() && 9674 ActiveTemplateInstantiations.empty()) { 9675 if (DeclRefExpr* DRL 9676 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9677 if (DeclRefExpr* DRR 9678 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9679 if (DRL->getDecl() == DRR->getDecl()) 9680 DiagRuntimeBehavior(Loc, nullptr, 9681 PDiag(diag::warn_comparison_always) 9682 << 0 // self- 9683 << 2 // "a constant" 9684 ); 9685 } 9686 9687 // Check for comparisons of floating point operands using != and ==. 9688 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9689 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9690 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9691 } 9692 9693 // Return a signed type for the vector. 9694 return GetSignedVectorType(vType); 9695 } 9696 9697 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9698 SourceLocation Loc) { 9699 // Ensure that either both operands are of the same vector type, or 9700 // one operand is of a vector type and the other is of its element type. 9701 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9702 /*AllowBothBool*/true, 9703 /*AllowBoolConversions*/false); 9704 if (vType.isNull()) 9705 return InvalidOperands(Loc, LHS, RHS); 9706 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9707 vType->hasFloatingRepresentation()) 9708 return InvalidOperands(Loc, LHS, RHS); 9709 9710 return GetSignedVectorType(LHS.get()->getType()); 9711 } 9712 9713 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 9714 SourceLocation Loc, 9715 BinaryOperatorKind Opc) { 9716 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9717 9718 bool IsCompAssign = 9719 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 9720 9721 if (LHS.get()->getType()->isVectorType() || 9722 RHS.get()->getType()->isVectorType()) { 9723 if (LHS.get()->getType()->hasIntegerRepresentation() && 9724 RHS.get()->getType()->hasIntegerRepresentation()) 9725 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9726 /*AllowBothBool*/true, 9727 /*AllowBoolConversions*/getLangOpts().ZVector); 9728 return InvalidOperands(Loc, LHS, RHS); 9729 } 9730 9731 if (Opc == BO_And) 9732 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9733 9734 ExprResult LHSResult = LHS, RHSResult = RHS; 9735 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9736 IsCompAssign); 9737 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9738 return QualType(); 9739 LHS = LHSResult.get(); 9740 RHS = RHSResult.get(); 9741 9742 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9743 return compType; 9744 return InvalidOperands(Loc, LHS, RHS); 9745 } 9746 9747 // C99 6.5.[13,14] 9748 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9749 SourceLocation Loc, 9750 BinaryOperatorKind Opc) { 9751 // Check vector operands differently. 9752 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9753 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9754 9755 // Diagnose cases where the user write a logical and/or but probably meant a 9756 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9757 // is a constant. 9758 if (LHS.get()->getType()->isIntegerType() && 9759 !LHS.get()->getType()->isBooleanType() && 9760 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9761 // Don't warn in macros or template instantiations. 9762 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9763 // If the RHS can be constant folded, and if it constant folds to something 9764 // that isn't 0 or 1 (which indicate a potential logical operation that 9765 // happened to fold to true/false) then warn. 9766 // Parens on the RHS are ignored. 9767 llvm::APSInt Result; 9768 if (RHS.get()->EvaluateAsInt(Result, Context)) 9769 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9770 !RHS.get()->getExprLoc().isMacroID()) || 9771 (Result != 0 && Result != 1)) { 9772 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9773 << RHS.get()->getSourceRange() 9774 << (Opc == BO_LAnd ? "&&" : "||"); 9775 // Suggest replacing the logical operator with the bitwise version 9776 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9777 << (Opc == BO_LAnd ? "&" : "|") 9778 << FixItHint::CreateReplacement(SourceRange( 9779 Loc, getLocForEndOfToken(Loc)), 9780 Opc == BO_LAnd ? "&" : "|"); 9781 if (Opc == BO_LAnd) 9782 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9783 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9784 << FixItHint::CreateRemoval( 9785 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9786 RHS.get()->getLocEnd())); 9787 } 9788 } 9789 9790 if (!Context.getLangOpts().CPlusPlus) { 9791 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9792 // not operate on the built-in scalar and vector float types. 9793 if (Context.getLangOpts().OpenCL && 9794 Context.getLangOpts().OpenCLVersion < 120) { 9795 if (LHS.get()->getType()->isFloatingType() || 9796 RHS.get()->getType()->isFloatingType()) 9797 return InvalidOperands(Loc, LHS, RHS); 9798 } 9799 9800 LHS = UsualUnaryConversions(LHS.get()); 9801 if (LHS.isInvalid()) 9802 return QualType(); 9803 9804 RHS = UsualUnaryConversions(RHS.get()); 9805 if (RHS.isInvalid()) 9806 return QualType(); 9807 9808 if (!LHS.get()->getType()->isScalarType() || 9809 !RHS.get()->getType()->isScalarType()) 9810 return InvalidOperands(Loc, LHS, RHS); 9811 9812 return Context.IntTy; 9813 } 9814 9815 // The following is safe because we only use this method for 9816 // non-overloadable operands. 9817 9818 // C++ [expr.log.and]p1 9819 // C++ [expr.log.or]p1 9820 // The operands are both contextually converted to type bool. 9821 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9822 if (LHSRes.isInvalid()) 9823 return InvalidOperands(Loc, LHS, RHS); 9824 LHS = LHSRes; 9825 9826 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9827 if (RHSRes.isInvalid()) 9828 return InvalidOperands(Loc, LHS, RHS); 9829 RHS = RHSRes; 9830 9831 // C++ [expr.log.and]p2 9832 // C++ [expr.log.or]p2 9833 // The result is a bool. 9834 return Context.BoolTy; 9835 } 9836 9837 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9838 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9839 if (!ME) return false; 9840 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9841 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 9842 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 9843 if (!Base) return false; 9844 return Base->getMethodDecl() != nullptr; 9845 } 9846 9847 /// Is the given expression (which must be 'const') a reference to a 9848 /// variable which was originally non-const, but which has become 9849 /// 'const' due to being captured within a block? 9850 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9851 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9852 assert(E->isLValue() && E->getType().isConstQualified()); 9853 E = E->IgnoreParens(); 9854 9855 // Must be a reference to a declaration from an enclosing scope. 9856 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9857 if (!DRE) return NCCK_None; 9858 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9859 9860 // The declaration must be a variable which is not declared 'const'. 9861 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9862 if (!var) return NCCK_None; 9863 if (var->getType().isConstQualified()) return NCCK_None; 9864 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9865 9866 // Decide whether the first capture was for a block or a lambda. 9867 DeclContext *DC = S.CurContext, *Prev = nullptr; 9868 // Decide whether the first capture was for a block or a lambda. 9869 while (DC) { 9870 // For init-capture, it is possible that the variable belongs to the 9871 // template pattern of the current context. 9872 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9873 if (var->isInitCapture() && 9874 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9875 break; 9876 if (DC == var->getDeclContext()) 9877 break; 9878 Prev = DC; 9879 DC = DC->getParent(); 9880 } 9881 // Unless we have an init-capture, we've gone one step too far. 9882 if (!var->isInitCapture()) 9883 DC = Prev; 9884 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9885 } 9886 9887 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9888 Ty = Ty.getNonReferenceType(); 9889 if (IsDereference && Ty->isPointerType()) 9890 Ty = Ty->getPointeeType(); 9891 return !Ty.isConstQualified(); 9892 } 9893 9894 /// Emit the "read-only variable not assignable" error and print notes to give 9895 /// more information about why the variable is not assignable, such as pointing 9896 /// to the declaration of a const variable, showing that a method is const, or 9897 /// that the function is returning a const reference. 9898 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9899 SourceLocation Loc) { 9900 // Update err_typecheck_assign_const and note_typecheck_assign_const 9901 // when this enum is changed. 9902 enum { 9903 ConstFunction, 9904 ConstVariable, 9905 ConstMember, 9906 ConstMethod, 9907 ConstUnknown, // Keep as last element 9908 }; 9909 9910 SourceRange ExprRange = E->getSourceRange(); 9911 9912 // Only emit one error on the first const found. All other consts will emit 9913 // a note to the error. 9914 bool DiagnosticEmitted = false; 9915 9916 // Track if the current expression is the result of a dereference, and if the 9917 // next checked expression is the result of a dereference. 9918 bool IsDereference = false; 9919 bool NextIsDereference = false; 9920 9921 // Loop to process MemberExpr chains. 9922 while (true) { 9923 IsDereference = NextIsDereference; 9924 9925 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 9926 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9927 NextIsDereference = ME->isArrow(); 9928 const ValueDecl *VD = ME->getMemberDecl(); 9929 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9930 // Mutable fields can be modified even if the class is const. 9931 if (Field->isMutable()) { 9932 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9933 break; 9934 } 9935 9936 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9937 if (!DiagnosticEmitted) { 9938 S.Diag(Loc, diag::err_typecheck_assign_const) 9939 << ExprRange << ConstMember << false /*static*/ << Field 9940 << Field->getType(); 9941 DiagnosticEmitted = true; 9942 } 9943 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9944 << ConstMember << false /*static*/ << Field << Field->getType() 9945 << Field->getSourceRange(); 9946 } 9947 E = ME->getBase(); 9948 continue; 9949 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9950 if (VDecl->getType().isConstQualified()) { 9951 if (!DiagnosticEmitted) { 9952 S.Diag(Loc, diag::err_typecheck_assign_const) 9953 << ExprRange << ConstMember << true /*static*/ << VDecl 9954 << VDecl->getType(); 9955 DiagnosticEmitted = true; 9956 } 9957 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9958 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9959 << VDecl->getSourceRange(); 9960 } 9961 // Static fields do not inherit constness from parents. 9962 break; 9963 } 9964 break; 9965 } // End MemberExpr 9966 break; 9967 } 9968 9969 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9970 // Function calls 9971 const FunctionDecl *FD = CE->getDirectCallee(); 9972 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9973 if (!DiagnosticEmitted) { 9974 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9975 << ConstFunction << FD; 9976 DiagnosticEmitted = true; 9977 } 9978 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9979 diag::note_typecheck_assign_const) 9980 << ConstFunction << FD << FD->getReturnType() 9981 << FD->getReturnTypeSourceRange(); 9982 } 9983 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9984 // Point to variable declaration. 9985 if (const ValueDecl *VD = DRE->getDecl()) { 9986 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9987 if (!DiagnosticEmitted) { 9988 S.Diag(Loc, diag::err_typecheck_assign_const) 9989 << ExprRange << ConstVariable << VD << VD->getType(); 9990 DiagnosticEmitted = true; 9991 } 9992 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9993 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9994 } 9995 } 9996 } else if (isa<CXXThisExpr>(E)) { 9997 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9998 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9999 if (MD->isConst()) { 10000 if (!DiagnosticEmitted) { 10001 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10002 << ConstMethod << MD; 10003 DiagnosticEmitted = true; 10004 } 10005 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10006 << ConstMethod << MD << MD->getSourceRange(); 10007 } 10008 } 10009 } 10010 } 10011 10012 if (DiagnosticEmitted) 10013 return; 10014 10015 // Can't determine a more specific message, so display the generic error. 10016 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10017 } 10018 10019 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10020 /// emit an error and return true. If so, return false. 10021 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10022 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10023 10024 S.CheckShadowingDeclModification(E, Loc); 10025 10026 SourceLocation OrigLoc = Loc; 10027 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10028 &Loc); 10029 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10030 IsLV = Expr::MLV_InvalidMessageExpression; 10031 if (IsLV == Expr::MLV_Valid) 10032 return false; 10033 10034 unsigned DiagID = 0; 10035 bool NeedType = false; 10036 switch (IsLV) { // C99 6.5.16p2 10037 case Expr::MLV_ConstQualified: 10038 // Use a specialized diagnostic when we're assigning to an object 10039 // from an enclosing function or block. 10040 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10041 if (NCCK == NCCK_Block) 10042 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10043 else 10044 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10045 break; 10046 } 10047 10048 // In ARC, use some specialized diagnostics for occasions where we 10049 // infer 'const'. These are always pseudo-strong variables. 10050 if (S.getLangOpts().ObjCAutoRefCount) { 10051 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10052 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10053 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10054 10055 // Use the normal diagnostic if it's pseudo-__strong but the 10056 // user actually wrote 'const'. 10057 if (var->isARCPseudoStrong() && 10058 (!var->getTypeSourceInfo() || 10059 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10060 // There are two pseudo-strong cases: 10061 // - self 10062 ObjCMethodDecl *method = S.getCurMethodDecl(); 10063 if (method && var == method->getSelfDecl()) 10064 DiagID = method->isClassMethod() 10065 ? diag::err_typecheck_arc_assign_self_class_method 10066 : diag::err_typecheck_arc_assign_self; 10067 10068 // - fast enumeration variables 10069 else 10070 DiagID = diag::err_typecheck_arr_assign_enumeration; 10071 10072 SourceRange Assign; 10073 if (Loc != OrigLoc) 10074 Assign = SourceRange(OrigLoc, OrigLoc); 10075 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10076 // We need to preserve the AST regardless, so migration tool 10077 // can do its job. 10078 return false; 10079 } 10080 } 10081 } 10082 10083 // If none of the special cases above are triggered, then this is a 10084 // simple const assignment. 10085 if (DiagID == 0) { 10086 DiagnoseConstAssignment(S, E, Loc); 10087 return true; 10088 } 10089 10090 break; 10091 case Expr::MLV_ConstAddrSpace: 10092 DiagnoseConstAssignment(S, E, Loc); 10093 return true; 10094 case Expr::MLV_ArrayType: 10095 case Expr::MLV_ArrayTemporary: 10096 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10097 NeedType = true; 10098 break; 10099 case Expr::MLV_NotObjectType: 10100 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10101 NeedType = true; 10102 break; 10103 case Expr::MLV_LValueCast: 10104 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10105 break; 10106 case Expr::MLV_Valid: 10107 llvm_unreachable("did not take early return for MLV_Valid"); 10108 case Expr::MLV_InvalidExpression: 10109 case Expr::MLV_MemberFunction: 10110 case Expr::MLV_ClassTemporary: 10111 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10112 break; 10113 case Expr::MLV_IncompleteType: 10114 case Expr::MLV_IncompleteVoidType: 10115 return S.RequireCompleteType(Loc, E->getType(), 10116 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10117 case Expr::MLV_DuplicateVectorComponents: 10118 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10119 break; 10120 case Expr::MLV_NoSetterProperty: 10121 llvm_unreachable("readonly properties should be processed differently"); 10122 case Expr::MLV_InvalidMessageExpression: 10123 DiagID = diag::err_readonly_message_assignment; 10124 break; 10125 case Expr::MLV_SubObjCPropertySetting: 10126 DiagID = diag::err_no_subobject_property_setting; 10127 break; 10128 } 10129 10130 SourceRange Assign; 10131 if (Loc != OrigLoc) 10132 Assign = SourceRange(OrigLoc, OrigLoc); 10133 if (NeedType) 10134 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10135 else 10136 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10137 return true; 10138 } 10139 10140 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10141 SourceLocation Loc, 10142 Sema &Sema) { 10143 // C / C++ fields 10144 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10145 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10146 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10147 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10148 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10149 } 10150 10151 // Objective-C instance variables 10152 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10153 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10154 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10155 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10156 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10157 if (RL && RR && RL->getDecl() == RR->getDecl()) 10158 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10159 } 10160 } 10161 10162 // C99 6.5.16.1 10163 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10164 SourceLocation Loc, 10165 QualType CompoundType) { 10166 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10167 10168 // Verify that LHS is a modifiable lvalue, and emit error if not. 10169 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10170 return QualType(); 10171 10172 QualType LHSType = LHSExpr->getType(); 10173 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10174 CompoundType; 10175 // OpenCL v1.2 s6.1.1.1 p2: 10176 // The half data type can only be used to declare a pointer to a buffer that 10177 // contains half values 10178 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 10179 LHSType->isHalfType()) { 10180 Diag(Loc, diag::err_opencl_half_load_store) << 1 10181 << LHSType.getUnqualifiedType(); 10182 return QualType(); 10183 } 10184 10185 AssignConvertType ConvTy; 10186 if (CompoundType.isNull()) { 10187 Expr *RHSCheck = RHS.get(); 10188 10189 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10190 10191 QualType LHSTy(LHSType); 10192 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10193 if (RHS.isInvalid()) 10194 return QualType(); 10195 // Special case of NSObject attributes on c-style pointer types. 10196 if (ConvTy == IncompatiblePointer && 10197 ((Context.isObjCNSObjectType(LHSType) && 10198 RHSType->isObjCObjectPointerType()) || 10199 (Context.isObjCNSObjectType(RHSType) && 10200 LHSType->isObjCObjectPointerType()))) 10201 ConvTy = Compatible; 10202 10203 if (ConvTy == Compatible && 10204 LHSType->isObjCObjectType()) 10205 Diag(Loc, diag::err_objc_object_assignment) 10206 << LHSType; 10207 10208 // If the RHS is a unary plus or minus, check to see if they = and + are 10209 // right next to each other. If so, the user may have typo'd "x =+ 4" 10210 // instead of "x += 4". 10211 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10212 RHSCheck = ICE->getSubExpr(); 10213 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10214 if ((UO->getOpcode() == UO_Plus || 10215 UO->getOpcode() == UO_Minus) && 10216 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10217 // Only if the two operators are exactly adjacent. 10218 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10219 // And there is a space or other character before the subexpr of the 10220 // unary +/-. We don't want to warn on "x=-1". 10221 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10222 UO->getSubExpr()->getLocStart().isFileID()) { 10223 Diag(Loc, diag::warn_not_compound_assign) 10224 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10225 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10226 } 10227 } 10228 10229 if (ConvTy == Compatible) { 10230 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10231 // Warn about retain cycles where a block captures the LHS, but 10232 // not if the LHS is a simple variable into which the block is 10233 // being stored...unless that variable can be captured by reference! 10234 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10235 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10236 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10237 checkRetainCycles(LHSExpr, RHS.get()); 10238 10239 // It is safe to assign a weak reference into a strong variable. 10240 // Although this code can still have problems: 10241 // id x = self.weakProp; 10242 // id y = self.weakProp; 10243 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10244 // paths through the function. This should be revisited if 10245 // -Wrepeated-use-of-weak is made flow-sensitive. 10246 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10247 RHS.get()->getLocStart())) 10248 getCurFunction()->markSafeWeakUse(RHS.get()); 10249 10250 } else if (getLangOpts().ObjCAutoRefCount) { 10251 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10252 } 10253 } 10254 } else { 10255 // Compound assignment "x += y" 10256 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10257 } 10258 10259 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10260 RHS.get(), AA_Assigning)) 10261 return QualType(); 10262 10263 CheckForNullPointerDereference(*this, LHSExpr); 10264 10265 // C99 6.5.16p3: The type of an assignment expression is the type of the 10266 // left operand unless the left operand has qualified type, in which case 10267 // it is the unqualified version of the type of the left operand. 10268 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10269 // is converted to the type of the assignment expression (above). 10270 // C++ 5.17p1: the type of the assignment expression is that of its left 10271 // operand. 10272 return (getLangOpts().CPlusPlus 10273 ? LHSType : LHSType.getUnqualifiedType()); 10274 } 10275 10276 // Only ignore explicit casts to void. 10277 static bool IgnoreCommaOperand(const Expr *E) { 10278 E = E->IgnoreParens(); 10279 10280 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10281 if (CE->getCastKind() == CK_ToVoid) { 10282 return true; 10283 } 10284 } 10285 10286 return false; 10287 } 10288 10289 // Look for instances where it is likely the comma operator is confused with 10290 // another operator. There is a whitelist of acceptable expressions for the 10291 // left hand side of the comma operator, otherwise emit a warning. 10292 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10293 // No warnings in macros 10294 if (Loc.isMacroID()) 10295 return; 10296 10297 // Don't warn in template instantiations. 10298 if (!ActiveTemplateInstantiations.empty()) 10299 return; 10300 10301 // Scope isn't fine-grained enough to whitelist the specific cases, so 10302 // instead, skip more than needed, then call back into here with the 10303 // CommaVisitor in SemaStmt.cpp. 10304 // The whitelisted locations are the initialization and increment portions 10305 // of a for loop. The additional checks are on the condition of 10306 // if statements, do/while loops, and for loops. 10307 const unsigned ForIncrementFlags = 10308 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10309 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10310 const unsigned ScopeFlags = getCurScope()->getFlags(); 10311 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10312 (ScopeFlags & ForInitFlags) == ForInitFlags) 10313 return; 10314 10315 // If there are multiple comma operators used together, get the RHS of the 10316 // of the comma operator as the LHS. 10317 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10318 if (BO->getOpcode() != BO_Comma) 10319 break; 10320 LHS = BO->getRHS(); 10321 } 10322 10323 // Only allow some expressions on LHS to not warn. 10324 if (IgnoreCommaOperand(LHS)) 10325 return; 10326 10327 Diag(Loc, diag::warn_comma_operator); 10328 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10329 << LHS->getSourceRange() 10330 << FixItHint::CreateInsertion(LHS->getLocStart(), 10331 LangOpts.CPlusPlus ? "static_cast<void>(" 10332 : "(void)(") 10333 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10334 ")"); 10335 } 10336 10337 // C99 6.5.17 10338 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10339 SourceLocation Loc) { 10340 LHS = S.CheckPlaceholderExpr(LHS.get()); 10341 RHS = S.CheckPlaceholderExpr(RHS.get()); 10342 if (LHS.isInvalid() || RHS.isInvalid()) 10343 return QualType(); 10344 10345 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10346 // operands, but not unary promotions. 10347 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10348 10349 // So we treat the LHS as a ignored value, and in C++ we allow the 10350 // containing site to determine what should be done with the RHS. 10351 LHS = S.IgnoredValueConversions(LHS.get()); 10352 if (LHS.isInvalid()) 10353 return QualType(); 10354 10355 S.DiagnoseUnusedExprResult(LHS.get()); 10356 10357 if (!S.getLangOpts().CPlusPlus) { 10358 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10359 if (RHS.isInvalid()) 10360 return QualType(); 10361 if (!RHS.get()->getType()->isVoidType()) 10362 S.RequireCompleteType(Loc, RHS.get()->getType(), 10363 diag::err_incomplete_type); 10364 } 10365 10366 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10367 S.DiagnoseCommaOperator(LHS.get(), Loc); 10368 10369 return RHS.get()->getType(); 10370 } 10371 10372 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10373 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10374 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10375 ExprValueKind &VK, 10376 ExprObjectKind &OK, 10377 SourceLocation OpLoc, 10378 bool IsInc, bool IsPrefix) { 10379 if (Op->isTypeDependent()) 10380 return S.Context.DependentTy; 10381 10382 QualType ResType = Op->getType(); 10383 // Atomic types can be used for increment / decrement where the non-atomic 10384 // versions can, so ignore the _Atomic() specifier for the purpose of 10385 // checking. 10386 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10387 ResType = ResAtomicType->getValueType(); 10388 10389 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10390 10391 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10392 // Decrement of bool is not allowed. 10393 if (!IsInc) { 10394 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10395 return QualType(); 10396 } 10397 // Increment of bool sets it to true, but is deprecated. 10398 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10399 : diag::warn_increment_bool) 10400 << Op->getSourceRange(); 10401 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10402 // Error on enum increments and decrements in C++ mode 10403 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10404 return QualType(); 10405 } else if (ResType->isRealType()) { 10406 // OK! 10407 } else if (ResType->isPointerType()) { 10408 // C99 6.5.2.4p2, 6.5.6p2 10409 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10410 return QualType(); 10411 } else if (ResType->isObjCObjectPointerType()) { 10412 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10413 // Otherwise, we just need a complete type. 10414 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10415 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10416 return QualType(); 10417 } else if (ResType->isAnyComplexType()) { 10418 // C99 does not support ++/-- on complex types, we allow as an extension. 10419 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10420 << ResType << Op->getSourceRange(); 10421 } else if (ResType->isPlaceholderType()) { 10422 ExprResult PR = S.CheckPlaceholderExpr(Op); 10423 if (PR.isInvalid()) return QualType(); 10424 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10425 IsInc, IsPrefix); 10426 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10427 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10428 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10429 (ResType->getAs<VectorType>()->getVectorKind() != 10430 VectorType::AltiVecBool)) { 10431 // The z vector extensions allow ++ and -- for non-bool vectors. 10432 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10433 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10434 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10435 } else { 10436 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10437 << ResType << int(IsInc) << Op->getSourceRange(); 10438 return QualType(); 10439 } 10440 // At this point, we know we have a real, complex or pointer type. 10441 // Now make sure the operand is a modifiable lvalue. 10442 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10443 return QualType(); 10444 // In C++, a prefix increment is the same type as the operand. Otherwise 10445 // (in C or with postfix), the increment is the unqualified type of the 10446 // operand. 10447 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10448 VK = VK_LValue; 10449 OK = Op->getObjectKind(); 10450 return ResType; 10451 } else { 10452 VK = VK_RValue; 10453 return ResType.getUnqualifiedType(); 10454 } 10455 } 10456 10457 10458 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10459 /// This routine allows us to typecheck complex/recursive expressions 10460 /// where the declaration is needed for type checking. We only need to 10461 /// handle cases when the expression references a function designator 10462 /// or is an lvalue. Here are some examples: 10463 /// - &(x) => x 10464 /// - &*****f => f for f a function designator. 10465 /// - &s.xx => s 10466 /// - &s.zz[1].yy -> s, if zz is an array 10467 /// - *(x + 1) -> x, if x is an array 10468 /// - &"123"[2] -> 0 10469 /// - & __real__ x -> x 10470 static ValueDecl *getPrimaryDecl(Expr *E) { 10471 switch (E->getStmtClass()) { 10472 case Stmt::DeclRefExprClass: 10473 return cast<DeclRefExpr>(E)->getDecl(); 10474 case Stmt::MemberExprClass: 10475 // If this is an arrow operator, the address is an offset from 10476 // the base's value, so the object the base refers to is 10477 // irrelevant. 10478 if (cast<MemberExpr>(E)->isArrow()) 10479 return nullptr; 10480 // Otherwise, the expression refers to a part of the base 10481 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10482 case Stmt::ArraySubscriptExprClass: { 10483 // FIXME: This code shouldn't be necessary! We should catch the implicit 10484 // promotion of register arrays earlier. 10485 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10486 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10487 if (ICE->getSubExpr()->getType()->isArrayType()) 10488 return getPrimaryDecl(ICE->getSubExpr()); 10489 } 10490 return nullptr; 10491 } 10492 case Stmt::UnaryOperatorClass: { 10493 UnaryOperator *UO = cast<UnaryOperator>(E); 10494 10495 switch(UO->getOpcode()) { 10496 case UO_Real: 10497 case UO_Imag: 10498 case UO_Extension: 10499 return getPrimaryDecl(UO->getSubExpr()); 10500 default: 10501 return nullptr; 10502 } 10503 } 10504 case Stmt::ParenExprClass: 10505 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10506 case Stmt::ImplicitCastExprClass: 10507 // If the result of an implicit cast is an l-value, we care about 10508 // the sub-expression; otherwise, the result here doesn't matter. 10509 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10510 default: 10511 return nullptr; 10512 } 10513 } 10514 10515 namespace { 10516 enum { 10517 AO_Bit_Field = 0, 10518 AO_Vector_Element = 1, 10519 AO_Property_Expansion = 2, 10520 AO_Register_Variable = 3, 10521 AO_No_Error = 4 10522 }; 10523 } 10524 /// \brief Diagnose invalid operand for address of operations. 10525 /// 10526 /// \param Type The type of operand which cannot have its address taken. 10527 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10528 Expr *E, unsigned Type) { 10529 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10530 } 10531 10532 /// CheckAddressOfOperand - The operand of & must be either a function 10533 /// designator or an lvalue designating an object. If it is an lvalue, the 10534 /// object cannot be declared with storage class register or be a bit field. 10535 /// Note: The usual conversions are *not* applied to the operand of the & 10536 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10537 /// In C++, the operand might be an overloaded function name, in which case 10538 /// we allow the '&' but retain the overloaded-function type. 10539 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10540 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10541 if (PTy->getKind() == BuiltinType::Overload) { 10542 Expr *E = OrigOp.get()->IgnoreParens(); 10543 if (!isa<OverloadExpr>(E)) { 10544 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10545 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10546 << OrigOp.get()->getSourceRange(); 10547 return QualType(); 10548 } 10549 10550 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10551 if (isa<UnresolvedMemberExpr>(Ovl)) 10552 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10553 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10554 << OrigOp.get()->getSourceRange(); 10555 return QualType(); 10556 } 10557 10558 return Context.OverloadTy; 10559 } 10560 10561 if (PTy->getKind() == BuiltinType::UnknownAny) 10562 return Context.UnknownAnyTy; 10563 10564 if (PTy->getKind() == BuiltinType::BoundMember) { 10565 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10566 << OrigOp.get()->getSourceRange(); 10567 return QualType(); 10568 } 10569 10570 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10571 if (OrigOp.isInvalid()) return QualType(); 10572 } 10573 10574 if (OrigOp.get()->isTypeDependent()) 10575 return Context.DependentTy; 10576 10577 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10578 10579 // Make sure to ignore parentheses in subsequent checks 10580 Expr *op = OrigOp.get()->IgnoreParens(); 10581 10582 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10583 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10584 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10585 return QualType(); 10586 } 10587 10588 if (getLangOpts().C99) { 10589 // Implement C99-only parts of addressof rules. 10590 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10591 if (uOp->getOpcode() == UO_Deref) 10592 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10593 // (assuming the deref expression is valid). 10594 return uOp->getSubExpr()->getType(); 10595 } 10596 // Technically, there should be a check for array subscript 10597 // expressions here, but the result of one is always an lvalue anyway. 10598 } 10599 ValueDecl *dcl = getPrimaryDecl(op); 10600 10601 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10602 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10603 op->getLocStart())) 10604 return QualType(); 10605 10606 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10607 unsigned AddressOfError = AO_No_Error; 10608 10609 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10610 bool sfinae = (bool)isSFINAEContext(); 10611 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10612 : diag::ext_typecheck_addrof_temporary) 10613 << op->getType() << op->getSourceRange(); 10614 if (sfinae) 10615 return QualType(); 10616 // Materialize the temporary as an lvalue so that we can take its address. 10617 OrigOp = op = 10618 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10619 } else if (isa<ObjCSelectorExpr>(op)) { 10620 return Context.getPointerType(op->getType()); 10621 } else if (lval == Expr::LV_MemberFunction) { 10622 // If it's an instance method, make a member pointer. 10623 // The expression must have exactly the form &A::foo. 10624 10625 // If the underlying expression isn't a decl ref, give up. 10626 if (!isa<DeclRefExpr>(op)) { 10627 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10628 << OrigOp.get()->getSourceRange(); 10629 return QualType(); 10630 } 10631 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10632 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10633 10634 // The id-expression was parenthesized. 10635 if (OrigOp.get() != DRE) { 10636 Diag(OpLoc, diag::err_parens_pointer_member_function) 10637 << OrigOp.get()->getSourceRange(); 10638 10639 // The method was named without a qualifier. 10640 } else if (!DRE->getQualifier()) { 10641 if (MD->getParent()->getName().empty()) 10642 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10643 << op->getSourceRange(); 10644 else { 10645 SmallString<32> Str; 10646 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10647 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10648 << op->getSourceRange() 10649 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10650 } 10651 } 10652 10653 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10654 if (isa<CXXDestructorDecl>(MD)) 10655 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10656 10657 QualType MPTy = Context.getMemberPointerType( 10658 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10659 // Under the MS ABI, lock down the inheritance model now. 10660 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10661 (void)isCompleteType(OpLoc, MPTy); 10662 return MPTy; 10663 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10664 // C99 6.5.3.2p1 10665 // The operand must be either an l-value or a function designator 10666 if (!op->getType()->isFunctionType()) { 10667 // Use a special diagnostic for loads from property references. 10668 if (isa<PseudoObjectExpr>(op)) { 10669 AddressOfError = AO_Property_Expansion; 10670 } else { 10671 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10672 << op->getType() << op->getSourceRange(); 10673 return QualType(); 10674 } 10675 } 10676 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10677 // The operand cannot be a bit-field 10678 AddressOfError = AO_Bit_Field; 10679 } else if (op->getObjectKind() == OK_VectorComponent) { 10680 // The operand cannot be an element of a vector 10681 AddressOfError = AO_Vector_Element; 10682 } else if (dcl) { // C99 6.5.3.2p1 10683 // We have an lvalue with a decl. Make sure the decl is not declared 10684 // with the register storage-class specifier. 10685 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10686 // in C++ it is not error to take address of a register 10687 // variable (c++03 7.1.1P3) 10688 if (vd->getStorageClass() == SC_Register && 10689 !getLangOpts().CPlusPlus) { 10690 AddressOfError = AO_Register_Variable; 10691 } 10692 } else if (isa<MSPropertyDecl>(dcl)) { 10693 AddressOfError = AO_Property_Expansion; 10694 } else if (isa<FunctionTemplateDecl>(dcl)) { 10695 return Context.OverloadTy; 10696 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10697 // Okay: we can take the address of a field. 10698 // Could be a pointer to member, though, if there is an explicit 10699 // scope qualifier for the class. 10700 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10701 DeclContext *Ctx = dcl->getDeclContext(); 10702 if (Ctx && Ctx->isRecord()) { 10703 if (dcl->getType()->isReferenceType()) { 10704 Diag(OpLoc, 10705 diag::err_cannot_form_pointer_to_member_of_reference_type) 10706 << dcl->getDeclName() << dcl->getType(); 10707 return QualType(); 10708 } 10709 10710 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10711 Ctx = Ctx->getParent(); 10712 10713 QualType MPTy = Context.getMemberPointerType( 10714 op->getType(), 10715 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10716 // Under the MS ABI, lock down the inheritance model now. 10717 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10718 (void)isCompleteType(OpLoc, MPTy); 10719 return MPTy; 10720 } 10721 } 10722 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10723 !isa<BindingDecl>(dcl)) 10724 llvm_unreachable("Unknown/unexpected decl type"); 10725 } 10726 10727 if (AddressOfError != AO_No_Error) { 10728 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10729 return QualType(); 10730 } 10731 10732 if (lval == Expr::LV_IncompleteVoidType) { 10733 // Taking the address of a void variable is technically illegal, but we 10734 // allow it in cases which are otherwise valid. 10735 // Example: "extern void x; void* y = &x;". 10736 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10737 } 10738 10739 // If the operand has type "type", the result has type "pointer to type". 10740 if (op->getType()->isObjCObjectType()) 10741 return Context.getObjCObjectPointerType(op->getType()); 10742 10743 CheckAddressOfPackedMember(op); 10744 10745 return Context.getPointerType(op->getType()); 10746 } 10747 10748 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10749 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10750 if (!DRE) 10751 return; 10752 const Decl *D = DRE->getDecl(); 10753 if (!D) 10754 return; 10755 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10756 if (!Param) 10757 return; 10758 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10759 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10760 return; 10761 if (FunctionScopeInfo *FD = S.getCurFunction()) 10762 if (!FD->ModifiedNonNullParams.count(Param)) 10763 FD->ModifiedNonNullParams.insert(Param); 10764 } 10765 10766 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10767 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10768 SourceLocation OpLoc) { 10769 if (Op->isTypeDependent()) 10770 return S.Context.DependentTy; 10771 10772 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10773 if (ConvResult.isInvalid()) 10774 return QualType(); 10775 Op = ConvResult.get(); 10776 QualType OpTy = Op->getType(); 10777 QualType Result; 10778 10779 if (isa<CXXReinterpretCastExpr>(Op)) { 10780 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10781 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10782 Op->getSourceRange()); 10783 } 10784 10785 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10786 { 10787 Result = PT->getPointeeType(); 10788 } 10789 else if (const ObjCObjectPointerType *OPT = 10790 OpTy->getAs<ObjCObjectPointerType>()) 10791 Result = OPT->getPointeeType(); 10792 else { 10793 ExprResult PR = S.CheckPlaceholderExpr(Op); 10794 if (PR.isInvalid()) return QualType(); 10795 if (PR.get() != Op) 10796 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10797 } 10798 10799 if (Result.isNull()) { 10800 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10801 << OpTy << Op->getSourceRange(); 10802 return QualType(); 10803 } 10804 10805 // Note that per both C89 and C99, indirection is always legal, even if Result 10806 // is an incomplete type or void. It would be possible to warn about 10807 // dereferencing a void pointer, but it's completely well-defined, and such a 10808 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10809 // for pointers to 'void' but is fine for any other pointer type: 10810 // 10811 // C++ [expr.unary.op]p1: 10812 // [...] the expression to which [the unary * operator] is applied shall 10813 // be a pointer to an object type, or a pointer to a function type 10814 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10815 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10816 << OpTy << Op->getSourceRange(); 10817 10818 // Dereferences are usually l-values... 10819 VK = VK_LValue; 10820 10821 // ...except that certain expressions are never l-values in C. 10822 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10823 VK = VK_RValue; 10824 10825 return Result; 10826 } 10827 10828 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10829 BinaryOperatorKind Opc; 10830 switch (Kind) { 10831 default: llvm_unreachable("Unknown binop!"); 10832 case tok::periodstar: Opc = BO_PtrMemD; break; 10833 case tok::arrowstar: Opc = BO_PtrMemI; break; 10834 case tok::star: Opc = BO_Mul; break; 10835 case tok::slash: Opc = BO_Div; break; 10836 case tok::percent: Opc = BO_Rem; break; 10837 case tok::plus: Opc = BO_Add; break; 10838 case tok::minus: Opc = BO_Sub; break; 10839 case tok::lessless: Opc = BO_Shl; break; 10840 case tok::greatergreater: Opc = BO_Shr; break; 10841 case tok::lessequal: Opc = BO_LE; break; 10842 case tok::less: Opc = BO_LT; break; 10843 case tok::greaterequal: Opc = BO_GE; break; 10844 case tok::greater: Opc = BO_GT; break; 10845 case tok::exclaimequal: Opc = BO_NE; break; 10846 case tok::equalequal: Opc = BO_EQ; break; 10847 case tok::amp: Opc = BO_And; break; 10848 case tok::caret: Opc = BO_Xor; break; 10849 case tok::pipe: Opc = BO_Or; break; 10850 case tok::ampamp: Opc = BO_LAnd; break; 10851 case tok::pipepipe: Opc = BO_LOr; break; 10852 case tok::equal: Opc = BO_Assign; break; 10853 case tok::starequal: Opc = BO_MulAssign; break; 10854 case tok::slashequal: Opc = BO_DivAssign; break; 10855 case tok::percentequal: Opc = BO_RemAssign; break; 10856 case tok::plusequal: Opc = BO_AddAssign; break; 10857 case tok::minusequal: Opc = BO_SubAssign; break; 10858 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10859 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10860 case tok::ampequal: Opc = BO_AndAssign; break; 10861 case tok::caretequal: Opc = BO_XorAssign; break; 10862 case tok::pipeequal: Opc = BO_OrAssign; break; 10863 case tok::comma: Opc = BO_Comma; break; 10864 } 10865 return Opc; 10866 } 10867 10868 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10869 tok::TokenKind Kind) { 10870 UnaryOperatorKind Opc; 10871 switch (Kind) { 10872 default: llvm_unreachable("Unknown unary op!"); 10873 case tok::plusplus: Opc = UO_PreInc; break; 10874 case tok::minusminus: Opc = UO_PreDec; break; 10875 case tok::amp: Opc = UO_AddrOf; break; 10876 case tok::star: Opc = UO_Deref; break; 10877 case tok::plus: Opc = UO_Plus; break; 10878 case tok::minus: Opc = UO_Minus; break; 10879 case tok::tilde: Opc = UO_Not; break; 10880 case tok::exclaim: Opc = UO_LNot; break; 10881 case tok::kw___real: Opc = UO_Real; break; 10882 case tok::kw___imag: Opc = UO_Imag; break; 10883 case tok::kw___extension__: Opc = UO_Extension; break; 10884 } 10885 return Opc; 10886 } 10887 10888 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10889 /// This warning is only emitted for builtin assignment operations. It is also 10890 /// suppressed in the event of macro expansions. 10891 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10892 SourceLocation OpLoc) { 10893 if (!S.ActiveTemplateInstantiations.empty()) 10894 return; 10895 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10896 return; 10897 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10898 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10899 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10900 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10901 if (!LHSDeclRef || !RHSDeclRef || 10902 LHSDeclRef->getLocation().isMacroID() || 10903 RHSDeclRef->getLocation().isMacroID()) 10904 return; 10905 const ValueDecl *LHSDecl = 10906 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10907 const ValueDecl *RHSDecl = 10908 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10909 if (LHSDecl != RHSDecl) 10910 return; 10911 if (LHSDecl->getType().isVolatileQualified()) 10912 return; 10913 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10914 if (RefTy->getPointeeType().isVolatileQualified()) 10915 return; 10916 10917 S.Diag(OpLoc, diag::warn_self_assignment) 10918 << LHSDeclRef->getType() 10919 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10920 } 10921 10922 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10923 /// is usually indicative of introspection within the Objective-C pointer. 10924 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10925 SourceLocation OpLoc) { 10926 if (!S.getLangOpts().ObjC1) 10927 return; 10928 10929 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10930 const Expr *LHS = L.get(); 10931 const Expr *RHS = R.get(); 10932 10933 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10934 ObjCPointerExpr = LHS; 10935 OtherExpr = RHS; 10936 } 10937 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10938 ObjCPointerExpr = RHS; 10939 OtherExpr = LHS; 10940 } 10941 10942 // This warning is deliberately made very specific to reduce false 10943 // positives with logic that uses '&' for hashing. This logic mainly 10944 // looks for code trying to introspect into tagged pointers, which 10945 // code should generally never do. 10946 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10947 unsigned Diag = diag::warn_objc_pointer_masking; 10948 // Determine if we are introspecting the result of performSelectorXXX. 10949 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10950 // Special case messages to -performSelector and friends, which 10951 // can return non-pointer values boxed in a pointer value. 10952 // Some clients may wish to silence warnings in this subcase. 10953 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10954 Selector S = ME->getSelector(); 10955 StringRef SelArg0 = S.getNameForSlot(0); 10956 if (SelArg0.startswith("performSelector")) 10957 Diag = diag::warn_objc_pointer_masking_performSelector; 10958 } 10959 10960 S.Diag(OpLoc, Diag) 10961 << ObjCPointerExpr->getSourceRange(); 10962 } 10963 } 10964 10965 static NamedDecl *getDeclFromExpr(Expr *E) { 10966 if (!E) 10967 return nullptr; 10968 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10969 return DRE->getDecl(); 10970 if (auto *ME = dyn_cast<MemberExpr>(E)) 10971 return ME->getMemberDecl(); 10972 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10973 return IRE->getDecl(); 10974 return nullptr; 10975 } 10976 10977 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10978 /// operator @p Opc at location @c TokLoc. This routine only supports 10979 /// built-in operations; ActOnBinOp handles overloaded operators. 10980 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10981 BinaryOperatorKind Opc, 10982 Expr *LHSExpr, Expr *RHSExpr) { 10983 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10984 // The syntax only allows initializer lists on the RHS of assignment, 10985 // so we don't need to worry about accepting invalid code for 10986 // non-assignment operators. 10987 // C++11 5.17p9: 10988 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10989 // of x = {} is x = T(). 10990 InitializationKind Kind = 10991 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10992 InitializedEntity Entity = 10993 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10994 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10995 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10996 if (Init.isInvalid()) 10997 return Init; 10998 RHSExpr = Init.get(); 10999 } 11000 11001 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11002 QualType ResultTy; // Result type of the binary operator. 11003 // The following two variables are used for compound assignment operators 11004 QualType CompLHSTy; // Type of LHS after promotions for computation 11005 QualType CompResultTy; // Type of computation result 11006 ExprValueKind VK = VK_RValue; 11007 ExprObjectKind OK = OK_Ordinary; 11008 11009 if (!getLangOpts().CPlusPlus) { 11010 // C cannot handle TypoExpr nodes on either side of a binop because it 11011 // doesn't handle dependent types properly, so make sure any TypoExprs have 11012 // been dealt with before checking the operands. 11013 LHS = CorrectDelayedTyposInExpr(LHSExpr); 11014 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 11015 if (Opc != BO_Assign) 11016 return ExprResult(E); 11017 // Avoid correcting the RHS to the same Expr as the LHS. 11018 Decl *D = getDeclFromExpr(E); 11019 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11020 }); 11021 if (!LHS.isUsable() || !RHS.isUsable()) 11022 return ExprError(); 11023 } 11024 11025 if (getLangOpts().OpenCL) { 11026 QualType LHSTy = LHSExpr->getType(); 11027 QualType RHSTy = RHSExpr->getType(); 11028 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11029 // the ATOMIC_VAR_INIT macro. 11030 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11031 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11032 if (BO_Assign == Opc) 11033 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 11034 else 11035 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11036 return ExprError(); 11037 } 11038 11039 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11040 // only with a builtin functions and therefore should be disallowed here. 11041 if (LHSTy->isImageType() || RHSTy->isImageType() || 11042 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11043 LHSTy->isPipeType() || RHSTy->isPipeType() || 11044 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11045 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11046 return ExprError(); 11047 } 11048 } 11049 11050 switch (Opc) { 11051 case BO_Assign: 11052 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11053 if (getLangOpts().CPlusPlus && 11054 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11055 VK = LHS.get()->getValueKind(); 11056 OK = LHS.get()->getObjectKind(); 11057 } 11058 if (!ResultTy.isNull()) { 11059 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11060 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11061 } 11062 RecordModifiableNonNullParam(*this, LHS.get()); 11063 break; 11064 case BO_PtrMemD: 11065 case BO_PtrMemI: 11066 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11067 Opc == BO_PtrMemI); 11068 break; 11069 case BO_Mul: 11070 case BO_Div: 11071 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11072 Opc == BO_Div); 11073 break; 11074 case BO_Rem: 11075 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11076 break; 11077 case BO_Add: 11078 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11079 break; 11080 case BO_Sub: 11081 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11082 break; 11083 case BO_Shl: 11084 case BO_Shr: 11085 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11086 break; 11087 case BO_LE: 11088 case BO_LT: 11089 case BO_GE: 11090 case BO_GT: 11091 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11092 break; 11093 case BO_EQ: 11094 case BO_NE: 11095 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11096 break; 11097 case BO_And: 11098 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11099 case BO_Xor: 11100 case BO_Or: 11101 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11102 break; 11103 case BO_LAnd: 11104 case BO_LOr: 11105 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11106 break; 11107 case BO_MulAssign: 11108 case BO_DivAssign: 11109 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11110 Opc == BO_DivAssign); 11111 CompLHSTy = CompResultTy; 11112 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11113 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11114 break; 11115 case BO_RemAssign: 11116 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11117 CompLHSTy = CompResultTy; 11118 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11119 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11120 break; 11121 case BO_AddAssign: 11122 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11123 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11124 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11125 break; 11126 case BO_SubAssign: 11127 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11128 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11129 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11130 break; 11131 case BO_ShlAssign: 11132 case BO_ShrAssign: 11133 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11134 CompLHSTy = CompResultTy; 11135 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11136 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11137 break; 11138 case BO_AndAssign: 11139 case BO_OrAssign: // fallthrough 11140 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11141 case BO_XorAssign: 11142 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11143 CompLHSTy = CompResultTy; 11144 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11145 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11146 break; 11147 case BO_Comma: 11148 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11149 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11150 VK = RHS.get()->getValueKind(); 11151 OK = RHS.get()->getObjectKind(); 11152 } 11153 break; 11154 } 11155 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11156 return ExprError(); 11157 11158 // Check for array bounds violations for both sides of the BinaryOperator 11159 CheckArrayAccess(LHS.get()); 11160 CheckArrayAccess(RHS.get()); 11161 11162 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11163 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11164 &Context.Idents.get("object_setClass"), 11165 SourceLocation(), LookupOrdinaryName); 11166 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11167 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11168 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11169 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11170 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11171 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11172 } 11173 else 11174 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11175 } 11176 else if (const ObjCIvarRefExpr *OIRE = 11177 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11178 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11179 11180 if (CompResultTy.isNull()) 11181 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11182 OK, OpLoc, FPFeatures.fp_contract); 11183 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11184 OK_ObjCProperty) { 11185 VK = VK_LValue; 11186 OK = LHS.get()->getObjectKind(); 11187 } 11188 return new (Context) CompoundAssignOperator( 11189 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11190 OpLoc, FPFeatures.fp_contract); 11191 } 11192 11193 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11194 /// operators are mixed in a way that suggests that the programmer forgot that 11195 /// comparison operators have higher precedence. The most typical example of 11196 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11197 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11198 SourceLocation OpLoc, Expr *LHSExpr, 11199 Expr *RHSExpr) { 11200 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11201 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11202 11203 // Check that one of the sides is a comparison operator and the other isn't. 11204 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11205 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11206 if (isLeftComp == isRightComp) 11207 return; 11208 11209 // Bitwise operations are sometimes used as eager logical ops. 11210 // Don't diagnose this. 11211 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11212 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11213 if (isLeftBitwise || isRightBitwise) 11214 return; 11215 11216 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11217 OpLoc) 11218 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11219 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11220 SourceRange ParensRange = isLeftComp ? 11221 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11222 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11223 11224 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11225 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11226 SuggestParentheses(Self, OpLoc, 11227 Self.PDiag(diag::note_precedence_silence) << OpStr, 11228 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11229 SuggestParentheses(Self, OpLoc, 11230 Self.PDiag(diag::note_precedence_bitwise_first) 11231 << BinaryOperator::getOpcodeStr(Opc), 11232 ParensRange); 11233 } 11234 11235 /// \brief It accepts a '&&' expr that is inside a '||' one. 11236 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11237 /// in parentheses. 11238 static void 11239 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11240 BinaryOperator *Bop) { 11241 assert(Bop->getOpcode() == BO_LAnd); 11242 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11243 << Bop->getSourceRange() << OpLoc; 11244 SuggestParentheses(Self, Bop->getOperatorLoc(), 11245 Self.PDiag(diag::note_precedence_silence) 11246 << Bop->getOpcodeStr(), 11247 Bop->getSourceRange()); 11248 } 11249 11250 /// \brief Returns true if the given expression can be evaluated as a constant 11251 /// 'true'. 11252 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11253 bool Res; 11254 return !E->isValueDependent() && 11255 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11256 } 11257 11258 /// \brief Returns true if the given expression can be evaluated as a constant 11259 /// 'false'. 11260 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11261 bool Res; 11262 return !E->isValueDependent() && 11263 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11264 } 11265 11266 /// \brief Look for '&&' in the left hand of a '||' expr. 11267 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11268 Expr *LHSExpr, Expr *RHSExpr) { 11269 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11270 if (Bop->getOpcode() == BO_LAnd) { 11271 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11272 if (EvaluatesAsFalse(S, RHSExpr)) 11273 return; 11274 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11275 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11276 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11277 } else if (Bop->getOpcode() == BO_LOr) { 11278 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11279 // If it's "a || b && 1 || c" we didn't warn earlier for 11280 // "a || b && 1", but warn now. 11281 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11282 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11283 } 11284 } 11285 } 11286 } 11287 11288 /// \brief Look for '&&' in the right hand of a '||' expr. 11289 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11290 Expr *LHSExpr, Expr *RHSExpr) { 11291 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11292 if (Bop->getOpcode() == BO_LAnd) { 11293 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11294 if (EvaluatesAsFalse(S, LHSExpr)) 11295 return; 11296 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11297 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11298 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11299 } 11300 } 11301 } 11302 11303 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11304 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11305 /// the '&' expression in parentheses. 11306 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11307 SourceLocation OpLoc, Expr *SubExpr) { 11308 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11309 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11310 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11311 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11312 << Bop->getSourceRange() << OpLoc; 11313 SuggestParentheses(S, Bop->getOperatorLoc(), 11314 S.PDiag(diag::note_precedence_silence) 11315 << Bop->getOpcodeStr(), 11316 Bop->getSourceRange()); 11317 } 11318 } 11319 } 11320 11321 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11322 Expr *SubExpr, StringRef Shift) { 11323 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11324 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11325 StringRef Op = Bop->getOpcodeStr(); 11326 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11327 << Bop->getSourceRange() << OpLoc << Shift << Op; 11328 SuggestParentheses(S, Bop->getOperatorLoc(), 11329 S.PDiag(diag::note_precedence_silence) << Op, 11330 Bop->getSourceRange()); 11331 } 11332 } 11333 } 11334 11335 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11336 Expr *LHSExpr, Expr *RHSExpr) { 11337 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11338 if (!OCE) 11339 return; 11340 11341 FunctionDecl *FD = OCE->getDirectCallee(); 11342 if (!FD || !FD->isOverloadedOperator()) 11343 return; 11344 11345 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11346 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11347 return; 11348 11349 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11350 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11351 << (Kind == OO_LessLess); 11352 SuggestParentheses(S, OCE->getOperatorLoc(), 11353 S.PDiag(diag::note_precedence_silence) 11354 << (Kind == OO_LessLess ? "<<" : ">>"), 11355 OCE->getSourceRange()); 11356 SuggestParentheses(S, OpLoc, 11357 S.PDiag(diag::note_evaluate_comparison_first), 11358 SourceRange(OCE->getArg(1)->getLocStart(), 11359 RHSExpr->getLocEnd())); 11360 } 11361 11362 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11363 /// precedence. 11364 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11365 SourceLocation OpLoc, Expr *LHSExpr, 11366 Expr *RHSExpr){ 11367 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11368 if (BinaryOperator::isBitwiseOp(Opc)) 11369 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11370 11371 // Diagnose "arg1 & arg2 | arg3" 11372 if ((Opc == BO_Or || Opc == BO_Xor) && 11373 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11374 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11375 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11376 } 11377 11378 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11379 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11380 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11381 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11382 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11383 } 11384 11385 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11386 || Opc == BO_Shr) { 11387 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11388 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11389 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11390 } 11391 11392 // Warn on overloaded shift operators and comparisons, such as: 11393 // cout << 5 == 4; 11394 if (BinaryOperator::isComparisonOp(Opc)) 11395 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11396 } 11397 11398 // Binary Operators. 'Tok' is the token for the operator. 11399 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11400 tok::TokenKind Kind, 11401 Expr *LHSExpr, Expr *RHSExpr) { 11402 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11403 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11404 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11405 11406 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11407 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11408 11409 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11410 } 11411 11412 /// Build an overloaded binary operator expression in the given scope. 11413 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11414 BinaryOperatorKind Opc, 11415 Expr *LHS, Expr *RHS) { 11416 // Find all of the overloaded operators visible from this 11417 // point. We perform both an operator-name lookup from the local 11418 // scope and an argument-dependent lookup based on the types of 11419 // the arguments. 11420 UnresolvedSet<16> Functions; 11421 OverloadedOperatorKind OverOp 11422 = BinaryOperator::getOverloadedOperator(Opc); 11423 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11424 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11425 RHS->getType(), Functions); 11426 11427 // Build the (potentially-overloaded, potentially-dependent) 11428 // binary operation. 11429 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11430 } 11431 11432 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11433 BinaryOperatorKind Opc, 11434 Expr *LHSExpr, Expr *RHSExpr) { 11435 // We want to end up calling one of checkPseudoObjectAssignment 11436 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11437 // both expressions are overloadable or either is type-dependent), 11438 // or CreateBuiltinBinOp (in any other case). We also want to get 11439 // any placeholder types out of the way. 11440 11441 // Handle pseudo-objects in the LHS. 11442 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11443 // Assignments with a pseudo-object l-value need special analysis. 11444 if (pty->getKind() == BuiltinType::PseudoObject && 11445 BinaryOperator::isAssignmentOp(Opc)) 11446 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11447 11448 // Don't resolve overloads if the other type is overloadable. 11449 if (pty->getKind() == BuiltinType::Overload) { 11450 // We can't actually test that if we still have a placeholder, 11451 // though. Fortunately, none of the exceptions we see in that 11452 // code below are valid when the LHS is an overload set. Note 11453 // that an overload set can be dependently-typed, but it never 11454 // instantiates to having an overloadable type. 11455 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11456 if (resolvedRHS.isInvalid()) return ExprError(); 11457 RHSExpr = resolvedRHS.get(); 11458 11459 if (RHSExpr->isTypeDependent() || 11460 RHSExpr->getType()->isOverloadableType()) 11461 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11462 } 11463 11464 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11465 if (LHS.isInvalid()) return ExprError(); 11466 LHSExpr = LHS.get(); 11467 } 11468 11469 // Handle pseudo-objects in the RHS. 11470 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11471 // An overload in the RHS can potentially be resolved by the type 11472 // being assigned to. 11473 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11474 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11475 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11476 11477 if (LHSExpr->getType()->isOverloadableType()) 11478 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11479 11480 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11481 } 11482 11483 // Don't resolve overloads if the other type is overloadable. 11484 if (pty->getKind() == BuiltinType::Overload && 11485 LHSExpr->getType()->isOverloadableType()) 11486 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11487 11488 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11489 if (!resolvedRHS.isUsable()) return ExprError(); 11490 RHSExpr = resolvedRHS.get(); 11491 } 11492 11493 if (getLangOpts().CPlusPlus) { 11494 // If either expression is type-dependent, always build an 11495 // overloaded op. 11496 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11497 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11498 11499 // Otherwise, build an overloaded op if either expression has an 11500 // overloadable type. 11501 if (LHSExpr->getType()->isOverloadableType() || 11502 RHSExpr->getType()->isOverloadableType()) 11503 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11504 } 11505 11506 // Build a built-in binary operation. 11507 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11508 } 11509 11510 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11511 UnaryOperatorKind Opc, 11512 Expr *InputExpr) { 11513 ExprResult Input = InputExpr; 11514 ExprValueKind VK = VK_RValue; 11515 ExprObjectKind OK = OK_Ordinary; 11516 QualType resultType; 11517 if (getLangOpts().OpenCL) { 11518 QualType Ty = InputExpr->getType(); 11519 // The only legal unary operation for atomics is '&'. 11520 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11521 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11522 // only with a builtin functions and therefore should be disallowed here. 11523 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11524 || Ty->isBlockPointerType())) { 11525 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11526 << InputExpr->getType() 11527 << Input.get()->getSourceRange()); 11528 } 11529 } 11530 switch (Opc) { 11531 case UO_PreInc: 11532 case UO_PreDec: 11533 case UO_PostInc: 11534 case UO_PostDec: 11535 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11536 OpLoc, 11537 Opc == UO_PreInc || 11538 Opc == UO_PostInc, 11539 Opc == UO_PreInc || 11540 Opc == UO_PreDec); 11541 break; 11542 case UO_AddrOf: 11543 resultType = CheckAddressOfOperand(Input, OpLoc); 11544 RecordModifiableNonNullParam(*this, InputExpr); 11545 break; 11546 case UO_Deref: { 11547 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11548 if (Input.isInvalid()) return ExprError(); 11549 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11550 break; 11551 } 11552 case UO_Plus: 11553 case UO_Minus: 11554 Input = UsualUnaryConversions(Input.get()); 11555 if (Input.isInvalid()) return ExprError(); 11556 resultType = Input.get()->getType(); 11557 if (resultType->isDependentType()) 11558 break; 11559 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11560 break; 11561 else if (resultType->isVectorType() && 11562 // The z vector extensions don't allow + or - with bool vectors. 11563 (!Context.getLangOpts().ZVector || 11564 resultType->getAs<VectorType>()->getVectorKind() != 11565 VectorType::AltiVecBool)) 11566 break; 11567 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11568 Opc == UO_Plus && 11569 resultType->isPointerType()) 11570 break; 11571 11572 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11573 << resultType << Input.get()->getSourceRange()); 11574 11575 case UO_Not: // bitwise complement 11576 Input = UsualUnaryConversions(Input.get()); 11577 if (Input.isInvalid()) 11578 return ExprError(); 11579 resultType = Input.get()->getType(); 11580 if (resultType->isDependentType()) 11581 break; 11582 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11583 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11584 // C99 does not support '~' for complex conjugation. 11585 Diag(OpLoc, diag::ext_integer_complement_complex) 11586 << resultType << Input.get()->getSourceRange(); 11587 else if (resultType->hasIntegerRepresentation()) 11588 break; 11589 else if (resultType->isExtVectorType()) { 11590 if (Context.getLangOpts().OpenCL) { 11591 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11592 // on vector float types. 11593 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11594 if (!T->isIntegerType()) 11595 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11596 << resultType << Input.get()->getSourceRange()); 11597 } 11598 break; 11599 } else { 11600 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11601 << resultType << Input.get()->getSourceRange()); 11602 } 11603 break; 11604 11605 case UO_LNot: // logical negation 11606 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11607 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11608 if (Input.isInvalid()) return ExprError(); 11609 resultType = Input.get()->getType(); 11610 11611 // Though we still have to promote half FP to float... 11612 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11613 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11614 resultType = Context.FloatTy; 11615 } 11616 11617 if (resultType->isDependentType()) 11618 break; 11619 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11620 // C99 6.5.3.3p1: ok, fallthrough; 11621 if (Context.getLangOpts().CPlusPlus) { 11622 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11623 // operand contextually converted to bool. 11624 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11625 ScalarTypeToBooleanCastKind(resultType)); 11626 } else if (Context.getLangOpts().OpenCL && 11627 Context.getLangOpts().OpenCLVersion < 120) { 11628 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11629 // operate on scalar float types. 11630 if (!resultType->isIntegerType()) 11631 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11632 << resultType << Input.get()->getSourceRange()); 11633 } 11634 } else if (resultType->isExtVectorType()) { 11635 if (Context.getLangOpts().OpenCL && 11636 Context.getLangOpts().OpenCLVersion < 120) { 11637 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11638 // operate on vector float types. 11639 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11640 if (!T->isIntegerType()) 11641 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11642 << resultType << Input.get()->getSourceRange()); 11643 } 11644 // Vector logical not returns the signed variant of the operand type. 11645 resultType = GetSignedVectorType(resultType); 11646 break; 11647 } else { 11648 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11649 << resultType << Input.get()->getSourceRange()); 11650 } 11651 11652 // LNot always has type int. C99 6.5.3.3p5. 11653 // In C++, it's bool. C++ 5.3.1p8 11654 resultType = Context.getLogicalOperationType(); 11655 break; 11656 case UO_Real: 11657 case UO_Imag: 11658 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11659 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11660 // complex l-values to ordinary l-values and all other values to r-values. 11661 if (Input.isInvalid()) return ExprError(); 11662 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11663 if (Input.get()->getValueKind() != VK_RValue && 11664 Input.get()->getObjectKind() == OK_Ordinary) 11665 VK = Input.get()->getValueKind(); 11666 } else if (!getLangOpts().CPlusPlus) { 11667 // In C, a volatile scalar is read by __imag. In C++, it is not. 11668 Input = DefaultLvalueConversion(Input.get()); 11669 } 11670 break; 11671 case UO_Extension: 11672 case UO_Coawait: 11673 resultType = Input.get()->getType(); 11674 VK = Input.get()->getValueKind(); 11675 OK = Input.get()->getObjectKind(); 11676 break; 11677 } 11678 if (resultType.isNull() || Input.isInvalid()) 11679 return ExprError(); 11680 11681 // Check for array bounds violations in the operand of the UnaryOperator, 11682 // except for the '*' and '&' operators that have to be handled specially 11683 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11684 // that are explicitly defined as valid by the standard). 11685 if (Opc != UO_AddrOf && Opc != UO_Deref) 11686 CheckArrayAccess(Input.get()); 11687 11688 return new (Context) 11689 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11690 } 11691 11692 /// \brief Determine whether the given expression is a qualified member 11693 /// access expression, of a form that could be turned into a pointer to member 11694 /// with the address-of operator. 11695 static bool isQualifiedMemberAccess(Expr *E) { 11696 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11697 if (!DRE->getQualifier()) 11698 return false; 11699 11700 ValueDecl *VD = DRE->getDecl(); 11701 if (!VD->isCXXClassMember()) 11702 return false; 11703 11704 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11705 return true; 11706 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11707 return Method->isInstance(); 11708 11709 return false; 11710 } 11711 11712 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11713 if (!ULE->getQualifier()) 11714 return false; 11715 11716 for (NamedDecl *D : ULE->decls()) { 11717 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11718 if (Method->isInstance()) 11719 return true; 11720 } else { 11721 // Overload set does not contain methods. 11722 break; 11723 } 11724 } 11725 11726 return false; 11727 } 11728 11729 return false; 11730 } 11731 11732 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11733 UnaryOperatorKind Opc, Expr *Input) { 11734 // First things first: handle placeholders so that the 11735 // overloaded-operator check considers the right type. 11736 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11737 // Increment and decrement of pseudo-object references. 11738 if (pty->getKind() == BuiltinType::PseudoObject && 11739 UnaryOperator::isIncrementDecrementOp(Opc)) 11740 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11741 11742 // extension is always a builtin operator. 11743 if (Opc == UO_Extension) 11744 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11745 11746 // & gets special logic for several kinds of placeholder. 11747 // The builtin code knows what to do. 11748 if (Opc == UO_AddrOf && 11749 (pty->getKind() == BuiltinType::Overload || 11750 pty->getKind() == BuiltinType::UnknownAny || 11751 pty->getKind() == BuiltinType::BoundMember)) 11752 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11753 11754 // Anything else needs to be handled now. 11755 ExprResult Result = CheckPlaceholderExpr(Input); 11756 if (Result.isInvalid()) return ExprError(); 11757 Input = Result.get(); 11758 } 11759 11760 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11761 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11762 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11763 // Find all of the overloaded operators visible from this 11764 // point. We perform both an operator-name lookup from the local 11765 // scope and an argument-dependent lookup based on the types of 11766 // the arguments. 11767 UnresolvedSet<16> Functions; 11768 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11769 if (S && OverOp != OO_None) 11770 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11771 Functions); 11772 11773 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11774 } 11775 11776 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11777 } 11778 11779 // Unary Operators. 'Tok' is the token for the operator. 11780 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11781 tok::TokenKind Op, Expr *Input) { 11782 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11783 } 11784 11785 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11786 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11787 LabelDecl *TheDecl) { 11788 TheDecl->markUsed(Context); 11789 // Create the AST node. The address of a label always has type 'void*'. 11790 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11791 Context.getPointerType(Context.VoidTy)); 11792 } 11793 11794 /// Given the last statement in a statement-expression, check whether 11795 /// the result is a producing expression (like a call to an 11796 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11797 /// release out of the full-expression. Otherwise, return null. 11798 /// Cannot fail. 11799 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11800 // Should always be wrapped with one of these. 11801 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11802 if (!cleanups) return nullptr; 11803 11804 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11805 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11806 return nullptr; 11807 11808 // Splice out the cast. This shouldn't modify any interesting 11809 // features of the statement. 11810 Expr *producer = cast->getSubExpr(); 11811 assert(producer->getType() == cast->getType()); 11812 assert(producer->getValueKind() == cast->getValueKind()); 11813 cleanups->setSubExpr(producer); 11814 return cleanups; 11815 } 11816 11817 void Sema::ActOnStartStmtExpr() { 11818 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11819 } 11820 11821 void Sema::ActOnStmtExprError() { 11822 // Note that function is also called by TreeTransform when leaving a 11823 // StmtExpr scope without rebuilding anything. 11824 11825 DiscardCleanupsInEvaluationContext(); 11826 PopExpressionEvaluationContext(); 11827 } 11828 11829 ExprResult 11830 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11831 SourceLocation RPLoc) { // "({..})" 11832 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11833 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11834 11835 if (hasAnyUnrecoverableErrorsInThisFunction()) 11836 DiscardCleanupsInEvaluationContext(); 11837 assert(!Cleanup.exprNeedsCleanups() && 11838 "cleanups within StmtExpr not correctly bound!"); 11839 PopExpressionEvaluationContext(); 11840 11841 // FIXME: there are a variety of strange constraints to enforce here, for 11842 // example, it is not possible to goto into a stmt expression apparently. 11843 // More semantic analysis is needed. 11844 11845 // If there are sub-stmts in the compound stmt, take the type of the last one 11846 // as the type of the stmtexpr. 11847 QualType Ty = Context.VoidTy; 11848 bool StmtExprMayBindToTemp = false; 11849 if (!Compound->body_empty()) { 11850 Stmt *LastStmt = Compound->body_back(); 11851 LabelStmt *LastLabelStmt = nullptr; 11852 // If LastStmt is a label, skip down through into the body. 11853 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11854 LastLabelStmt = Label; 11855 LastStmt = Label->getSubStmt(); 11856 } 11857 11858 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11859 // Do function/array conversion on the last expression, but not 11860 // lvalue-to-rvalue. However, initialize an unqualified type. 11861 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11862 if (LastExpr.isInvalid()) 11863 return ExprError(); 11864 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11865 11866 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11867 // In ARC, if the final expression ends in a consume, splice 11868 // the consume out and bind it later. In the alternate case 11869 // (when dealing with a retainable type), the result 11870 // initialization will create a produce. In both cases the 11871 // result will be +1, and we'll need to balance that out with 11872 // a bind. 11873 if (Expr *rebuiltLastStmt 11874 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11875 LastExpr = rebuiltLastStmt; 11876 } else { 11877 LastExpr = PerformCopyInitialization( 11878 InitializedEntity::InitializeResult(LPLoc, 11879 Ty, 11880 false), 11881 SourceLocation(), 11882 LastExpr); 11883 } 11884 11885 if (LastExpr.isInvalid()) 11886 return ExprError(); 11887 if (LastExpr.get() != nullptr) { 11888 if (!LastLabelStmt) 11889 Compound->setLastStmt(LastExpr.get()); 11890 else 11891 LastLabelStmt->setSubStmt(LastExpr.get()); 11892 StmtExprMayBindToTemp = true; 11893 } 11894 } 11895 } 11896 } 11897 11898 // FIXME: Check that expression type is complete/non-abstract; statement 11899 // expressions are not lvalues. 11900 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11901 if (StmtExprMayBindToTemp) 11902 return MaybeBindToTemporary(ResStmtExpr); 11903 return ResStmtExpr; 11904 } 11905 11906 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11907 TypeSourceInfo *TInfo, 11908 ArrayRef<OffsetOfComponent> Components, 11909 SourceLocation RParenLoc) { 11910 QualType ArgTy = TInfo->getType(); 11911 bool Dependent = ArgTy->isDependentType(); 11912 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11913 11914 // We must have at least one component that refers to the type, and the first 11915 // one is known to be a field designator. Verify that the ArgTy represents 11916 // a struct/union/class. 11917 if (!Dependent && !ArgTy->isRecordType()) 11918 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11919 << ArgTy << TypeRange); 11920 11921 // Type must be complete per C99 7.17p3 because a declaring a variable 11922 // with an incomplete type would be ill-formed. 11923 if (!Dependent 11924 && RequireCompleteType(BuiltinLoc, ArgTy, 11925 diag::err_offsetof_incomplete_type, TypeRange)) 11926 return ExprError(); 11927 11928 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11929 // GCC extension, diagnose them. 11930 // FIXME: This diagnostic isn't actually visible because the location is in 11931 // a system header! 11932 if (Components.size() != 1) 11933 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11934 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11935 11936 bool DidWarnAboutNonPOD = false; 11937 QualType CurrentType = ArgTy; 11938 SmallVector<OffsetOfNode, 4> Comps; 11939 SmallVector<Expr*, 4> Exprs; 11940 for (const OffsetOfComponent &OC : Components) { 11941 if (OC.isBrackets) { 11942 // Offset of an array sub-field. TODO: Should we allow vector elements? 11943 if (!CurrentType->isDependentType()) { 11944 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11945 if(!AT) 11946 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11947 << CurrentType); 11948 CurrentType = AT->getElementType(); 11949 } else 11950 CurrentType = Context.DependentTy; 11951 11952 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11953 if (IdxRval.isInvalid()) 11954 return ExprError(); 11955 Expr *Idx = IdxRval.get(); 11956 11957 // The expression must be an integral expression. 11958 // FIXME: An integral constant expression? 11959 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11960 !Idx->getType()->isIntegerType()) 11961 return ExprError(Diag(Idx->getLocStart(), 11962 diag::err_typecheck_subscript_not_integer) 11963 << Idx->getSourceRange()); 11964 11965 // Record this array index. 11966 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11967 Exprs.push_back(Idx); 11968 continue; 11969 } 11970 11971 // Offset of a field. 11972 if (CurrentType->isDependentType()) { 11973 // We have the offset of a field, but we can't look into the dependent 11974 // type. Just record the identifier of the field. 11975 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11976 CurrentType = Context.DependentTy; 11977 continue; 11978 } 11979 11980 // We need to have a complete type to look into. 11981 if (RequireCompleteType(OC.LocStart, CurrentType, 11982 diag::err_offsetof_incomplete_type)) 11983 return ExprError(); 11984 11985 // Look for the designated field. 11986 const RecordType *RC = CurrentType->getAs<RecordType>(); 11987 if (!RC) 11988 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11989 << CurrentType); 11990 RecordDecl *RD = RC->getDecl(); 11991 11992 // C++ [lib.support.types]p5: 11993 // The macro offsetof accepts a restricted set of type arguments in this 11994 // International Standard. type shall be a POD structure or a POD union 11995 // (clause 9). 11996 // C++11 [support.types]p4: 11997 // If type is not a standard-layout class (Clause 9), the results are 11998 // undefined. 11999 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12000 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12001 unsigned DiagID = 12002 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12003 : diag::ext_offsetof_non_pod_type; 12004 12005 if (!IsSafe && !DidWarnAboutNonPOD && 12006 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12007 PDiag(DiagID) 12008 << SourceRange(Components[0].LocStart, OC.LocEnd) 12009 << CurrentType)) 12010 DidWarnAboutNonPOD = true; 12011 } 12012 12013 // Look for the field. 12014 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12015 LookupQualifiedName(R, RD); 12016 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12017 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12018 if (!MemberDecl) { 12019 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12020 MemberDecl = IndirectMemberDecl->getAnonField(); 12021 } 12022 12023 if (!MemberDecl) 12024 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12025 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12026 OC.LocEnd)); 12027 12028 // C99 7.17p3: 12029 // (If the specified member is a bit-field, the behavior is undefined.) 12030 // 12031 // We diagnose this as an error. 12032 if (MemberDecl->isBitField()) { 12033 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12034 << MemberDecl->getDeclName() 12035 << SourceRange(BuiltinLoc, RParenLoc); 12036 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12037 return ExprError(); 12038 } 12039 12040 RecordDecl *Parent = MemberDecl->getParent(); 12041 if (IndirectMemberDecl) 12042 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12043 12044 // If the member was found in a base class, introduce OffsetOfNodes for 12045 // the base class indirections. 12046 CXXBasePaths Paths; 12047 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12048 Paths)) { 12049 if (Paths.getDetectedVirtual()) { 12050 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12051 << MemberDecl->getDeclName() 12052 << SourceRange(BuiltinLoc, RParenLoc); 12053 return ExprError(); 12054 } 12055 12056 CXXBasePath &Path = Paths.front(); 12057 for (const CXXBasePathElement &B : Path) 12058 Comps.push_back(OffsetOfNode(B.Base)); 12059 } 12060 12061 if (IndirectMemberDecl) { 12062 for (auto *FI : IndirectMemberDecl->chain()) { 12063 assert(isa<FieldDecl>(FI)); 12064 Comps.push_back(OffsetOfNode(OC.LocStart, 12065 cast<FieldDecl>(FI), OC.LocEnd)); 12066 } 12067 } else 12068 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12069 12070 CurrentType = MemberDecl->getType().getNonReferenceType(); 12071 } 12072 12073 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12074 Comps, Exprs, RParenLoc); 12075 } 12076 12077 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12078 SourceLocation BuiltinLoc, 12079 SourceLocation TypeLoc, 12080 ParsedType ParsedArgTy, 12081 ArrayRef<OffsetOfComponent> Components, 12082 SourceLocation RParenLoc) { 12083 12084 TypeSourceInfo *ArgTInfo; 12085 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12086 if (ArgTy.isNull()) 12087 return ExprError(); 12088 12089 if (!ArgTInfo) 12090 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12091 12092 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12093 } 12094 12095 12096 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12097 Expr *CondExpr, 12098 Expr *LHSExpr, Expr *RHSExpr, 12099 SourceLocation RPLoc) { 12100 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12101 12102 ExprValueKind VK = VK_RValue; 12103 ExprObjectKind OK = OK_Ordinary; 12104 QualType resType; 12105 bool ValueDependent = false; 12106 bool CondIsTrue = false; 12107 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12108 resType = Context.DependentTy; 12109 ValueDependent = true; 12110 } else { 12111 // The conditional expression is required to be a constant expression. 12112 llvm::APSInt condEval(32); 12113 ExprResult CondICE 12114 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12115 diag::err_typecheck_choose_expr_requires_constant, false); 12116 if (CondICE.isInvalid()) 12117 return ExprError(); 12118 CondExpr = CondICE.get(); 12119 CondIsTrue = condEval.getZExtValue(); 12120 12121 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12122 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12123 12124 resType = ActiveExpr->getType(); 12125 ValueDependent = ActiveExpr->isValueDependent(); 12126 VK = ActiveExpr->getValueKind(); 12127 OK = ActiveExpr->getObjectKind(); 12128 } 12129 12130 return new (Context) 12131 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12132 CondIsTrue, resType->isDependentType(), ValueDependent); 12133 } 12134 12135 //===----------------------------------------------------------------------===// 12136 // Clang Extensions. 12137 //===----------------------------------------------------------------------===// 12138 12139 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12140 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12141 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12142 12143 if (LangOpts.CPlusPlus) { 12144 Decl *ManglingContextDecl; 12145 if (MangleNumberingContext *MCtx = 12146 getCurrentMangleNumberContext(Block->getDeclContext(), 12147 ManglingContextDecl)) { 12148 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12149 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12150 } 12151 } 12152 12153 PushBlockScope(CurScope, Block); 12154 CurContext->addDecl(Block); 12155 if (CurScope) 12156 PushDeclContext(CurScope, Block); 12157 else 12158 CurContext = Block; 12159 12160 getCurBlock()->HasImplicitReturnType = true; 12161 12162 // Enter a new evaluation context to insulate the block from any 12163 // cleanups from the enclosing full-expression. 12164 PushExpressionEvaluationContext(PotentiallyEvaluated); 12165 } 12166 12167 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12168 Scope *CurScope) { 12169 assert(ParamInfo.getIdentifier() == nullptr && 12170 "block-id should have no identifier!"); 12171 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12172 BlockScopeInfo *CurBlock = getCurBlock(); 12173 12174 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12175 QualType T = Sig->getType(); 12176 12177 // FIXME: We should allow unexpanded parameter packs here, but that would, 12178 // in turn, make the block expression contain unexpanded parameter packs. 12179 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12180 // Drop the parameters. 12181 FunctionProtoType::ExtProtoInfo EPI; 12182 EPI.HasTrailingReturn = false; 12183 EPI.TypeQuals |= DeclSpec::TQ_const; 12184 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12185 Sig = Context.getTrivialTypeSourceInfo(T); 12186 } 12187 12188 // GetTypeForDeclarator always produces a function type for a block 12189 // literal signature. Furthermore, it is always a FunctionProtoType 12190 // unless the function was written with a typedef. 12191 assert(T->isFunctionType() && 12192 "GetTypeForDeclarator made a non-function block signature"); 12193 12194 // Look for an explicit signature in that function type. 12195 FunctionProtoTypeLoc ExplicitSignature; 12196 12197 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12198 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12199 12200 // Check whether that explicit signature was synthesized by 12201 // GetTypeForDeclarator. If so, don't save that as part of the 12202 // written signature. 12203 if (ExplicitSignature.getLocalRangeBegin() == 12204 ExplicitSignature.getLocalRangeEnd()) { 12205 // This would be much cheaper if we stored TypeLocs instead of 12206 // TypeSourceInfos. 12207 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12208 unsigned Size = Result.getFullDataSize(); 12209 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12210 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12211 12212 ExplicitSignature = FunctionProtoTypeLoc(); 12213 } 12214 } 12215 12216 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12217 CurBlock->FunctionType = T; 12218 12219 const FunctionType *Fn = T->getAs<FunctionType>(); 12220 QualType RetTy = Fn->getReturnType(); 12221 bool isVariadic = 12222 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12223 12224 CurBlock->TheDecl->setIsVariadic(isVariadic); 12225 12226 // Context.DependentTy is used as a placeholder for a missing block 12227 // return type. TODO: what should we do with declarators like: 12228 // ^ * { ... } 12229 // If the answer is "apply template argument deduction".... 12230 if (RetTy != Context.DependentTy) { 12231 CurBlock->ReturnType = RetTy; 12232 CurBlock->TheDecl->setBlockMissingReturnType(false); 12233 CurBlock->HasImplicitReturnType = false; 12234 } 12235 12236 // Push block parameters from the declarator if we had them. 12237 SmallVector<ParmVarDecl*, 8> Params; 12238 if (ExplicitSignature) { 12239 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12240 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12241 if (Param->getIdentifier() == nullptr && 12242 !Param->isImplicit() && 12243 !Param->isInvalidDecl() && 12244 !getLangOpts().CPlusPlus) 12245 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12246 Params.push_back(Param); 12247 } 12248 12249 // Fake up parameter variables if we have a typedef, like 12250 // ^ fntype { ... } 12251 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12252 for (const auto &I : Fn->param_types()) { 12253 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12254 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12255 Params.push_back(Param); 12256 } 12257 } 12258 12259 // Set the parameters on the block decl. 12260 if (!Params.empty()) { 12261 CurBlock->TheDecl->setParams(Params); 12262 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12263 /*CheckParameterNames=*/false); 12264 } 12265 12266 // Finally we can process decl attributes. 12267 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12268 12269 // Put the parameter variables in scope. 12270 for (auto AI : CurBlock->TheDecl->parameters()) { 12271 AI->setOwningFunction(CurBlock->TheDecl); 12272 12273 // If this has an identifier, add it to the scope stack. 12274 if (AI->getIdentifier()) { 12275 CheckShadow(CurBlock->TheScope, AI); 12276 12277 PushOnScopeChains(AI, CurBlock->TheScope); 12278 } 12279 } 12280 } 12281 12282 /// ActOnBlockError - If there is an error parsing a block, this callback 12283 /// is invoked to pop the information about the block from the action impl. 12284 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12285 // Leave the expression-evaluation context. 12286 DiscardCleanupsInEvaluationContext(); 12287 PopExpressionEvaluationContext(); 12288 12289 // Pop off CurBlock, handle nested blocks. 12290 PopDeclContext(); 12291 PopFunctionScopeInfo(); 12292 } 12293 12294 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12295 /// literal was successfully completed. ^(int x){...} 12296 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12297 Stmt *Body, Scope *CurScope) { 12298 // If blocks are disabled, emit an error. 12299 if (!LangOpts.Blocks) 12300 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12301 12302 // Leave the expression-evaluation context. 12303 if (hasAnyUnrecoverableErrorsInThisFunction()) 12304 DiscardCleanupsInEvaluationContext(); 12305 assert(!Cleanup.exprNeedsCleanups() && 12306 "cleanups within block not correctly bound!"); 12307 PopExpressionEvaluationContext(); 12308 12309 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12310 12311 if (BSI->HasImplicitReturnType) 12312 deduceClosureReturnType(*BSI); 12313 12314 PopDeclContext(); 12315 12316 QualType RetTy = Context.VoidTy; 12317 if (!BSI->ReturnType.isNull()) 12318 RetTy = BSI->ReturnType; 12319 12320 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12321 QualType BlockTy; 12322 12323 // Set the captured variables on the block. 12324 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12325 SmallVector<BlockDecl::Capture, 4> Captures; 12326 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12327 if (Cap.isThisCapture()) 12328 continue; 12329 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12330 Cap.isNested(), Cap.getInitExpr()); 12331 Captures.push_back(NewCap); 12332 } 12333 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12334 12335 // If the user wrote a function type in some form, try to use that. 12336 if (!BSI->FunctionType.isNull()) { 12337 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12338 12339 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12340 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12341 12342 // Turn protoless block types into nullary block types. 12343 if (isa<FunctionNoProtoType>(FTy)) { 12344 FunctionProtoType::ExtProtoInfo EPI; 12345 EPI.ExtInfo = Ext; 12346 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12347 12348 // Otherwise, if we don't need to change anything about the function type, 12349 // preserve its sugar structure. 12350 } else if (FTy->getReturnType() == RetTy && 12351 (!NoReturn || FTy->getNoReturnAttr())) { 12352 BlockTy = BSI->FunctionType; 12353 12354 // Otherwise, make the minimal modifications to the function type. 12355 } else { 12356 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12357 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12358 EPI.TypeQuals = 0; // FIXME: silently? 12359 EPI.ExtInfo = Ext; 12360 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12361 } 12362 12363 // If we don't have a function type, just build one from nothing. 12364 } else { 12365 FunctionProtoType::ExtProtoInfo EPI; 12366 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12367 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12368 } 12369 12370 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12371 BlockTy = Context.getBlockPointerType(BlockTy); 12372 12373 // If needed, diagnose invalid gotos and switches in the block. 12374 if (getCurFunction()->NeedsScopeChecking() && 12375 !PP.isCodeCompletionEnabled()) 12376 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12377 12378 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12379 12380 // Try to apply the named return value optimization. We have to check again 12381 // if we can do this, though, because blocks keep return statements around 12382 // to deduce an implicit return type. 12383 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12384 !BSI->TheDecl->isDependentContext()) 12385 computeNRVO(Body, BSI); 12386 12387 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12388 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12389 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12390 12391 // If the block isn't obviously global, i.e. it captures anything at 12392 // all, then we need to do a few things in the surrounding context: 12393 if (Result->getBlockDecl()->hasCaptures()) { 12394 // First, this expression has a new cleanup object. 12395 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12396 Cleanup.setExprNeedsCleanups(true); 12397 12398 // It also gets a branch-protected scope if any of the captured 12399 // variables needs destruction. 12400 for (const auto &CI : Result->getBlockDecl()->captures()) { 12401 const VarDecl *var = CI.getVariable(); 12402 if (var->getType().isDestructedType() != QualType::DK_none) { 12403 getCurFunction()->setHasBranchProtectedScope(); 12404 break; 12405 } 12406 } 12407 } 12408 12409 return Result; 12410 } 12411 12412 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12413 SourceLocation RPLoc) { 12414 TypeSourceInfo *TInfo; 12415 GetTypeFromParser(Ty, &TInfo); 12416 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12417 } 12418 12419 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12420 Expr *E, TypeSourceInfo *TInfo, 12421 SourceLocation RPLoc) { 12422 Expr *OrigExpr = E; 12423 bool IsMS = false; 12424 12425 // CUDA device code does not support varargs. 12426 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12427 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12428 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12429 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12430 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12431 } 12432 } 12433 12434 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12435 // as Microsoft ABI on an actual Microsoft platform, where 12436 // __builtin_ms_va_list and __builtin_va_list are the same.) 12437 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12438 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12439 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12440 if (Context.hasSameType(MSVaListType, E->getType())) { 12441 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12442 return ExprError(); 12443 IsMS = true; 12444 } 12445 } 12446 12447 // Get the va_list type 12448 QualType VaListType = Context.getBuiltinVaListType(); 12449 if (!IsMS) { 12450 if (VaListType->isArrayType()) { 12451 // Deal with implicit array decay; for example, on x86-64, 12452 // va_list is an array, but it's supposed to decay to 12453 // a pointer for va_arg. 12454 VaListType = Context.getArrayDecayedType(VaListType); 12455 // Make sure the input expression also decays appropriately. 12456 ExprResult Result = UsualUnaryConversions(E); 12457 if (Result.isInvalid()) 12458 return ExprError(); 12459 E = Result.get(); 12460 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12461 // If va_list is a record type and we are compiling in C++ mode, 12462 // check the argument using reference binding. 12463 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12464 Context, Context.getLValueReferenceType(VaListType), false); 12465 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12466 if (Init.isInvalid()) 12467 return ExprError(); 12468 E = Init.getAs<Expr>(); 12469 } else { 12470 // Otherwise, the va_list argument must be an l-value because 12471 // it is modified by va_arg. 12472 if (!E->isTypeDependent() && 12473 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12474 return ExprError(); 12475 } 12476 } 12477 12478 if (!IsMS && !E->isTypeDependent() && 12479 !Context.hasSameType(VaListType, E->getType())) 12480 return ExprError(Diag(E->getLocStart(), 12481 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12482 << OrigExpr->getType() << E->getSourceRange()); 12483 12484 if (!TInfo->getType()->isDependentType()) { 12485 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12486 diag::err_second_parameter_to_va_arg_incomplete, 12487 TInfo->getTypeLoc())) 12488 return ExprError(); 12489 12490 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12491 TInfo->getType(), 12492 diag::err_second_parameter_to_va_arg_abstract, 12493 TInfo->getTypeLoc())) 12494 return ExprError(); 12495 12496 if (!TInfo->getType().isPODType(Context)) { 12497 Diag(TInfo->getTypeLoc().getBeginLoc(), 12498 TInfo->getType()->isObjCLifetimeType() 12499 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12500 : diag::warn_second_parameter_to_va_arg_not_pod) 12501 << TInfo->getType() 12502 << TInfo->getTypeLoc().getSourceRange(); 12503 } 12504 12505 // Check for va_arg where arguments of the given type will be promoted 12506 // (i.e. this va_arg is guaranteed to have undefined behavior). 12507 QualType PromoteType; 12508 if (TInfo->getType()->isPromotableIntegerType()) { 12509 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12510 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12511 PromoteType = QualType(); 12512 } 12513 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12514 PromoteType = Context.DoubleTy; 12515 if (!PromoteType.isNull()) 12516 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12517 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12518 << TInfo->getType() 12519 << PromoteType 12520 << TInfo->getTypeLoc().getSourceRange()); 12521 } 12522 12523 QualType T = TInfo->getType().getNonLValueExprType(Context); 12524 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12525 } 12526 12527 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12528 // The type of __null will be int or long, depending on the size of 12529 // pointers on the target. 12530 QualType Ty; 12531 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12532 if (pw == Context.getTargetInfo().getIntWidth()) 12533 Ty = Context.IntTy; 12534 else if (pw == Context.getTargetInfo().getLongWidth()) 12535 Ty = Context.LongTy; 12536 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12537 Ty = Context.LongLongTy; 12538 else { 12539 llvm_unreachable("I don't know size of pointer!"); 12540 } 12541 12542 return new (Context) GNUNullExpr(Ty, TokenLoc); 12543 } 12544 12545 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12546 bool Diagnose) { 12547 if (!getLangOpts().ObjC1) 12548 return false; 12549 12550 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12551 if (!PT) 12552 return false; 12553 12554 if (!PT->isObjCIdType()) { 12555 // Check if the destination is the 'NSString' interface. 12556 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12557 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12558 return false; 12559 } 12560 12561 // Ignore any parens, implicit casts (should only be 12562 // array-to-pointer decays), and not-so-opaque values. The last is 12563 // important for making this trigger for property assignments. 12564 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12565 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12566 if (OV->getSourceExpr()) 12567 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12568 12569 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12570 if (!SL || !SL->isAscii()) 12571 return false; 12572 if (Diagnose) { 12573 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12574 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12575 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12576 } 12577 return true; 12578 } 12579 12580 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12581 const Expr *SrcExpr) { 12582 if (!DstType->isFunctionPointerType() || 12583 !SrcExpr->getType()->isFunctionType()) 12584 return false; 12585 12586 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12587 if (!DRE) 12588 return false; 12589 12590 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12591 if (!FD) 12592 return false; 12593 12594 return !S.checkAddressOfFunctionIsAvailable(FD, 12595 /*Complain=*/true, 12596 SrcExpr->getLocStart()); 12597 } 12598 12599 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12600 SourceLocation Loc, 12601 QualType DstType, QualType SrcType, 12602 Expr *SrcExpr, AssignmentAction Action, 12603 bool *Complained) { 12604 if (Complained) 12605 *Complained = false; 12606 12607 // Decode the result (notice that AST's are still created for extensions). 12608 bool CheckInferredResultType = false; 12609 bool isInvalid = false; 12610 unsigned DiagKind = 0; 12611 FixItHint Hint; 12612 ConversionFixItGenerator ConvHints; 12613 bool MayHaveConvFixit = false; 12614 bool MayHaveFunctionDiff = false; 12615 const ObjCInterfaceDecl *IFace = nullptr; 12616 const ObjCProtocolDecl *PDecl = nullptr; 12617 12618 switch (ConvTy) { 12619 case Compatible: 12620 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12621 return false; 12622 12623 case PointerToInt: 12624 DiagKind = diag::ext_typecheck_convert_pointer_int; 12625 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12626 MayHaveConvFixit = true; 12627 break; 12628 case IntToPointer: 12629 DiagKind = diag::ext_typecheck_convert_int_pointer; 12630 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12631 MayHaveConvFixit = true; 12632 break; 12633 case IncompatiblePointer: 12634 if (Action == AA_Passing_CFAudited) 12635 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12636 else if (SrcType->isFunctionPointerType() && 12637 DstType->isFunctionPointerType()) 12638 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12639 else 12640 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12641 12642 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12643 SrcType->isObjCObjectPointerType(); 12644 if (Hint.isNull() && !CheckInferredResultType) { 12645 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12646 } 12647 else if (CheckInferredResultType) { 12648 SrcType = SrcType.getUnqualifiedType(); 12649 DstType = DstType.getUnqualifiedType(); 12650 } 12651 MayHaveConvFixit = true; 12652 break; 12653 case IncompatiblePointerSign: 12654 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12655 break; 12656 case FunctionVoidPointer: 12657 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12658 break; 12659 case IncompatiblePointerDiscardsQualifiers: { 12660 // Perform array-to-pointer decay if necessary. 12661 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12662 12663 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12664 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12665 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12666 DiagKind = diag::err_typecheck_incompatible_address_space; 12667 break; 12668 12669 12670 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12671 DiagKind = diag::err_typecheck_incompatible_ownership; 12672 break; 12673 } 12674 12675 llvm_unreachable("unknown error case for discarding qualifiers!"); 12676 // fallthrough 12677 } 12678 case CompatiblePointerDiscardsQualifiers: 12679 // If the qualifiers lost were because we were applying the 12680 // (deprecated) C++ conversion from a string literal to a char* 12681 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12682 // Ideally, this check would be performed in 12683 // checkPointerTypesForAssignment. However, that would require a 12684 // bit of refactoring (so that the second argument is an 12685 // expression, rather than a type), which should be done as part 12686 // of a larger effort to fix checkPointerTypesForAssignment for 12687 // C++ semantics. 12688 if (getLangOpts().CPlusPlus && 12689 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12690 return false; 12691 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12692 break; 12693 case IncompatibleNestedPointerQualifiers: 12694 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12695 break; 12696 case IntToBlockPointer: 12697 DiagKind = diag::err_int_to_block_pointer; 12698 break; 12699 case IncompatibleBlockPointer: 12700 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12701 break; 12702 case IncompatibleObjCQualifiedId: { 12703 if (SrcType->isObjCQualifiedIdType()) { 12704 const ObjCObjectPointerType *srcOPT = 12705 SrcType->getAs<ObjCObjectPointerType>(); 12706 for (auto *srcProto : srcOPT->quals()) { 12707 PDecl = srcProto; 12708 break; 12709 } 12710 if (const ObjCInterfaceType *IFaceT = 12711 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12712 IFace = IFaceT->getDecl(); 12713 } 12714 else if (DstType->isObjCQualifiedIdType()) { 12715 const ObjCObjectPointerType *dstOPT = 12716 DstType->getAs<ObjCObjectPointerType>(); 12717 for (auto *dstProto : dstOPT->quals()) { 12718 PDecl = dstProto; 12719 break; 12720 } 12721 if (const ObjCInterfaceType *IFaceT = 12722 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12723 IFace = IFaceT->getDecl(); 12724 } 12725 DiagKind = diag::warn_incompatible_qualified_id; 12726 break; 12727 } 12728 case IncompatibleVectors: 12729 DiagKind = diag::warn_incompatible_vectors; 12730 break; 12731 case IncompatibleObjCWeakRef: 12732 DiagKind = diag::err_arc_weak_unavailable_assign; 12733 break; 12734 case Incompatible: 12735 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12736 if (Complained) 12737 *Complained = true; 12738 return true; 12739 } 12740 12741 DiagKind = diag::err_typecheck_convert_incompatible; 12742 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12743 MayHaveConvFixit = true; 12744 isInvalid = true; 12745 MayHaveFunctionDiff = true; 12746 break; 12747 } 12748 12749 QualType FirstType, SecondType; 12750 switch (Action) { 12751 case AA_Assigning: 12752 case AA_Initializing: 12753 // The destination type comes first. 12754 FirstType = DstType; 12755 SecondType = SrcType; 12756 break; 12757 12758 case AA_Returning: 12759 case AA_Passing: 12760 case AA_Passing_CFAudited: 12761 case AA_Converting: 12762 case AA_Sending: 12763 case AA_Casting: 12764 // The source type comes first. 12765 FirstType = SrcType; 12766 SecondType = DstType; 12767 break; 12768 } 12769 12770 PartialDiagnostic FDiag = PDiag(DiagKind); 12771 if (Action == AA_Passing_CFAudited) 12772 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12773 else 12774 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12775 12776 // If we can fix the conversion, suggest the FixIts. 12777 assert(ConvHints.isNull() || Hint.isNull()); 12778 if (!ConvHints.isNull()) { 12779 for (FixItHint &H : ConvHints.Hints) 12780 FDiag << H; 12781 } else { 12782 FDiag << Hint; 12783 } 12784 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12785 12786 if (MayHaveFunctionDiff) 12787 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12788 12789 Diag(Loc, FDiag); 12790 if (DiagKind == diag::warn_incompatible_qualified_id && 12791 PDecl && IFace && !IFace->hasDefinition()) 12792 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 12793 << IFace->getName() << PDecl->getName(); 12794 12795 if (SecondType == Context.OverloadTy) 12796 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12797 FirstType, /*TakingAddress=*/true); 12798 12799 if (CheckInferredResultType) 12800 EmitRelatedResultTypeNote(SrcExpr); 12801 12802 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12803 EmitRelatedResultTypeNoteForReturn(DstType); 12804 12805 if (Complained) 12806 *Complained = true; 12807 return isInvalid; 12808 } 12809 12810 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12811 llvm::APSInt *Result) { 12812 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12813 public: 12814 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12815 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12816 } 12817 } Diagnoser; 12818 12819 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12820 } 12821 12822 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12823 llvm::APSInt *Result, 12824 unsigned DiagID, 12825 bool AllowFold) { 12826 class IDDiagnoser : public VerifyICEDiagnoser { 12827 unsigned DiagID; 12828 12829 public: 12830 IDDiagnoser(unsigned DiagID) 12831 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12832 12833 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12834 S.Diag(Loc, DiagID) << SR; 12835 } 12836 } Diagnoser(DiagID); 12837 12838 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12839 } 12840 12841 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12842 SourceRange SR) { 12843 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12844 } 12845 12846 ExprResult 12847 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12848 VerifyICEDiagnoser &Diagnoser, 12849 bool AllowFold) { 12850 SourceLocation DiagLoc = E->getLocStart(); 12851 12852 if (getLangOpts().CPlusPlus11) { 12853 // C++11 [expr.const]p5: 12854 // If an expression of literal class type is used in a context where an 12855 // integral constant expression is required, then that class type shall 12856 // have a single non-explicit conversion function to an integral or 12857 // unscoped enumeration type 12858 ExprResult Converted; 12859 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12860 public: 12861 CXX11ConvertDiagnoser(bool Silent) 12862 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12863 Silent, true) {} 12864 12865 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12866 QualType T) override { 12867 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12868 } 12869 12870 SemaDiagnosticBuilder diagnoseIncomplete( 12871 Sema &S, SourceLocation Loc, QualType T) override { 12872 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12873 } 12874 12875 SemaDiagnosticBuilder diagnoseExplicitConv( 12876 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12877 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12878 } 12879 12880 SemaDiagnosticBuilder noteExplicitConv( 12881 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12882 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12883 << ConvTy->isEnumeralType() << ConvTy; 12884 } 12885 12886 SemaDiagnosticBuilder diagnoseAmbiguous( 12887 Sema &S, SourceLocation Loc, QualType T) override { 12888 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12889 } 12890 12891 SemaDiagnosticBuilder noteAmbiguous( 12892 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12893 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12894 << ConvTy->isEnumeralType() << ConvTy; 12895 } 12896 12897 SemaDiagnosticBuilder diagnoseConversion( 12898 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12899 llvm_unreachable("conversion functions are permitted"); 12900 } 12901 } ConvertDiagnoser(Diagnoser.Suppress); 12902 12903 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12904 ConvertDiagnoser); 12905 if (Converted.isInvalid()) 12906 return Converted; 12907 E = Converted.get(); 12908 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12909 return ExprError(); 12910 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12911 // An ICE must be of integral or unscoped enumeration type. 12912 if (!Diagnoser.Suppress) 12913 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12914 return ExprError(); 12915 } 12916 12917 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12918 // in the non-ICE case. 12919 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12920 if (Result) 12921 *Result = E->EvaluateKnownConstInt(Context); 12922 return E; 12923 } 12924 12925 Expr::EvalResult EvalResult; 12926 SmallVector<PartialDiagnosticAt, 8> Notes; 12927 EvalResult.Diag = &Notes; 12928 12929 // Try to evaluate the expression, and produce diagnostics explaining why it's 12930 // not a constant expression as a side-effect. 12931 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12932 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12933 12934 // In C++11, we can rely on diagnostics being produced for any expression 12935 // which is not a constant expression. If no diagnostics were produced, then 12936 // this is a constant expression. 12937 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12938 if (Result) 12939 *Result = EvalResult.Val.getInt(); 12940 return E; 12941 } 12942 12943 // If our only note is the usual "invalid subexpression" note, just point 12944 // the caret at its location rather than producing an essentially 12945 // redundant note. 12946 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12947 diag::note_invalid_subexpr_in_const_expr) { 12948 DiagLoc = Notes[0].first; 12949 Notes.clear(); 12950 } 12951 12952 if (!Folded || !AllowFold) { 12953 if (!Diagnoser.Suppress) { 12954 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12955 for (const PartialDiagnosticAt &Note : Notes) 12956 Diag(Note.first, Note.second); 12957 } 12958 12959 return ExprError(); 12960 } 12961 12962 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12963 for (const PartialDiagnosticAt &Note : Notes) 12964 Diag(Note.first, Note.second); 12965 12966 if (Result) 12967 *Result = EvalResult.Val.getInt(); 12968 return E; 12969 } 12970 12971 namespace { 12972 // Handle the case where we conclude a expression which we speculatively 12973 // considered to be unevaluated is actually evaluated. 12974 class TransformToPE : public TreeTransform<TransformToPE> { 12975 typedef TreeTransform<TransformToPE> BaseTransform; 12976 12977 public: 12978 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12979 12980 // Make sure we redo semantic analysis 12981 bool AlwaysRebuild() { return true; } 12982 12983 // Make sure we handle LabelStmts correctly. 12984 // FIXME: This does the right thing, but maybe we need a more general 12985 // fix to TreeTransform? 12986 StmtResult TransformLabelStmt(LabelStmt *S) { 12987 S->getDecl()->setStmt(nullptr); 12988 return BaseTransform::TransformLabelStmt(S); 12989 } 12990 12991 // We need to special-case DeclRefExprs referring to FieldDecls which 12992 // are not part of a member pointer formation; normal TreeTransforming 12993 // doesn't catch this case because of the way we represent them in the AST. 12994 // FIXME: This is a bit ugly; is it really the best way to handle this 12995 // case? 12996 // 12997 // Error on DeclRefExprs referring to FieldDecls. 12998 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12999 if (isa<FieldDecl>(E->getDecl()) && 13000 !SemaRef.isUnevaluatedContext()) 13001 return SemaRef.Diag(E->getLocation(), 13002 diag::err_invalid_non_static_member_use) 13003 << E->getDecl() << E->getSourceRange(); 13004 13005 return BaseTransform::TransformDeclRefExpr(E); 13006 } 13007 13008 // Exception: filter out member pointer formation 13009 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13010 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13011 return E; 13012 13013 return BaseTransform::TransformUnaryOperator(E); 13014 } 13015 13016 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13017 // Lambdas never need to be transformed. 13018 return E; 13019 } 13020 }; 13021 } 13022 13023 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13024 assert(isUnevaluatedContext() && 13025 "Should only transform unevaluated expressions"); 13026 ExprEvalContexts.back().Context = 13027 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13028 if (isUnevaluatedContext()) 13029 return E; 13030 return TransformToPE(*this).TransformExpr(E); 13031 } 13032 13033 void 13034 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13035 Decl *LambdaContextDecl, 13036 bool IsDecltype) { 13037 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13038 LambdaContextDecl, IsDecltype); 13039 Cleanup.reset(); 13040 if (!MaybeODRUseExprs.empty()) 13041 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13042 } 13043 13044 void 13045 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13046 ReuseLambdaContextDecl_t, 13047 bool IsDecltype) { 13048 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13049 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13050 } 13051 13052 void Sema::PopExpressionEvaluationContext() { 13053 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13054 unsigned NumTypos = Rec.NumTypos; 13055 13056 if (!Rec.Lambdas.empty()) { 13057 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13058 unsigned D; 13059 if (Rec.isUnevaluated()) { 13060 // C++11 [expr.prim.lambda]p2: 13061 // A lambda-expression shall not appear in an unevaluated operand 13062 // (Clause 5). 13063 D = diag::err_lambda_unevaluated_operand; 13064 } else { 13065 // C++1y [expr.const]p2: 13066 // A conditional-expression e is a core constant expression unless the 13067 // evaluation of e, following the rules of the abstract machine, would 13068 // evaluate [...] a lambda-expression. 13069 D = diag::err_lambda_in_constant_expression; 13070 } 13071 for (const auto *L : Rec.Lambdas) 13072 Diag(L->getLocStart(), D); 13073 } else { 13074 // Mark the capture expressions odr-used. This was deferred 13075 // during lambda expression creation. 13076 for (auto *Lambda : Rec.Lambdas) { 13077 for (auto *C : Lambda->capture_inits()) 13078 MarkDeclarationsReferencedInExpr(C); 13079 } 13080 } 13081 } 13082 13083 // When are coming out of an unevaluated context, clear out any 13084 // temporaries that we may have created as part of the evaluation of 13085 // the expression in that context: they aren't relevant because they 13086 // will never be constructed. 13087 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13088 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13089 ExprCleanupObjects.end()); 13090 Cleanup = Rec.ParentCleanup; 13091 CleanupVarDeclMarking(); 13092 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13093 // Otherwise, merge the contexts together. 13094 } else { 13095 Cleanup.mergeFrom(Rec.ParentCleanup); 13096 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13097 Rec.SavedMaybeODRUseExprs.end()); 13098 } 13099 13100 // Pop the current expression evaluation context off the stack. 13101 ExprEvalContexts.pop_back(); 13102 13103 if (!ExprEvalContexts.empty()) 13104 ExprEvalContexts.back().NumTypos += NumTypos; 13105 else 13106 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13107 "last ExpressionEvaluationContextRecord"); 13108 } 13109 13110 void Sema::DiscardCleanupsInEvaluationContext() { 13111 ExprCleanupObjects.erase( 13112 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13113 ExprCleanupObjects.end()); 13114 Cleanup.reset(); 13115 MaybeODRUseExprs.clear(); 13116 } 13117 13118 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13119 if (!E->getType()->isVariablyModifiedType()) 13120 return E; 13121 return TransformToPotentiallyEvaluated(E); 13122 } 13123 13124 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 13125 // Do not mark anything as "used" within a dependent context; wait for 13126 // an instantiation. 13127 if (SemaRef.CurContext->isDependentContext()) 13128 return false; 13129 13130 switch (SemaRef.ExprEvalContexts.back().Context) { 13131 case Sema::Unevaluated: 13132 case Sema::UnevaluatedAbstract: 13133 // We are in an expression that is not potentially evaluated; do nothing. 13134 // (Depending on how you read the standard, we actually do need to do 13135 // something here for null pointer constants, but the standard's 13136 // definition of a null pointer constant is completely crazy.) 13137 return false; 13138 13139 case Sema::DiscardedStatement: 13140 // These are technically a potentially evaluated but they have the effect 13141 // of suppressing use marking. 13142 return false; 13143 13144 case Sema::ConstantEvaluated: 13145 case Sema::PotentiallyEvaluated: 13146 // We are in a potentially evaluated expression (or a constant-expression 13147 // in C++03); we need to do implicit template instantiation, implicitly 13148 // define class members, and mark most declarations as used. 13149 return true; 13150 13151 case Sema::PotentiallyEvaluatedIfUsed: 13152 // Referenced declarations will only be used if the construct in the 13153 // containing expression is used. 13154 return false; 13155 } 13156 llvm_unreachable("Invalid context"); 13157 } 13158 13159 /// \brief Mark a function referenced, and check whether it is odr-used 13160 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13161 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13162 bool MightBeOdrUse) { 13163 assert(Func && "No function?"); 13164 13165 Func->setReferenced(); 13166 13167 // C++11 [basic.def.odr]p3: 13168 // A function whose name appears as a potentially-evaluated expression is 13169 // odr-used if it is the unique lookup result or the selected member of a 13170 // set of overloaded functions [...]. 13171 // 13172 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13173 // can just check that here. 13174 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13175 13176 // Determine whether we require a function definition to exist, per 13177 // C++11 [temp.inst]p3: 13178 // Unless a function template specialization has been explicitly 13179 // instantiated or explicitly specialized, the function template 13180 // specialization is implicitly instantiated when the specialization is 13181 // referenced in a context that requires a function definition to exist. 13182 // 13183 // We consider constexpr function templates to be referenced in a context 13184 // that requires a definition to exist whenever they are referenced. 13185 // 13186 // FIXME: This instantiates constexpr functions too frequently. If this is 13187 // really an unevaluated context (and we're not just in the definition of a 13188 // function template or overload resolution or other cases which we 13189 // incorrectly consider to be unevaluated contexts), and we're not in a 13190 // subexpression which we actually need to evaluate (for instance, a 13191 // template argument, array bound or an expression in a braced-init-list), 13192 // we are not permitted to instantiate this constexpr function definition. 13193 // 13194 // FIXME: This also implicitly defines special members too frequently. They 13195 // are only supposed to be implicitly defined if they are odr-used, but they 13196 // are not odr-used from constant expressions in unevaluated contexts. 13197 // However, they cannot be referenced if they are deleted, and they are 13198 // deleted whenever the implicit definition of the special member would 13199 // fail (with very few exceptions). 13200 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13201 bool NeedDefinition = 13202 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13203 (MD && !MD->isUserProvided()))); 13204 13205 // C++14 [temp.expl.spec]p6: 13206 // If a template [...] is explicitly specialized then that specialization 13207 // shall be declared before the first use of that specialization that would 13208 // cause an implicit instantiation to take place, in every translation unit 13209 // in which such a use occurs 13210 if (NeedDefinition && 13211 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13212 Func->getMemberSpecializationInfo())) 13213 checkSpecializationVisibility(Loc, Func); 13214 13215 // C++14 [except.spec]p17: 13216 // An exception-specification is considered to be needed when: 13217 // - the function is odr-used or, if it appears in an unevaluated operand, 13218 // would be odr-used if the expression were potentially-evaluated; 13219 // 13220 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13221 // function is a pure virtual function we're calling, and in that case the 13222 // function was selected by overload resolution and we need to resolve its 13223 // exception specification for a different reason. 13224 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13225 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13226 ResolveExceptionSpec(Loc, FPT); 13227 13228 // If we don't need to mark the function as used, and we don't need to 13229 // try to provide a definition, there's nothing more to do. 13230 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13231 (!NeedDefinition || Func->getBody())) 13232 return; 13233 13234 // Note that this declaration has been used. 13235 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13236 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13237 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13238 if (Constructor->isDefaultConstructor()) { 13239 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13240 return; 13241 DefineImplicitDefaultConstructor(Loc, Constructor); 13242 } else if (Constructor->isCopyConstructor()) { 13243 DefineImplicitCopyConstructor(Loc, Constructor); 13244 } else if (Constructor->isMoveConstructor()) { 13245 DefineImplicitMoveConstructor(Loc, Constructor); 13246 } 13247 } else if (Constructor->getInheritedConstructor()) { 13248 DefineInheritingConstructor(Loc, Constructor); 13249 } 13250 } else if (CXXDestructorDecl *Destructor = 13251 dyn_cast<CXXDestructorDecl>(Func)) { 13252 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13253 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13254 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13255 return; 13256 DefineImplicitDestructor(Loc, Destructor); 13257 } 13258 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13259 MarkVTableUsed(Loc, Destructor->getParent()); 13260 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13261 if (MethodDecl->isOverloadedOperator() && 13262 MethodDecl->getOverloadedOperator() == OO_Equal) { 13263 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13264 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13265 if (MethodDecl->isCopyAssignmentOperator()) 13266 DefineImplicitCopyAssignment(Loc, MethodDecl); 13267 else if (MethodDecl->isMoveAssignmentOperator()) 13268 DefineImplicitMoveAssignment(Loc, MethodDecl); 13269 } 13270 } else if (isa<CXXConversionDecl>(MethodDecl) && 13271 MethodDecl->getParent()->isLambda()) { 13272 CXXConversionDecl *Conversion = 13273 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13274 if (Conversion->isLambdaToBlockPointerConversion()) 13275 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13276 else 13277 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13278 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13279 MarkVTableUsed(Loc, MethodDecl->getParent()); 13280 } 13281 13282 // Recursive functions should be marked when used from another function. 13283 // FIXME: Is this really right? 13284 if (CurContext == Func) return; 13285 13286 // Implicit instantiation of function templates and member functions of 13287 // class templates. 13288 if (Func->isImplicitlyInstantiable()) { 13289 bool AlreadyInstantiated = false; 13290 SourceLocation PointOfInstantiation = Loc; 13291 if (FunctionTemplateSpecializationInfo *SpecInfo 13292 = Func->getTemplateSpecializationInfo()) { 13293 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13294 SpecInfo->setPointOfInstantiation(Loc); 13295 else if (SpecInfo->getTemplateSpecializationKind() 13296 == TSK_ImplicitInstantiation) { 13297 AlreadyInstantiated = true; 13298 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13299 } 13300 } else if (MemberSpecializationInfo *MSInfo 13301 = Func->getMemberSpecializationInfo()) { 13302 if (MSInfo->getPointOfInstantiation().isInvalid()) 13303 MSInfo->setPointOfInstantiation(Loc); 13304 else if (MSInfo->getTemplateSpecializationKind() 13305 == TSK_ImplicitInstantiation) { 13306 AlreadyInstantiated = true; 13307 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13308 } 13309 } 13310 13311 if (!AlreadyInstantiated || Func->isConstexpr()) { 13312 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13313 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13314 ActiveTemplateInstantiations.size()) 13315 PendingLocalImplicitInstantiations.push_back( 13316 std::make_pair(Func, PointOfInstantiation)); 13317 else if (Func->isConstexpr()) 13318 // Do not defer instantiations of constexpr functions, to avoid the 13319 // expression evaluator needing to call back into Sema if it sees a 13320 // call to such a function. 13321 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13322 else { 13323 PendingInstantiations.push_back(std::make_pair(Func, 13324 PointOfInstantiation)); 13325 // Notify the consumer that a function was implicitly instantiated. 13326 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13327 } 13328 } 13329 } else { 13330 // Walk redefinitions, as some of them may be instantiable. 13331 for (auto i : Func->redecls()) { 13332 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13333 MarkFunctionReferenced(Loc, i, OdrUse); 13334 } 13335 } 13336 13337 if (!OdrUse) return; 13338 13339 // Keep track of used but undefined functions. 13340 if (!Func->isDefined()) { 13341 if (mightHaveNonExternalLinkage(Func)) 13342 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13343 else if (Func->getMostRecentDecl()->isInlined() && 13344 !LangOpts.GNUInline && 13345 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13346 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13347 } 13348 13349 Func->markUsed(Context); 13350 } 13351 13352 static void 13353 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13354 ValueDecl *var, DeclContext *DC) { 13355 DeclContext *VarDC = var->getDeclContext(); 13356 13357 // If the parameter still belongs to the translation unit, then 13358 // we're actually just using one parameter in the declaration of 13359 // the next. 13360 if (isa<ParmVarDecl>(var) && 13361 isa<TranslationUnitDecl>(VarDC)) 13362 return; 13363 13364 // For C code, don't diagnose about capture if we're not actually in code 13365 // right now; it's impossible to write a non-constant expression outside of 13366 // function context, so we'll get other (more useful) diagnostics later. 13367 // 13368 // For C++, things get a bit more nasty... it would be nice to suppress this 13369 // diagnostic for certain cases like using a local variable in an array bound 13370 // for a member of a local class, but the correct predicate is not obvious. 13371 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13372 return; 13373 13374 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13375 unsigned ContextKind = 3; // unknown 13376 if (isa<CXXMethodDecl>(VarDC) && 13377 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13378 ContextKind = 2; 13379 } else if (isa<FunctionDecl>(VarDC)) { 13380 ContextKind = 0; 13381 } else if (isa<BlockDecl>(VarDC)) { 13382 ContextKind = 1; 13383 } 13384 13385 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13386 << var << ValueKind << ContextKind << VarDC; 13387 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13388 << var; 13389 13390 // FIXME: Add additional diagnostic info about class etc. which prevents 13391 // capture. 13392 } 13393 13394 13395 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13396 bool &SubCapturesAreNested, 13397 QualType &CaptureType, 13398 QualType &DeclRefType) { 13399 // Check whether we've already captured it. 13400 if (CSI->CaptureMap.count(Var)) { 13401 // If we found a capture, any subcaptures are nested. 13402 SubCapturesAreNested = true; 13403 13404 // Retrieve the capture type for this variable. 13405 CaptureType = CSI->getCapture(Var).getCaptureType(); 13406 13407 // Compute the type of an expression that refers to this variable. 13408 DeclRefType = CaptureType.getNonReferenceType(); 13409 13410 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13411 // are mutable in the sense that user can change their value - they are 13412 // private instances of the captured declarations. 13413 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13414 if (Cap.isCopyCapture() && 13415 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13416 !(isa<CapturedRegionScopeInfo>(CSI) && 13417 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13418 DeclRefType.addConst(); 13419 return true; 13420 } 13421 return false; 13422 } 13423 13424 // Only block literals, captured statements, and lambda expressions can 13425 // capture; other scopes don't work. 13426 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13427 SourceLocation Loc, 13428 const bool Diagnose, Sema &S) { 13429 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13430 return getLambdaAwareParentOfDeclContext(DC); 13431 else if (Var->hasLocalStorage()) { 13432 if (Diagnose) 13433 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13434 } 13435 return nullptr; 13436 } 13437 13438 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13439 // certain types of variables (unnamed, variably modified types etc.) 13440 // so check for eligibility. 13441 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13442 SourceLocation Loc, 13443 const bool Diagnose, Sema &S) { 13444 13445 bool IsBlock = isa<BlockScopeInfo>(CSI); 13446 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13447 13448 // Lambdas are not allowed to capture unnamed variables 13449 // (e.g. anonymous unions). 13450 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13451 // assuming that's the intent. 13452 if (IsLambda && !Var->getDeclName()) { 13453 if (Diagnose) { 13454 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13455 S.Diag(Var->getLocation(), diag::note_declared_at); 13456 } 13457 return false; 13458 } 13459 13460 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13461 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13462 if (Diagnose) { 13463 S.Diag(Loc, diag::err_ref_vm_type); 13464 S.Diag(Var->getLocation(), diag::note_previous_decl) 13465 << Var->getDeclName(); 13466 } 13467 return false; 13468 } 13469 // Prohibit structs with flexible array members too. 13470 // We cannot capture what is in the tail end of the struct. 13471 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13472 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13473 if (Diagnose) { 13474 if (IsBlock) 13475 S.Diag(Loc, diag::err_ref_flexarray_type); 13476 else 13477 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13478 << Var->getDeclName(); 13479 S.Diag(Var->getLocation(), diag::note_previous_decl) 13480 << Var->getDeclName(); 13481 } 13482 return false; 13483 } 13484 } 13485 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13486 // Lambdas and captured statements are not allowed to capture __block 13487 // variables; they don't support the expected semantics. 13488 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13489 if (Diagnose) { 13490 S.Diag(Loc, diag::err_capture_block_variable) 13491 << Var->getDeclName() << !IsLambda; 13492 S.Diag(Var->getLocation(), diag::note_previous_decl) 13493 << Var->getDeclName(); 13494 } 13495 return false; 13496 } 13497 13498 return true; 13499 } 13500 13501 // Returns true if the capture by block was successful. 13502 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13503 SourceLocation Loc, 13504 const bool BuildAndDiagnose, 13505 QualType &CaptureType, 13506 QualType &DeclRefType, 13507 const bool Nested, 13508 Sema &S) { 13509 Expr *CopyExpr = nullptr; 13510 bool ByRef = false; 13511 13512 // Blocks are not allowed to capture arrays. 13513 if (CaptureType->isArrayType()) { 13514 if (BuildAndDiagnose) { 13515 S.Diag(Loc, diag::err_ref_array_type); 13516 S.Diag(Var->getLocation(), diag::note_previous_decl) 13517 << Var->getDeclName(); 13518 } 13519 return false; 13520 } 13521 13522 // Forbid the block-capture of autoreleasing variables. 13523 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13524 if (BuildAndDiagnose) { 13525 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13526 << /*block*/ 0; 13527 S.Diag(Var->getLocation(), diag::note_previous_decl) 13528 << Var->getDeclName(); 13529 } 13530 return false; 13531 } 13532 13533 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13534 if (auto *PT = dyn_cast<PointerType>(CaptureType)) { 13535 QualType PointeeTy = PT->getPointeeType(); 13536 if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) && 13537 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13538 !isa<AttributedType>(PointeeTy)) { 13539 if (BuildAndDiagnose) { 13540 SourceLocation VarLoc = Var->getLocation(); 13541 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13542 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) << 13543 FixItHint::CreateInsertion(VarLoc, "__autoreleasing"); 13544 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13545 } 13546 } 13547 } 13548 13549 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13550 if (HasBlocksAttr || CaptureType->isReferenceType() || 13551 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13552 // Block capture by reference does not change the capture or 13553 // declaration reference types. 13554 ByRef = true; 13555 } else { 13556 // Block capture by copy introduces 'const'. 13557 CaptureType = CaptureType.getNonReferenceType().withConst(); 13558 DeclRefType = CaptureType; 13559 13560 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13561 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13562 // The capture logic needs the destructor, so make sure we mark it. 13563 // Usually this is unnecessary because most local variables have 13564 // their destructors marked at declaration time, but parameters are 13565 // an exception because it's technically only the call site that 13566 // actually requires the destructor. 13567 if (isa<ParmVarDecl>(Var)) 13568 S.FinalizeVarWithDestructor(Var, Record); 13569 13570 // Enter a new evaluation context to insulate the copy 13571 // full-expression. 13572 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13573 13574 // According to the blocks spec, the capture of a variable from 13575 // the stack requires a const copy constructor. This is not true 13576 // of the copy/move done to move a __block variable to the heap. 13577 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13578 DeclRefType.withConst(), 13579 VK_LValue, Loc); 13580 13581 ExprResult Result 13582 = S.PerformCopyInitialization( 13583 InitializedEntity::InitializeBlock(Var->getLocation(), 13584 CaptureType, false), 13585 Loc, DeclRef); 13586 13587 // Build a full-expression copy expression if initialization 13588 // succeeded and used a non-trivial constructor. Recover from 13589 // errors by pretending that the copy isn't necessary. 13590 if (!Result.isInvalid() && 13591 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13592 ->isTrivial()) { 13593 Result = S.MaybeCreateExprWithCleanups(Result); 13594 CopyExpr = Result.get(); 13595 } 13596 } 13597 } 13598 } 13599 13600 // Actually capture the variable. 13601 if (BuildAndDiagnose) 13602 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13603 SourceLocation(), CaptureType, CopyExpr); 13604 13605 return true; 13606 13607 } 13608 13609 13610 /// \brief Capture the given variable in the captured region. 13611 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13612 VarDecl *Var, 13613 SourceLocation Loc, 13614 const bool BuildAndDiagnose, 13615 QualType &CaptureType, 13616 QualType &DeclRefType, 13617 const bool RefersToCapturedVariable, 13618 Sema &S) { 13619 // By default, capture variables by reference. 13620 bool ByRef = true; 13621 // Using an LValue reference type is consistent with Lambdas (see below). 13622 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13623 if (S.IsOpenMPCapturedDecl(Var)) 13624 DeclRefType = DeclRefType.getUnqualifiedType(); 13625 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13626 } 13627 13628 if (ByRef) 13629 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13630 else 13631 CaptureType = DeclRefType; 13632 13633 Expr *CopyExpr = nullptr; 13634 if (BuildAndDiagnose) { 13635 // The current implementation assumes that all variables are captured 13636 // by references. Since there is no capture by copy, no expression 13637 // evaluation will be needed. 13638 RecordDecl *RD = RSI->TheRecordDecl; 13639 13640 FieldDecl *Field 13641 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13642 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13643 nullptr, false, ICIS_NoInit); 13644 Field->setImplicit(true); 13645 Field->setAccess(AS_private); 13646 RD->addDecl(Field); 13647 13648 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13649 DeclRefType, VK_LValue, Loc); 13650 Var->setReferenced(true); 13651 Var->markUsed(S.Context); 13652 } 13653 13654 // Actually capture the variable. 13655 if (BuildAndDiagnose) 13656 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13657 SourceLocation(), CaptureType, CopyExpr); 13658 13659 13660 return true; 13661 } 13662 13663 /// \brief Create a field within the lambda class for the variable 13664 /// being captured. 13665 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13666 QualType FieldType, QualType DeclRefType, 13667 SourceLocation Loc, 13668 bool RefersToCapturedVariable) { 13669 CXXRecordDecl *Lambda = LSI->Lambda; 13670 13671 // Build the non-static data member. 13672 FieldDecl *Field 13673 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13674 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13675 nullptr, false, ICIS_NoInit); 13676 Field->setImplicit(true); 13677 Field->setAccess(AS_private); 13678 Lambda->addDecl(Field); 13679 } 13680 13681 /// \brief Capture the given variable in the lambda. 13682 static bool captureInLambda(LambdaScopeInfo *LSI, 13683 VarDecl *Var, 13684 SourceLocation Loc, 13685 const bool BuildAndDiagnose, 13686 QualType &CaptureType, 13687 QualType &DeclRefType, 13688 const bool RefersToCapturedVariable, 13689 const Sema::TryCaptureKind Kind, 13690 SourceLocation EllipsisLoc, 13691 const bool IsTopScope, 13692 Sema &S) { 13693 13694 // Determine whether we are capturing by reference or by value. 13695 bool ByRef = false; 13696 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13697 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13698 } else { 13699 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13700 } 13701 13702 // Compute the type of the field that will capture this variable. 13703 if (ByRef) { 13704 // C++11 [expr.prim.lambda]p15: 13705 // An entity is captured by reference if it is implicitly or 13706 // explicitly captured but not captured by copy. It is 13707 // unspecified whether additional unnamed non-static data 13708 // members are declared in the closure type for entities 13709 // captured by reference. 13710 // 13711 // FIXME: It is not clear whether we want to build an lvalue reference 13712 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13713 // to do the former, while EDG does the latter. Core issue 1249 will 13714 // clarify, but for now we follow GCC because it's a more permissive and 13715 // easily defensible position. 13716 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13717 } else { 13718 // C++11 [expr.prim.lambda]p14: 13719 // For each entity captured by copy, an unnamed non-static 13720 // data member is declared in the closure type. The 13721 // declaration order of these members is unspecified. The type 13722 // of such a data member is the type of the corresponding 13723 // captured entity if the entity is not a reference to an 13724 // object, or the referenced type otherwise. [Note: If the 13725 // captured entity is a reference to a function, the 13726 // corresponding data member is also a reference to a 13727 // function. - end note ] 13728 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13729 if (!RefType->getPointeeType()->isFunctionType()) 13730 CaptureType = RefType->getPointeeType(); 13731 } 13732 13733 // Forbid the lambda copy-capture of autoreleasing variables. 13734 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13735 if (BuildAndDiagnose) { 13736 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13737 S.Diag(Var->getLocation(), diag::note_previous_decl) 13738 << Var->getDeclName(); 13739 } 13740 return false; 13741 } 13742 13743 // Make sure that by-copy captures are of a complete and non-abstract type. 13744 if (BuildAndDiagnose) { 13745 if (!CaptureType->isDependentType() && 13746 S.RequireCompleteType(Loc, CaptureType, 13747 diag::err_capture_of_incomplete_type, 13748 Var->getDeclName())) 13749 return false; 13750 13751 if (S.RequireNonAbstractType(Loc, CaptureType, 13752 diag::err_capture_of_abstract_type)) 13753 return false; 13754 } 13755 } 13756 13757 // Capture this variable in the lambda. 13758 if (BuildAndDiagnose) 13759 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13760 RefersToCapturedVariable); 13761 13762 // Compute the type of a reference to this captured variable. 13763 if (ByRef) 13764 DeclRefType = CaptureType.getNonReferenceType(); 13765 else { 13766 // C++ [expr.prim.lambda]p5: 13767 // The closure type for a lambda-expression has a public inline 13768 // function call operator [...]. This function call operator is 13769 // declared const (9.3.1) if and only if the lambda-expression's 13770 // parameter-declaration-clause is not followed by mutable. 13771 DeclRefType = CaptureType.getNonReferenceType(); 13772 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13773 DeclRefType.addConst(); 13774 } 13775 13776 // Add the capture. 13777 if (BuildAndDiagnose) 13778 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13779 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13780 13781 return true; 13782 } 13783 13784 bool Sema::tryCaptureVariable( 13785 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13786 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13787 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13788 // An init-capture is notionally from the context surrounding its 13789 // declaration, but its parent DC is the lambda class. 13790 DeclContext *VarDC = Var->getDeclContext(); 13791 if (Var->isInitCapture()) 13792 VarDC = VarDC->getParent(); 13793 13794 DeclContext *DC = CurContext; 13795 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13796 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13797 // We need to sync up the Declaration Context with the 13798 // FunctionScopeIndexToStopAt 13799 if (FunctionScopeIndexToStopAt) { 13800 unsigned FSIndex = FunctionScopes.size() - 1; 13801 while (FSIndex != MaxFunctionScopesIndex) { 13802 DC = getLambdaAwareParentOfDeclContext(DC); 13803 --FSIndex; 13804 } 13805 } 13806 13807 13808 // If the variable is declared in the current context, there is no need to 13809 // capture it. 13810 if (VarDC == DC) return true; 13811 13812 // Capture global variables if it is required to use private copy of this 13813 // variable. 13814 bool IsGlobal = !Var->hasLocalStorage(); 13815 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13816 return true; 13817 13818 // Walk up the stack to determine whether we can capture the variable, 13819 // performing the "simple" checks that don't depend on type. We stop when 13820 // we've either hit the declared scope of the variable or find an existing 13821 // capture of that variable. We start from the innermost capturing-entity 13822 // (the DC) and ensure that all intervening capturing-entities 13823 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13824 // declcontext can either capture the variable or have already captured 13825 // the variable. 13826 CaptureType = Var->getType(); 13827 DeclRefType = CaptureType.getNonReferenceType(); 13828 bool Nested = false; 13829 bool Explicit = (Kind != TryCapture_Implicit); 13830 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13831 do { 13832 // Only block literals, captured statements, and lambda expressions can 13833 // capture; other scopes don't work. 13834 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13835 ExprLoc, 13836 BuildAndDiagnose, 13837 *this); 13838 // We need to check for the parent *first* because, if we *have* 13839 // private-captured a global variable, we need to recursively capture it in 13840 // intermediate blocks, lambdas, etc. 13841 if (!ParentDC) { 13842 if (IsGlobal) { 13843 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13844 break; 13845 } 13846 return true; 13847 } 13848 13849 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13850 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13851 13852 13853 // Check whether we've already captured it. 13854 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13855 DeclRefType)) 13856 break; 13857 // If we are instantiating a generic lambda call operator body, 13858 // we do not want to capture new variables. What was captured 13859 // during either a lambdas transformation or initial parsing 13860 // should be used. 13861 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13862 if (BuildAndDiagnose) { 13863 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13864 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13865 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13866 Diag(Var->getLocation(), diag::note_previous_decl) 13867 << Var->getDeclName(); 13868 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13869 } else 13870 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13871 } 13872 return true; 13873 } 13874 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13875 // certain types of variables (unnamed, variably modified types etc.) 13876 // so check for eligibility. 13877 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13878 return true; 13879 13880 // Try to capture variable-length arrays types. 13881 if (Var->getType()->isVariablyModifiedType()) { 13882 // We're going to walk down into the type and look for VLA 13883 // expressions. 13884 QualType QTy = Var->getType(); 13885 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13886 QTy = PVD->getOriginalType(); 13887 captureVariablyModifiedType(Context, QTy, CSI); 13888 } 13889 13890 if (getLangOpts().OpenMP) { 13891 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13892 // OpenMP private variables should not be captured in outer scope, so 13893 // just break here. Similarly, global variables that are captured in a 13894 // target region should not be captured outside the scope of the region. 13895 if (RSI->CapRegionKind == CR_OpenMP) { 13896 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13897 // When we detect target captures we are looking from inside the 13898 // target region, therefore we need to propagate the capture from the 13899 // enclosing region. Therefore, the capture is not initially nested. 13900 if (IsTargetCap) 13901 FunctionScopesIndex--; 13902 13903 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13904 Nested = !IsTargetCap; 13905 DeclRefType = DeclRefType.getUnqualifiedType(); 13906 CaptureType = Context.getLValueReferenceType(DeclRefType); 13907 break; 13908 } 13909 } 13910 } 13911 } 13912 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13913 // No capture-default, and this is not an explicit capture 13914 // so cannot capture this variable. 13915 if (BuildAndDiagnose) { 13916 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13917 Diag(Var->getLocation(), diag::note_previous_decl) 13918 << Var->getDeclName(); 13919 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13920 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13921 diag::note_lambda_decl); 13922 // FIXME: If we error out because an outer lambda can not implicitly 13923 // capture a variable that an inner lambda explicitly captures, we 13924 // should have the inner lambda do the explicit capture - because 13925 // it makes for cleaner diagnostics later. This would purely be done 13926 // so that the diagnostic does not misleadingly claim that a variable 13927 // can not be captured by a lambda implicitly even though it is captured 13928 // explicitly. Suggestion: 13929 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13930 // at the function head 13931 // - cache the StartingDeclContext - this must be a lambda 13932 // - captureInLambda in the innermost lambda the variable. 13933 } 13934 return true; 13935 } 13936 13937 FunctionScopesIndex--; 13938 DC = ParentDC; 13939 Explicit = false; 13940 } while (!VarDC->Equals(DC)); 13941 13942 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13943 // computing the type of the capture at each step, checking type-specific 13944 // requirements, and adding captures if requested. 13945 // If the variable had already been captured previously, we start capturing 13946 // at the lambda nested within that one. 13947 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13948 ++I) { 13949 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13950 13951 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13952 if (!captureInBlock(BSI, Var, ExprLoc, 13953 BuildAndDiagnose, CaptureType, 13954 DeclRefType, Nested, *this)) 13955 return true; 13956 Nested = true; 13957 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13958 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13959 BuildAndDiagnose, CaptureType, 13960 DeclRefType, Nested, *this)) 13961 return true; 13962 Nested = true; 13963 } else { 13964 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13965 if (!captureInLambda(LSI, Var, ExprLoc, 13966 BuildAndDiagnose, CaptureType, 13967 DeclRefType, Nested, Kind, EllipsisLoc, 13968 /*IsTopScope*/I == N - 1, *this)) 13969 return true; 13970 Nested = true; 13971 } 13972 } 13973 return false; 13974 } 13975 13976 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13977 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13978 QualType CaptureType; 13979 QualType DeclRefType; 13980 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13981 /*BuildAndDiagnose=*/true, CaptureType, 13982 DeclRefType, nullptr); 13983 } 13984 13985 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13986 QualType CaptureType; 13987 QualType DeclRefType; 13988 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13989 /*BuildAndDiagnose=*/false, CaptureType, 13990 DeclRefType, nullptr); 13991 } 13992 13993 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13994 QualType CaptureType; 13995 QualType DeclRefType; 13996 13997 // Determine whether we can capture this variable. 13998 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13999 /*BuildAndDiagnose=*/false, CaptureType, 14000 DeclRefType, nullptr)) 14001 return QualType(); 14002 14003 return DeclRefType; 14004 } 14005 14006 14007 14008 // If either the type of the variable or the initializer is dependent, 14009 // return false. Otherwise, determine whether the variable is a constant 14010 // expression. Use this if you need to know if a variable that might or 14011 // might not be dependent is truly a constant expression. 14012 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14013 ASTContext &Context) { 14014 14015 if (Var->getType()->isDependentType()) 14016 return false; 14017 const VarDecl *DefVD = nullptr; 14018 Var->getAnyInitializer(DefVD); 14019 if (!DefVD) 14020 return false; 14021 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14022 Expr *Init = cast<Expr>(Eval->Value); 14023 if (Init->isValueDependent()) 14024 return false; 14025 return IsVariableAConstantExpression(Var, Context); 14026 } 14027 14028 14029 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14030 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14031 // an object that satisfies the requirements for appearing in a 14032 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14033 // is immediately applied." This function handles the lvalue-to-rvalue 14034 // conversion part. 14035 MaybeODRUseExprs.erase(E->IgnoreParens()); 14036 14037 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14038 // to a variable that is a constant expression, and if so, identify it as 14039 // a reference to a variable that does not involve an odr-use of that 14040 // variable. 14041 if (LambdaScopeInfo *LSI = getCurLambda()) { 14042 Expr *SansParensExpr = E->IgnoreParens(); 14043 VarDecl *Var = nullptr; 14044 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14045 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14046 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14047 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14048 14049 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14050 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14051 } 14052 } 14053 14054 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14055 Res = CorrectDelayedTyposInExpr(Res); 14056 14057 if (!Res.isUsable()) 14058 return Res; 14059 14060 // If a constant-expression is a reference to a variable where we delay 14061 // deciding whether it is an odr-use, just assume we will apply the 14062 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14063 // (a non-type template argument), we have special handling anyway. 14064 UpdateMarkingForLValueToRValue(Res.get()); 14065 return Res; 14066 } 14067 14068 void Sema::CleanupVarDeclMarking() { 14069 for (Expr *E : MaybeODRUseExprs) { 14070 VarDecl *Var; 14071 SourceLocation Loc; 14072 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14073 Var = cast<VarDecl>(DRE->getDecl()); 14074 Loc = DRE->getLocation(); 14075 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14076 Var = cast<VarDecl>(ME->getMemberDecl()); 14077 Loc = ME->getMemberLoc(); 14078 } else { 14079 llvm_unreachable("Unexpected expression"); 14080 } 14081 14082 MarkVarDeclODRUsed(Var, Loc, *this, 14083 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14084 } 14085 14086 MaybeODRUseExprs.clear(); 14087 } 14088 14089 14090 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14091 VarDecl *Var, Expr *E) { 14092 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14093 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14094 Var->setReferenced(); 14095 14096 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14097 bool MarkODRUsed = true; 14098 14099 // If the context is not potentially evaluated, this is not an odr-use and 14100 // does not trigger instantiation. 14101 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 14102 if (SemaRef.isUnevaluatedContext()) 14103 return; 14104 14105 // If we don't yet know whether this context is going to end up being an 14106 // evaluated context, and we're referencing a variable from an enclosing 14107 // scope, add a potential capture. 14108 // 14109 // FIXME: Is this necessary? These contexts are only used for default 14110 // arguments, where local variables can't be used. 14111 const bool RefersToEnclosingScope = 14112 (SemaRef.CurContext != Var->getDeclContext() && 14113 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14114 if (RefersToEnclosingScope) { 14115 if (LambdaScopeInfo *const LSI = 14116 SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) { 14117 // If a variable could potentially be odr-used, defer marking it so 14118 // until we finish analyzing the full expression for any 14119 // lvalue-to-rvalue 14120 // or discarded value conversions that would obviate odr-use. 14121 // Add it to the list of potential captures that will be analyzed 14122 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14123 // unless the variable is a reference that was initialized by a constant 14124 // expression (this will never need to be captured or odr-used). 14125 assert(E && "Capture variable should be used in an expression."); 14126 if (!Var->getType()->isReferenceType() || 14127 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14128 LSI->addPotentialCapture(E->IgnoreParens()); 14129 } 14130 } 14131 14132 if (!isTemplateInstantiation(TSK)) 14133 return; 14134 14135 // Instantiate, but do not mark as odr-used, variable templates. 14136 MarkODRUsed = false; 14137 } 14138 14139 VarTemplateSpecializationDecl *VarSpec = 14140 dyn_cast<VarTemplateSpecializationDecl>(Var); 14141 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14142 "Can't instantiate a partial template specialization."); 14143 14144 // If this might be a member specialization of a static data member, check 14145 // the specialization is visible. We already did the checks for variable 14146 // template specializations when we created them. 14147 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 14148 SemaRef.checkSpecializationVisibility(Loc, Var); 14149 14150 // Perform implicit instantiation of static data members, static data member 14151 // templates of class templates, and variable template specializations. Delay 14152 // instantiations of variable templates, except for those that could be used 14153 // in a constant expression. 14154 if (isTemplateInstantiation(TSK)) { 14155 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14156 14157 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14158 if (Var->getPointOfInstantiation().isInvalid()) { 14159 // This is a modification of an existing AST node. Notify listeners. 14160 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14161 L->StaticDataMemberInstantiated(Var); 14162 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14163 // Don't bother trying to instantiate it again, unless we might need 14164 // its initializer before we get to the end of the TU. 14165 TryInstantiating = false; 14166 } 14167 14168 if (Var->getPointOfInstantiation().isInvalid()) 14169 Var->setTemplateSpecializationKind(TSK, Loc); 14170 14171 if (TryInstantiating) { 14172 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14173 bool InstantiationDependent = false; 14174 bool IsNonDependent = 14175 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14176 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14177 : true; 14178 14179 // Do not instantiate specializations that are still type-dependent. 14180 if (IsNonDependent) { 14181 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14182 // Do not defer instantiations of variables which could be used in a 14183 // constant expression. 14184 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14185 } else { 14186 SemaRef.PendingInstantiations 14187 .push_back(std::make_pair(Var, PointOfInstantiation)); 14188 } 14189 } 14190 } 14191 } 14192 14193 if (!MarkODRUsed) 14194 return; 14195 14196 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14197 // the requirements for appearing in a constant expression (5.19) and, if 14198 // it is an object, the lvalue-to-rvalue conversion (4.1) 14199 // is immediately applied." We check the first part here, and 14200 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14201 // Note that we use the C++11 definition everywhere because nothing in 14202 // C++03 depends on whether we get the C++03 version correct. The second 14203 // part does not apply to references, since they are not objects. 14204 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14205 // A reference initialized by a constant expression can never be 14206 // odr-used, so simply ignore it. 14207 if (!Var->getType()->isReferenceType()) 14208 SemaRef.MaybeODRUseExprs.insert(E); 14209 } else 14210 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14211 /*MaxFunctionScopeIndex ptr*/ nullptr); 14212 } 14213 14214 /// \brief Mark a variable referenced, and check whether it is odr-used 14215 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14216 /// used directly for normal expressions referring to VarDecl. 14217 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14218 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14219 } 14220 14221 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14222 Decl *D, Expr *E, bool MightBeOdrUse) { 14223 if (SemaRef.isInOpenMPDeclareTargetContext()) 14224 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14225 14226 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14227 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14228 return; 14229 } 14230 14231 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14232 14233 // If this is a call to a method via a cast, also mark the method in the 14234 // derived class used in case codegen can devirtualize the call. 14235 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14236 if (!ME) 14237 return; 14238 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14239 if (!MD) 14240 return; 14241 // Only attempt to devirtualize if this is truly a virtual call. 14242 bool IsVirtualCall = MD->isVirtual() && 14243 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14244 if (!IsVirtualCall) 14245 return; 14246 const Expr *Base = ME->getBase(); 14247 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14248 if (!MostDerivedClassDecl) 14249 return; 14250 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14251 if (!DM || DM->isPure()) 14252 return; 14253 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14254 } 14255 14256 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14257 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14258 // TODO: update this with DR# once a defect report is filed. 14259 // C++11 defect. The address of a pure member should not be an ODR use, even 14260 // if it's a qualified reference. 14261 bool OdrUse = true; 14262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14263 if (Method->isVirtual()) 14264 OdrUse = false; 14265 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14266 } 14267 14268 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14269 void Sema::MarkMemberReferenced(MemberExpr *E) { 14270 // C++11 [basic.def.odr]p2: 14271 // A non-overloaded function whose name appears as a potentially-evaluated 14272 // expression or a member of a set of candidate functions, if selected by 14273 // overload resolution when referred to from a potentially-evaluated 14274 // expression, is odr-used, unless it is a pure virtual function and its 14275 // name is not explicitly qualified. 14276 bool MightBeOdrUse = true; 14277 if (E->performsVirtualDispatch(getLangOpts())) { 14278 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14279 if (Method->isPure()) 14280 MightBeOdrUse = false; 14281 } 14282 SourceLocation Loc = E->getMemberLoc().isValid() ? 14283 E->getMemberLoc() : E->getLocStart(); 14284 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14285 } 14286 14287 /// \brief Perform marking for a reference to an arbitrary declaration. It 14288 /// marks the declaration referenced, and performs odr-use checking for 14289 /// functions and variables. This method should not be used when building a 14290 /// normal expression which refers to a variable. 14291 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14292 bool MightBeOdrUse) { 14293 if (MightBeOdrUse) { 14294 if (auto *VD = dyn_cast<VarDecl>(D)) { 14295 MarkVariableReferenced(Loc, VD); 14296 return; 14297 } 14298 } 14299 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14300 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14301 return; 14302 } 14303 D->setReferenced(); 14304 } 14305 14306 namespace { 14307 // Mark all of the declarations referenced 14308 // FIXME: Not fully implemented yet! We need to have a better understanding 14309 // of when we're entering 14310 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14311 Sema &S; 14312 SourceLocation Loc; 14313 14314 public: 14315 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14316 14317 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14318 14319 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14320 bool TraverseRecordType(RecordType *T); 14321 }; 14322 } 14323 14324 bool MarkReferencedDecls::TraverseTemplateArgument( 14325 const TemplateArgument &Arg) { 14326 if (Arg.getKind() == TemplateArgument::Declaration) { 14327 if (Decl *D = Arg.getAsDecl()) 14328 S.MarkAnyDeclReferenced(Loc, D, true); 14329 } 14330 14331 return Inherited::TraverseTemplateArgument(Arg); 14332 } 14333 14334 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14335 if (ClassTemplateSpecializationDecl *Spec 14336 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14337 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14338 return TraverseTemplateArguments(Args.data(), Args.size()); 14339 } 14340 14341 return true; 14342 } 14343 14344 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14345 MarkReferencedDecls Marker(*this, Loc); 14346 Marker.TraverseType(Context.getCanonicalType(T)); 14347 } 14348 14349 namespace { 14350 /// \brief Helper class that marks all of the declarations referenced by 14351 /// potentially-evaluated subexpressions as "referenced". 14352 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14353 Sema &S; 14354 bool SkipLocalVariables; 14355 14356 public: 14357 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14358 14359 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14360 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14361 14362 void VisitDeclRefExpr(DeclRefExpr *E) { 14363 // If we were asked not to visit local variables, don't. 14364 if (SkipLocalVariables) { 14365 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14366 if (VD->hasLocalStorage()) 14367 return; 14368 } 14369 14370 S.MarkDeclRefReferenced(E); 14371 } 14372 14373 void VisitMemberExpr(MemberExpr *E) { 14374 S.MarkMemberReferenced(E); 14375 Inherited::VisitMemberExpr(E); 14376 } 14377 14378 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14379 S.MarkFunctionReferenced(E->getLocStart(), 14380 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14381 Visit(E->getSubExpr()); 14382 } 14383 14384 void VisitCXXNewExpr(CXXNewExpr *E) { 14385 if (E->getOperatorNew()) 14386 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14387 if (E->getOperatorDelete()) 14388 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14389 Inherited::VisitCXXNewExpr(E); 14390 } 14391 14392 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14393 if (E->getOperatorDelete()) 14394 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14395 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14396 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14397 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14398 S.MarkFunctionReferenced(E->getLocStart(), 14399 S.LookupDestructor(Record)); 14400 } 14401 14402 Inherited::VisitCXXDeleteExpr(E); 14403 } 14404 14405 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14406 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14407 Inherited::VisitCXXConstructExpr(E); 14408 } 14409 14410 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14411 Visit(E->getExpr()); 14412 } 14413 14414 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14415 Inherited::VisitImplicitCastExpr(E); 14416 14417 if (E->getCastKind() == CK_LValueToRValue) 14418 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14419 } 14420 }; 14421 } 14422 14423 /// \brief Mark any declarations that appear within this expression or any 14424 /// potentially-evaluated subexpressions as "referenced". 14425 /// 14426 /// \param SkipLocalVariables If true, don't mark local variables as 14427 /// 'referenced'. 14428 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14429 bool SkipLocalVariables) { 14430 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14431 } 14432 14433 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14434 /// of the program being compiled. 14435 /// 14436 /// This routine emits the given diagnostic when the code currently being 14437 /// type-checked is "potentially evaluated", meaning that there is a 14438 /// possibility that the code will actually be executable. Code in sizeof() 14439 /// expressions, code used only during overload resolution, etc., are not 14440 /// potentially evaluated. This routine will suppress such diagnostics or, 14441 /// in the absolutely nutty case of potentially potentially evaluated 14442 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14443 /// later. 14444 /// 14445 /// This routine should be used for all diagnostics that describe the run-time 14446 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14447 /// Failure to do so will likely result in spurious diagnostics or failures 14448 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14449 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14450 const PartialDiagnostic &PD) { 14451 switch (ExprEvalContexts.back().Context) { 14452 case Unevaluated: 14453 case UnevaluatedAbstract: 14454 case DiscardedStatement: 14455 // The argument will never be evaluated, so don't complain. 14456 break; 14457 14458 case ConstantEvaluated: 14459 // Relevant diagnostics should be produced by constant evaluation. 14460 break; 14461 14462 case PotentiallyEvaluated: 14463 case PotentiallyEvaluatedIfUsed: 14464 if (Statement && getCurFunctionOrMethodDecl()) { 14465 FunctionScopes.back()->PossiblyUnreachableDiags. 14466 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14467 } 14468 else 14469 Diag(Loc, PD); 14470 14471 return true; 14472 } 14473 14474 return false; 14475 } 14476 14477 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14478 CallExpr *CE, FunctionDecl *FD) { 14479 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14480 return false; 14481 14482 // If we're inside a decltype's expression, don't check for a valid return 14483 // type or construct temporaries until we know whether this is the last call. 14484 if (ExprEvalContexts.back().IsDecltype) { 14485 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14486 return false; 14487 } 14488 14489 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14490 FunctionDecl *FD; 14491 CallExpr *CE; 14492 14493 public: 14494 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14495 : FD(FD), CE(CE) { } 14496 14497 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14498 if (!FD) { 14499 S.Diag(Loc, diag::err_call_incomplete_return) 14500 << T << CE->getSourceRange(); 14501 return; 14502 } 14503 14504 S.Diag(Loc, diag::err_call_function_incomplete_return) 14505 << CE->getSourceRange() << FD->getDeclName() << T; 14506 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14507 << FD->getDeclName(); 14508 } 14509 } Diagnoser(FD, CE); 14510 14511 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14512 return true; 14513 14514 return false; 14515 } 14516 14517 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14518 // will prevent this condition from triggering, which is what we want. 14519 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14520 SourceLocation Loc; 14521 14522 unsigned diagnostic = diag::warn_condition_is_assignment; 14523 bool IsOrAssign = false; 14524 14525 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14526 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14527 return; 14528 14529 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14530 14531 // Greylist some idioms by putting them into a warning subcategory. 14532 if (ObjCMessageExpr *ME 14533 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14534 Selector Sel = ME->getSelector(); 14535 14536 // self = [<foo> init...] 14537 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14538 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14539 14540 // <foo> = [<bar> nextObject] 14541 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14542 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14543 } 14544 14545 Loc = Op->getOperatorLoc(); 14546 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14547 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14548 return; 14549 14550 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14551 Loc = Op->getOperatorLoc(); 14552 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14553 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14554 else { 14555 // Not an assignment. 14556 return; 14557 } 14558 14559 Diag(Loc, diagnostic) << E->getSourceRange(); 14560 14561 SourceLocation Open = E->getLocStart(); 14562 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14563 Diag(Loc, diag::note_condition_assign_silence) 14564 << FixItHint::CreateInsertion(Open, "(") 14565 << FixItHint::CreateInsertion(Close, ")"); 14566 14567 if (IsOrAssign) 14568 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14569 << FixItHint::CreateReplacement(Loc, "!="); 14570 else 14571 Diag(Loc, diag::note_condition_assign_to_comparison) 14572 << FixItHint::CreateReplacement(Loc, "=="); 14573 } 14574 14575 /// \brief Redundant parentheses over an equality comparison can indicate 14576 /// that the user intended an assignment used as condition. 14577 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14578 // Don't warn if the parens came from a macro. 14579 SourceLocation parenLoc = ParenE->getLocStart(); 14580 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14581 return; 14582 // Don't warn for dependent expressions. 14583 if (ParenE->isTypeDependent()) 14584 return; 14585 14586 Expr *E = ParenE->IgnoreParens(); 14587 14588 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14589 if (opE->getOpcode() == BO_EQ && 14590 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14591 == Expr::MLV_Valid) { 14592 SourceLocation Loc = opE->getOperatorLoc(); 14593 14594 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14595 SourceRange ParenERange = ParenE->getSourceRange(); 14596 Diag(Loc, diag::note_equality_comparison_silence) 14597 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14598 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14599 Diag(Loc, diag::note_equality_comparison_to_assign) 14600 << FixItHint::CreateReplacement(Loc, "="); 14601 } 14602 } 14603 14604 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14605 bool IsConstexpr) { 14606 DiagnoseAssignmentAsCondition(E); 14607 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14608 DiagnoseEqualityWithExtraParens(parenE); 14609 14610 ExprResult result = CheckPlaceholderExpr(E); 14611 if (result.isInvalid()) return ExprError(); 14612 E = result.get(); 14613 14614 if (!E->isTypeDependent()) { 14615 if (getLangOpts().CPlusPlus) 14616 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14617 14618 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14619 if (ERes.isInvalid()) 14620 return ExprError(); 14621 E = ERes.get(); 14622 14623 QualType T = E->getType(); 14624 if (!T->isScalarType()) { // C99 6.8.4.1p1 14625 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14626 << T << E->getSourceRange(); 14627 return ExprError(); 14628 } 14629 CheckBoolLikeConversion(E, Loc); 14630 } 14631 14632 return E; 14633 } 14634 14635 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14636 Expr *SubExpr, ConditionKind CK) { 14637 // Empty conditions are valid in for-statements. 14638 if (!SubExpr) 14639 return ConditionResult(); 14640 14641 ExprResult Cond; 14642 switch (CK) { 14643 case ConditionKind::Boolean: 14644 Cond = CheckBooleanCondition(Loc, SubExpr); 14645 break; 14646 14647 case ConditionKind::ConstexprIf: 14648 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14649 break; 14650 14651 case ConditionKind::Switch: 14652 Cond = CheckSwitchCondition(Loc, SubExpr); 14653 break; 14654 } 14655 if (Cond.isInvalid()) 14656 return ConditionError(); 14657 14658 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14659 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14660 if (!FullExpr.get()) 14661 return ConditionError(); 14662 14663 return ConditionResult(*this, nullptr, FullExpr, 14664 CK == ConditionKind::ConstexprIf); 14665 } 14666 14667 namespace { 14668 /// A visitor for rebuilding a call to an __unknown_any expression 14669 /// to have an appropriate type. 14670 struct RebuildUnknownAnyFunction 14671 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14672 14673 Sema &S; 14674 14675 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14676 14677 ExprResult VisitStmt(Stmt *S) { 14678 llvm_unreachable("unexpected statement!"); 14679 } 14680 14681 ExprResult VisitExpr(Expr *E) { 14682 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14683 << E->getSourceRange(); 14684 return ExprError(); 14685 } 14686 14687 /// Rebuild an expression which simply semantically wraps another 14688 /// expression which it shares the type and value kind of. 14689 template <class T> ExprResult rebuildSugarExpr(T *E) { 14690 ExprResult SubResult = Visit(E->getSubExpr()); 14691 if (SubResult.isInvalid()) return ExprError(); 14692 14693 Expr *SubExpr = SubResult.get(); 14694 E->setSubExpr(SubExpr); 14695 E->setType(SubExpr->getType()); 14696 E->setValueKind(SubExpr->getValueKind()); 14697 assert(E->getObjectKind() == OK_Ordinary); 14698 return E; 14699 } 14700 14701 ExprResult VisitParenExpr(ParenExpr *E) { 14702 return rebuildSugarExpr(E); 14703 } 14704 14705 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14706 return rebuildSugarExpr(E); 14707 } 14708 14709 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14710 ExprResult SubResult = Visit(E->getSubExpr()); 14711 if (SubResult.isInvalid()) return ExprError(); 14712 14713 Expr *SubExpr = SubResult.get(); 14714 E->setSubExpr(SubExpr); 14715 E->setType(S.Context.getPointerType(SubExpr->getType())); 14716 assert(E->getValueKind() == VK_RValue); 14717 assert(E->getObjectKind() == OK_Ordinary); 14718 return E; 14719 } 14720 14721 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14722 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14723 14724 E->setType(VD->getType()); 14725 14726 assert(E->getValueKind() == VK_RValue); 14727 if (S.getLangOpts().CPlusPlus && 14728 !(isa<CXXMethodDecl>(VD) && 14729 cast<CXXMethodDecl>(VD)->isInstance())) 14730 E->setValueKind(VK_LValue); 14731 14732 return E; 14733 } 14734 14735 ExprResult VisitMemberExpr(MemberExpr *E) { 14736 return resolveDecl(E, E->getMemberDecl()); 14737 } 14738 14739 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14740 return resolveDecl(E, E->getDecl()); 14741 } 14742 }; 14743 } 14744 14745 /// Given a function expression of unknown-any type, try to rebuild it 14746 /// to have a function type. 14747 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14748 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14749 if (Result.isInvalid()) return ExprError(); 14750 return S.DefaultFunctionArrayConversion(Result.get()); 14751 } 14752 14753 namespace { 14754 /// A visitor for rebuilding an expression of type __unknown_anytype 14755 /// into one which resolves the type directly on the referring 14756 /// expression. Strict preservation of the original source 14757 /// structure is not a goal. 14758 struct RebuildUnknownAnyExpr 14759 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14760 14761 Sema &S; 14762 14763 /// The current destination type. 14764 QualType DestType; 14765 14766 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14767 : S(S), DestType(CastType) {} 14768 14769 ExprResult VisitStmt(Stmt *S) { 14770 llvm_unreachable("unexpected statement!"); 14771 } 14772 14773 ExprResult VisitExpr(Expr *E) { 14774 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14775 << E->getSourceRange(); 14776 return ExprError(); 14777 } 14778 14779 ExprResult VisitCallExpr(CallExpr *E); 14780 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14781 14782 /// Rebuild an expression which simply semantically wraps another 14783 /// expression which it shares the type and value kind of. 14784 template <class T> ExprResult rebuildSugarExpr(T *E) { 14785 ExprResult SubResult = Visit(E->getSubExpr()); 14786 if (SubResult.isInvalid()) return ExprError(); 14787 Expr *SubExpr = SubResult.get(); 14788 E->setSubExpr(SubExpr); 14789 E->setType(SubExpr->getType()); 14790 E->setValueKind(SubExpr->getValueKind()); 14791 assert(E->getObjectKind() == OK_Ordinary); 14792 return E; 14793 } 14794 14795 ExprResult VisitParenExpr(ParenExpr *E) { 14796 return rebuildSugarExpr(E); 14797 } 14798 14799 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14800 return rebuildSugarExpr(E); 14801 } 14802 14803 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14804 const PointerType *Ptr = DestType->getAs<PointerType>(); 14805 if (!Ptr) { 14806 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14807 << E->getSourceRange(); 14808 return ExprError(); 14809 } 14810 14811 if (isa<CallExpr>(E->getSubExpr())) { 14812 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 14813 << E->getSourceRange(); 14814 return ExprError(); 14815 } 14816 14817 assert(E->getValueKind() == VK_RValue); 14818 assert(E->getObjectKind() == OK_Ordinary); 14819 E->setType(DestType); 14820 14821 // Build the sub-expression as if it were an object of the pointee type. 14822 DestType = Ptr->getPointeeType(); 14823 ExprResult SubResult = Visit(E->getSubExpr()); 14824 if (SubResult.isInvalid()) return ExprError(); 14825 E->setSubExpr(SubResult.get()); 14826 return E; 14827 } 14828 14829 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14830 14831 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14832 14833 ExprResult VisitMemberExpr(MemberExpr *E) { 14834 return resolveDecl(E, E->getMemberDecl()); 14835 } 14836 14837 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14838 return resolveDecl(E, E->getDecl()); 14839 } 14840 }; 14841 } 14842 14843 /// Rebuilds a call expression which yielded __unknown_anytype. 14844 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14845 Expr *CalleeExpr = E->getCallee(); 14846 14847 enum FnKind { 14848 FK_MemberFunction, 14849 FK_FunctionPointer, 14850 FK_BlockPointer 14851 }; 14852 14853 FnKind Kind; 14854 QualType CalleeType = CalleeExpr->getType(); 14855 if (CalleeType == S.Context.BoundMemberTy) { 14856 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14857 Kind = FK_MemberFunction; 14858 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14859 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14860 CalleeType = Ptr->getPointeeType(); 14861 Kind = FK_FunctionPointer; 14862 } else { 14863 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14864 Kind = FK_BlockPointer; 14865 } 14866 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14867 14868 // Verify that this is a legal result type of a function. 14869 if (DestType->isArrayType() || DestType->isFunctionType()) { 14870 unsigned diagID = diag::err_func_returning_array_function; 14871 if (Kind == FK_BlockPointer) 14872 diagID = diag::err_block_returning_array_function; 14873 14874 S.Diag(E->getExprLoc(), diagID) 14875 << DestType->isFunctionType() << DestType; 14876 return ExprError(); 14877 } 14878 14879 // Otherwise, go ahead and set DestType as the call's result. 14880 E->setType(DestType.getNonLValueExprType(S.Context)); 14881 E->setValueKind(Expr::getValueKindForType(DestType)); 14882 assert(E->getObjectKind() == OK_Ordinary); 14883 14884 // Rebuild the function type, replacing the result type with DestType. 14885 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14886 if (Proto) { 14887 // __unknown_anytype(...) is a special case used by the debugger when 14888 // it has no idea what a function's signature is. 14889 // 14890 // We want to build this call essentially under the K&R 14891 // unprototyped rules, but making a FunctionNoProtoType in C++ 14892 // would foul up all sorts of assumptions. However, we cannot 14893 // simply pass all arguments as variadic arguments, nor can we 14894 // portably just call the function under a non-variadic type; see 14895 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14896 // However, it turns out that in practice it is generally safe to 14897 // call a function declared as "A foo(B,C,D);" under the prototype 14898 // "A foo(B,C,D,...);". The only known exception is with the 14899 // Windows ABI, where any variadic function is implicitly cdecl 14900 // regardless of its normal CC. Therefore we change the parameter 14901 // types to match the types of the arguments. 14902 // 14903 // This is a hack, but it is far superior to moving the 14904 // corresponding target-specific code from IR-gen to Sema/AST. 14905 14906 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14907 SmallVector<QualType, 8> ArgTypes; 14908 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14909 ArgTypes.reserve(E->getNumArgs()); 14910 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14911 Expr *Arg = E->getArg(i); 14912 QualType ArgType = Arg->getType(); 14913 if (E->isLValue()) { 14914 ArgType = S.Context.getLValueReferenceType(ArgType); 14915 } else if (E->isXValue()) { 14916 ArgType = S.Context.getRValueReferenceType(ArgType); 14917 } 14918 ArgTypes.push_back(ArgType); 14919 } 14920 ParamTypes = ArgTypes; 14921 } 14922 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14923 Proto->getExtProtoInfo()); 14924 } else { 14925 DestType = S.Context.getFunctionNoProtoType(DestType, 14926 FnType->getExtInfo()); 14927 } 14928 14929 // Rebuild the appropriate pointer-to-function type. 14930 switch (Kind) { 14931 case FK_MemberFunction: 14932 // Nothing to do. 14933 break; 14934 14935 case FK_FunctionPointer: 14936 DestType = S.Context.getPointerType(DestType); 14937 break; 14938 14939 case FK_BlockPointer: 14940 DestType = S.Context.getBlockPointerType(DestType); 14941 break; 14942 } 14943 14944 // Finally, we can recurse. 14945 ExprResult CalleeResult = Visit(CalleeExpr); 14946 if (!CalleeResult.isUsable()) return ExprError(); 14947 E->setCallee(CalleeResult.get()); 14948 14949 // Bind a temporary if necessary. 14950 return S.MaybeBindToTemporary(E); 14951 } 14952 14953 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14954 // Verify that this is a legal result type of a call. 14955 if (DestType->isArrayType() || DestType->isFunctionType()) { 14956 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14957 << DestType->isFunctionType() << DestType; 14958 return ExprError(); 14959 } 14960 14961 // Rewrite the method result type if available. 14962 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14963 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14964 Method->setReturnType(DestType); 14965 } 14966 14967 // Change the type of the message. 14968 E->setType(DestType.getNonReferenceType()); 14969 E->setValueKind(Expr::getValueKindForType(DestType)); 14970 14971 return S.MaybeBindToTemporary(E); 14972 } 14973 14974 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14975 // The only case we should ever see here is a function-to-pointer decay. 14976 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14977 assert(E->getValueKind() == VK_RValue); 14978 assert(E->getObjectKind() == OK_Ordinary); 14979 14980 E->setType(DestType); 14981 14982 // Rebuild the sub-expression as the pointee (function) type. 14983 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14984 14985 ExprResult Result = Visit(E->getSubExpr()); 14986 if (!Result.isUsable()) return ExprError(); 14987 14988 E->setSubExpr(Result.get()); 14989 return E; 14990 } else if (E->getCastKind() == CK_LValueToRValue) { 14991 assert(E->getValueKind() == VK_RValue); 14992 assert(E->getObjectKind() == OK_Ordinary); 14993 14994 assert(isa<BlockPointerType>(E->getType())); 14995 14996 E->setType(DestType); 14997 14998 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14999 DestType = S.Context.getLValueReferenceType(DestType); 15000 15001 ExprResult Result = Visit(E->getSubExpr()); 15002 if (!Result.isUsable()) return ExprError(); 15003 15004 E->setSubExpr(Result.get()); 15005 return E; 15006 } else { 15007 llvm_unreachable("Unhandled cast type!"); 15008 } 15009 } 15010 15011 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15012 ExprValueKind ValueKind = VK_LValue; 15013 QualType Type = DestType; 15014 15015 // We know how to make this work for certain kinds of decls: 15016 15017 // - functions 15018 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15019 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15020 DestType = Ptr->getPointeeType(); 15021 ExprResult Result = resolveDecl(E, VD); 15022 if (Result.isInvalid()) return ExprError(); 15023 return S.ImpCastExprToType(Result.get(), Type, 15024 CK_FunctionToPointerDecay, VK_RValue); 15025 } 15026 15027 if (!Type->isFunctionType()) { 15028 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15029 << VD << E->getSourceRange(); 15030 return ExprError(); 15031 } 15032 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15033 // We must match the FunctionDecl's type to the hack introduced in 15034 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15035 // type. See the lengthy commentary in that routine. 15036 QualType FDT = FD->getType(); 15037 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15038 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15039 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15040 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15041 SourceLocation Loc = FD->getLocation(); 15042 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15043 FD->getDeclContext(), 15044 Loc, Loc, FD->getNameInfo().getName(), 15045 DestType, FD->getTypeSourceInfo(), 15046 SC_None, false/*isInlineSpecified*/, 15047 FD->hasPrototype(), 15048 false/*isConstexprSpecified*/); 15049 15050 if (FD->getQualifier()) 15051 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15052 15053 SmallVector<ParmVarDecl*, 16> Params; 15054 for (const auto &AI : FT->param_types()) { 15055 ParmVarDecl *Param = 15056 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15057 Param->setScopeInfo(0, Params.size()); 15058 Params.push_back(Param); 15059 } 15060 NewFD->setParams(Params); 15061 DRE->setDecl(NewFD); 15062 VD = DRE->getDecl(); 15063 } 15064 } 15065 15066 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15067 if (MD->isInstance()) { 15068 ValueKind = VK_RValue; 15069 Type = S.Context.BoundMemberTy; 15070 } 15071 15072 // Function references aren't l-values in C. 15073 if (!S.getLangOpts().CPlusPlus) 15074 ValueKind = VK_RValue; 15075 15076 // - variables 15077 } else if (isa<VarDecl>(VD)) { 15078 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15079 Type = RefTy->getPointeeType(); 15080 } else if (Type->isFunctionType()) { 15081 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15082 << VD << E->getSourceRange(); 15083 return ExprError(); 15084 } 15085 15086 // - nothing else 15087 } else { 15088 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15089 << VD << E->getSourceRange(); 15090 return ExprError(); 15091 } 15092 15093 // Modifying the declaration like this is friendly to IR-gen but 15094 // also really dangerous. 15095 VD->setType(DestType); 15096 E->setType(Type); 15097 E->setValueKind(ValueKind); 15098 return E; 15099 } 15100 15101 /// Check a cast of an unknown-any type. We intentionally only 15102 /// trigger this for C-style casts. 15103 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15104 Expr *CastExpr, CastKind &CastKind, 15105 ExprValueKind &VK, CXXCastPath &Path) { 15106 // The type we're casting to must be either void or complete. 15107 if (!CastType->isVoidType() && 15108 RequireCompleteType(TypeRange.getBegin(), CastType, 15109 diag::err_typecheck_cast_to_incomplete)) 15110 return ExprError(); 15111 15112 // Rewrite the casted expression from scratch. 15113 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15114 if (!result.isUsable()) return ExprError(); 15115 15116 CastExpr = result.get(); 15117 VK = CastExpr->getValueKind(); 15118 CastKind = CK_NoOp; 15119 15120 return CastExpr; 15121 } 15122 15123 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15124 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15125 } 15126 15127 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15128 Expr *arg, QualType ¶mType) { 15129 // If the syntactic form of the argument is not an explicit cast of 15130 // any sort, just do default argument promotion. 15131 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15132 if (!castArg) { 15133 ExprResult result = DefaultArgumentPromotion(arg); 15134 if (result.isInvalid()) return ExprError(); 15135 paramType = result.get()->getType(); 15136 return result; 15137 } 15138 15139 // Otherwise, use the type that was written in the explicit cast. 15140 assert(!arg->hasPlaceholderType()); 15141 paramType = castArg->getTypeAsWritten(); 15142 15143 // Copy-initialize a parameter of that type. 15144 InitializedEntity entity = 15145 InitializedEntity::InitializeParameter(Context, paramType, 15146 /*consumed*/ false); 15147 return PerformCopyInitialization(entity, callLoc, arg); 15148 } 15149 15150 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15151 Expr *orig = E; 15152 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15153 while (true) { 15154 E = E->IgnoreParenImpCasts(); 15155 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15156 E = call->getCallee(); 15157 diagID = diag::err_uncasted_call_of_unknown_any; 15158 } else { 15159 break; 15160 } 15161 } 15162 15163 SourceLocation loc; 15164 NamedDecl *d; 15165 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15166 loc = ref->getLocation(); 15167 d = ref->getDecl(); 15168 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15169 loc = mem->getMemberLoc(); 15170 d = mem->getMemberDecl(); 15171 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15172 diagID = diag::err_uncasted_call_of_unknown_any; 15173 loc = msg->getSelectorStartLoc(); 15174 d = msg->getMethodDecl(); 15175 if (!d) { 15176 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15177 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15178 << orig->getSourceRange(); 15179 return ExprError(); 15180 } 15181 } else { 15182 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15183 << E->getSourceRange(); 15184 return ExprError(); 15185 } 15186 15187 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15188 15189 // Never recoverable. 15190 return ExprError(); 15191 } 15192 15193 /// Check for operands with placeholder types and complain if found. 15194 /// Returns true if there was an error and no recovery was possible. 15195 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15196 if (!getLangOpts().CPlusPlus) { 15197 // C cannot handle TypoExpr nodes on either side of a binop because it 15198 // doesn't handle dependent types properly, so make sure any TypoExprs have 15199 // been dealt with before checking the operands. 15200 ExprResult Result = CorrectDelayedTyposInExpr(E); 15201 if (!Result.isUsable()) return ExprError(); 15202 E = Result.get(); 15203 } 15204 15205 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15206 if (!placeholderType) return E; 15207 15208 switch (placeholderType->getKind()) { 15209 15210 // Overloaded expressions. 15211 case BuiltinType::Overload: { 15212 // Try to resolve a single function template specialization. 15213 // This is obligatory. 15214 ExprResult Result = E; 15215 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15216 return Result; 15217 15218 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15219 // leaves Result unchanged on failure. 15220 Result = E; 15221 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15222 return Result; 15223 15224 // If that failed, try to recover with a call. 15225 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15226 /*complain*/ true); 15227 return Result; 15228 } 15229 15230 // Bound member functions. 15231 case BuiltinType::BoundMember: { 15232 ExprResult result = E; 15233 const Expr *BME = E->IgnoreParens(); 15234 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15235 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15236 if (isa<CXXPseudoDestructorExpr>(BME)) { 15237 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15238 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15239 if (ME->getMemberNameInfo().getName().getNameKind() == 15240 DeclarationName::CXXDestructorName) 15241 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15242 } 15243 tryToRecoverWithCall(result, PD, 15244 /*complain*/ true); 15245 return result; 15246 } 15247 15248 // ARC unbridged casts. 15249 case BuiltinType::ARCUnbridgedCast: { 15250 Expr *realCast = stripARCUnbridgedCast(E); 15251 diagnoseARCUnbridgedCast(realCast); 15252 return realCast; 15253 } 15254 15255 // Expressions of unknown type. 15256 case BuiltinType::UnknownAny: 15257 return diagnoseUnknownAnyExpr(*this, E); 15258 15259 // Pseudo-objects. 15260 case BuiltinType::PseudoObject: 15261 return checkPseudoObjectRValue(E); 15262 15263 case BuiltinType::BuiltinFn: { 15264 // Accept __noop without parens by implicitly converting it to a call expr. 15265 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15266 if (DRE) { 15267 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15268 if (FD->getBuiltinID() == Builtin::BI__noop) { 15269 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15270 CK_BuiltinFnToFnPtr).get(); 15271 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15272 VK_RValue, SourceLocation()); 15273 } 15274 } 15275 15276 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15277 return ExprError(); 15278 } 15279 15280 // Expressions of unknown type. 15281 case BuiltinType::OMPArraySection: 15282 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15283 return ExprError(); 15284 15285 // Everything else should be impossible. 15286 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15287 case BuiltinType::Id: 15288 #include "clang/Basic/OpenCLImageTypes.def" 15289 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15290 #define PLACEHOLDER_TYPE(Id, SingletonId) 15291 #include "clang/AST/BuiltinTypes.def" 15292 break; 15293 } 15294 15295 llvm_unreachable("invalid placeholder type!"); 15296 } 15297 15298 bool Sema::CheckCaseExpression(Expr *E) { 15299 if (E->isTypeDependent()) 15300 return true; 15301 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15302 return E->getType()->isIntegralOrEnumerationType(); 15303 return false; 15304 } 15305 15306 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15307 ExprResult 15308 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15309 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15310 "Unknown Objective-C Boolean value!"); 15311 QualType BoolT = Context.ObjCBuiltinBoolTy; 15312 if (!Context.getBOOLDecl()) { 15313 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15314 Sema::LookupOrdinaryName); 15315 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15316 NamedDecl *ND = Result.getFoundDecl(); 15317 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15318 Context.setBOOLDecl(TD); 15319 } 15320 } 15321 if (Context.getBOOLDecl()) 15322 BoolT = Context.getBOOLType(); 15323 return new (Context) 15324 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15325 } 15326 15327 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15328 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15329 SourceLocation RParen) { 15330 15331 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15332 15333 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15334 [&](const AvailabilitySpec &Spec) { 15335 return Spec.getPlatform() == Platform; 15336 }); 15337 15338 VersionTuple Version; 15339 if (Spec != AvailSpecs.end()) 15340 Version = Spec->getVersion(); 15341 15342 return new (Context) 15343 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15344 } 15345