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 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 337 << D->getDeclName() << cast<VarDecl>(D)->getType(); 338 } 339 return true; 340 } 341 342 // See if this is a deleted function. 343 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 344 if (FD->isDeleted()) { 345 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 346 if (Ctor && Ctor->isInheritingConstructor()) 347 Diag(Loc, diag::err_deleted_inherited_ctor_use) 348 << Ctor->getParent() 349 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 350 else 351 Diag(Loc, diag::err_deleted_function_use); 352 NoteDeletedFunction(FD); 353 return true; 354 } 355 356 // If the function has a deduced return type, and we can't deduce it, 357 // then we can't use it either. 358 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 359 DeduceReturnType(FD, Loc)) 360 return true; 361 362 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 363 return true; 364 365 if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc)) 366 return true; 367 } 368 369 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 370 // Only the variables omp_in and omp_out are allowed in the combiner. 371 // Only the variables omp_priv and omp_orig are allowed in the 372 // initializer-clause. 373 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 374 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 375 isa<VarDecl>(D)) { 376 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 377 << getCurFunction()->HasOMPDeclareReductionCombiner; 378 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 379 return true; 380 } 381 382 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 383 ObjCPropertyAccess); 384 385 DiagnoseUnusedOfDecl(*this, D, Loc); 386 387 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 388 389 return false; 390 } 391 392 /// \brief Retrieve the message suffix that should be added to a 393 /// diagnostic complaining about the given function being deleted or 394 /// unavailable. 395 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 396 std::string Message; 397 if (FD->getAvailability(&Message)) 398 return ": " + Message; 399 400 return std::string(); 401 } 402 403 /// DiagnoseSentinelCalls - This routine checks whether a call or 404 /// message-send is to a declaration with the sentinel attribute, and 405 /// if so, it checks that the requirements of the sentinel are 406 /// satisfied. 407 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 408 ArrayRef<Expr *> Args) { 409 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 410 if (!attr) 411 return; 412 413 // The number of formal parameters of the declaration. 414 unsigned numFormalParams; 415 416 // The kind of declaration. This is also an index into a %select in 417 // the diagnostic. 418 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 419 420 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 421 numFormalParams = MD->param_size(); 422 calleeType = CT_Method; 423 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 424 numFormalParams = FD->param_size(); 425 calleeType = CT_Function; 426 } else if (isa<VarDecl>(D)) { 427 QualType type = cast<ValueDecl>(D)->getType(); 428 const FunctionType *fn = nullptr; 429 if (const PointerType *ptr = type->getAs<PointerType>()) { 430 fn = ptr->getPointeeType()->getAs<FunctionType>(); 431 if (!fn) return; 432 calleeType = CT_Function; 433 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 434 fn = ptr->getPointeeType()->castAs<FunctionType>(); 435 calleeType = CT_Block; 436 } else { 437 return; 438 } 439 440 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 441 numFormalParams = proto->getNumParams(); 442 } else { 443 numFormalParams = 0; 444 } 445 } else { 446 return; 447 } 448 449 // "nullPos" is the number of formal parameters at the end which 450 // effectively count as part of the variadic arguments. This is 451 // useful if you would prefer to not have *any* formal parameters, 452 // but the language forces you to have at least one. 453 unsigned nullPos = attr->getNullPos(); 454 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 455 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 456 457 // The number of arguments which should follow the sentinel. 458 unsigned numArgsAfterSentinel = attr->getSentinel(); 459 460 // If there aren't enough arguments for all the formal parameters, 461 // the sentinel, and the args after the sentinel, complain. 462 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 463 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 464 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 465 return; 466 } 467 468 // Otherwise, find the sentinel expression. 469 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 470 if (!sentinelExpr) return; 471 if (sentinelExpr->isValueDependent()) return; 472 if (Context.isSentinelNullExpr(sentinelExpr)) return; 473 474 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 475 // or 'NULL' if those are actually defined in the context. Only use 476 // 'nil' for ObjC methods, where it's much more likely that the 477 // variadic arguments form a list of object pointers. 478 SourceLocation MissingNilLoc 479 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 480 std::string NullValue; 481 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 482 NullValue = "nil"; 483 else if (getLangOpts().CPlusPlus11) 484 NullValue = "nullptr"; 485 else if (PP.isMacroDefined("NULL")) 486 NullValue = "NULL"; 487 else 488 NullValue = "(void*) 0"; 489 490 if (MissingNilLoc.isInvalid()) 491 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 492 else 493 Diag(MissingNilLoc, diag::warn_missing_sentinel) 494 << int(calleeType) 495 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 496 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 497 } 498 499 SourceRange Sema::getExprRange(Expr *E) const { 500 return E ? E->getSourceRange() : SourceRange(); 501 } 502 503 //===----------------------------------------------------------------------===// 504 // Standard Promotions and Conversions 505 //===----------------------------------------------------------------------===// 506 507 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 508 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 509 // Handle any placeholder expressions which made it here. 510 if (E->getType()->isPlaceholderType()) { 511 ExprResult result = CheckPlaceholderExpr(E); 512 if (result.isInvalid()) return ExprError(); 513 E = result.get(); 514 } 515 516 QualType Ty = E->getType(); 517 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 518 519 if (Ty->isFunctionType()) { 520 // If we are here, we are not calling a function but taking 521 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 522 if (getLangOpts().OpenCL) { 523 if (Diagnose) 524 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 525 return ExprError(); 526 } 527 528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 530 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 531 return ExprError(); 532 533 E = ImpCastExprToType(E, Context.getPointerType(Ty), 534 CK_FunctionToPointerDecay).get(); 535 } else if (Ty->isArrayType()) { 536 // In C90 mode, arrays only promote to pointers if the array expression is 537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 538 // type 'array of type' is converted to an expression that has type 'pointer 539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 540 // that has type 'array of type' ...". The relevant change is "an lvalue" 541 // (C90) to "an expression" (C99). 542 // 543 // C++ 4.2p1: 544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 545 // T" can be converted to an rvalue of type "pointer to T". 546 // 547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 548 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 549 CK_ArrayToPointerDecay).get(); 550 } 551 return E; 552 } 553 554 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 555 // Check to see if we are dereferencing a null pointer. If so, 556 // and if not volatile-qualified, this is undefined behavior that the 557 // optimizer will delete, so warn about it. People sometimes try to use this 558 // to get a deterministic trap and are surprised by clang's behavior. This 559 // only handles the pattern "*null", which is a very syntactic check. 560 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 561 if (UO->getOpcode() == UO_Deref && 562 UO->getSubExpr()->IgnoreParenCasts()-> 563 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 564 !UO->getType().isVolatileQualified()) { 565 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 566 S.PDiag(diag::warn_indirection_through_null) 567 << UO->getSubExpr()->getSourceRange()); 568 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 569 S.PDiag(diag::note_indirection_through_null)); 570 } 571 } 572 573 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 574 SourceLocation AssignLoc, 575 const Expr* RHS) { 576 const ObjCIvarDecl *IV = OIRE->getDecl(); 577 if (!IV) 578 return; 579 580 DeclarationName MemberName = IV->getDeclName(); 581 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 582 if (!Member || !Member->isStr("isa")) 583 return; 584 585 const Expr *Base = OIRE->getBase(); 586 QualType BaseType = Base->getType(); 587 if (OIRE->isArrow()) 588 BaseType = BaseType->getPointeeType(); 589 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 590 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 591 ObjCInterfaceDecl *ClassDeclared = nullptr; 592 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 593 if (!ClassDeclared->getSuperClass() 594 && (*ClassDeclared->ivar_begin()) == IV) { 595 if (RHS) { 596 NamedDecl *ObjectSetClass = 597 S.LookupSingleName(S.TUScope, 598 &S.Context.Idents.get("object_setClass"), 599 SourceLocation(), S.LookupOrdinaryName); 600 if (ObjectSetClass) { 601 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 602 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 603 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 604 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 605 AssignLoc), ",") << 606 FixItHint::CreateInsertion(RHSLocEnd, ")"); 607 } 608 else 609 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 610 } else { 611 NamedDecl *ObjectGetClass = 612 S.LookupSingleName(S.TUScope, 613 &S.Context.Idents.get("object_getClass"), 614 SourceLocation(), S.LookupOrdinaryName); 615 if (ObjectGetClass) 616 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 617 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 618 FixItHint::CreateReplacement( 619 SourceRange(OIRE->getOpLoc(), 620 OIRE->getLocEnd()), ")"); 621 else 622 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 623 } 624 S.Diag(IV->getLocation(), diag::note_ivar_decl); 625 } 626 } 627 } 628 629 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 630 // Handle any placeholder expressions which made it here. 631 if (E->getType()->isPlaceholderType()) { 632 ExprResult result = CheckPlaceholderExpr(E); 633 if (result.isInvalid()) return ExprError(); 634 E = result.get(); 635 } 636 637 // C++ [conv.lval]p1: 638 // A glvalue of a non-function, non-array type T can be 639 // converted to a prvalue. 640 if (!E->isGLValue()) return E; 641 642 QualType T = E->getType(); 643 assert(!T.isNull() && "r-value conversion on typeless expression?"); 644 645 // We don't want to throw lvalue-to-rvalue casts on top of 646 // expressions of certain types in C++. 647 if (getLangOpts().CPlusPlus && 648 (E->getType() == Context.OverloadTy || 649 T->isDependentType() || 650 T->isRecordType())) 651 return E; 652 653 // The C standard is actually really unclear on this point, and 654 // DR106 tells us what the result should be but not why. It's 655 // generally best to say that void types just doesn't undergo 656 // lvalue-to-rvalue at all. Note that expressions of unqualified 657 // 'void' type are never l-values, but qualified void can be. 658 if (T->isVoidType()) 659 return E; 660 661 // OpenCL usually rejects direct accesses to values of 'half' type. 662 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 663 T->isHalfType()) { 664 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 665 << 0 << T; 666 return ExprError(); 667 } 668 669 CheckForNullPointerDereference(*this, E); 670 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 671 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 672 &Context.Idents.get("object_getClass"), 673 SourceLocation(), LookupOrdinaryName); 674 if (ObjectGetClass) 675 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 676 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 677 FixItHint::CreateReplacement( 678 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 679 else 680 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 681 } 682 else if (const ObjCIvarRefExpr *OIRE = 683 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 684 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 685 686 // C++ [conv.lval]p1: 687 // [...] If T is a non-class type, the type of the prvalue is the 688 // cv-unqualified version of T. Otherwise, the type of the 689 // rvalue is T. 690 // 691 // C99 6.3.2.1p2: 692 // If the lvalue has qualified type, the value has the unqualified 693 // version of the type of the lvalue; otherwise, the value has the 694 // type of the lvalue. 695 if (T.hasQualifiers()) 696 T = T.getUnqualifiedType(); 697 698 // Under the MS ABI, lock down the inheritance model now. 699 if (T->isMemberPointerType() && 700 Context.getTargetInfo().getCXXABI().isMicrosoft()) 701 (void)isCompleteType(E->getExprLoc(), T); 702 703 UpdateMarkingForLValueToRValue(E); 704 705 // Loading a __weak object implicitly retains the value, so we need a cleanup to 706 // balance that. 707 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 708 Cleanup.setExprNeedsCleanups(true); 709 710 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 711 nullptr, VK_RValue); 712 713 // C11 6.3.2.1p2: 714 // ... if the lvalue has atomic type, the value has the non-atomic version 715 // of the type of the lvalue ... 716 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 717 T = Atomic->getValueType().getUnqualifiedType(); 718 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 719 nullptr, VK_RValue); 720 } 721 722 return Res; 723 } 724 725 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 726 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 727 if (Res.isInvalid()) 728 return ExprError(); 729 Res = DefaultLvalueConversion(Res.get()); 730 if (Res.isInvalid()) 731 return ExprError(); 732 return Res; 733 } 734 735 /// CallExprUnaryConversions - a special case of an unary conversion 736 /// performed on a function designator of a call expression. 737 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 738 QualType Ty = E->getType(); 739 ExprResult Res = E; 740 // Only do implicit cast for a function type, but not for a pointer 741 // to function type. 742 if (Ty->isFunctionType()) { 743 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 744 CK_FunctionToPointerDecay).get(); 745 if (Res.isInvalid()) 746 return ExprError(); 747 } 748 Res = DefaultLvalueConversion(Res.get()); 749 if (Res.isInvalid()) 750 return ExprError(); 751 return Res.get(); 752 } 753 754 /// UsualUnaryConversions - Performs various conversions that are common to most 755 /// operators (C99 6.3). The conversions of array and function types are 756 /// sometimes suppressed. For example, the array->pointer conversion doesn't 757 /// apply if the array is an argument to the sizeof or address (&) operators. 758 /// In these instances, this routine should *not* be called. 759 ExprResult Sema::UsualUnaryConversions(Expr *E) { 760 // First, convert to an r-value. 761 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 762 if (Res.isInvalid()) 763 return ExprError(); 764 E = Res.get(); 765 766 QualType Ty = E->getType(); 767 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 768 769 // Half FP have to be promoted to float unless it is natively supported 770 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 771 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 772 773 // Try to perform integral promotions if the object has a theoretically 774 // promotable type. 775 if (Ty->isIntegralOrUnscopedEnumerationType()) { 776 // C99 6.3.1.1p2: 777 // 778 // The following may be used in an expression wherever an int or 779 // unsigned int may be used: 780 // - an object or expression with an integer type whose integer 781 // conversion rank is less than or equal to the rank of int 782 // and unsigned int. 783 // - A bit-field of type _Bool, int, signed int, or unsigned int. 784 // 785 // If an int can represent all values of the original type, the 786 // value is converted to an int; otherwise, it is converted to an 787 // unsigned int. These are called the integer promotions. All 788 // other types are unchanged by the integer promotions. 789 790 QualType PTy = Context.isPromotableBitField(E); 791 if (!PTy.isNull()) { 792 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 793 return E; 794 } 795 if (Ty->isPromotableIntegerType()) { 796 QualType PT = Context.getPromotedIntegerType(Ty); 797 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 798 return E; 799 } 800 } 801 return E; 802 } 803 804 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 805 /// do not have a prototype. Arguments that have type float or __fp16 806 /// are promoted to double. All other argument types are converted by 807 /// UsualUnaryConversions(). 808 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 809 QualType Ty = E->getType(); 810 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 811 812 ExprResult Res = UsualUnaryConversions(E); 813 if (Res.isInvalid()) 814 return ExprError(); 815 E = Res.get(); 816 817 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 818 // double. 819 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 820 if (BTy && (BTy->getKind() == BuiltinType::Half || 821 BTy->getKind() == BuiltinType::Float)) { 822 if (getLangOpts().OpenCL && 823 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 824 if (BTy->getKind() == BuiltinType::Half) { 825 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 826 } 827 } else { 828 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 829 } 830 } 831 832 // C++ performs lvalue-to-rvalue conversion as a default argument 833 // promotion, even on class types, but note: 834 // C++11 [conv.lval]p2: 835 // When an lvalue-to-rvalue conversion occurs in an unevaluated 836 // operand or a subexpression thereof the value contained in the 837 // referenced object is not accessed. Otherwise, if the glvalue 838 // has a class type, the conversion copy-initializes a temporary 839 // of type T from the glvalue and the result of the conversion 840 // is a prvalue for the temporary. 841 // FIXME: add some way to gate this entire thing for correctness in 842 // potentially potentially evaluated contexts. 843 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 844 ExprResult Temp = PerformCopyInitialization( 845 InitializedEntity::InitializeTemporary(E->getType()), 846 E->getExprLoc(), E); 847 if (Temp.isInvalid()) 848 return ExprError(); 849 E = Temp.get(); 850 } 851 852 return E; 853 } 854 855 /// Determine the degree of POD-ness for an expression. 856 /// Incomplete types are considered POD, since this check can be performed 857 /// when we're in an unevaluated context. 858 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 859 if (Ty->isIncompleteType()) { 860 // C++11 [expr.call]p7: 861 // After these conversions, if the argument does not have arithmetic, 862 // enumeration, pointer, pointer to member, or class type, the program 863 // is ill-formed. 864 // 865 // Since we've already performed array-to-pointer and function-to-pointer 866 // decay, the only such type in C++ is cv void. This also handles 867 // initializer lists as variadic arguments. 868 if (Ty->isVoidType()) 869 return VAK_Invalid; 870 871 if (Ty->isObjCObjectType()) 872 return VAK_Invalid; 873 return VAK_Valid; 874 } 875 876 if (Ty.isCXX98PODType(Context)) 877 return VAK_Valid; 878 879 // C++11 [expr.call]p7: 880 // Passing a potentially-evaluated argument of class type (Clause 9) 881 // having a non-trivial copy constructor, a non-trivial move constructor, 882 // or a non-trivial destructor, with no corresponding parameter, 883 // is conditionally-supported with implementation-defined semantics. 884 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 885 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 886 if (!Record->hasNonTrivialCopyConstructor() && 887 !Record->hasNonTrivialMoveConstructor() && 888 !Record->hasNonTrivialDestructor()) 889 return VAK_ValidInCXX11; 890 891 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 892 return VAK_Valid; 893 894 if (Ty->isObjCObjectType()) 895 return VAK_Invalid; 896 897 if (getLangOpts().MSVCCompat) 898 return VAK_MSVCUndefined; 899 900 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 901 // permitted to reject them. We should consider doing so. 902 return VAK_Undefined; 903 } 904 905 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 906 // Don't allow one to pass an Objective-C interface to a vararg. 907 const QualType &Ty = E->getType(); 908 VarArgKind VAK = isValidVarArgType(Ty); 909 910 // Complain about passing non-POD types through varargs. 911 switch (VAK) { 912 case VAK_ValidInCXX11: 913 DiagRuntimeBehavior( 914 E->getLocStart(), nullptr, 915 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 916 << Ty << CT); 917 // Fall through. 918 case VAK_Valid: 919 if (Ty->isRecordType()) { 920 // This is unlikely to be what the user intended. If the class has a 921 // 'c_str' member function, the user probably meant to call that. 922 DiagRuntimeBehavior(E->getLocStart(), nullptr, 923 PDiag(diag::warn_pass_class_arg_to_vararg) 924 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 925 } 926 break; 927 928 case VAK_Undefined: 929 case VAK_MSVCUndefined: 930 DiagRuntimeBehavior( 931 E->getLocStart(), nullptr, 932 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 933 << getLangOpts().CPlusPlus11 << Ty << CT); 934 break; 935 936 case VAK_Invalid: 937 if (Ty->isObjCObjectType()) 938 DiagRuntimeBehavior( 939 E->getLocStart(), nullptr, 940 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 941 << Ty << CT); 942 else 943 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 944 << isa<InitListExpr>(E) << Ty << CT; 945 break; 946 } 947 } 948 949 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 950 /// will create a trap if the resulting type is not a POD type. 951 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 952 FunctionDecl *FDecl) { 953 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 954 // Strip the unbridged-cast placeholder expression off, if applicable. 955 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 956 (CT == VariadicMethod || 957 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 958 E = stripARCUnbridgedCast(E); 959 960 // Otherwise, do normal placeholder checking. 961 } else { 962 ExprResult ExprRes = CheckPlaceholderExpr(E); 963 if (ExprRes.isInvalid()) 964 return ExprError(); 965 E = ExprRes.get(); 966 } 967 } 968 969 ExprResult ExprRes = DefaultArgumentPromotion(E); 970 if (ExprRes.isInvalid()) 971 return ExprError(); 972 E = ExprRes.get(); 973 974 // Diagnostics regarding non-POD argument types are 975 // emitted along with format string checking in Sema::CheckFunctionCall(). 976 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 977 // Turn this into a trap. 978 CXXScopeSpec SS; 979 SourceLocation TemplateKWLoc; 980 UnqualifiedId Name; 981 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 982 E->getLocStart()); 983 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 984 Name, true, false); 985 if (TrapFn.isInvalid()) 986 return ExprError(); 987 988 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 989 E->getLocStart(), None, 990 E->getLocEnd()); 991 if (Call.isInvalid()) 992 return ExprError(); 993 994 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 995 Call.get(), E); 996 if (Comma.isInvalid()) 997 return ExprError(); 998 return Comma.get(); 999 } 1000 1001 if (!getLangOpts().CPlusPlus && 1002 RequireCompleteType(E->getExprLoc(), E->getType(), 1003 diag::err_call_incomplete_argument)) 1004 return ExprError(); 1005 1006 return E; 1007 } 1008 1009 /// \brief Converts an integer to complex float type. Helper function of 1010 /// UsualArithmeticConversions() 1011 /// 1012 /// \return false if the integer expression is an integer type and is 1013 /// successfully converted to the complex type. 1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1015 ExprResult &ComplexExpr, 1016 QualType IntTy, 1017 QualType ComplexTy, 1018 bool SkipCast) { 1019 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1020 if (SkipCast) return false; 1021 if (IntTy->isIntegerType()) { 1022 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1025 CK_FloatingRealToComplex); 1026 } else { 1027 assert(IntTy->isComplexIntegerType()); 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1029 CK_IntegralComplexToFloatingComplex); 1030 } 1031 return false; 1032 } 1033 1034 /// \brief Handle arithmetic conversion with complex types. Helper function of 1035 /// UsualArithmeticConversions() 1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1037 ExprResult &RHS, QualType LHSType, 1038 QualType RHSType, 1039 bool IsCompAssign) { 1040 // if we have an integer operand, the result is the complex type. 1041 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1042 /*skipCast*/false)) 1043 return LHSType; 1044 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1045 /*skipCast*/IsCompAssign)) 1046 return RHSType; 1047 1048 // This handles complex/complex, complex/float, or float/complex. 1049 // When both operands are complex, the shorter operand is converted to the 1050 // type of the longer, and that is the type of the result. This corresponds 1051 // to what is done when combining two real floating-point operands. 1052 // The fun begins when size promotion occur across type domains. 1053 // From H&S 6.3.4: When one operand is complex and the other is a real 1054 // floating-point type, the less precise type is converted, within it's 1055 // real or complex domain, to the precision of the other type. For example, 1056 // when combining a "long double" with a "double _Complex", the 1057 // "double _Complex" is promoted to "long double _Complex". 1058 1059 // Compute the rank of the two types, regardless of whether they are complex. 1060 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1061 1062 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1063 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1064 QualType LHSElementType = 1065 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1066 QualType RHSElementType = 1067 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1068 1069 QualType ResultType = S.Context.getComplexType(LHSElementType); 1070 if (Order < 0) { 1071 // Promote the precision of the LHS if not an assignment. 1072 ResultType = S.Context.getComplexType(RHSElementType); 1073 if (!IsCompAssign) { 1074 if (LHSComplexType) 1075 LHS = 1076 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1077 else 1078 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1079 } 1080 } else if (Order > 0) { 1081 // Promote the precision of the RHS. 1082 if (RHSComplexType) 1083 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1084 else 1085 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1086 } 1087 return ResultType; 1088 } 1089 1090 /// \brief Hande arithmetic conversion from integer to float. Helper function 1091 /// of UsualArithmeticConversions() 1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1093 ExprResult &IntExpr, 1094 QualType FloatTy, QualType IntTy, 1095 bool ConvertFloat, bool ConvertInt) { 1096 if (IntTy->isIntegerType()) { 1097 if (ConvertInt) 1098 // Convert intExpr to the lhs floating point type. 1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1100 CK_IntegralToFloating); 1101 return FloatTy; 1102 } 1103 1104 // Convert both sides to the appropriate complex float. 1105 assert(IntTy->isComplexIntegerType()); 1106 QualType result = S.Context.getComplexType(FloatTy); 1107 1108 // _Complex int -> _Complex float 1109 if (ConvertInt) 1110 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1111 CK_IntegralComplexToFloatingComplex); 1112 1113 // float -> _Complex float 1114 if (ConvertFloat) 1115 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1116 CK_FloatingRealToComplex); 1117 1118 return result; 1119 } 1120 1121 /// \brief Handle arithmethic conversion with floating point types. Helper 1122 /// function of UsualArithmeticConversions() 1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1124 ExprResult &RHS, QualType LHSType, 1125 QualType RHSType, bool IsCompAssign) { 1126 bool LHSFloat = LHSType->isRealFloatingType(); 1127 bool RHSFloat = RHSType->isRealFloatingType(); 1128 1129 // If we have two real floating types, convert the smaller operand 1130 // to the bigger result. 1131 if (LHSFloat && RHSFloat) { 1132 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1133 if (order > 0) { 1134 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1135 return LHSType; 1136 } 1137 1138 assert(order < 0 && "illegal float comparison"); 1139 if (!IsCompAssign) 1140 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1141 return RHSType; 1142 } 1143 1144 if (LHSFloat) { 1145 // Half FP has to be promoted to float unless it is natively supported 1146 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1147 LHSType = S.Context.FloatTy; 1148 1149 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1150 /*convertFloat=*/!IsCompAssign, 1151 /*convertInt=*/ true); 1152 } 1153 assert(RHSFloat); 1154 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1155 /*convertInt=*/ true, 1156 /*convertFloat=*/!IsCompAssign); 1157 } 1158 1159 /// \brief Diagnose attempts to convert between __float128 and long double if 1160 /// there is no support for such conversion. Helper function of 1161 /// UsualArithmeticConversions(). 1162 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1163 QualType RHSType) { 1164 /* No issue converting if at least one of the types is not a floating point 1165 type or the two types have the same rank. 1166 */ 1167 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1168 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1169 return false; 1170 1171 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1172 "The remaining types must be floating point types."); 1173 1174 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1175 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1176 1177 QualType LHSElemType = LHSComplex ? 1178 LHSComplex->getElementType() : LHSType; 1179 QualType RHSElemType = RHSComplex ? 1180 RHSComplex->getElementType() : RHSType; 1181 1182 // No issue if the two types have the same representation 1183 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1184 &S.Context.getFloatTypeSemantics(RHSElemType)) 1185 return false; 1186 1187 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1188 RHSElemType == S.Context.LongDoubleTy); 1189 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1190 RHSElemType == S.Context.Float128Ty); 1191 1192 /* We've handled the situation where __float128 and long double have the same 1193 representation. The only other allowable conversion is if long double is 1194 really just double. 1195 */ 1196 return Float128AndLongDouble && 1197 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1198 &llvm::APFloat::IEEEdouble()); 1199 } 1200 1201 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1202 1203 namespace { 1204 /// These helper callbacks are placed in an anonymous namespace to 1205 /// permit their use as function template parameters. 1206 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1207 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1208 } 1209 1210 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1211 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1212 CK_IntegralComplexCast); 1213 } 1214 } 1215 1216 /// \brief Handle integer arithmetic conversions. Helper function of 1217 /// UsualArithmeticConversions() 1218 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1219 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1220 ExprResult &RHS, QualType LHSType, 1221 QualType RHSType, bool IsCompAssign) { 1222 // The rules for this case are in C99 6.3.1.8 1223 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1224 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1225 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1226 if (LHSSigned == RHSSigned) { 1227 // Same signedness; use the higher-ranked type 1228 if (order >= 0) { 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 (order != (LHSSigned ? 1 : -1)) { 1235 // The unsigned type has greater than or equal rank to the 1236 // signed type, so use the unsigned type 1237 if (RHSSigned) { 1238 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1239 return LHSType; 1240 } else if (!IsCompAssign) 1241 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1242 return RHSType; 1243 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1244 // The two types are different widths; if we are here, that 1245 // means the signed type is larger than the unsigned type, so 1246 // use the signed type. 1247 if (LHSSigned) { 1248 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1249 return LHSType; 1250 } else if (!IsCompAssign) 1251 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1252 return RHSType; 1253 } else { 1254 // The signed type is higher-ranked than the unsigned type, 1255 // but isn't actually any bigger (like unsigned int and long 1256 // on most 32-bit systems). Use the unsigned type corresponding 1257 // to the signed type. 1258 QualType result = 1259 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1260 RHS = (*doRHSCast)(S, RHS.get(), result); 1261 if (!IsCompAssign) 1262 LHS = (*doLHSCast)(S, LHS.get(), result); 1263 return result; 1264 } 1265 } 1266 1267 /// \brief Handle conversions with GCC complex int extension. Helper function 1268 /// of UsualArithmeticConversions() 1269 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1270 ExprResult &RHS, QualType LHSType, 1271 QualType RHSType, 1272 bool IsCompAssign) { 1273 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1274 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1275 1276 if (LHSComplexInt && RHSComplexInt) { 1277 QualType LHSEltType = LHSComplexInt->getElementType(); 1278 QualType RHSEltType = RHSComplexInt->getElementType(); 1279 QualType ScalarType = 1280 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1281 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1282 1283 return S.Context.getComplexType(ScalarType); 1284 } 1285 1286 if (LHSComplexInt) { 1287 QualType LHSEltType = LHSComplexInt->getElementType(); 1288 QualType ScalarType = 1289 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1290 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1291 QualType ComplexType = S.Context.getComplexType(ScalarType); 1292 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1293 CK_IntegralRealToComplex); 1294 1295 return ComplexType; 1296 } 1297 1298 assert(RHSComplexInt); 1299 1300 QualType RHSEltType = RHSComplexInt->getElementType(); 1301 QualType ScalarType = 1302 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1303 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1304 QualType ComplexType = S.Context.getComplexType(ScalarType); 1305 1306 if (!IsCompAssign) 1307 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1308 CK_IntegralRealToComplex); 1309 return ComplexType; 1310 } 1311 1312 /// UsualArithmeticConversions - Performs various conversions that are common to 1313 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1314 /// routine returns the first non-arithmetic type found. The client is 1315 /// responsible for emitting appropriate error diagnostics. 1316 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1317 bool IsCompAssign) { 1318 if (!IsCompAssign) { 1319 LHS = UsualUnaryConversions(LHS.get()); 1320 if (LHS.isInvalid()) 1321 return QualType(); 1322 } 1323 1324 RHS = UsualUnaryConversions(RHS.get()); 1325 if (RHS.isInvalid()) 1326 return QualType(); 1327 1328 // For conversion purposes, we ignore any qualifiers. 1329 // For example, "const float" and "float" are equivalent. 1330 QualType LHSType = 1331 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1332 QualType RHSType = 1333 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1334 1335 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1336 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1337 LHSType = AtomicLHS->getValueType(); 1338 1339 // If both types are identical, no conversion is needed. 1340 if (LHSType == RHSType) 1341 return LHSType; 1342 1343 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1344 // The caller can deal with this (e.g. pointer + int). 1345 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1346 return QualType(); 1347 1348 // Apply unary and bitfield promotions to the LHS's type. 1349 QualType LHSUnpromotedType = LHSType; 1350 if (LHSType->isPromotableIntegerType()) 1351 LHSType = Context.getPromotedIntegerType(LHSType); 1352 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1353 if (!LHSBitfieldPromoteTy.isNull()) 1354 LHSType = LHSBitfieldPromoteTy; 1355 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1356 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1357 1358 // If both types are identical, no conversion is needed. 1359 if (LHSType == RHSType) 1360 return LHSType; 1361 1362 // At this point, we have two different arithmetic types. 1363 1364 // Diagnose attempts to convert between __float128 and long double where 1365 // such conversions currently can't be handled. 1366 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1367 return QualType(); 1368 1369 // Handle complex types first (C99 6.3.1.8p1). 1370 if (LHSType->isComplexType() || RHSType->isComplexType()) 1371 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1372 IsCompAssign); 1373 1374 // Now handle "real" floating types (i.e. float, double, long double). 1375 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1376 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1377 IsCompAssign); 1378 1379 // Handle GCC complex int extension. 1380 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1381 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1382 IsCompAssign); 1383 1384 // Finally, we have two differing integer types. 1385 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1386 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1387 } 1388 1389 1390 //===----------------------------------------------------------------------===// 1391 // Semantic Analysis for various Expression Types 1392 //===----------------------------------------------------------------------===// 1393 1394 1395 ExprResult 1396 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1397 SourceLocation DefaultLoc, 1398 SourceLocation RParenLoc, 1399 Expr *ControllingExpr, 1400 ArrayRef<ParsedType> ArgTypes, 1401 ArrayRef<Expr *> ArgExprs) { 1402 unsigned NumAssocs = ArgTypes.size(); 1403 assert(NumAssocs == ArgExprs.size()); 1404 1405 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1406 for (unsigned i = 0; i < NumAssocs; ++i) { 1407 if (ArgTypes[i]) 1408 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1409 else 1410 Types[i] = nullptr; 1411 } 1412 1413 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1414 ControllingExpr, 1415 llvm::makeArrayRef(Types, NumAssocs), 1416 ArgExprs); 1417 delete [] Types; 1418 return ER; 1419 } 1420 1421 ExprResult 1422 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1423 SourceLocation DefaultLoc, 1424 SourceLocation RParenLoc, 1425 Expr *ControllingExpr, 1426 ArrayRef<TypeSourceInfo *> Types, 1427 ArrayRef<Expr *> Exprs) { 1428 unsigned NumAssocs = Types.size(); 1429 assert(NumAssocs == Exprs.size()); 1430 1431 // Decay and strip qualifiers for the controlling expression type, and handle 1432 // placeholder type replacement. See committee discussion from WG14 DR423. 1433 { 1434 EnterExpressionEvaluationContext Unevaluated( 1435 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1436 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1437 if (R.isInvalid()) 1438 return ExprError(); 1439 ControllingExpr = R.get(); 1440 } 1441 1442 // The controlling expression is an unevaluated operand, so side effects are 1443 // likely unintended. 1444 if (!inTemplateInstantiation() && 1445 ControllingExpr->HasSideEffects(Context, false)) 1446 Diag(ControllingExpr->getExprLoc(), 1447 diag::warn_side_effects_unevaluated_context); 1448 1449 bool TypeErrorFound = false, 1450 IsResultDependent = ControllingExpr->isTypeDependent(), 1451 ContainsUnexpandedParameterPack 1452 = ControllingExpr->containsUnexpandedParameterPack(); 1453 1454 for (unsigned i = 0; i < NumAssocs; ++i) { 1455 if (Exprs[i]->containsUnexpandedParameterPack()) 1456 ContainsUnexpandedParameterPack = true; 1457 1458 if (Types[i]) { 1459 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1460 ContainsUnexpandedParameterPack = true; 1461 1462 if (Types[i]->getType()->isDependentType()) { 1463 IsResultDependent = true; 1464 } else { 1465 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1466 // complete object type other than a variably modified type." 1467 unsigned D = 0; 1468 if (Types[i]->getType()->isIncompleteType()) 1469 D = diag::err_assoc_type_incomplete; 1470 else if (!Types[i]->getType()->isObjectType()) 1471 D = diag::err_assoc_type_nonobject; 1472 else if (Types[i]->getType()->isVariablyModifiedType()) 1473 D = diag::err_assoc_type_variably_modified; 1474 1475 if (D != 0) { 1476 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1477 << Types[i]->getTypeLoc().getSourceRange() 1478 << Types[i]->getType(); 1479 TypeErrorFound = true; 1480 } 1481 1482 // C11 6.5.1.1p2 "No two generic associations in the same generic 1483 // selection shall specify compatible types." 1484 for (unsigned j = i+1; j < NumAssocs; ++j) 1485 if (Types[j] && !Types[j]->getType()->isDependentType() && 1486 Context.typesAreCompatible(Types[i]->getType(), 1487 Types[j]->getType())) { 1488 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1489 diag::err_assoc_compatible_types) 1490 << Types[j]->getTypeLoc().getSourceRange() 1491 << Types[j]->getType() 1492 << Types[i]->getType(); 1493 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1494 diag::note_compat_assoc) 1495 << Types[i]->getTypeLoc().getSourceRange() 1496 << Types[i]->getType(); 1497 TypeErrorFound = true; 1498 } 1499 } 1500 } 1501 } 1502 if (TypeErrorFound) 1503 return ExprError(); 1504 1505 // If we determined that the generic selection is result-dependent, don't 1506 // try to compute the result expression. 1507 if (IsResultDependent) 1508 return new (Context) GenericSelectionExpr( 1509 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1510 ContainsUnexpandedParameterPack); 1511 1512 SmallVector<unsigned, 1> CompatIndices; 1513 unsigned DefaultIndex = -1U; 1514 for (unsigned i = 0; i < NumAssocs; ++i) { 1515 if (!Types[i]) 1516 DefaultIndex = i; 1517 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1518 Types[i]->getType())) 1519 CompatIndices.push_back(i); 1520 } 1521 1522 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1523 // type compatible with at most one of the types named in its generic 1524 // association list." 1525 if (CompatIndices.size() > 1) { 1526 // We strip parens here because the controlling expression is typically 1527 // parenthesized in macro definitions. 1528 ControllingExpr = ControllingExpr->IgnoreParens(); 1529 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1530 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1531 << (unsigned) CompatIndices.size(); 1532 for (unsigned I : CompatIndices) { 1533 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1534 diag::note_compat_assoc) 1535 << Types[I]->getTypeLoc().getSourceRange() 1536 << Types[I]->getType(); 1537 } 1538 return ExprError(); 1539 } 1540 1541 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1542 // its controlling expression shall have type compatible with exactly one of 1543 // the types named in its generic association list." 1544 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1545 // We strip parens here because the controlling expression is typically 1546 // parenthesized in macro definitions. 1547 ControllingExpr = ControllingExpr->IgnoreParens(); 1548 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1549 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1550 return ExprError(); 1551 } 1552 1553 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1554 // type name that is compatible with the type of the controlling expression, 1555 // then the result expression of the generic selection is the expression 1556 // in that generic association. Otherwise, the result expression of the 1557 // generic selection is the expression in the default generic association." 1558 unsigned ResultIndex = 1559 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1560 1561 return new (Context) GenericSelectionExpr( 1562 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1563 ContainsUnexpandedParameterPack, ResultIndex); 1564 } 1565 1566 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1567 /// location of the token and the offset of the ud-suffix within it. 1568 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1569 unsigned Offset) { 1570 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1571 S.getLangOpts()); 1572 } 1573 1574 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1575 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1576 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1577 IdentifierInfo *UDSuffix, 1578 SourceLocation UDSuffixLoc, 1579 ArrayRef<Expr*> Args, 1580 SourceLocation LitEndLoc) { 1581 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1582 1583 QualType ArgTy[2]; 1584 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1585 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1586 if (ArgTy[ArgIdx]->isArrayType()) 1587 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1588 } 1589 1590 DeclarationName OpName = 1591 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1592 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1593 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1594 1595 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1596 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1597 /*AllowRaw*/false, /*AllowTemplate*/false, 1598 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1599 return ExprError(); 1600 1601 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1602 } 1603 1604 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1605 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1606 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1607 /// multiple tokens. However, the common case is that StringToks points to one 1608 /// string. 1609 /// 1610 ExprResult 1611 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1612 assert(!StringToks.empty() && "Must have at least one string!"); 1613 1614 StringLiteralParser Literal(StringToks, PP); 1615 if (Literal.hadError) 1616 return ExprError(); 1617 1618 SmallVector<SourceLocation, 4> StringTokLocs; 1619 for (const Token &Tok : StringToks) 1620 StringTokLocs.push_back(Tok.getLocation()); 1621 1622 QualType CharTy = Context.CharTy; 1623 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1624 if (Literal.isWide()) { 1625 CharTy = Context.getWideCharType(); 1626 Kind = StringLiteral::Wide; 1627 } else if (Literal.isUTF8()) { 1628 Kind = StringLiteral::UTF8; 1629 } else if (Literal.isUTF16()) { 1630 CharTy = Context.Char16Ty; 1631 Kind = StringLiteral::UTF16; 1632 } else if (Literal.isUTF32()) { 1633 CharTy = Context.Char32Ty; 1634 Kind = StringLiteral::UTF32; 1635 } else if (Literal.isPascal()) { 1636 CharTy = Context.UnsignedCharTy; 1637 } 1638 1639 QualType CharTyConst = CharTy; 1640 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1641 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1642 CharTyConst.addConst(); 1643 1644 // Get an array type for the string, according to C99 6.4.5. This includes 1645 // the nul terminator character as well as the string length for pascal 1646 // strings. 1647 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1648 llvm::APInt(32, Literal.GetNumStringChars()+1), 1649 ArrayType::Normal, 0); 1650 1651 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1652 if (getLangOpts().OpenCL) { 1653 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1654 } 1655 1656 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1657 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1658 Kind, Literal.Pascal, StrTy, 1659 &StringTokLocs[0], 1660 StringTokLocs.size()); 1661 if (Literal.getUDSuffix().empty()) 1662 return Lit; 1663 1664 // We're building a user-defined literal. 1665 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1666 SourceLocation UDSuffixLoc = 1667 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1668 Literal.getUDSuffixOffset()); 1669 1670 // Make sure we're allowed user-defined literals here. 1671 if (!UDLScope) 1672 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1673 1674 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1675 // operator "" X (str, len) 1676 QualType SizeType = Context.getSizeType(); 1677 1678 DeclarationName OpName = 1679 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1680 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1681 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1682 1683 QualType ArgTy[] = { 1684 Context.getArrayDecayedType(StrTy), SizeType 1685 }; 1686 1687 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1688 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1689 /*AllowRaw*/false, /*AllowTemplate*/false, 1690 /*AllowStringTemplate*/true)) { 1691 1692 case LOLR_Cooked: { 1693 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1694 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1695 StringTokLocs[0]); 1696 Expr *Args[] = { Lit, LenArg }; 1697 1698 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1699 } 1700 1701 case LOLR_StringTemplate: { 1702 TemplateArgumentListInfo ExplicitArgs; 1703 1704 unsigned CharBits = Context.getIntWidth(CharTy); 1705 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1706 llvm::APSInt Value(CharBits, CharIsUnsigned); 1707 1708 TemplateArgument TypeArg(CharTy); 1709 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1710 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1711 1712 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1713 Value = Lit->getCodeUnit(I); 1714 TemplateArgument Arg(Context, Value, CharTy); 1715 TemplateArgumentLocInfo ArgInfo; 1716 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1717 } 1718 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1719 &ExplicitArgs); 1720 } 1721 case LOLR_Raw: 1722 case LOLR_Template: 1723 llvm_unreachable("unexpected literal operator lookup result"); 1724 case LOLR_Error: 1725 return ExprError(); 1726 } 1727 llvm_unreachable("unexpected literal operator lookup result"); 1728 } 1729 1730 ExprResult 1731 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1732 SourceLocation Loc, 1733 const CXXScopeSpec *SS) { 1734 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1735 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1736 } 1737 1738 /// BuildDeclRefExpr - Build an expression that references a 1739 /// declaration that does not require a closure capture. 1740 ExprResult 1741 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1742 const DeclarationNameInfo &NameInfo, 1743 const CXXScopeSpec *SS, NamedDecl *FoundD, 1744 const TemplateArgumentListInfo *TemplateArgs) { 1745 bool RefersToCapturedVariable = 1746 isa<VarDecl>(D) && 1747 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1748 1749 DeclRefExpr *E; 1750 if (isa<VarTemplateSpecializationDecl>(D)) { 1751 VarTemplateSpecializationDecl *VarSpec = 1752 cast<VarTemplateSpecializationDecl>(D); 1753 1754 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1755 : NestedNameSpecifierLoc(), 1756 VarSpec->getTemplateKeywordLoc(), D, 1757 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1758 FoundD, TemplateArgs); 1759 } else { 1760 assert(!TemplateArgs && "No template arguments for non-variable" 1761 " template specialization references"); 1762 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1763 : NestedNameSpecifierLoc(), 1764 SourceLocation(), D, RefersToCapturedVariable, 1765 NameInfo, Ty, VK, FoundD); 1766 } 1767 1768 MarkDeclRefReferenced(E); 1769 1770 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1771 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1772 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1773 recordUseOfEvaluatedWeak(E); 1774 1775 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1776 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1777 FD = IFD->getAnonField(); 1778 if (FD) { 1779 UnusedPrivateFields.remove(FD); 1780 // Just in case we're building an illegal pointer-to-member. 1781 if (FD->isBitField()) 1782 E->setObjectKind(OK_BitField); 1783 } 1784 1785 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1786 // designates a bit-field. 1787 if (auto *BD = dyn_cast<BindingDecl>(D)) 1788 if (auto *BE = BD->getBinding()) 1789 E->setObjectKind(BE->getObjectKind()); 1790 1791 return E; 1792 } 1793 1794 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1795 /// possibly a list of template arguments. 1796 /// 1797 /// If this produces template arguments, it is permitted to call 1798 /// DecomposeTemplateName. 1799 /// 1800 /// This actually loses a lot of source location information for 1801 /// non-standard name kinds; we should consider preserving that in 1802 /// some way. 1803 void 1804 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1805 TemplateArgumentListInfo &Buffer, 1806 DeclarationNameInfo &NameInfo, 1807 const TemplateArgumentListInfo *&TemplateArgs) { 1808 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1809 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1810 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1811 1812 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1813 Id.TemplateId->NumArgs); 1814 translateTemplateArguments(TemplateArgsPtr, Buffer); 1815 1816 TemplateName TName = Id.TemplateId->Template.get(); 1817 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1818 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1819 TemplateArgs = &Buffer; 1820 } else { 1821 NameInfo = GetNameFromUnqualifiedId(Id); 1822 TemplateArgs = nullptr; 1823 } 1824 } 1825 1826 static void emitEmptyLookupTypoDiagnostic( 1827 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1828 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1829 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1830 DeclContext *Ctx = 1831 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1832 if (!TC) { 1833 // Emit a special diagnostic for failed member lookups. 1834 // FIXME: computing the declaration context might fail here (?) 1835 if (Ctx) 1836 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1837 << SS.getRange(); 1838 else 1839 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1840 return; 1841 } 1842 1843 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1844 bool DroppedSpecifier = 1845 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1846 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1847 ? diag::note_implicit_param_decl 1848 : diag::note_previous_decl; 1849 if (!Ctx) 1850 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1851 SemaRef.PDiag(NoteID)); 1852 else 1853 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1854 << Typo << Ctx << DroppedSpecifier 1855 << SS.getRange(), 1856 SemaRef.PDiag(NoteID)); 1857 } 1858 1859 /// Diagnose an empty lookup. 1860 /// 1861 /// \return false if new lookup candidates were found 1862 bool 1863 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1864 std::unique_ptr<CorrectionCandidateCallback> CCC, 1865 TemplateArgumentListInfo *ExplicitTemplateArgs, 1866 ArrayRef<Expr *> Args, TypoExpr **Out) { 1867 DeclarationName Name = R.getLookupName(); 1868 1869 unsigned diagnostic = diag::err_undeclared_var_use; 1870 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1871 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1872 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1873 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1874 diagnostic = diag::err_undeclared_use; 1875 diagnostic_suggest = diag::err_undeclared_use_suggest; 1876 } 1877 1878 // If the original lookup was an unqualified lookup, fake an 1879 // unqualified lookup. This is useful when (for example) the 1880 // original lookup would not have found something because it was a 1881 // dependent name. 1882 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1883 while (DC) { 1884 if (isa<CXXRecordDecl>(DC)) { 1885 LookupQualifiedName(R, DC); 1886 1887 if (!R.empty()) { 1888 // Don't give errors about ambiguities in this lookup. 1889 R.suppressDiagnostics(); 1890 1891 // During a default argument instantiation the CurContext points 1892 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1893 // function parameter list, hence add an explicit check. 1894 bool isDefaultArgument = 1895 !CodeSynthesisContexts.empty() && 1896 CodeSynthesisContexts.back().Kind == 1897 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1898 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1899 bool isInstance = CurMethod && 1900 CurMethod->isInstance() && 1901 DC == CurMethod->getParent() && !isDefaultArgument; 1902 1903 // Give a code modification hint to insert 'this->'. 1904 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1905 // Actually quite difficult! 1906 if (getLangOpts().MSVCCompat) 1907 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1908 if (isInstance) { 1909 Diag(R.getNameLoc(), diagnostic) << Name 1910 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1911 CheckCXXThisCapture(R.getNameLoc()); 1912 } else { 1913 Diag(R.getNameLoc(), diagnostic) << Name; 1914 } 1915 1916 // Do we really want to note all of these? 1917 for (NamedDecl *D : R) 1918 Diag(D->getLocation(), diag::note_dependent_var_use); 1919 1920 // Return true if we are inside a default argument instantiation 1921 // and the found name refers to an instance member function, otherwise 1922 // the function calling DiagnoseEmptyLookup will try to create an 1923 // implicit member call and this is wrong for default argument. 1924 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1925 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1926 return true; 1927 } 1928 1929 // Tell the callee to try to recover. 1930 return false; 1931 } 1932 1933 R.clear(); 1934 } 1935 1936 // In Microsoft mode, if we are performing lookup from within a friend 1937 // function definition declared at class scope then we must set 1938 // DC to the lexical parent to be able to search into the parent 1939 // class. 1940 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1941 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1942 DC->getLexicalParent()->isRecord()) 1943 DC = DC->getLexicalParent(); 1944 else 1945 DC = DC->getParent(); 1946 } 1947 1948 // We didn't find anything, so try to correct for a typo. 1949 TypoCorrection Corrected; 1950 if (S && Out) { 1951 SourceLocation TypoLoc = R.getNameLoc(); 1952 assert(!ExplicitTemplateArgs && 1953 "Diagnosing an empty lookup with explicit template args!"); 1954 *Out = CorrectTypoDelayed( 1955 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1956 [=](const TypoCorrection &TC) { 1957 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1958 diagnostic, diagnostic_suggest); 1959 }, 1960 nullptr, CTK_ErrorRecovery); 1961 if (*Out) 1962 return true; 1963 } else if (S && (Corrected = 1964 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1965 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1966 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1967 bool DroppedSpecifier = 1968 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1969 R.setLookupName(Corrected.getCorrection()); 1970 1971 bool AcceptableWithRecovery = false; 1972 bool AcceptableWithoutRecovery = false; 1973 NamedDecl *ND = Corrected.getFoundDecl(); 1974 if (ND) { 1975 if (Corrected.isOverloaded()) { 1976 OverloadCandidateSet OCS(R.getNameLoc(), 1977 OverloadCandidateSet::CSK_Normal); 1978 OverloadCandidateSet::iterator Best; 1979 for (NamedDecl *CD : Corrected) { 1980 if (FunctionTemplateDecl *FTD = 1981 dyn_cast<FunctionTemplateDecl>(CD)) 1982 AddTemplateOverloadCandidate( 1983 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1984 Args, OCS); 1985 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1986 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1987 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1988 Args, OCS); 1989 } 1990 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1991 case OR_Success: 1992 ND = Best->FoundDecl; 1993 Corrected.setCorrectionDecl(ND); 1994 break; 1995 default: 1996 // FIXME: Arbitrarily pick the first declaration for the note. 1997 Corrected.setCorrectionDecl(ND); 1998 break; 1999 } 2000 } 2001 R.addDecl(ND); 2002 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2003 CXXRecordDecl *Record = nullptr; 2004 if (Corrected.getCorrectionSpecifier()) { 2005 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2006 Record = Ty->getAsCXXRecordDecl(); 2007 } 2008 if (!Record) 2009 Record = cast<CXXRecordDecl>( 2010 ND->getDeclContext()->getRedeclContext()); 2011 R.setNamingClass(Record); 2012 } 2013 2014 auto *UnderlyingND = ND->getUnderlyingDecl(); 2015 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2016 isa<FunctionTemplateDecl>(UnderlyingND); 2017 // FIXME: If we ended up with a typo for a type name or 2018 // Objective-C class name, we're in trouble because the parser 2019 // is in the wrong place to recover. Suggest the typo 2020 // correction, but don't make it a fix-it since we're not going 2021 // to recover well anyway. 2022 AcceptableWithoutRecovery = 2023 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2024 } else { 2025 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2026 // because we aren't able to recover. 2027 AcceptableWithoutRecovery = true; 2028 } 2029 2030 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2031 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2032 ? diag::note_implicit_param_decl 2033 : diag::note_previous_decl; 2034 if (SS.isEmpty()) 2035 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2036 PDiag(NoteID), AcceptableWithRecovery); 2037 else 2038 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2039 << Name << computeDeclContext(SS, false) 2040 << DroppedSpecifier << SS.getRange(), 2041 PDiag(NoteID), AcceptableWithRecovery); 2042 2043 // Tell the callee whether to try to recover. 2044 return !AcceptableWithRecovery; 2045 } 2046 } 2047 R.clear(); 2048 2049 // Emit a special diagnostic for failed member lookups. 2050 // FIXME: computing the declaration context might fail here (?) 2051 if (!SS.isEmpty()) { 2052 Diag(R.getNameLoc(), diag::err_no_member) 2053 << Name << computeDeclContext(SS, false) 2054 << SS.getRange(); 2055 return true; 2056 } 2057 2058 // Give up, we can't recover. 2059 Diag(R.getNameLoc(), diagnostic) << Name; 2060 return true; 2061 } 2062 2063 /// In Microsoft mode, if we are inside a template class whose parent class has 2064 /// dependent base classes, and we can't resolve an unqualified identifier, then 2065 /// assume the identifier is a member of a dependent base class. We can only 2066 /// recover successfully in static methods, instance methods, and other contexts 2067 /// where 'this' is available. This doesn't precisely match MSVC's 2068 /// instantiation model, but it's close enough. 2069 static Expr * 2070 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2071 DeclarationNameInfo &NameInfo, 2072 SourceLocation TemplateKWLoc, 2073 const TemplateArgumentListInfo *TemplateArgs) { 2074 // Only try to recover from lookup into dependent bases in static methods or 2075 // contexts where 'this' is available. 2076 QualType ThisType = S.getCurrentThisType(); 2077 const CXXRecordDecl *RD = nullptr; 2078 if (!ThisType.isNull()) 2079 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2080 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2081 RD = MD->getParent(); 2082 if (!RD || !RD->hasAnyDependentBases()) 2083 return nullptr; 2084 2085 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2086 // is available, suggest inserting 'this->' as a fixit. 2087 SourceLocation Loc = NameInfo.getLoc(); 2088 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2089 DB << NameInfo.getName() << RD; 2090 2091 if (!ThisType.isNull()) { 2092 DB << FixItHint::CreateInsertion(Loc, "this->"); 2093 return CXXDependentScopeMemberExpr::Create( 2094 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2095 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2096 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2097 } 2098 2099 // Synthesize a fake NNS that points to the derived class. This will 2100 // perform name lookup during template instantiation. 2101 CXXScopeSpec SS; 2102 auto *NNS = 2103 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2104 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2105 return DependentScopeDeclRefExpr::Create( 2106 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2107 TemplateArgs); 2108 } 2109 2110 ExprResult 2111 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2112 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2113 bool HasTrailingLParen, bool IsAddressOfOperand, 2114 std::unique_ptr<CorrectionCandidateCallback> CCC, 2115 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2116 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2117 "cannot be direct & operand and have a trailing lparen"); 2118 if (SS.isInvalid()) 2119 return ExprError(); 2120 2121 TemplateArgumentListInfo TemplateArgsBuffer; 2122 2123 // Decompose the UnqualifiedId into the following data. 2124 DeclarationNameInfo NameInfo; 2125 const TemplateArgumentListInfo *TemplateArgs; 2126 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2127 2128 DeclarationName Name = NameInfo.getName(); 2129 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2130 SourceLocation NameLoc = NameInfo.getLoc(); 2131 2132 // C++ [temp.dep.expr]p3: 2133 // An id-expression is type-dependent if it contains: 2134 // -- an identifier that was declared with a dependent type, 2135 // (note: handled after lookup) 2136 // -- a template-id that is dependent, 2137 // (note: handled in BuildTemplateIdExpr) 2138 // -- a conversion-function-id that specifies a dependent type, 2139 // -- a nested-name-specifier that contains a class-name that 2140 // names a dependent type. 2141 // Determine whether this is a member of an unknown specialization; 2142 // we need to handle these differently. 2143 bool DependentID = false; 2144 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2145 Name.getCXXNameType()->isDependentType()) { 2146 DependentID = true; 2147 } else if (SS.isSet()) { 2148 if (DeclContext *DC = computeDeclContext(SS, false)) { 2149 if (RequireCompleteDeclContext(SS, DC)) 2150 return ExprError(); 2151 } else { 2152 DependentID = true; 2153 } 2154 } 2155 2156 if (DependentID) 2157 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2158 IsAddressOfOperand, TemplateArgs); 2159 2160 // Perform the required lookup. 2161 LookupResult R(*this, NameInfo, 2162 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2163 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2164 if (TemplateArgs) { 2165 // Lookup the template name again to correctly establish the context in 2166 // which it was found. This is really unfortunate as we already did the 2167 // lookup to determine that it was a template name in the first place. If 2168 // this becomes a performance hit, we can work harder to preserve those 2169 // results until we get here but it's likely not worth it. 2170 bool MemberOfUnknownSpecialization; 2171 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2172 MemberOfUnknownSpecialization); 2173 2174 if (MemberOfUnknownSpecialization || 2175 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2176 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2177 IsAddressOfOperand, TemplateArgs); 2178 } else { 2179 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2180 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2181 2182 // If the result might be in a dependent base class, this is a dependent 2183 // id-expression. 2184 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2185 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2186 IsAddressOfOperand, TemplateArgs); 2187 2188 // If this reference is in an Objective-C method, then we need to do 2189 // some special Objective-C lookup, too. 2190 if (IvarLookupFollowUp) { 2191 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2192 if (E.isInvalid()) 2193 return ExprError(); 2194 2195 if (Expr *Ex = E.getAs<Expr>()) 2196 return Ex; 2197 } 2198 } 2199 2200 if (R.isAmbiguous()) 2201 return ExprError(); 2202 2203 // This could be an implicitly declared function reference (legal in C90, 2204 // extension in C99, forbidden in C++). 2205 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2206 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2207 if (D) R.addDecl(D); 2208 } 2209 2210 // Determine whether this name might be a candidate for 2211 // argument-dependent lookup. 2212 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2213 2214 if (R.empty() && !ADL) { 2215 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2216 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2217 TemplateKWLoc, TemplateArgs)) 2218 return E; 2219 } 2220 2221 // Don't diagnose an empty lookup for inline assembly. 2222 if (IsInlineAsmIdentifier) 2223 return ExprError(); 2224 2225 // If this name wasn't predeclared and if this is not a function 2226 // call, diagnose the problem. 2227 TypoExpr *TE = nullptr; 2228 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2229 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2230 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2231 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2232 "Typo correction callback misconfigured"); 2233 if (CCC) { 2234 // Make sure the callback knows what the typo being diagnosed is. 2235 CCC->setTypoName(II); 2236 if (SS.isValid()) 2237 CCC->setTypoNNS(SS.getScopeRep()); 2238 } 2239 if (DiagnoseEmptyLookup(S, SS, R, 2240 CCC ? std::move(CCC) : std::move(DefaultValidator), 2241 nullptr, None, &TE)) { 2242 if (TE && KeywordReplacement) { 2243 auto &State = getTypoExprState(TE); 2244 auto BestTC = State.Consumer->getNextCorrection(); 2245 if (BestTC.isKeyword()) { 2246 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2247 if (State.DiagHandler) 2248 State.DiagHandler(BestTC); 2249 KeywordReplacement->startToken(); 2250 KeywordReplacement->setKind(II->getTokenID()); 2251 KeywordReplacement->setIdentifierInfo(II); 2252 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2253 // Clean up the state associated with the TypoExpr, since it has 2254 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2255 clearDelayedTypo(TE); 2256 // Signal that a correction to a keyword was performed by returning a 2257 // valid-but-null ExprResult. 2258 return (Expr*)nullptr; 2259 } 2260 State.Consumer->resetCorrectionStream(); 2261 } 2262 return TE ? TE : ExprError(); 2263 } 2264 2265 assert(!R.empty() && 2266 "DiagnoseEmptyLookup returned false but added no results"); 2267 2268 // If we found an Objective-C instance variable, let 2269 // LookupInObjCMethod build the appropriate expression to 2270 // reference the ivar. 2271 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2272 R.clear(); 2273 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2274 // In a hopelessly buggy code, Objective-C instance variable 2275 // lookup fails and no expression will be built to reference it. 2276 if (!E.isInvalid() && !E.get()) 2277 return ExprError(); 2278 return E; 2279 } 2280 } 2281 2282 // This is guaranteed from this point on. 2283 assert(!R.empty() || ADL); 2284 2285 // Check whether this might be a C++ implicit instance member access. 2286 // C++ [class.mfct.non-static]p3: 2287 // When an id-expression that is not part of a class member access 2288 // syntax and not used to form a pointer to member is used in the 2289 // body of a non-static member function of class X, if name lookup 2290 // resolves the name in the id-expression to a non-static non-type 2291 // member of some class C, the id-expression is transformed into a 2292 // class member access expression using (*this) as the 2293 // postfix-expression to the left of the . operator. 2294 // 2295 // But we don't actually need to do this for '&' operands if R 2296 // resolved to a function or overloaded function set, because the 2297 // expression is ill-formed if it actually works out to be a 2298 // non-static member function: 2299 // 2300 // C++ [expr.ref]p4: 2301 // Otherwise, if E1.E2 refers to a non-static member function. . . 2302 // [t]he expression can be used only as the left-hand operand of a 2303 // member function call. 2304 // 2305 // There are other safeguards against such uses, but it's important 2306 // to get this right here so that we don't end up making a 2307 // spuriously dependent expression if we're inside a dependent 2308 // instance method. 2309 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2310 bool MightBeImplicitMember; 2311 if (!IsAddressOfOperand) 2312 MightBeImplicitMember = true; 2313 else if (!SS.isEmpty()) 2314 MightBeImplicitMember = false; 2315 else if (R.isOverloadedResult()) 2316 MightBeImplicitMember = false; 2317 else if (R.isUnresolvableResult()) 2318 MightBeImplicitMember = true; 2319 else 2320 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2321 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2322 isa<MSPropertyDecl>(R.getFoundDecl()); 2323 2324 if (MightBeImplicitMember) 2325 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2326 R, TemplateArgs, S); 2327 } 2328 2329 if (TemplateArgs || TemplateKWLoc.isValid()) { 2330 2331 // In C++1y, if this is a variable template id, then check it 2332 // in BuildTemplateIdExpr(). 2333 // The single lookup result must be a variable template declaration. 2334 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2335 Id.TemplateId->Kind == TNK_Var_template) { 2336 assert(R.getAsSingle<VarTemplateDecl>() && 2337 "There should only be one declaration found."); 2338 } 2339 2340 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2341 } 2342 2343 return BuildDeclarationNameExpr(SS, R, ADL); 2344 } 2345 2346 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2347 /// declaration name, generally during template instantiation. 2348 /// There's a large number of things which don't need to be done along 2349 /// this path. 2350 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2351 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2352 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2353 DeclContext *DC = computeDeclContext(SS, false); 2354 if (!DC) 2355 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2356 NameInfo, /*TemplateArgs=*/nullptr); 2357 2358 if (RequireCompleteDeclContext(SS, DC)) 2359 return ExprError(); 2360 2361 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2362 LookupQualifiedName(R, DC); 2363 2364 if (R.isAmbiguous()) 2365 return ExprError(); 2366 2367 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2368 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2369 NameInfo, /*TemplateArgs=*/nullptr); 2370 2371 if (R.empty()) { 2372 Diag(NameInfo.getLoc(), diag::err_no_member) 2373 << NameInfo.getName() << DC << SS.getRange(); 2374 return ExprError(); 2375 } 2376 2377 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2378 // Diagnose a missing typename if this resolved unambiguously to a type in 2379 // a dependent context. If we can recover with a type, downgrade this to 2380 // a warning in Microsoft compatibility mode. 2381 unsigned DiagID = diag::err_typename_missing; 2382 if (RecoveryTSI && getLangOpts().MSVCCompat) 2383 DiagID = diag::ext_typename_missing; 2384 SourceLocation Loc = SS.getBeginLoc(); 2385 auto D = Diag(Loc, DiagID); 2386 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2387 << SourceRange(Loc, NameInfo.getEndLoc()); 2388 2389 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2390 // context. 2391 if (!RecoveryTSI) 2392 return ExprError(); 2393 2394 // Only issue the fixit if we're prepared to recover. 2395 D << FixItHint::CreateInsertion(Loc, "typename "); 2396 2397 // Recover by pretending this was an elaborated type. 2398 QualType Ty = Context.getTypeDeclType(TD); 2399 TypeLocBuilder TLB; 2400 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2401 2402 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2403 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2404 QTL.setElaboratedKeywordLoc(SourceLocation()); 2405 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2406 2407 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2408 2409 return ExprEmpty(); 2410 } 2411 2412 // Defend against this resolving to an implicit member access. We usually 2413 // won't get here if this might be a legitimate a class member (we end up in 2414 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2415 // a pointer-to-member or in an unevaluated context in C++11. 2416 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2417 return BuildPossibleImplicitMemberExpr(SS, 2418 /*TemplateKWLoc=*/SourceLocation(), 2419 R, /*TemplateArgs=*/nullptr, S); 2420 2421 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2422 } 2423 2424 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2425 /// detected that we're currently inside an ObjC method. Perform some 2426 /// additional lookup. 2427 /// 2428 /// Ideally, most of this would be done by lookup, but there's 2429 /// actually quite a lot of extra work involved. 2430 /// 2431 /// Returns a null sentinel to indicate trivial success. 2432 ExprResult 2433 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2434 IdentifierInfo *II, bool AllowBuiltinCreation) { 2435 SourceLocation Loc = Lookup.getNameLoc(); 2436 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2437 2438 // Check for error condition which is already reported. 2439 if (!CurMethod) 2440 return ExprError(); 2441 2442 // There are two cases to handle here. 1) scoped lookup could have failed, 2443 // in which case we should look for an ivar. 2) scoped lookup could have 2444 // found a decl, but that decl is outside the current instance method (i.e. 2445 // a global variable). In these two cases, we do a lookup for an ivar with 2446 // this name, if the lookup sucedes, we replace it our current decl. 2447 2448 // If we're in a class method, we don't normally want to look for 2449 // ivars. But if we don't find anything else, and there's an 2450 // ivar, that's an error. 2451 bool IsClassMethod = CurMethod->isClassMethod(); 2452 2453 bool LookForIvars; 2454 if (Lookup.empty()) 2455 LookForIvars = true; 2456 else if (IsClassMethod) 2457 LookForIvars = false; 2458 else 2459 LookForIvars = (Lookup.isSingleResult() && 2460 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2461 ObjCInterfaceDecl *IFace = nullptr; 2462 if (LookForIvars) { 2463 IFace = CurMethod->getClassInterface(); 2464 ObjCInterfaceDecl *ClassDeclared; 2465 ObjCIvarDecl *IV = nullptr; 2466 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2467 // Diagnose using an ivar in a class method. 2468 if (IsClassMethod) 2469 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2470 << IV->getDeclName()); 2471 2472 // If we're referencing an invalid decl, just return this as a silent 2473 // error node. The error diagnostic was already emitted on the decl. 2474 if (IV->isInvalidDecl()) 2475 return ExprError(); 2476 2477 // Check if referencing a field with __attribute__((deprecated)). 2478 if (DiagnoseUseOfDecl(IV, Loc)) 2479 return ExprError(); 2480 2481 // Diagnose the use of an ivar outside of the declaring class. 2482 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2483 !declaresSameEntity(ClassDeclared, IFace) && 2484 !getLangOpts().DebuggerSupport) 2485 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2486 2487 // FIXME: This should use a new expr for a direct reference, don't 2488 // turn this into Self->ivar, just return a BareIVarExpr or something. 2489 IdentifierInfo &II = Context.Idents.get("self"); 2490 UnqualifiedId SelfName; 2491 SelfName.setIdentifier(&II, SourceLocation()); 2492 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2493 CXXScopeSpec SelfScopeSpec; 2494 SourceLocation TemplateKWLoc; 2495 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2496 SelfName, false, false); 2497 if (SelfExpr.isInvalid()) 2498 return ExprError(); 2499 2500 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2501 if (SelfExpr.isInvalid()) 2502 return ExprError(); 2503 2504 MarkAnyDeclReferenced(Loc, IV, true); 2505 2506 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2507 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2508 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2509 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2510 2511 ObjCIvarRefExpr *Result = new (Context) 2512 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2513 IV->getLocation(), SelfExpr.get(), true, true); 2514 2515 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2516 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2517 recordUseOfEvaluatedWeak(Result); 2518 } 2519 if (getLangOpts().ObjCAutoRefCount) { 2520 if (CurContext->isClosure()) 2521 Diag(Loc, diag::warn_implicitly_retains_self) 2522 << FixItHint::CreateInsertion(Loc, "self->"); 2523 } 2524 2525 return Result; 2526 } 2527 } else if (CurMethod->isInstanceMethod()) { 2528 // We should warn if a local variable hides an ivar. 2529 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2530 ObjCInterfaceDecl *ClassDeclared; 2531 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2532 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2533 declaresSameEntity(IFace, ClassDeclared)) 2534 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2535 } 2536 } 2537 } else if (Lookup.isSingleResult() && 2538 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2539 // If accessing a stand-alone ivar in a class method, this is an error. 2540 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2541 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2542 << IV->getDeclName()); 2543 } 2544 2545 if (Lookup.empty() && II && AllowBuiltinCreation) { 2546 // FIXME. Consolidate this with similar code in LookupName. 2547 if (unsigned BuiltinID = II->getBuiltinID()) { 2548 if (!(getLangOpts().CPlusPlus && 2549 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2550 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2551 S, Lookup.isForRedeclaration(), 2552 Lookup.getNameLoc()); 2553 if (D) Lookup.addDecl(D); 2554 } 2555 } 2556 } 2557 // Sentinel value saying that we didn't do anything special. 2558 return ExprResult((Expr *)nullptr); 2559 } 2560 2561 /// \brief Cast a base object to a member's actual type. 2562 /// 2563 /// Logically this happens in three phases: 2564 /// 2565 /// * First we cast from the base type to the naming class. 2566 /// The naming class is the class into which we were looking 2567 /// when we found the member; it's the qualifier type if a 2568 /// qualifier was provided, and otherwise it's the base type. 2569 /// 2570 /// * Next we cast from the naming class to the declaring class. 2571 /// If the member we found was brought into a class's scope by 2572 /// a using declaration, this is that class; otherwise it's 2573 /// the class declaring the member. 2574 /// 2575 /// * Finally we cast from the declaring class to the "true" 2576 /// declaring class of the member. This conversion does not 2577 /// obey access control. 2578 ExprResult 2579 Sema::PerformObjectMemberConversion(Expr *From, 2580 NestedNameSpecifier *Qualifier, 2581 NamedDecl *FoundDecl, 2582 NamedDecl *Member) { 2583 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2584 if (!RD) 2585 return From; 2586 2587 QualType DestRecordType; 2588 QualType DestType; 2589 QualType FromRecordType; 2590 QualType FromType = From->getType(); 2591 bool PointerConversions = false; 2592 if (isa<FieldDecl>(Member)) { 2593 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2594 2595 if (FromType->getAs<PointerType>()) { 2596 DestType = Context.getPointerType(DestRecordType); 2597 FromRecordType = FromType->getPointeeType(); 2598 PointerConversions = true; 2599 } else { 2600 DestType = DestRecordType; 2601 FromRecordType = FromType; 2602 } 2603 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2604 if (Method->isStatic()) 2605 return From; 2606 2607 DestType = Method->getThisType(Context); 2608 DestRecordType = DestType->getPointeeType(); 2609 2610 if (FromType->getAs<PointerType>()) { 2611 FromRecordType = FromType->getPointeeType(); 2612 PointerConversions = true; 2613 } else { 2614 FromRecordType = FromType; 2615 DestType = DestRecordType; 2616 } 2617 } else { 2618 // No conversion necessary. 2619 return From; 2620 } 2621 2622 if (DestType->isDependentType() || FromType->isDependentType()) 2623 return From; 2624 2625 // If the unqualified types are the same, no conversion is necessary. 2626 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2627 return From; 2628 2629 SourceRange FromRange = From->getSourceRange(); 2630 SourceLocation FromLoc = FromRange.getBegin(); 2631 2632 ExprValueKind VK = From->getValueKind(); 2633 2634 // C++ [class.member.lookup]p8: 2635 // [...] Ambiguities can often be resolved by qualifying a name with its 2636 // class name. 2637 // 2638 // If the member was a qualified name and the qualified referred to a 2639 // specific base subobject type, we'll cast to that intermediate type 2640 // first and then to the object in which the member is declared. That allows 2641 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2642 // 2643 // class Base { public: int x; }; 2644 // class Derived1 : public Base { }; 2645 // class Derived2 : public Base { }; 2646 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2647 // 2648 // void VeryDerived::f() { 2649 // x = 17; // error: ambiguous base subobjects 2650 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2651 // } 2652 if (Qualifier && Qualifier->getAsType()) { 2653 QualType QType = QualType(Qualifier->getAsType(), 0); 2654 assert(QType->isRecordType() && "lookup done with non-record type"); 2655 2656 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2657 2658 // In C++98, the qualifier type doesn't actually have to be a base 2659 // type of the object type, in which case we just ignore it. 2660 // Otherwise build the appropriate casts. 2661 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2662 CXXCastPath BasePath; 2663 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2664 FromLoc, FromRange, &BasePath)) 2665 return ExprError(); 2666 2667 if (PointerConversions) 2668 QType = Context.getPointerType(QType); 2669 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2670 VK, &BasePath).get(); 2671 2672 FromType = QType; 2673 FromRecordType = QRecordType; 2674 2675 // If the qualifier type was the same as the destination type, 2676 // we're done. 2677 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2678 return From; 2679 } 2680 } 2681 2682 bool IgnoreAccess = false; 2683 2684 // If we actually found the member through a using declaration, cast 2685 // down to the using declaration's type. 2686 // 2687 // Pointer equality is fine here because only one declaration of a 2688 // class ever has member declarations. 2689 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2690 assert(isa<UsingShadowDecl>(FoundDecl)); 2691 QualType URecordType = Context.getTypeDeclType( 2692 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2693 2694 // We only need to do this if the naming-class to declaring-class 2695 // conversion is non-trivial. 2696 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2697 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2698 CXXCastPath BasePath; 2699 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2700 FromLoc, FromRange, &BasePath)) 2701 return ExprError(); 2702 2703 QualType UType = URecordType; 2704 if (PointerConversions) 2705 UType = Context.getPointerType(UType); 2706 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2707 VK, &BasePath).get(); 2708 FromType = UType; 2709 FromRecordType = URecordType; 2710 } 2711 2712 // We don't do access control for the conversion from the 2713 // declaring class to the true declaring class. 2714 IgnoreAccess = true; 2715 } 2716 2717 CXXCastPath BasePath; 2718 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2719 FromLoc, FromRange, &BasePath, 2720 IgnoreAccess)) 2721 return ExprError(); 2722 2723 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2724 VK, &BasePath); 2725 } 2726 2727 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2728 const LookupResult &R, 2729 bool HasTrailingLParen) { 2730 // Only when used directly as the postfix-expression of a call. 2731 if (!HasTrailingLParen) 2732 return false; 2733 2734 // Never if a scope specifier was provided. 2735 if (SS.isSet()) 2736 return false; 2737 2738 // Only in C++ or ObjC++. 2739 if (!getLangOpts().CPlusPlus) 2740 return false; 2741 2742 // Turn off ADL when we find certain kinds of declarations during 2743 // normal lookup: 2744 for (NamedDecl *D : R) { 2745 // C++0x [basic.lookup.argdep]p3: 2746 // -- a declaration of a class member 2747 // Since using decls preserve this property, we check this on the 2748 // original decl. 2749 if (D->isCXXClassMember()) 2750 return false; 2751 2752 // C++0x [basic.lookup.argdep]p3: 2753 // -- a block-scope function declaration that is not a 2754 // using-declaration 2755 // NOTE: we also trigger this for function templates (in fact, we 2756 // don't check the decl type at all, since all other decl types 2757 // turn off ADL anyway). 2758 if (isa<UsingShadowDecl>(D)) 2759 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2760 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2761 return false; 2762 2763 // C++0x [basic.lookup.argdep]p3: 2764 // -- a declaration that is neither a function or a function 2765 // template 2766 // And also for builtin functions. 2767 if (isa<FunctionDecl>(D)) { 2768 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2769 2770 // But also builtin functions. 2771 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2772 return false; 2773 } else if (!isa<FunctionTemplateDecl>(D)) 2774 return false; 2775 } 2776 2777 return true; 2778 } 2779 2780 2781 /// Diagnoses obvious problems with the use of the given declaration 2782 /// as an expression. This is only actually called for lookups that 2783 /// were not overloaded, and it doesn't promise that the declaration 2784 /// will in fact be used. 2785 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2786 if (D->isInvalidDecl()) 2787 return true; 2788 2789 if (isa<TypedefNameDecl>(D)) { 2790 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2791 return true; 2792 } 2793 2794 if (isa<ObjCInterfaceDecl>(D)) { 2795 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2796 return true; 2797 } 2798 2799 if (isa<NamespaceDecl>(D)) { 2800 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2801 return true; 2802 } 2803 2804 return false; 2805 } 2806 2807 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2808 LookupResult &R, bool NeedsADL, 2809 bool AcceptInvalidDecl) { 2810 // If this is a single, fully-resolved result and we don't need ADL, 2811 // just build an ordinary singleton decl ref. 2812 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2813 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2814 R.getRepresentativeDecl(), nullptr, 2815 AcceptInvalidDecl); 2816 2817 // We only need to check the declaration if there's exactly one 2818 // result, because in the overloaded case the results can only be 2819 // functions and function templates. 2820 if (R.isSingleResult() && 2821 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2822 return ExprError(); 2823 2824 // Otherwise, just build an unresolved lookup expression. Suppress 2825 // any lookup-related diagnostics; we'll hash these out later, when 2826 // we've picked a target. 2827 R.suppressDiagnostics(); 2828 2829 UnresolvedLookupExpr *ULE 2830 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2831 SS.getWithLocInContext(Context), 2832 R.getLookupNameInfo(), 2833 NeedsADL, R.isOverloadedResult(), 2834 R.begin(), R.end()); 2835 2836 return ULE; 2837 } 2838 2839 static void 2840 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2841 ValueDecl *var, DeclContext *DC); 2842 2843 /// \brief Complete semantic analysis for a reference to the given declaration. 2844 ExprResult Sema::BuildDeclarationNameExpr( 2845 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2846 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2847 bool AcceptInvalidDecl) { 2848 assert(D && "Cannot refer to a NULL declaration"); 2849 assert(!isa<FunctionTemplateDecl>(D) && 2850 "Cannot refer unambiguously to a function template"); 2851 2852 SourceLocation Loc = NameInfo.getLoc(); 2853 if (CheckDeclInExpr(*this, Loc, D)) 2854 return ExprError(); 2855 2856 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2857 // Specifically diagnose references to class templates that are missing 2858 // a template argument list. 2859 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2860 << Template << SS.getRange(); 2861 Diag(Template->getLocation(), diag::note_template_decl_here); 2862 return ExprError(); 2863 } 2864 2865 // Make sure that we're referring to a value. 2866 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2867 if (!VD) { 2868 Diag(Loc, diag::err_ref_non_value) 2869 << D << SS.getRange(); 2870 Diag(D->getLocation(), diag::note_declared_at); 2871 return ExprError(); 2872 } 2873 2874 // Check whether this declaration can be used. Note that we suppress 2875 // this check when we're going to perform argument-dependent lookup 2876 // on this function name, because this might not be the function 2877 // that overload resolution actually selects. 2878 if (DiagnoseUseOfDecl(VD, Loc)) 2879 return ExprError(); 2880 2881 // Only create DeclRefExpr's for valid Decl's. 2882 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2883 return ExprError(); 2884 2885 // Handle members of anonymous structs and unions. If we got here, 2886 // and the reference is to a class member indirect field, then this 2887 // must be the subject of a pointer-to-member expression. 2888 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2889 if (!indirectField->isCXXClassMember()) 2890 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2891 indirectField); 2892 2893 { 2894 QualType type = VD->getType(); 2895 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2896 // C++ [except.spec]p17: 2897 // An exception-specification is considered to be needed when: 2898 // - in an expression, the function is the unique lookup result or 2899 // the selected member of a set of overloaded functions. 2900 ResolveExceptionSpec(Loc, FPT); 2901 type = VD->getType(); 2902 } 2903 ExprValueKind valueKind = VK_RValue; 2904 2905 switch (D->getKind()) { 2906 // Ignore all the non-ValueDecl kinds. 2907 #define ABSTRACT_DECL(kind) 2908 #define VALUE(type, base) 2909 #define DECL(type, base) \ 2910 case Decl::type: 2911 #include "clang/AST/DeclNodes.inc" 2912 llvm_unreachable("invalid value decl kind"); 2913 2914 // These shouldn't make it here. 2915 case Decl::ObjCAtDefsField: 2916 case Decl::ObjCIvar: 2917 llvm_unreachable("forming non-member reference to ivar?"); 2918 2919 // Enum constants are always r-values and never references. 2920 // Unresolved using declarations are dependent. 2921 case Decl::EnumConstant: 2922 case Decl::UnresolvedUsingValue: 2923 case Decl::OMPDeclareReduction: 2924 valueKind = VK_RValue; 2925 break; 2926 2927 // Fields and indirect fields that got here must be for 2928 // pointer-to-member expressions; we just call them l-values for 2929 // internal consistency, because this subexpression doesn't really 2930 // exist in the high-level semantics. 2931 case Decl::Field: 2932 case Decl::IndirectField: 2933 assert(getLangOpts().CPlusPlus && 2934 "building reference to field in C?"); 2935 2936 // These can't have reference type in well-formed programs, but 2937 // for internal consistency we do this anyway. 2938 type = type.getNonReferenceType(); 2939 valueKind = VK_LValue; 2940 break; 2941 2942 // Non-type template parameters are either l-values or r-values 2943 // depending on the type. 2944 case Decl::NonTypeTemplateParm: { 2945 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2946 type = reftype->getPointeeType(); 2947 valueKind = VK_LValue; // even if the parameter is an r-value reference 2948 break; 2949 } 2950 2951 // For non-references, we need to strip qualifiers just in case 2952 // the template parameter was declared as 'const int' or whatever. 2953 valueKind = VK_RValue; 2954 type = type.getUnqualifiedType(); 2955 break; 2956 } 2957 2958 case Decl::Var: 2959 case Decl::VarTemplateSpecialization: 2960 case Decl::VarTemplatePartialSpecialization: 2961 case Decl::Decomposition: 2962 case Decl::OMPCapturedExpr: 2963 // In C, "extern void blah;" is valid and is an r-value. 2964 if (!getLangOpts().CPlusPlus && 2965 !type.hasQualifiers() && 2966 type->isVoidType()) { 2967 valueKind = VK_RValue; 2968 break; 2969 } 2970 // fallthrough 2971 2972 case Decl::ImplicitParam: 2973 case Decl::ParmVar: { 2974 // These are always l-values. 2975 valueKind = VK_LValue; 2976 type = type.getNonReferenceType(); 2977 2978 // FIXME: Does the addition of const really only apply in 2979 // potentially-evaluated contexts? Since the variable isn't actually 2980 // captured in an unevaluated context, it seems that the answer is no. 2981 if (!isUnevaluatedContext()) { 2982 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2983 if (!CapturedType.isNull()) 2984 type = CapturedType; 2985 } 2986 2987 break; 2988 } 2989 2990 case Decl::Binding: { 2991 // These are always lvalues. 2992 valueKind = VK_LValue; 2993 type = type.getNonReferenceType(); 2994 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2995 // decides how that's supposed to work. 2996 auto *BD = cast<BindingDecl>(VD); 2997 if (BD->getDeclContext()->isFunctionOrMethod() && 2998 BD->getDeclContext() != CurContext) 2999 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3000 break; 3001 } 3002 3003 case Decl::Function: { 3004 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3005 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3006 type = Context.BuiltinFnTy; 3007 valueKind = VK_RValue; 3008 break; 3009 } 3010 } 3011 3012 const FunctionType *fty = type->castAs<FunctionType>(); 3013 3014 // If we're referring to a function with an __unknown_anytype 3015 // result type, make the entire expression __unknown_anytype. 3016 if (fty->getReturnType() == Context.UnknownAnyTy) { 3017 type = Context.UnknownAnyTy; 3018 valueKind = VK_RValue; 3019 break; 3020 } 3021 3022 // Functions are l-values in C++. 3023 if (getLangOpts().CPlusPlus) { 3024 valueKind = VK_LValue; 3025 break; 3026 } 3027 3028 // C99 DR 316 says that, if a function type comes from a 3029 // function definition (without a prototype), that type is only 3030 // used for checking compatibility. Therefore, when referencing 3031 // the function, we pretend that we don't have the full function 3032 // type. 3033 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3034 isa<FunctionProtoType>(fty)) 3035 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3036 fty->getExtInfo()); 3037 3038 // Functions are r-values in C. 3039 valueKind = VK_RValue; 3040 break; 3041 } 3042 3043 case Decl::CXXDeductionGuide: 3044 llvm_unreachable("building reference to deduction guide"); 3045 3046 case Decl::MSProperty: 3047 valueKind = VK_LValue; 3048 break; 3049 3050 case Decl::CXXMethod: 3051 // If we're referring to a method with an __unknown_anytype 3052 // result type, make the entire expression __unknown_anytype. 3053 // This should only be possible with a type written directly. 3054 if (const FunctionProtoType *proto 3055 = dyn_cast<FunctionProtoType>(VD->getType())) 3056 if (proto->getReturnType() == Context.UnknownAnyTy) { 3057 type = Context.UnknownAnyTy; 3058 valueKind = VK_RValue; 3059 break; 3060 } 3061 3062 // C++ methods are l-values if static, r-values if non-static. 3063 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3064 valueKind = VK_LValue; 3065 break; 3066 } 3067 // fallthrough 3068 3069 case Decl::CXXConversion: 3070 case Decl::CXXDestructor: 3071 case Decl::CXXConstructor: 3072 valueKind = VK_RValue; 3073 break; 3074 } 3075 3076 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3077 TemplateArgs); 3078 } 3079 } 3080 3081 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3082 SmallString<32> &Target) { 3083 Target.resize(CharByteWidth * (Source.size() + 1)); 3084 char *ResultPtr = &Target[0]; 3085 const llvm::UTF8 *ErrorPtr; 3086 bool success = 3087 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3088 (void)success; 3089 assert(success); 3090 Target.resize(ResultPtr - &Target[0]); 3091 } 3092 3093 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3094 PredefinedExpr::IdentType IT) { 3095 // Pick the current block, lambda, captured statement or function. 3096 Decl *currentDecl = nullptr; 3097 if (const BlockScopeInfo *BSI = getCurBlock()) 3098 currentDecl = BSI->TheDecl; 3099 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3100 currentDecl = LSI->CallOperator; 3101 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3102 currentDecl = CSI->TheCapturedDecl; 3103 else 3104 currentDecl = getCurFunctionOrMethodDecl(); 3105 3106 if (!currentDecl) { 3107 Diag(Loc, diag::ext_predef_outside_function); 3108 currentDecl = Context.getTranslationUnitDecl(); 3109 } 3110 3111 QualType ResTy; 3112 StringLiteral *SL = nullptr; 3113 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3114 ResTy = Context.DependentTy; 3115 else { 3116 // Pre-defined identifiers are of type char[x], where x is the length of 3117 // the string. 3118 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3119 unsigned Length = Str.length(); 3120 3121 llvm::APInt LengthI(32, Length + 1); 3122 if (IT == PredefinedExpr::LFunction) { 3123 ResTy = Context.WideCharTy.withConst(); 3124 SmallString<32> RawChars; 3125 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3126 Str, RawChars); 3127 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3128 /*IndexTypeQuals*/ 0); 3129 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3130 /*Pascal*/ false, ResTy, Loc); 3131 } else { 3132 ResTy = Context.CharTy.withConst(); 3133 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3134 /*IndexTypeQuals*/ 0); 3135 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3136 /*Pascal*/ false, ResTy, Loc); 3137 } 3138 } 3139 3140 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3141 } 3142 3143 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3144 PredefinedExpr::IdentType IT; 3145 3146 switch (Kind) { 3147 default: llvm_unreachable("Unknown simple primary expr!"); 3148 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3149 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3150 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3151 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3152 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3153 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3154 } 3155 3156 return BuildPredefinedExpr(Loc, IT); 3157 } 3158 3159 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3160 SmallString<16> CharBuffer; 3161 bool Invalid = false; 3162 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3163 if (Invalid) 3164 return ExprError(); 3165 3166 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3167 PP, Tok.getKind()); 3168 if (Literal.hadError()) 3169 return ExprError(); 3170 3171 QualType Ty; 3172 if (Literal.isWide()) 3173 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3174 else if (Literal.isUTF16()) 3175 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3176 else if (Literal.isUTF32()) 3177 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3178 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3179 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3180 else 3181 Ty = Context.CharTy; // 'x' -> char in C++ 3182 3183 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3184 if (Literal.isWide()) 3185 Kind = CharacterLiteral::Wide; 3186 else if (Literal.isUTF16()) 3187 Kind = CharacterLiteral::UTF16; 3188 else if (Literal.isUTF32()) 3189 Kind = CharacterLiteral::UTF32; 3190 else if (Literal.isUTF8()) 3191 Kind = CharacterLiteral::UTF8; 3192 3193 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3194 Tok.getLocation()); 3195 3196 if (Literal.getUDSuffix().empty()) 3197 return Lit; 3198 3199 // We're building a user-defined literal. 3200 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3201 SourceLocation UDSuffixLoc = 3202 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3203 3204 // Make sure we're allowed user-defined literals here. 3205 if (!UDLScope) 3206 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3207 3208 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3209 // operator "" X (ch) 3210 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3211 Lit, Tok.getLocation()); 3212 } 3213 3214 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3215 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3216 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3217 Context.IntTy, Loc); 3218 } 3219 3220 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3221 QualType Ty, SourceLocation Loc) { 3222 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3223 3224 using llvm::APFloat; 3225 APFloat Val(Format); 3226 3227 APFloat::opStatus result = Literal.GetFloatValue(Val); 3228 3229 // Overflow is always an error, but underflow is only an error if 3230 // we underflowed to zero (APFloat reports denormals as underflow). 3231 if ((result & APFloat::opOverflow) || 3232 ((result & APFloat::opUnderflow) && Val.isZero())) { 3233 unsigned diagnostic; 3234 SmallString<20> buffer; 3235 if (result & APFloat::opOverflow) { 3236 diagnostic = diag::warn_float_overflow; 3237 APFloat::getLargest(Format).toString(buffer); 3238 } else { 3239 diagnostic = diag::warn_float_underflow; 3240 APFloat::getSmallest(Format).toString(buffer); 3241 } 3242 3243 S.Diag(Loc, diagnostic) 3244 << Ty 3245 << StringRef(buffer.data(), buffer.size()); 3246 } 3247 3248 bool isExact = (result == APFloat::opOK); 3249 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3250 } 3251 3252 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3253 assert(E && "Invalid expression"); 3254 3255 if (E->isValueDependent()) 3256 return false; 3257 3258 QualType QT = E->getType(); 3259 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3260 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3261 return true; 3262 } 3263 3264 llvm::APSInt ValueAPS; 3265 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3266 3267 if (R.isInvalid()) 3268 return true; 3269 3270 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3271 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3272 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3273 << ValueAPS.toString(10) << ValueIsPositive; 3274 return true; 3275 } 3276 3277 return false; 3278 } 3279 3280 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3281 // Fast path for a single digit (which is quite common). A single digit 3282 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3283 if (Tok.getLength() == 1) { 3284 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3285 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3286 } 3287 3288 SmallString<128> SpellingBuffer; 3289 // NumericLiteralParser wants to overread by one character. Add padding to 3290 // the buffer in case the token is copied to the buffer. If getSpelling() 3291 // returns a StringRef to the memory buffer, it should have a null char at 3292 // the EOF, so it is also safe. 3293 SpellingBuffer.resize(Tok.getLength() + 1); 3294 3295 // Get the spelling of the token, which eliminates trigraphs, etc. 3296 bool Invalid = false; 3297 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3298 if (Invalid) 3299 return ExprError(); 3300 3301 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3302 if (Literal.hadError) 3303 return ExprError(); 3304 3305 if (Literal.hasUDSuffix()) { 3306 // We're building a user-defined literal. 3307 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3308 SourceLocation UDSuffixLoc = 3309 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3310 3311 // Make sure we're allowed user-defined literals here. 3312 if (!UDLScope) 3313 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3314 3315 QualType CookedTy; 3316 if (Literal.isFloatingLiteral()) { 3317 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3318 // long double, the literal is treated as a call of the form 3319 // operator "" X (f L) 3320 CookedTy = Context.LongDoubleTy; 3321 } else { 3322 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3323 // unsigned long long, the literal is treated as a call of the form 3324 // operator "" X (n ULL) 3325 CookedTy = Context.UnsignedLongLongTy; 3326 } 3327 3328 DeclarationName OpName = 3329 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3330 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3331 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3332 3333 SourceLocation TokLoc = Tok.getLocation(); 3334 3335 // Perform literal operator lookup to determine if we're building a raw 3336 // literal or a cooked one. 3337 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3338 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3339 /*AllowRaw*/true, /*AllowTemplate*/true, 3340 /*AllowStringTemplate*/false)) { 3341 case LOLR_Error: 3342 return ExprError(); 3343 3344 case LOLR_Cooked: { 3345 Expr *Lit; 3346 if (Literal.isFloatingLiteral()) { 3347 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3348 } else { 3349 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3350 if (Literal.GetIntegerValue(ResultVal)) 3351 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3352 << /* Unsigned */ 1; 3353 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3354 Tok.getLocation()); 3355 } 3356 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3357 } 3358 3359 case LOLR_Raw: { 3360 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3361 // literal is treated as a call of the form 3362 // operator "" X ("n") 3363 unsigned Length = Literal.getUDSuffixOffset(); 3364 QualType StrTy = Context.getConstantArrayType( 3365 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3366 ArrayType::Normal, 0); 3367 Expr *Lit = StringLiteral::Create( 3368 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3369 /*Pascal*/false, StrTy, &TokLoc, 1); 3370 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3371 } 3372 3373 case LOLR_Template: { 3374 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3375 // template), L is treated as a call fo the form 3376 // operator "" X <'c1', 'c2', ... 'ck'>() 3377 // where n is the source character sequence c1 c2 ... ck. 3378 TemplateArgumentListInfo ExplicitArgs; 3379 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3380 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3381 llvm::APSInt Value(CharBits, CharIsUnsigned); 3382 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3383 Value = TokSpelling[I]; 3384 TemplateArgument Arg(Context, Value, Context.CharTy); 3385 TemplateArgumentLocInfo ArgInfo; 3386 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3387 } 3388 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3389 &ExplicitArgs); 3390 } 3391 case LOLR_StringTemplate: 3392 llvm_unreachable("unexpected literal operator lookup result"); 3393 } 3394 } 3395 3396 Expr *Res; 3397 3398 if (Literal.isFloatingLiteral()) { 3399 QualType Ty; 3400 if (Literal.isHalf){ 3401 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3402 Ty = Context.HalfTy; 3403 else { 3404 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3405 return ExprError(); 3406 } 3407 } else if (Literal.isFloat) 3408 Ty = Context.FloatTy; 3409 else if (Literal.isLong) 3410 Ty = Context.LongDoubleTy; 3411 else if (Literal.isFloat128) 3412 Ty = Context.Float128Ty; 3413 else 3414 Ty = Context.DoubleTy; 3415 3416 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3417 3418 if (Ty == Context.DoubleTy) { 3419 if (getLangOpts().SinglePrecisionConstants) { 3420 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3421 if (BTy->getKind() != BuiltinType::Float) { 3422 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3423 } 3424 } else if (getLangOpts().OpenCL && 3425 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3426 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3427 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3428 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3429 } 3430 } 3431 } else if (!Literal.isIntegerLiteral()) { 3432 return ExprError(); 3433 } else { 3434 QualType Ty; 3435 3436 // 'long long' is a C99 or C++11 feature. 3437 if (!getLangOpts().C99 && Literal.isLongLong) { 3438 if (getLangOpts().CPlusPlus) 3439 Diag(Tok.getLocation(), 3440 getLangOpts().CPlusPlus11 ? 3441 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3442 else 3443 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3444 } 3445 3446 // Get the value in the widest-possible width. 3447 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3448 llvm::APInt ResultVal(MaxWidth, 0); 3449 3450 if (Literal.GetIntegerValue(ResultVal)) { 3451 // If this value didn't fit into uintmax_t, error and force to ull. 3452 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3453 << /* Unsigned */ 1; 3454 Ty = Context.UnsignedLongLongTy; 3455 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3456 "long long is not intmax_t?"); 3457 } else { 3458 // If this value fits into a ULL, try to figure out what else it fits into 3459 // according to the rules of C99 6.4.4.1p5. 3460 3461 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3462 // be an unsigned int. 3463 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3464 3465 // Check from smallest to largest, picking the smallest type we can. 3466 unsigned Width = 0; 3467 3468 // Microsoft specific integer suffixes are explicitly sized. 3469 if (Literal.MicrosoftInteger) { 3470 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3471 Width = 8; 3472 Ty = Context.CharTy; 3473 } else { 3474 Width = Literal.MicrosoftInteger; 3475 Ty = Context.getIntTypeForBitwidth(Width, 3476 /*Signed=*/!Literal.isUnsigned); 3477 } 3478 } 3479 3480 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3481 // Are int/unsigned possibilities? 3482 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3483 3484 // Does it fit in a unsigned int? 3485 if (ResultVal.isIntN(IntSize)) { 3486 // Does it fit in a signed int? 3487 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3488 Ty = Context.IntTy; 3489 else if (AllowUnsigned) 3490 Ty = Context.UnsignedIntTy; 3491 Width = IntSize; 3492 } 3493 } 3494 3495 // Are long/unsigned long possibilities? 3496 if (Ty.isNull() && !Literal.isLongLong) { 3497 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3498 3499 // Does it fit in a unsigned long? 3500 if (ResultVal.isIntN(LongSize)) { 3501 // Does it fit in a signed long? 3502 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3503 Ty = Context.LongTy; 3504 else if (AllowUnsigned) 3505 Ty = Context.UnsignedLongTy; 3506 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3507 // is compatible. 3508 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3509 const unsigned LongLongSize = 3510 Context.getTargetInfo().getLongLongWidth(); 3511 Diag(Tok.getLocation(), 3512 getLangOpts().CPlusPlus 3513 ? Literal.isLong 3514 ? diag::warn_old_implicitly_unsigned_long_cxx 3515 : /*C++98 UB*/ diag:: 3516 ext_old_implicitly_unsigned_long_cxx 3517 : diag::warn_old_implicitly_unsigned_long) 3518 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3519 : /*will be ill-formed*/ 1); 3520 Ty = Context.UnsignedLongTy; 3521 } 3522 Width = LongSize; 3523 } 3524 } 3525 3526 // Check long long if needed. 3527 if (Ty.isNull()) { 3528 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3529 3530 // Does it fit in a unsigned long long? 3531 if (ResultVal.isIntN(LongLongSize)) { 3532 // Does it fit in a signed long long? 3533 // To be compatible with MSVC, hex integer literals ending with the 3534 // LL or i64 suffix are always signed in Microsoft mode. 3535 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3536 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3537 Ty = Context.LongLongTy; 3538 else if (AllowUnsigned) 3539 Ty = Context.UnsignedLongLongTy; 3540 Width = LongLongSize; 3541 } 3542 } 3543 3544 // If we still couldn't decide a type, we probably have something that 3545 // does not fit in a signed long long, but has no U suffix. 3546 if (Ty.isNull()) { 3547 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3548 Ty = Context.UnsignedLongLongTy; 3549 Width = Context.getTargetInfo().getLongLongWidth(); 3550 } 3551 3552 if (ResultVal.getBitWidth() != Width) 3553 ResultVal = ResultVal.trunc(Width); 3554 } 3555 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3556 } 3557 3558 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3559 if (Literal.isImaginary) 3560 Res = new (Context) ImaginaryLiteral(Res, 3561 Context.getComplexType(Res->getType())); 3562 3563 return Res; 3564 } 3565 3566 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3567 assert(E && "ActOnParenExpr() missing expr"); 3568 return new (Context) ParenExpr(L, R, E); 3569 } 3570 3571 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3572 SourceLocation Loc, 3573 SourceRange ArgRange) { 3574 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3575 // scalar or vector data type argument..." 3576 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3577 // type (C99 6.2.5p18) or void. 3578 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3579 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3580 << T << ArgRange; 3581 return true; 3582 } 3583 3584 assert((T->isVoidType() || !T->isIncompleteType()) && 3585 "Scalar types should always be complete"); 3586 return false; 3587 } 3588 3589 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3590 SourceLocation Loc, 3591 SourceRange ArgRange, 3592 UnaryExprOrTypeTrait TraitKind) { 3593 // Invalid types must be hard errors for SFINAE in C++. 3594 if (S.LangOpts.CPlusPlus) 3595 return true; 3596 3597 // C99 6.5.3.4p1: 3598 if (T->isFunctionType() && 3599 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3600 // sizeof(function)/alignof(function) is allowed as an extension. 3601 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3602 << TraitKind << ArgRange; 3603 return false; 3604 } 3605 3606 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3607 // this is an error (OpenCL v1.1 s6.3.k) 3608 if (T->isVoidType()) { 3609 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3610 : diag::ext_sizeof_alignof_void_type; 3611 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3612 return false; 3613 } 3614 3615 return true; 3616 } 3617 3618 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3619 SourceLocation Loc, 3620 SourceRange ArgRange, 3621 UnaryExprOrTypeTrait TraitKind) { 3622 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3623 // runtime doesn't allow it. 3624 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3625 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3626 << T << (TraitKind == UETT_SizeOf) 3627 << ArgRange; 3628 return true; 3629 } 3630 3631 return false; 3632 } 3633 3634 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3635 /// pointer type is equal to T) and emit a warning if it is. 3636 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3637 Expr *E) { 3638 // Don't warn if the operation changed the type. 3639 if (T != E->getType()) 3640 return; 3641 3642 // Now look for array decays. 3643 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3644 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3645 return; 3646 3647 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3648 << ICE->getType() 3649 << ICE->getSubExpr()->getType(); 3650 } 3651 3652 /// \brief Check the constraints on expression operands to unary type expression 3653 /// and type traits. 3654 /// 3655 /// Completes any types necessary and validates the constraints on the operand 3656 /// expression. The logic mostly mirrors the type-based overload, but may modify 3657 /// the expression as it completes the type for that expression through template 3658 /// instantiation, etc. 3659 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3660 UnaryExprOrTypeTrait ExprKind) { 3661 QualType ExprTy = E->getType(); 3662 assert(!ExprTy->isReferenceType()); 3663 3664 if (ExprKind == UETT_VecStep) 3665 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3666 E->getSourceRange()); 3667 3668 // Whitelist some types as extensions 3669 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3670 E->getSourceRange(), ExprKind)) 3671 return false; 3672 3673 // 'alignof' applied to an expression only requires the base element type of 3674 // the expression to be complete. 'sizeof' requires the expression's type to 3675 // be complete (and will attempt to complete it if it's an array of unknown 3676 // bound). 3677 if (ExprKind == UETT_AlignOf) { 3678 if (RequireCompleteType(E->getExprLoc(), 3679 Context.getBaseElementType(E->getType()), 3680 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3681 E->getSourceRange())) 3682 return true; 3683 } else { 3684 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3685 ExprKind, E->getSourceRange())) 3686 return true; 3687 } 3688 3689 // Completing the expression's type may have changed it. 3690 ExprTy = E->getType(); 3691 assert(!ExprTy->isReferenceType()); 3692 3693 if (ExprTy->isFunctionType()) { 3694 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3695 << ExprKind << E->getSourceRange(); 3696 return true; 3697 } 3698 3699 // The operand for sizeof and alignof is in an unevaluated expression context, 3700 // so side effects could result in unintended consequences. 3701 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3702 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3703 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3704 3705 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3706 E->getSourceRange(), ExprKind)) 3707 return true; 3708 3709 if (ExprKind == UETT_SizeOf) { 3710 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3711 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3712 QualType OType = PVD->getOriginalType(); 3713 QualType Type = PVD->getType(); 3714 if (Type->isPointerType() && OType->isArrayType()) { 3715 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3716 << Type << OType; 3717 Diag(PVD->getLocation(), diag::note_declared_at); 3718 } 3719 } 3720 } 3721 3722 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3723 // decays into a pointer and returns an unintended result. This is most 3724 // likely a typo for "sizeof(array) op x". 3725 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3726 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3727 BO->getLHS()); 3728 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3729 BO->getRHS()); 3730 } 3731 } 3732 3733 return false; 3734 } 3735 3736 /// \brief Check the constraints on operands to unary expression and type 3737 /// traits. 3738 /// 3739 /// This will complete any types necessary, and validate the various constraints 3740 /// on those operands. 3741 /// 3742 /// The UsualUnaryConversions() function is *not* called by this routine. 3743 /// C99 6.3.2.1p[2-4] all state: 3744 /// Except when it is the operand of the sizeof operator ... 3745 /// 3746 /// C++ [expr.sizeof]p4 3747 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3748 /// standard conversions are not applied to the operand of sizeof. 3749 /// 3750 /// This policy is followed for all of the unary trait expressions. 3751 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3752 SourceLocation OpLoc, 3753 SourceRange ExprRange, 3754 UnaryExprOrTypeTrait ExprKind) { 3755 if (ExprType->isDependentType()) 3756 return false; 3757 3758 // C++ [expr.sizeof]p2: 3759 // When applied to a reference or a reference type, the result 3760 // is the size of the referenced type. 3761 // C++11 [expr.alignof]p3: 3762 // When alignof is applied to a reference type, the result 3763 // shall be the alignment of the referenced type. 3764 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3765 ExprType = Ref->getPointeeType(); 3766 3767 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3768 // When alignof or _Alignof is applied to an array type, the result 3769 // is the alignment of the element type. 3770 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3771 ExprType = Context.getBaseElementType(ExprType); 3772 3773 if (ExprKind == UETT_VecStep) 3774 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3775 3776 // Whitelist some types as extensions 3777 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3778 ExprKind)) 3779 return false; 3780 3781 if (RequireCompleteType(OpLoc, ExprType, 3782 diag::err_sizeof_alignof_incomplete_type, 3783 ExprKind, ExprRange)) 3784 return true; 3785 3786 if (ExprType->isFunctionType()) { 3787 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3788 << ExprKind << ExprRange; 3789 return true; 3790 } 3791 3792 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3793 ExprKind)) 3794 return true; 3795 3796 return false; 3797 } 3798 3799 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3800 E = E->IgnoreParens(); 3801 3802 // Cannot know anything else if the expression is dependent. 3803 if (E->isTypeDependent()) 3804 return false; 3805 3806 if (E->getObjectKind() == OK_BitField) { 3807 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3808 << 1 << E->getSourceRange(); 3809 return true; 3810 } 3811 3812 ValueDecl *D = nullptr; 3813 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3814 D = DRE->getDecl(); 3815 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3816 D = ME->getMemberDecl(); 3817 } 3818 3819 // If it's a field, require the containing struct to have a 3820 // complete definition so that we can compute the layout. 3821 // 3822 // This can happen in C++11 onwards, either by naming the member 3823 // in a way that is not transformed into a member access expression 3824 // (in an unevaluated operand, for instance), or by naming the member 3825 // in a trailing-return-type. 3826 // 3827 // For the record, since __alignof__ on expressions is a GCC 3828 // extension, GCC seems to permit this but always gives the 3829 // nonsensical answer 0. 3830 // 3831 // We don't really need the layout here --- we could instead just 3832 // directly check for all the appropriate alignment-lowing 3833 // attributes --- but that would require duplicating a lot of 3834 // logic that just isn't worth duplicating for such a marginal 3835 // use-case. 3836 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3837 // Fast path this check, since we at least know the record has a 3838 // definition if we can find a member of it. 3839 if (!FD->getParent()->isCompleteDefinition()) { 3840 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3841 << E->getSourceRange(); 3842 return true; 3843 } 3844 3845 // Otherwise, if it's a field, and the field doesn't have 3846 // reference type, then it must have a complete type (or be a 3847 // flexible array member, which we explicitly want to 3848 // white-list anyway), which makes the following checks trivial. 3849 if (!FD->getType()->isReferenceType()) 3850 return false; 3851 } 3852 3853 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3854 } 3855 3856 bool Sema::CheckVecStepExpr(Expr *E) { 3857 E = E->IgnoreParens(); 3858 3859 // Cannot know anything else if the expression is dependent. 3860 if (E->isTypeDependent()) 3861 return false; 3862 3863 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3864 } 3865 3866 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3867 CapturingScopeInfo *CSI) { 3868 assert(T->isVariablyModifiedType()); 3869 assert(CSI != nullptr); 3870 3871 // We're going to walk down into the type and look for VLA expressions. 3872 do { 3873 const Type *Ty = T.getTypePtr(); 3874 switch (Ty->getTypeClass()) { 3875 #define TYPE(Class, Base) 3876 #define ABSTRACT_TYPE(Class, Base) 3877 #define NON_CANONICAL_TYPE(Class, Base) 3878 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3879 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3880 #include "clang/AST/TypeNodes.def" 3881 T = QualType(); 3882 break; 3883 // These types are never variably-modified. 3884 case Type::Builtin: 3885 case Type::Complex: 3886 case Type::Vector: 3887 case Type::ExtVector: 3888 case Type::Record: 3889 case Type::Enum: 3890 case Type::Elaborated: 3891 case Type::TemplateSpecialization: 3892 case Type::ObjCObject: 3893 case Type::ObjCInterface: 3894 case Type::ObjCObjectPointer: 3895 case Type::ObjCTypeParam: 3896 case Type::Pipe: 3897 llvm_unreachable("type class is never variably-modified!"); 3898 case Type::Adjusted: 3899 T = cast<AdjustedType>(Ty)->getOriginalType(); 3900 break; 3901 case Type::Decayed: 3902 T = cast<DecayedType>(Ty)->getPointeeType(); 3903 break; 3904 case Type::Pointer: 3905 T = cast<PointerType>(Ty)->getPointeeType(); 3906 break; 3907 case Type::BlockPointer: 3908 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3909 break; 3910 case Type::LValueReference: 3911 case Type::RValueReference: 3912 T = cast<ReferenceType>(Ty)->getPointeeType(); 3913 break; 3914 case Type::MemberPointer: 3915 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3916 break; 3917 case Type::ConstantArray: 3918 case Type::IncompleteArray: 3919 // Losing element qualification here is fine. 3920 T = cast<ArrayType>(Ty)->getElementType(); 3921 break; 3922 case Type::VariableArray: { 3923 // Losing element qualification here is fine. 3924 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3925 3926 // Unknown size indication requires no size computation. 3927 // Otherwise, evaluate and record it. 3928 if (auto Size = VAT->getSizeExpr()) { 3929 if (!CSI->isVLATypeCaptured(VAT)) { 3930 RecordDecl *CapRecord = nullptr; 3931 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3932 CapRecord = LSI->Lambda; 3933 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3934 CapRecord = CRSI->TheRecordDecl; 3935 } 3936 if (CapRecord) { 3937 auto ExprLoc = Size->getExprLoc(); 3938 auto SizeType = Context.getSizeType(); 3939 // Build the non-static data member. 3940 auto Field = 3941 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3942 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3943 /*BW*/ nullptr, /*Mutable*/ false, 3944 /*InitStyle*/ ICIS_NoInit); 3945 Field->setImplicit(true); 3946 Field->setAccess(AS_private); 3947 Field->setCapturedVLAType(VAT); 3948 CapRecord->addDecl(Field); 3949 3950 CSI->addVLATypeCapture(ExprLoc, SizeType); 3951 } 3952 } 3953 } 3954 T = VAT->getElementType(); 3955 break; 3956 } 3957 case Type::FunctionProto: 3958 case Type::FunctionNoProto: 3959 T = cast<FunctionType>(Ty)->getReturnType(); 3960 break; 3961 case Type::Paren: 3962 case Type::TypeOf: 3963 case Type::UnaryTransform: 3964 case Type::Attributed: 3965 case Type::SubstTemplateTypeParm: 3966 case Type::PackExpansion: 3967 // Keep walking after single level desugaring. 3968 T = T.getSingleStepDesugaredType(Context); 3969 break; 3970 case Type::Typedef: 3971 T = cast<TypedefType>(Ty)->desugar(); 3972 break; 3973 case Type::Decltype: 3974 T = cast<DecltypeType>(Ty)->desugar(); 3975 break; 3976 case Type::Auto: 3977 case Type::DeducedTemplateSpecialization: 3978 T = cast<DeducedType>(Ty)->getDeducedType(); 3979 break; 3980 case Type::TypeOfExpr: 3981 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3982 break; 3983 case Type::Atomic: 3984 T = cast<AtomicType>(Ty)->getValueType(); 3985 break; 3986 } 3987 } while (!T.isNull() && T->isVariablyModifiedType()); 3988 } 3989 3990 /// \brief Build a sizeof or alignof expression given a type operand. 3991 ExprResult 3992 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3993 SourceLocation OpLoc, 3994 UnaryExprOrTypeTrait ExprKind, 3995 SourceRange R) { 3996 if (!TInfo) 3997 return ExprError(); 3998 3999 QualType T = TInfo->getType(); 4000 4001 if (!T->isDependentType() && 4002 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4003 return ExprError(); 4004 4005 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4006 if (auto *TT = T->getAs<TypedefType>()) { 4007 for (auto I = FunctionScopes.rbegin(), 4008 E = std::prev(FunctionScopes.rend()); 4009 I != E; ++I) { 4010 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4011 if (CSI == nullptr) 4012 break; 4013 DeclContext *DC = nullptr; 4014 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4015 DC = LSI->CallOperator; 4016 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4017 DC = CRSI->TheCapturedDecl; 4018 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4019 DC = BSI->TheDecl; 4020 if (DC) { 4021 if (DC->containsDecl(TT->getDecl())) 4022 break; 4023 captureVariablyModifiedType(Context, T, CSI); 4024 } 4025 } 4026 } 4027 } 4028 4029 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4030 return new (Context) UnaryExprOrTypeTraitExpr( 4031 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4032 } 4033 4034 /// \brief Build a sizeof or alignof expression given an expression 4035 /// operand. 4036 ExprResult 4037 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4038 UnaryExprOrTypeTrait ExprKind) { 4039 ExprResult PE = CheckPlaceholderExpr(E); 4040 if (PE.isInvalid()) 4041 return ExprError(); 4042 4043 E = PE.get(); 4044 4045 // Verify that the operand is valid. 4046 bool isInvalid = false; 4047 if (E->isTypeDependent()) { 4048 // Delay type-checking for type-dependent expressions. 4049 } else if (ExprKind == UETT_AlignOf) { 4050 isInvalid = CheckAlignOfExpr(*this, E); 4051 } else if (ExprKind == UETT_VecStep) { 4052 isInvalid = CheckVecStepExpr(E); 4053 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4054 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4055 isInvalid = true; 4056 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4057 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4058 isInvalid = true; 4059 } else { 4060 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4061 } 4062 4063 if (isInvalid) 4064 return ExprError(); 4065 4066 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4067 PE = TransformToPotentiallyEvaluated(E); 4068 if (PE.isInvalid()) return ExprError(); 4069 E = PE.get(); 4070 } 4071 4072 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4073 return new (Context) UnaryExprOrTypeTraitExpr( 4074 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4075 } 4076 4077 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4078 /// expr and the same for @c alignof and @c __alignof 4079 /// Note that the ArgRange is invalid if isType is false. 4080 ExprResult 4081 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4082 UnaryExprOrTypeTrait ExprKind, bool IsType, 4083 void *TyOrEx, SourceRange ArgRange) { 4084 // If error parsing type, ignore. 4085 if (!TyOrEx) return ExprError(); 4086 4087 if (IsType) { 4088 TypeSourceInfo *TInfo; 4089 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4090 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4091 } 4092 4093 Expr *ArgEx = (Expr *)TyOrEx; 4094 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4095 return Result; 4096 } 4097 4098 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4099 bool IsReal) { 4100 if (V.get()->isTypeDependent()) 4101 return S.Context.DependentTy; 4102 4103 // _Real and _Imag are only l-values for normal l-values. 4104 if (V.get()->getObjectKind() != OK_Ordinary) { 4105 V = S.DefaultLvalueConversion(V.get()); 4106 if (V.isInvalid()) 4107 return QualType(); 4108 } 4109 4110 // These operators return the element type of a complex type. 4111 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4112 return CT->getElementType(); 4113 4114 // Otherwise they pass through real integer and floating point types here. 4115 if (V.get()->getType()->isArithmeticType()) 4116 return V.get()->getType(); 4117 4118 // Test for placeholders. 4119 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4120 if (PR.isInvalid()) return QualType(); 4121 if (PR.get() != V.get()) { 4122 V = PR; 4123 return CheckRealImagOperand(S, V, Loc, IsReal); 4124 } 4125 4126 // Reject anything else. 4127 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4128 << (IsReal ? "__real" : "__imag"); 4129 return QualType(); 4130 } 4131 4132 4133 4134 ExprResult 4135 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4136 tok::TokenKind Kind, Expr *Input) { 4137 UnaryOperatorKind Opc; 4138 switch (Kind) { 4139 default: llvm_unreachable("Unknown unary op!"); 4140 case tok::plusplus: Opc = UO_PostInc; break; 4141 case tok::minusminus: Opc = UO_PostDec; break; 4142 } 4143 4144 // Since this might is a postfix expression, get rid of ParenListExprs. 4145 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4146 if (Result.isInvalid()) return ExprError(); 4147 Input = Result.get(); 4148 4149 return BuildUnaryOp(S, OpLoc, Opc, Input); 4150 } 4151 4152 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4153 /// 4154 /// \return true on error 4155 static bool checkArithmeticOnObjCPointer(Sema &S, 4156 SourceLocation opLoc, 4157 Expr *op) { 4158 assert(op->getType()->isObjCObjectPointerType()); 4159 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4160 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4161 return false; 4162 4163 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4164 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4165 << op->getSourceRange(); 4166 return true; 4167 } 4168 4169 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4170 auto *BaseNoParens = Base->IgnoreParens(); 4171 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4172 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4173 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4174 } 4175 4176 ExprResult 4177 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4178 Expr *idx, SourceLocation rbLoc) { 4179 if (base && !base->getType().isNull() && 4180 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4181 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4182 /*Length=*/nullptr, rbLoc); 4183 4184 // Since this might be a postfix expression, get rid of ParenListExprs. 4185 if (isa<ParenListExpr>(base)) { 4186 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4187 if (result.isInvalid()) return ExprError(); 4188 base = result.get(); 4189 } 4190 4191 // Handle any non-overload placeholder types in the base and index 4192 // expressions. We can't handle overloads here because the other 4193 // operand might be an overloadable type, in which case the overload 4194 // resolution for the operator overload should get the first crack 4195 // at the overload. 4196 bool IsMSPropertySubscript = false; 4197 if (base->getType()->isNonOverloadPlaceholderType()) { 4198 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4199 if (!IsMSPropertySubscript) { 4200 ExprResult result = CheckPlaceholderExpr(base); 4201 if (result.isInvalid()) 4202 return ExprError(); 4203 base = result.get(); 4204 } 4205 } 4206 if (idx->getType()->isNonOverloadPlaceholderType()) { 4207 ExprResult result = CheckPlaceholderExpr(idx); 4208 if (result.isInvalid()) return ExprError(); 4209 idx = result.get(); 4210 } 4211 4212 // Build an unanalyzed expression if either operand is type-dependent. 4213 if (getLangOpts().CPlusPlus && 4214 (base->isTypeDependent() || idx->isTypeDependent())) { 4215 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4216 VK_LValue, OK_Ordinary, rbLoc); 4217 } 4218 4219 // MSDN, property (C++) 4220 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4221 // This attribute can also be used in the declaration of an empty array in a 4222 // class or structure definition. For example: 4223 // __declspec(property(get=GetX, put=PutX)) int x[]; 4224 // The above statement indicates that x[] can be used with one or more array 4225 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4226 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4227 if (IsMSPropertySubscript) { 4228 // Build MS property subscript expression if base is MS property reference 4229 // or MS property subscript. 4230 return new (Context) MSPropertySubscriptExpr( 4231 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4232 } 4233 4234 // Use C++ overloaded-operator rules if either operand has record 4235 // type. The spec says to do this if either type is *overloadable*, 4236 // but enum types can't declare subscript operators or conversion 4237 // operators, so there's nothing interesting for overload resolution 4238 // to do if there aren't any record types involved. 4239 // 4240 // ObjC pointers have their own subscripting logic that is not tied 4241 // to overload resolution and so should not take this path. 4242 if (getLangOpts().CPlusPlus && 4243 (base->getType()->isRecordType() || 4244 (!base->getType()->isObjCObjectPointerType() && 4245 idx->getType()->isRecordType()))) { 4246 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4247 } 4248 4249 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4250 } 4251 4252 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4253 Expr *LowerBound, 4254 SourceLocation ColonLoc, Expr *Length, 4255 SourceLocation RBLoc) { 4256 if (Base->getType()->isPlaceholderType() && 4257 !Base->getType()->isSpecificPlaceholderType( 4258 BuiltinType::OMPArraySection)) { 4259 ExprResult Result = CheckPlaceholderExpr(Base); 4260 if (Result.isInvalid()) 4261 return ExprError(); 4262 Base = Result.get(); 4263 } 4264 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4265 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4266 if (Result.isInvalid()) 4267 return ExprError(); 4268 Result = DefaultLvalueConversion(Result.get()); 4269 if (Result.isInvalid()) 4270 return ExprError(); 4271 LowerBound = Result.get(); 4272 } 4273 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4274 ExprResult Result = CheckPlaceholderExpr(Length); 4275 if (Result.isInvalid()) 4276 return ExprError(); 4277 Result = DefaultLvalueConversion(Result.get()); 4278 if (Result.isInvalid()) 4279 return ExprError(); 4280 Length = Result.get(); 4281 } 4282 4283 // Build an unanalyzed expression if either operand is type-dependent. 4284 if (Base->isTypeDependent() || 4285 (LowerBound && 4286 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4287 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4288 return new (Context) 4289 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4290 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4291 } 4292 4293 // Perform default conversions. 4294 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4295 QualType ResultTy; 4296 if (OriginalTy->isAnyPointerType()) { 4297 ResultTy = OriginalTy->getPointeeType(); 4298 } else if (OriginalTy->isArrayType()) { 4299 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4300 } else { 4301 return ExprError( 4302 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4303 << Base->getSourceRange()); 4304 } 4305 // C99 6.5.2.1p1 4306 if (LowerBound) { 4307 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4308 LowerBound); 4309 if (Res.isInvalid()) 4310 return ExprError(Diag(LowerBound->getExprLoc(), 4311 diag::err_omp_typecheck_section_not_integer) 4312 << 0 << LowerBound->getSourceRange()); 4313 LowerBound = Res.get(); 4314 4315 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4316 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4317 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4318 << 0 << LowerBound->getSourceRange(); 4319 } 4320 if (Length) { 4321 auto Res = 4322 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4323 if (Res.isInvalid()) 4324 return ExprError(Diag(Length->getExprLoc(), 4325 diag::err_omp_typecheck_section_not_integer) 4326 << 1 << Length->getSourceRange()); 4327 Length = Res.get(); 4328 4329 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4330 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4331 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4332 << 1 << Length->getSourceRange(); 4333 } 4334 4335 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4336 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4337 // type. Note that functions are not objects, and that (in C99 parlance) 4338 // incomplete types are not object types. 4339 if (ResultTy->isFunctionType()) { 4340 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4341 << ResultTy << Base->getSourceRange(); 4342 return ExprError(); 4343 } 4344 4345 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4346 diag::err_omp_section_incomplete_type, Base)) 4347 return ExprError(); 4348 4349 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4350 llvm::APSInt LowerBoundValue; 4351 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4352 // OpenMP 4.5, [2.4 Array Sections] 4353 // The array section must be a subset of the original array. 4354 if (LowerBoundValue.isNegative()) { 4355 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4356 << LowerBound->getSourceRange(); 4357 return ExprError(); 4358 } 4359 } 4360 } 4361 4362 if (Length) { 4363 llvm::APSInt LengthValue; 4364 if (Length->EvaluateAsInt(LengthValue, Context)) { 4365 // OpenMP 4.5, [2.4 Array Sections] 4366 // The length must evaluate to non-negative integers. 4367 if (LengthValue.isNegative()) { 4368 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4369 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4370 << Length->getSourceRange(); 4371 return ExprError(); 4372 } 4373 } 4374 } else if (ColonLoc.isValid() && 4375 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4376 !OriginalTy->isVariableArrayType()))) { 4377 // OpenMP 4.5, [2.4 Array Sections] 4378 // When the size of the array dimension is not known, the length must be 4379 // specified explicitly. 4380 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4381 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4382 return ExprError(); 4383 } 4384 4385 if (!Base->getType()->isSpecificPlaceholderType( 4386 BuiltinType::OMPArraySection)) { 4387 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4388 if (Result.isInvalid()) 4389 return ExprError(); 4390 Base = Result.get(); 4391 } 4392 return new (Context) 4393 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4394 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4395 } 4396 4397 ExprResult 4398 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4399 Expr *Idx, SourceLocation RLoc) { 4400 Expr *LHSExp = Base; 4401 Expr *RHSExp = Idx; 4402 4403 ExprValueKind VK = VK_LValue; 4404 ExprObjectKind OK = OK_Ordinary; 4405 4406 // Per C++ core issue 1213, the result is an xvalue if either operand is 4407 // a non-lvalue array, and an lvalue otherwise. 4408 if (getLangOpts().CPlusPlus11 && 4409 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4410 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4411 VK = VK_XValue; 4412 4413 // Perform default conversions. 4414 if (!LHSExp->getType()->getAs<VectorType>()) { 4415 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4416 if (Result.isInvalid()) 4417 return ExprError(); 4418 LHSExp = Result.get(); 4419 } 4420 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4421 if (Result.isInvalid()) 4422 return ExprError(); 4423 RHSExp = Result.get(); 4424 4425 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4426 4427 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4428 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4429 // in the subscript position. As a result, we need to derive the array base 4430 // and index from the expression types. 4431 Expr *BaseExpr, *IndexExpr; 4432 QualType ResultType; 4433 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4434 BaseExpr = LHSExp; 4435 IndexExpr = RHSExp; 4436 ResultType = Context.DependentTy; 4437 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4438 BaseExpr = LHSExp; 4439 IndexExpr = RHSExp; 4440 ResultType = PTy->getPointeeType(); 4441 } else if (const ObjCObjectPointerType *PTy = 4442 LHSTy->getAs<ObjCObjectPointerType>()) { 4443 BaseExpr = LHSExp; 4444 IndexExpr = RHSExp; 4445 4446 // Use custom logic if this should be the pseudo-object subscript 4447 // expression. 4448 if (!LangOpts.isSubscriptPointerArithmetic()) 4449 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4450 nullptr); 4451 4452 ResultType = PTy->getPointeeType(); 4453 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4454 // Handle the uncommon case of "123[Ptr]". 4455 BaseExpr = RHSExp; 4456 IndexExpr = LHSExp; 4457 ResultType = PTy->getPointeeType(); 4458 } else if (const ObjCObjectPointerType *PTy = 4459 RHSTy->getAs<ObjCObjectPointerType>()) { 4460 // Handle the uncommon case of "123[Ptr]". 4461 BaseExpr = RHSExp; 4462 IndexExpr = LHSExp; 4463 ResultType = PTy->getPointeeType(); 4464 if (!LangOpts.isSubscriptPointerArithmetic()) { 4465 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4466 << ResultType << BaseExpr->getSourceRange(); 4467 return ExprError(); 4468 } 4469 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4470 BaseExpr = LHSExp; // vectors: V[123] 4471 IndexExpr = RHSExp; 4472 VK = LHSExp->getValueKind(); 4473 if (VK != VK_RValue) 4474 OK = OK_VectorComponent; 4475 4476 // FIXME: need to deal with const... 4477 ResultType = VTy->getElementType(); 4478 } else if (LHSTy->isArrayType()) { 4479 // If we see an array that wasn't promoted by 4480 // DefaultFunctionArrayLvalueConversion, it must be an array that 4481 // wasn't promoted because of the C90 rule that doesn't 4482 // allow promoting non-lvalue arrays. Warn, then 4483 // force the promotion here. 4484 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4485 LHSExp->getSourceRange(); 4486 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4487 CK_ArrayToPointerDecay).get(); 4488 LHSTy = LHSExp->getType(); 4489 4490 BaseExpr = LHSExp; 4491 IndexExpr = RHSExp; 4492 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4493 } else if (RHSTy->isArrayType()) { 4494 // Same as previous, except for 123[f().a] case 4495 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4496 RHSExp->getSourceRange(); 4497 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4498 CK_ArrayToPointerDecay).get(); 4499 RHSTy = RHSExp->getType(); 4500 4501 BaseExpr = RHSExp; 4502 IndexExpr = LHSExp; 4503 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4504 } else { 4505 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4506 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4507 } 4508 // C99 6.5.2.1p1 4509 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4510 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4511 << IndexExpr->getSourceRange()); 4512 4513 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4514 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4515 && !IndexExpr->isTypeDependent()) 4516 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4517 4518 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4519 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4520 // type. Note that Functions are not objects, and that (in C99 parlance) 4521 // incomplete types are not object types. 4522 if (ResultType->isFunctionType()) { 4523 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4524 << ResultType << BaseExpr->getSourceRange(); 4525 return ExprError(); 4526 } 4527 4528 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4529 // GNU extension: subscripting on pointer to void 4530 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4531 << BaseExpr->getSourceRange(); 4532 4533 // C forbids expressions of unqualified void type from being l-values. 4534 // See IsCForbiddenLValueType. 4535 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4536 } else if (!ResultType->isDependentType() && 4537 RequireCompleteType(LLoc, ResultType, 4538 diag::err_subscript_incomplete_type, BaseExpr)) 4539 return ExprError(); 4540 4541 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4542 !ResultType.isCForbiddenLValueType()); 4543 4544 return new (Context) 4545 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4546 } 4547 4548 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4549 ParmVarDecl *Param) { 4550 if (Param->hasUnparsedDefaultArg()) { 4551 Diag(CallLoc, 4552 diag::err_use_of_default_argument_to_function_declared_later) << 4553 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4554 Diag(UnparsedDefaultArgLocs[Param], 4555 diag::note_default_argument_declared_here); 4556 return true; 4557 } 4558 4559 if (Param->hasUninstantiatedDefaultArg()) { 4560 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4561 4562 EnterExpressionEvaluationContext EvalContext( 4563 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4564 4565 // Instantiate the expression. 4566 MultiLevelTemplateArgumentList MutiLevelArgList 4567 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4568 4569 InstantiatingTemplate Inst(*this, CallLoc, Param, 4570 MutiLevelArgList.getInnermost()); 4571 if (Inst.isInvalid()) 4572 return true; 4573 if (Inst.isAlreadyInstantiating()) { 4574 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4575 Param->setInvalidDecl(); 4576 return true; 4577 } 4578 4579 ExprResult Result; 4580 { 4581 // C++ [dcl.fct.default]p5: 4582 // The names in the [default argument] expression are bound, and 4583 // the semantic constraints are checked, at the point where the 4584 // default argument expression appears. 4585 ContextRAII SavedContext(*this, FD); 4586 LocalInstantiationScope Local(*this); 4587 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4588 /*DirectInit*/false); 4589 } 4590 if (Result.isInvalid()) 4591 return true; 4592 4593 // Check the expression as an initializer for the parameter. 4594 InitializedEntity Entity 4595 = InitializedEntity::InitializeParameter(Context, Param); 4596 InitializationKind Kind 4597 = InitializationKind::CreateCopy(Param->getLocation(), 4598 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4599 Expr *ResultE = Result.getAs<Expr>(); 4600 4601 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4602 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4603 if (Result.isInvalid()) 4604 return true; 4605 4606 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4607 Param->getOuterLocStart()); 4608 if (Result.isInvalid()) 4609 return true; 4610 4611 // Remember the instantiated default argument. 4612 Param->setDefaultArg(Result.getAs<Expr>()); 4613 if (ASTMutationListener *L = getASTMutationListener()) { 4614 L->DefaultArgumentInstantiated(Param); 4615 } 4616 } 4617 4618 // If the default argument expression is not set yet, we are building it now. 4619 if (!Param->hasInit()) { 4620 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4621 Param->setInvalidDecl(); 4622 return true; 4623 } 4624 4625 // If the default expression creates temporaries, we need to 4626 // push them to the current stack of expression temporaries so they'll 4627 // be properly destroyed. 4628 // FIXME: We should really be rebuilding the default argument with new 4629 // bound temporaries; see the comment in PR5810. 4630 // We don't need to do that with block decls, though, because 4631 // blocks in default argument expression can never capture anything. 4632 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4633 // Set the "needs cleanups" bit regardless of whether there are 4634 // any explicit objects. 4635 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4636 4637 // Append all the objects to the cleanup list. Right now, this 4638 // should always be a no-op, because blocks in default argument 4639 // expressions should never be able to capture anything. 4640 assert(!Init->getNumObjects() && 4641 "default argument expression has capturing blocks?"); 4642 } 4643 4644 // We already type-checked the argument, so we know it works. 4645 // Just mark all of the declarations in this potentially-evaluated expression 4646 // as being "referenced". 4647 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4648 /*SkipLocalVariables=*/true); 4649 return false; 4650 } 4651 4652 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4653 FunctionDecl *FD, ParmVarDecl *Param) { 4654 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4655 return ExprError(); 4656 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4657 } 4658 4659 Sema::VariadicCallType 4660 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4661 Expr *Fn) { 4662 if (Proto && Proto->isVariadic()) { 4663 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4664 return VariadicConstructor; 4665 else if (Fn && Fn->getType()->isBlockPointerType()) 4666 return VariadicBlock; 4667 else if (FDecl) { 4668 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4669 if (Method->isInstance()) 4670 return VariadicMethod; 4671 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4672 return VariadicMethod; 4673 return VariadicFunction; 4674 } 4675 return VariadicDoesNotApply; 4676 } 4677 4678 namespace { 4679 class FunctionCallCCC : public FunctionCallFilterCCC { 4680 public: 4681 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4682 unsigned NumArgs, MemberExpr *ME) 4683 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4684 FunctionName(FuncName) {} 4685 4686 bool ValidateCandidate(const TypoCorrection &candidate) override { 4687 if (!candidate.getCorrectionSpecifier() || 4688 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4689 return false; 4690 } 4691 4692 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4693 } 4694 4695 private: 4696 const IdentifierInfo *const FunctionName; 4697 }; 4698 } 4699 4700 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4701 FunctionDecl *FDecl, 4702 ArrayRef<Expr *> Args) { 4703 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4704 DeclarationName FuncName = FDecl->getDeclName(); 4705 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4706 4707 if (TypoCorrection Corrected = S.CorrectTypo( 4708 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4709 S.getScopeForContext(S.CurContext), nullptr, 4710 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4711 Args.size(), ME), 4712 Sema::CTK_ErrorRecovery)) { 4713 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4714 if (Corrected.isOverloaded()) { 4715 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4716 OverloadCandidateSet::iterator Best; 4717 for (NamedDecl *CD : Corrected) { 4718 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4719 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4720 OCS); 4721 } 4722 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4723 case OR_Success: 4724 ND = Best->FoundDecl; 4725 Corrected.setCorrectionDecl(ND); 4726 break; 4727 default: 4728 break; 4729 } 4730 } 4731 ND = ND->getUnderlyingDecl(); 4732 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4733 return Corrected; 4734 } 4735 } 4736 return TypoCorrection(); 4737 } 4738 4739 /// ConvertArgumentsForCall - Converts the arguments specified in 4740 /// Args/NumArgs to the parameter types of the function FDecl with 4741 /// function prototype Proto. Call is the call expression itself, and 4742 /// Fn is the function expression. For a C++ member function, this 4743 /// routine does not attempt to convert the object argument. Returns 4744 /// true if the call is ill-formed. 4745 bool 4746 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4747 FunctionDecl *FDecl, 4748 const FunctionProtoType *Proto, 4749 ArrayRef<Expr *> Args, 4750 SourceLocation RParenLoc, 4751 bool IsExecConfig) { 4752 // Bail out early if calling a builtin with custom typechecking. 4753 if (FDecl) 4754 if (unsigned ID = FDecl->getBuiltinID()) 4755 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4756 return false; 4757 4758 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4759 // assignment, to the types of the corresponding parameter, ... 4760 unsigned NumParams = Proto->getNumParams(); 4761 bool Invalid = false; 4762 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4763 unsigned FnKind = Fn->getType()->isBlockPointerType() 4764 ? 1 /* block */ 4765 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4766 : 0 /* function */); 4767 4768 // If too few arguments are available (and we don't have default 4769 // arguments for the remaining parameters), don't make the call. 4770 if (Args.size() < NumParams) { 4771 if (Args.size() < MinArgs) { 4772 TypoCorrection TC; 4773 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4774 unsigned diag_id = 4775 MinArgs == NumParams && !Proto->isVariadic() 4776 ? diag::err_typecheck_call_too_few_args_suggest 4777 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4778 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4779 << static_cast<unsigned>(Args.size()) 4780 << TC.getCorrectionRange()); 4781 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4782 Diag(RParenLoc, 4783 MinArgs == NumParams && !Proto->isVariadic() 4784 ? diag::err_typecheck_call_too_few_args_one 4785 : diag::err_typecheck_call_too_few_args_at_least_one) 4786 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4787 else 4788 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4789 ? diag::err_typecheck_call_too_few_args 4790 : diag::err_typecheck_call_too_few_args_at_least) 4791 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4792 << Fn->getSourceRange(); 4793 4794 // Emit the location of the prototype. 4795 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4796 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4797 << FDecl; 4798 4799 return true; 4800 } 4801 Call->setNumArgs(Context, NumParams); 4802 } 4803 4804 // If too many are passed and not variadic, error on the extras and drop 4805 // them. 4806 if (Args.size() > NumParams) { 4807 if (!Proto->isVariadic()) { 4808 TypoCorrection TC; 4809 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4810 unsigned diag_id = 4811 MinArgs == NumParams && !Proto->isVariadic() 4812 ? diag::err_typecheck_call_too_many_args_suggest 4813 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4814 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4815 << static_cast<unsigned>(Args.size()) 4816 << TC.getCorrectionRange()); 4817 } else if (NumParams == 1 && FDecl && 4818 FDecl->getParamDecl(0)->getDeclName()) 4819 Diag(Args[NumParams]->getLocStart(), 4820 MinArgs == NumParams 4821 ? diag::err_typecheck_call_too_many_args_one 4822 : diag::err_typecheck_call_too_many_args_at_most_one) 4823 << FnKind << FDecl->getParamDecl(0) 4824 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4825 << SourceRange(Args[NumParams]->getLocStart(), 4826 Args.back()->getLocEnd()); 4827 else 4828 Diag(Args[NumParams]->getLocStart(), 4829 MinArgs == NumParams 4830 ? diag::err_typecheck_call_too_many_args 4831 : diag::err_typecheck_call_too_many_args_at_most) 4832 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4833 << Fn->getSourceRange() 4834 << SourceRange(Args[NumParams]->getLocStart(), 4835 Args.back()->getLocEnd()); 4836 4837 // Emit the location of the prototype. 4838 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4839 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4840 << FDecl; 4841 4842 // This deletes the extra arguments. 4843 Call->setNumArgs(Context, NumParams); 4844 return true; 4845 } 4846 } 4847 SmallVector<Expr *, 8> AllArgs; 4848 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4849 4850 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4851 Proto, 0, Args, AllArgs, CallType); 4852 if (Invalid) 4853 return true; 4854 unsigned TotalNumArgs = AllArgs.size(); 4855 for (unsigned i = 0; i < TotalNumArgs; ++i) 4856 Call->setArg(i, AllArgs[i]); 4857 4858 return false; 4859 } 4860 4861 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4862 const FunctionProtoType *Proto, 4863 unsigned FirstParam, ArrayRef<Expr *> Args, 4864 SmallVectorImpl<Expr *> &AllArgs, 4865 VariadicCallType CallType, bool AllowExplicit, 4866 bool IsListInitialization) { 4867 unsigned NumParams = Proto->getNumParams(); 4868 bool Invalid = false; 4869 size_t ArgIx = 0; 4870 // Continue to check argument types (even if we have too few/many args). 4871 for (unsigned i = FirstParam; i < NumParams; i++) { 4872 QualType ProtoArgType = Proto->getParamType(i); 4873 4874 Expr *Arg; 4875 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4876 if (ArgIx < Args.size()) { 4877 Arg = Args[ArgIx++]; 4878 4879 if (RequireCompleteType(Arg->getLocStart(), 4880 ProtoArgType, 4881 diag::err_call_incomplete_argument, Arg)) 4882 return true; 4883 4884 // Strip the unbridged-cast placeholder expression off, if applicable. 4885 bool CFAudited = false; 4886 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4887 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4888 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4889 Arg = stripARCUnbridgedCast(Arg); 4890 else if (getLangOpts().ObjCAutoRefCount && 4891 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4892 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4893 CFAudited = true; 4894 4895 InitializedEntity Entity = 4896 Param ? InitializedEntity::InitializeParameter(Context, Param, 4897 ProtoArgType) 4898 : InitializedEntity::InitializeParameter( 4899 Context, ProtoArgType, Proto->isParamConsumed(i)); 4900 4901 // Remember that parameter belongs to a CF audited API. 4902 if (CFAudited) 4903 Entity.setParameterCFAudited(); 4904 4905 ExprResult ArgE = PerformCopyInitialization( 4906 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4907 if (ArgE.isInvalid()) 4908 return true; 4909 4910 Arg = ArgE.getAs<Expr>(); 4911 } else { 4912 assert(Param && "can't use default arguments without a known callee"); 4913 4914 ExprResult ArgExpr = 4915 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4916 if (ArgExpr.isInvalid()) 4917 return true; 4918 4919 Arg = ArgExpr.getAs<Expr>(); 4920 } 4921 4922 // Check for array bounds violations for each argument to the call. This 4923 // check only triggers warnings when the argument isn't a more complex Expr 4924 // with its own checking, such as a BinaryOperator. 4925 CheckArrayAccess(Arg); 4926 4927 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4928 CheckStaticArrayArgument(CallLoc, Param, Arg); 4929 4930 AllArgs.push_back(Arg); 4931 } 4932 4933 // If this is a variadic call, handle args passed through "...". 4934 if (CallType != VariadicDoesNotApply) { 4935 // Assume that extern "C" functions with variadic arguments that 4936 // return __unknown_anytype aren't *really* variadic. 4937 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4938 FDecl->isExternC()) { 4939 for (Expr *A : Args.slice(ArgIx)) { 4940 QualType paramType; // ignored 4941 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4942 Invalid |= arg.isInvalid(); 4943 AllArgs.push_back(arg.get()); 4944 } 4945 4946 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4947 } else { 4948 for (Expr *A : Args.slice(ArgIx)) { 4949 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4950 Invalid |= Arg.isInvalid(); 4951 AllArgs.push_back(Arg.get()); 4952 } 4953 } 4954 4955 // Check for array bounds violations. 4956 for (Expr *A : Args.slice(ArgIx)) 4957 CheckArrayAccess(A); 4958 } 4959 return Invalid; 4960 } 4961 4962 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4963 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4964 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4965 TL = DTL.getOriginalLoc(); 4966 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4967 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4968 << ATL.getLocalSourceRange(); 4969 } 4970 4971 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4972 /// array parameter, check that it is non-null, and that if it is formed by 4973 /// array-to-pointer decay, the underlying array is sufficiently large. 4974 /// 4975 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4976 /// array type derivation, then for each call to the function, the value of the 4977 /// corresponding actual argument shall provide access to the first element of 4978 /// an array with at least as many elements as specified by the size expression. 4979 void 4980 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4981 ParmVarDecl *Param, 4982 const Expr *ArgExpr) { 4983 // Static array parameters are not supported in C++. 4984 if (!Param || getLangOpts().CPlusPlus) 4985 return; 4986 4987 QualType OrigTy = Param->getOriginalType(); 4988 4989 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4990 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4991 return; 4992 4993 if (ArgExpr->isNullPointerConstant(Context, 4994 Expr::NPC_NeverValueDependent)) { 4995 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4996 DiagnoseCalleeStaticArrayParam(*this, Param); 4997 return; 4998 } 4999 5000 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5001 if (!CAT) 5002 return; 5003 5004 const ConstantArrayType *ArgCAT = 5005 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5006 if (!ArgCAT) 5007 return; 5008 5009 if (ArgCAT->getSize().ult(CAT->getSize())) { 5010 Diag(CallLoc, diag::warn_static_array_too_small) 5011 << ArgExpr->getSourceRange() 5012 << (unsigned) ArgCAT->getSize().getZExtValue() 5013 << (unsigned) CAT->getSize().getZExtValue(); 5014 DiagnoseCalleeStaticArrayParam(*this, Param); 5015 } 5016 } 5017 5018 /// Given a function expression of unknown-any type, try to rebuild it 5019 /// to have a function type. 5020 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5021 5022 /// Is the given type a placeholder that we need to lower out 5023 /// immediately during argument processing? 5024 static bool isPlaceholderToRemoveAsArg(QualType type) { 5025 // Placeholders are never sugared. 5026 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5027 if (!placeholder) return false; 5028 5029 switch (placeholder->getKind()) { 5030 // Ignore all the non-placeholder types. 5031 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5032 case BuiltinType::Id: 5033 #include "clang/Basic/OpenCLImageTypes.def" 5034 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5035 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5036 #include "clang/AST/BuiltinTypes.def" 5037 return false; 5038 5039 // We cannot lower out overload sets; they might validly be resolved 5040 // by the call machinery. 5041 case BuiltinType::Overload: 5042 return false; 5043 5044 // Unbridged casts in ARC can be handled in some call positions and 5045 // should be left in place. 5046 case BuiltinType::ARCUnbridgedCast: 5047 return false; 5048 5049 // Pseudo-objects should be converted as soon as possible. 5050 case BuiltinType::PseudoObject: 5051 return true; 5052 5053 // The debugger mode could theoretically but currently does not try 5054 // to resolve unknown-typed arguments based on known parameter types. 5055 case BuiltinType::UnknownAny: 5056 return true; 5057 5058 // These are always invalid as call arguments and should be reported. 5059 case BuiltinType::BoundMember: 5060 case BuiltinType::BuiltinFn: 5061 case BuiltinType::OMPArraySection: 5062 return true; 5063 5064 } 5065 llvm_unreachable("bad builtin type kind"); 5066 } 5067 5068 /// Check an argument list for placeholders that we won't try to 5069 /// handle later. 5070 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5071 // Apply this processing to all the arguments at once instead of 5072 // dying at the first failure. 5073 bool hasInvalid = false; 5074 for (size_t i = 0, e = args.size(); i != e; i++) { 5075 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5076 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5077 if (result.isInvalid()) hasInvalid = true; 5078 else args[i] = result.get(); 5079 } else if (hasInvalid) { 5080 (void)S.CorrectDelayedTyposInExpr(args[i]); 5081 } 5082 } 5083 return hasInvalid; 5084 } 5085 5086 /// If a builtin function has a pointer argument with no explicit address 5087 /// space, then it should be able to accept a pointer to any address 5088 /// space as input. In order to do this, we need to replace the 5089 /// standard builtin declaration with one that uses the same address space 5090 /// as the call. 5091 /// 5092 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5093 /// it does not contain any pointer arguments without 5094 /// an address space qualifer. Otherwise the rewritten 5095 /// FunctionDecl is returned. 5096 /// TODO: Handle pointer return types. 5097 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5098 const FunctionDecl *FDecl, 5099 MultiExprArg ArgExprs) { 5100 5101 QualType DeclType = FDecl->getType(); 5102 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5103 5104 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5105 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5106 return nullptr; 5107 5108 bool NeedsNewDecl = false; 5109 unsigned i = 0; 5110 SmallVector<QualType, 8> OverloadParams; 5111 5112 for (QualType ParamType : FT->param_types()) { 5113 5114 // Convert array arguments to pointer to simplify type lookup. 5115 ExprResult ArgRes = 5116 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5117 if (ArgRes.isInvalid()) 5118 return nullptr; 5119 Expr *Arg = ArgRes.get(); 5120 QualType ArgType = Arg->getType(); 5121 if (!ParamType->isPointerType() || 5122 ParamType.getQualifiers().hasAddressSpace() || 5123 !ArgType->isPointerType() || 5124 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5125 OverloadParams.push_back(ParamType); 5126 continue; 5127 } 5128 5129 NeedsNewDecl = true; 5130 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5131 5132 QualType PointeeType = ParamType->getPointeeType(); 5133 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5134 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5135 } 5136 5137 if (!NeedsNewDecl) 5138 return nullptr; 5139 5140 FunctionProtoType::ExtProtoInfo EPI; 5141 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5142 OverloadParams, EPI); 5143 DeclContext *Parent = Context.getTranslationUnitDecl(); 5144 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5145 FDecl->getLocation(), 5146 FDecl->getLocation(), 5147 FDecl->getIdentifier(), 5148 OverloadTy, 5149 /*TInfo=*/nullptr, 5150 SC_Extern, false, 5151 /*hasPrototype=*/true); 5152 SmallVector<ParmVarDecl*, 16> Params; 5153 FT = cast<FunctionProtoType>(OverloadTy); 5154 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5155 QualType ParamType = FT->getParamType(i); 5156 ParmVarDecl *Parm = 5157 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5158 SourceLocation(), nullptr, ParamType, 5159 /*TInfo=*/nullptr, SC_None, nullptr); 5160 Parm->setScopeInfo(0, i); 5161 Params.push_back(Parm); 5162 } 5163 OverloadDecl->setParams(Params); 5164 return OverloadDecl; 5165 } 5166 5167 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5168 FunctionDecl *Callee, 5169 MultiExprArg ArgExprs) { 5170 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5171 // similar attributes) really don't like it when functions are called with an 5172 // invalid number of args. 5173 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5174 /*PartialOverloading=*/false) && 5175 !Callee->isVariadic()) 5176 return; 5177 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5178 return; 5179 5180 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5181 S.Diag(Fn->getLocStart(), 5182 isa<CXXMethodDecl>(Callee) 5183 ? diag::err_ovl_no_viable_member_function_in_call 5184 : diag::err_ovl_no_viable_function_in_call) 5185 << Callee << Callee->getSourceRange(); 5186 S.Diag(Callee->getLocation(), 5187 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5188 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5189 return; 5190 } 5191 } 5192 5193 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5194 /// This provides the location of the left/right parens and a list of comma 5195 /// locations. 5196 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5197 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5198 Expr *ExecConfig, bool IsExecConfig) { 5199 // Since this might be a postfix expression, get rid of ParenListExprs. 5200 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5201 if (Result.isInvalid()) return ExprError(); 5202 Fn = Result.get(); 5203 5204 if (checkArgsForPlaceholders(*this, ArgExprs)) 5205 return ExprError(); 5206 5207 if (getLangOpts().CPlusPlus) { 5208 // If this is a pseudo-destructor expression, build the call immediately. 5209 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5210 if (!ArgExprs.empty()) { 5211 // Pseudo-destructor calls should not have any arguments. 5212 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5213 << FixItHint::CreateRemoval( 5214 SourceRange(ArgExprs.front()->getLocStart(), 5215 ArgExprs.back()->getLocEnd())); 5216 } 5217 5218 return new (Context) 5219 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5220 } 5221 if (Fn->getType() == Context.PseudoObjectTy) { 5222 ExprResult result = CheckPlaceholderExpr(Fn); 5223 if (result.isInvalid()) return ExprError(); 5224 Fn = result.get(); 5225 } 5226 5227 // Determine whether this is a dependent call inside a C++ template, 5228 // in which case we won't do any semantic analysis now. 5229 bool Dependent = false; 5230 if (Fn->isTypeDependent()) 5231 Dependent = true; 5232 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5233 Dependent = true; 5234 5235 if (Dependent) { 5236 if (ExecConfig) { 5237 return new (Context) CUDAKernelCallExpr( 5238 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5239 Context.DependentTy, VK_RValue, RParenLoc); 5240 } else { 5241 return new (Context) CallExpr( 5242 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5243 } 5244 } 5245 5246 // Determine whether this is a call to an object (C++ [over.call.object]). 5247 if (Fn->getType()->isRecordType()) 5248 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5249 RParenLoc); 5250 5251 if (Fn->getType() == Context.UnknownAnyTy) { 5252 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5253 if (result.isInvalid()) return ExprError(); 5254 Fn = result.get(); 5255 } 5256 5257 if (Fn->getType() == Context.BoundMemberTy) { 5258 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5259 RParenLoc); 5260 } 5261 } 5262 5263 // Check for overloaded calls. This can happen even in C due to extensions. 5264 if (Fn->getType() == Context.OverloadTy) { 5265 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5266 5267 // We aren't supposed to apply this logic for if there'Scope an '&' 5268 // involved. 5269 if (!find.HasFormOfMemberPointer) { 5270 OverloadExpr *ovl = find.Expression; 5271 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5272 return BuildOverloadedCallExpr( 5273 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5274 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5275 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5276 RParenLoc); 5277 } 5278 } 5279 5280 // If we're directly calling a function, get the appropriate declaration. 5281 if (Fn->getType() == Context.UnknownAnyTy) { 5282 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5283 if (result.isInvalid()) return ExprError(); 5284 Fn = result.get(); 5285 } 5286 5287 Expr *NakedFn = Fn->IgnoreParens(); 5288 5289 bool CallingNDeclIndirectly = false; 5290 NamedDecl *NDecl = nullptr; 5291 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5292 if (UnOp->getOpcode() == UO_AddrOf) { 5293 CallingNDeclIndirectly = true; 5294 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5295 } 5296 } 5297 5298 if (isa<DeclRefExpr>(NakedFn)) { 5299 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5300 5301 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5302 if (FDecl && FDecl->getBuiltinID()) { 5303 // Rewrite the function decl for this builtin by replacing parameters 5304 // with no explicit address space with the address space of the arguments 5305 // in ArgExprs. 5306 if ((FDecl = 5307 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5308 NDecl = FDecl; 5309 Fn = DeclRefExpr::Create( 5310 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5311 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5312 } 5313 } 5314 } else if (isa<MemberExpr>(NakedFn)) 5315 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5316 5317 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5318 if (CallingNDeclIndirectly && 5319 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5320 Fn->getLocStart())) 5321 return ExprError(); 5322 5323 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5324 return ExprError(); 5325 5326 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5327 } 5328 5329 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5330 ExecConfig, IsExecConfig); 5331 } 5332 5333 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5334 /// 5335 /// __builtin_astype( value, dst type ) 5336 /// 5337 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5338 SourceLocation BuiltinLoc, 5339 SourceLocation RParenLoc) { 5340 ExprValueKind VK = VK_RValue; 5341 ExprObjectKind OK = OK_Ordinary; 5342 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5343 QualType SrcTy = E->getType(); 5344 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5345 return ExprError(Diag(BuiltinLoc, 5346 diag::err_invalid_astype_of_different_size) 5347 << DstTy 5348 << SrcTy 5349 << E->getSourceRange()); 5350 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5351 } 5352 5353 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5354 /// provided arguments. 5355 /// 5356 /// __builtin_convertvector( value, dst type ) 5357 /// 5358 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5359 SourceLocation BuiltinLoc, 5360 SourceLocation RParenLoc) { 5361 TypeSourceInfo *TInfo; 5362 GetTypeFromParser(ParsedDestTy, &TInfo); 5363 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5364 } 5365 5366 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5367 /// i.e. an expression not of \p OverloadTy. The expression should 5368 /// unary-convert to an expression of function-pointer or 5369 /// block-pointer type. 5370 /// 5371 /// \param NDecl the declaration being called, if available 5372 ExprResult 5373 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5374 SourceLocation LParenLoc, 5375 ArrayRef<Expr *> Args, 5376 SourceLocation RParenLoc, 5377 Expr *Config, bool IsExecConfig) { 5378 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5379 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5380 5381 // Functions with 'interrupt' attribute cannot be called directly. 5382 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5383 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5384 return ExprError(); 5385 } 5386 5387 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5388 // so there's some risk when calling out to non-interrupt handler functions 5389 // that the callee might not preserve them. This is easy to diagnose here, 5390 // but can be very challenging to debug. 5391 if (auto *Caller = getCurFunctionDecl()) 5392 if (Caller->hasAttr<ARMInterruptAttr>()) 5393 if (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()) 5394 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5395 5396 // Promote the function operand. 5397 // We special-case function promotion here because we only allow promoting 5398 // builtin functions to function pointers in the callee of a call. 5399 ExprResult Result; 5400 if (BuiltinID && 5401 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5402 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5403 CK_BuiltinFnToFnPtr).get(); 5404 } else { 5405 Result = CallExprUnaryConversions(Fn); 5406 } 5407 if (Result.isInvalid()) 5408 return ExprError(); 5409 Fn = Result.get(); 5410 5411 // Make the call expr early, before semantic checks. This guarantees cleanup 5412 // of arguments and function on error. 5413 CallExpr *TheCall; 5414 if (Config) 5415 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5416 cast<CallExpr>(Config), Args, 5417 Context.BoolTy, VK_RValue, 5418 RParenLoc); 5419 else 5420 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5421 VK_RValue, RParenLoc); 5422 5423 if (!getLangOpts().CPlusPlus) { 5424 // C cannot always handle TypoExpr nodes in builtin calls and direct 5425 // function calls as their argument checking don't necessarily handle 5426 // dependent types properly, so make sure any TypoExprs have been 5427 // dealt with. 5428 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5429 if (!Result.isUsable()) return ExprError(); 5430 TheCall = dyn_cast<CallExpr>(Result.get()); 5431 if (!TheCall) return Result; 5432 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5433 } 5434 5435 // Bail out early if calling a builtin with custom typechecking. 5436 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5437 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5438 5439 retry: 5440 const FunctionType *FuncT; 5441 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5442 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5443 // have type pointer to function". 5444 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5445 if (!FuncT) 5446 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5447 << Fn->getType() << Fn->getSourceRange()); 5448 } else if (const BlockPointerType *BPT = 5449 Fn->getType()->getAs<BlockPointerType>()) { 5450 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5451 } else { 5452 // Handle calls to expressions of unknown-any type. 5453 if (Fn->getType() == Context.UnknownAnyTy) { 5454 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5455 if (rewrite.isInvalid()) return ExprError(); 5456 Fn = rewrite.get(); 5457 TheCall->setCallee(Fn); 5458 goto retry; 5459 } 5460 5461 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5462 << Fn->getType() << Fn->getSourceRange()); 5463 } 5464 5465 if (getLangOpts().CUDA) { 5466 if (Config) { 5467 // CUDA: Kernel calls must be to global functions 5468 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5469 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5470 << FDecl->getName() << Fn->getSourceRange()); 5471 5472 // CUDA: Kernel function must have 'void' return type 5473 if (!FuncT->getReturnType()->isVoidType()) 5474 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5475 << Fn->getType() << Fn->getSourceRange()); 5476 } else { 5477 // CUDA: Calls to global functions must be configured 5478 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5479 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5480 << FDecl->getName() << Fn->getSourceRange()); 5481 } 5482 } 5483 5484 // Check for a valid return type 5485 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5486 FDecl)) 5487 return ExprError(); 5488 5489 // We know the result type of the call, set it. 5490 TheCall->setType(FuncT->getCallResultType(Context)); 5491 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5492 5493 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5494 if (Proto) { 5495 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5496 IsExecConfig)) 5497 return ExprError(); 5498 } else { 5499 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5500 5501 if (FDecl) { 5502 // Check if we have too few/too many template arguments, based 5503 // on our knowledge of the function definition. 5504 const FunctionDecl *Def = nullptr; 5505 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5506 Proto = Def->getType()->getAs<FunctionProtoType>(); 5507 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5508 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5509 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5510 } 5511 5512 // If the function we're calling isn't a function prototype, but we have 5513 // a function prototype from a prior declaratiom, use that prototype. 5514 if (!FDecl->hasPrototype()) 5515 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5516 } 5517 5518 // Promote the arguments (C99 6.5.2.2p6). 5519 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5520 Expr *Arg = Args[i]; 5521 5522 if (Proto && i < Proto->getNumParams()) { 5523 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5524 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5525 ExprResult ArgE = 5526 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5527 if (ArgE.isInvalid()) 5528 return true; 5529 5530 Arg = ArgE.getAs<Expr>(); 5531 5532 } else { 5533 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5534 5535 if (ArgE.isInvalid()) 5536 return true; 5537 5538 Arg = ArgE.getAs<Expr>(); 5539 } 5540 5541 if (RequireCompleteType(Arg->getLocStart(), 5542 Arg->getType(), 5543 diag::err_call_incomplete_argument, Arg)) 5544 return ExprError(); 5545 5546 TheCall->setArg(i, Arg); 5547 } 5548 } 5549 5550 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5551 if (!Method->isStatic()) 5552 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5553 << Fn->getSourceRange()); 5554 5555 // Check for sentinels 5556 if (NDecl) 5557 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5558 5559 // Do special checking on direct calls to functions. 5560 if (FDecl) { 5561 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5562 return ExprError(); 5563 5564 if (BuiltinID) 5565 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5566 } else if (NDecl) { 5567 if (CheckPointerCall(NDecl, TheCall, Proto)) 5568 return ExprError(); 5569 } else { 5570 if (CheckOtherCall(TheCall, Proto)) 5571 return ExprError(); 5572 } 5573 5574 return MaybeBindToTemporary(TheCall); 5575 } 5576 5577 ExprResult 5578 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5579 SourceLocation RParenLoc, Expr *InitExpr) { 5580 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5581 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5582 5583 TypeSourceInfo *TInfo; 5584 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5585 if (!TInfo) 5586 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5587 5588 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5589 } 5590 5591 ExprResult 5592 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5593 SourceLocation RParenLoc, Expr *LiteralExpr) { 5594 QualType literalType = TInfo->getType(); 5595 5596 if (literalType->isArrayType()) { 5597 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5598 diag::err_illegal_decl_array_incomplete_type, 5599 SourceRange(LParenLoc, 5600 LiteralExpr->getSourceRange().getEnd()))) 5601 return ExprError(); 5602 if (literalType->isVariableArrayType()) 5603 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5604 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5605 } else if (!literalType->isDependentType() && 5606 RequireCompleteType(LParenLoc, literalType, 5607 diag::err_typecheck_decl_incomplete_type, 5608 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5609 return ExprError(); 5610 5611 InitializedEntity Entity 5612 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5613 InitializationKind Kind 5614 = InitializationKind::CreateCStyleCast(LParenLoc, 5615 SourceRange(LParenLoc, RParenLoc), 5616 /*InitList=*/true); 5617 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5618 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5619 &literalType); 5620 if (Result.isInvalid()) 5621 return ExprError(); 5622 LiteralExpr = Result.get(); 5623 5624 bool isFileScope = !CurContext->isFunctionOrMethod(); 5625 if (isFileScope && 5626 !LiteralExpr->isTypeDependent() && 5627 !LiteralExpr->isValueDependent() && 5628 !literalType->isDependentType()) { // 6.5.2.5p3 5629 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5630 return ExprError(); 5631 } 5632 5633 // In C, compound literals are l-values for some reason. 5634 // For GCC compatibility, in C++, file-scope array compound literals with 5635 // constant initializers are also l-values, and compound literals are 5636 // otherwise prvalues. 5637 // 5638 // (GCC also treats C++ list-initialized file-scope array prvalues with 5639 // constant initializers as l-values, but that's non-conforming, so we don't 5640 // follow it there.) 5641 // 5642 // FIXME: It would be better to handle the lvalue cases as materializing and 5643 // lifetime-extending a temporary object, but our materialized temporaries 5644 // representation only supports lifetime extension from a variable, not "out 5645 // of thin air". 5646 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5647 // is bound to the result of applying array-to-pointer decay to the compound 5648 // literal. 5649 // FIXME: GCC supports compound literals of reference type, which should 5650 // obviously have a value kind derived from the kind of reference involved. 5651 ExprValueKind VK = 5652 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5653 ? VK_RValue 5654 : VK_LValue; 5655 5656 return MaybeBindToTemporary( 5657 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5658 VK, LiteralExpr, isFileScope)); 5659 } 5660 5661 ExprResult 5662 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5663 SourceLocation RBraceLoc) { 5664 // Immediately handle non-overload placeholders. Overloads can be 5665 // resolved contextually, but everything else here can't. 5666 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5667 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5668 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5669 5670 // Ignore failures; dropping the entire initializer list because 5671 // of one failure would be terrible for indexing/etc. 5672 if (result.isInvalid()) continue; 5673 5674 InitArgList[I] = result.get(); 5675 } 5676 } 5677 5678 // Semantic analysis for initializers is done by ActOnDeclarator() and 5679 // CheckInitializer() - it requires knowledge of the object being intialized. 5680 5681 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5682 RBraceLoc); 5683 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5684 return E; 5685 } 5686 5687 /// Do an explicit extend of the given block pointer if we're in ARC. 5688 void Sema::maybeExtendBlockObject(ExprResult &E) { 5689 assert(E.get()->getType()->isBlockPointerType()); 5690 assert(E.get()->isRValue()); 5691 5692 // Only do this in an r-value context. 5693 if (!getLangOpts().ObjCAutoRefCount) return; 5694 5695 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5696 CK_ARCExtendBlockObject, E.get(), 5697 /*base path*/ nullptr, VK_RValue); 5698 Cleanup.setExprNeedsCleanups(true); 5699 } 5700 5701 /// Prepare a conversion of the given expression to an ObjC object 5702 /// pointer type. 5703 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5704 QualType type = E.get()->getType(); 5705 if (type->isObjCObjectPointerType()) { 5706 return CK_BitCast; 5707 } else if (type->isBlockPointerType()) { 5708 maybeExtendBlockObject(E); 5709 return CK_BlockPointerToObjCPointerCast; 5710 } else { 5711 assert(type->isPointerType()); 5712 return CK_CPointerToObjCPointerCast; 5713 } 5714 } 5715 5716 /// Prepares for a scalar cast, performing all the necessary stages 5717 /// except the final cast and returning the kind required. 5718 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5719 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5720 // Also, callers should have filtered out the invalid cases with 5721 // pointers. Everything else should be possible. 5722 5723 QualType SrcTy = Src.get()->getType(); 5724 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5725 return CK_NoOp; 5726 5727 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5728 case Type::STK_MemberPointer: 5729 llvm_unreachable("member pointer type in C"); 5730 5731 case Type::STK_CPointer: 5732 case Type::STK_BlockPointer: 5733 case Type::STK_ObjCObjectPointer: 5734 switch (DestTy->getScalarTypeKind()) { 5735 case Type::STK_CPointer: { 5736 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5737 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5738 if (SrcAS != DestAS) 5739 return CK_AddressSpaceConversion; 5740 return CK_BitCast; 5741 } 5742 case Type::STK_BlockPointer: 5743 return (SrcKind == Type::STK_BlockPointer 5744 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5745 case Type::STK_ObjCObjectPointer: 5746 if (SrcKind == Type::STK_ObjCObjectPointer) 5747 return CK_BitCast; 5748 if (SrcKind == Type::STK_CPointer) 5749 return CK_CPointerToObjCPointerCast; 5750 maybeExtendBlockObject(Src); 5751 return CK_BlockPointerToObjCPointerCast; 5752 case Type::STK_Bool: 5753 return CK_PointerToBoolean; 5754 case Type::STK_Integral: 5755 return CK_PointerToIntegral; 5756 case Type::STK_Floating: 5757 case Type::STK_FloatingComplex: 5758 case Type::STK_IntegralComplex: 5759 case Type::STK_MemberPointer: 5760 llvm_unreachable("illegal cast from pointer"); 5761 } 5762 llvm_unreachable("Should have returned before this"); 5763 5764 case Type::STK_Bool: // casting from bool is like casting from an integer 5765 case Type::STK_Integral: 5766 switch (DestTy->getScalarTypeKind()) { 5767 case Type::STK_CPointer: 5768 case Type::STK_ObjCObjectPointer: 5769 case Type::STK_BlockPointer: 5770 if (Src.get()->isNullPointerConstant(Context, 5771 Expr::NPC_ValueDependentIsNull)) 5772 return CK_NullToPointer; 5773 return CK_IntegralToPointer; 5774 case Type::STK_Bool: 5775 return CK_IntegralToBoolean; 5776 case Type::STK_Integral: 5777 return CK_IntegralCast; 5778 case Type::STK_Floating: 5779 return CK_IntegralToFloating; 5780 case Type::STK_IntegralComplex: 5781 Src = ImpCastExprToType(Src.get(), 5782 DestTy->castAs<ComplexType>()->getElementType(), 5783 CK_IntegralCast); 5784 return CK_IntegralRealToComplex; 5785 case Type::STK_FloatingComplex: 5786 Src = ImpCastExprToType(Src.get(), 5787 DestTy->castAs<ComplexType>()->getElementType(), 5788 CK_IntegralToFloating); 5789 return CK_FloatingRealToComplex; 5790 case Type::STK_MemberPointer: 5791 llvm_unreachable("member pointer type in C"); 5792 } 5793 llvm_unreachable("Should have returned before this"); 5794 5795 case Type::STK_Floating: 5796 switch (DestTy->getScalarTypeKind()) { 5797 case Type::STK_Floating: 5798 return CK_FloatingCast; 5799 case Type::STK_Bool: 5800 return CK_FloatingToBoolean; 5801 case Type::STK_Integral: 5802 return CK_FloatingToIntegral; 5803 case Type::STK_FloatingComplex: 5804 Src = ImpCastExprToType(Src.get(), 5805 DestTy->castAs<ComplexType>()->getElementType(), 5806 CK_FloatingCast); 5807 return CK_FloatingRealToComplex; 5808 case Type::STK_IntegralComplex: 5809 Src = ImpCastExprToType(Src.get(), 5810 DestTy->castAs<ComplexType>()->getElementType(), 5811 CK_FloatingToIntegral); 5812 return CK_IntegralRealToComplex; 5813 case Type::STK_CPointer: 5814 case Type::STK_ObjCObjectPointer: 5815 case Type::STK_BlockPointer: 5816 llvm_unreachable("valid float->pointer cast?"); 5817 case Type::STK_MemberPointer: 5818 llvm_unreachable("member pointer type in C"); 5819 } 5820 llvm_unreachable("Should have returned before this"); 5821 5822 case Type::STK_FloatingComplex: 5823 switch (DestTy->getScalarTypeKind()) { 5824 case Type::STK_FloatingComplex: 5825 return CK_FloatingComplexCast; 5826 case Type::STK_IntegralComplex: 5827 return CK_FloatingComplexToIntegralComplex; 5828 case Type::STK_Floating: { 5829 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5830 if (Context.hasSameType(ET, DestTy)) 5831 return CK_FloatingComplexToReal; 5832 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5833 return CK_FloatingCast; 5834 } 5835 case Type::STK_Bool: 5836 return CK_FloatingComplexToBoolean; 5837 case Type::STK_Integral: 5838 Src = ImpCastExprToType(Src.get(), 5839 SrcTy->castAs<ComplexType>()->getElementType(), 5840 CK_FloatingComplexToReal); 5841 return CK_FloatingToIntegral; 5842 case Type::STK_CPointer: 5843 case Type::STK_ObjCObjectPointer: 5844 case Type::STK_BlockPointer: 5845 llvm_unreachable("valid complex float->pointer cast?"); 5846 case Type::STK_MemberPointer: 5847 llvm_unreachable("member pointer type in C"); 5848 } 5849 llvm_unreachable("Should have returned before this"); 5850 5851 case Type::STK_IntegralComplex: 5852 switch (DestTy->getScalarTypeKind()) { 5853 case Type::STK_FloatingComplex: 5854 return CK_IntegralComplexToFloatingComplex; 5855 case Type::STK_IntegralComplex: 5856 return CK_IntegralComplexCast; 5857 case Type::STK_Integral: { 5858 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5859 if (Context.hasSameType(ET, DestTy)) 5860 return CK_IntegralComplexToReal; 5861 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5862 return CK_IntegralCast; 5863 } 5864 case Type::STK_Bool: 5865 return CK_IntegralComplexToBoolean; 5866 case Type::STK_Floating: 5867 Src = ImpCastExprToType(Src.get(), 5868 SrcTy->castAs<ComplexType>()->getElementType(), 5869 CK_IntegralComplexToReal); 5870 return CK_IntegralToFloating; 5871 case Type::STK_CPointer: 5872 case Type::STK_ObjCObjectPointer: 5873 case Type::STK_BlockPointer: 5874 llvm_unreachable("valid complex int->pointer cast?"); 5875 case Type::STK_MemberPointer: 5876 llvm_unreachable("member pointer type in C"); 5877 } 5878 llvm_unreachable("Should have returned before this"); 5879 } 5880 5881 llvm_unreachable("Unhandled scalar cast"); 5882 } 5883 5884 static bool breakDownVectorType(QualType type, uint64_t &len, 5885 QualType &eltType) { 5886 // Vectors are simple. 5887 if (const VectorType *vecType = type->getAs<VectorType>()) { 5888 len = vecType->getNumElements(); 5889 eltType = vecType->getElementType(); 5890 assert(eltType->isScalarType()); 5891 return true; 5892 } 5893 5894 // We allow lax conversion to and from non-vector types, but only if 5895 // they're real types (i.e. non-complex, non-pointer scalar types). 5896 if (!type->isRealType()) return false; 5897 5898 len = 1; 5899 eltType = type; 5900 return true; 5901 } 5902 5903 /// Are the two types lax-compatible vector types? That is, given 5904 /// that one of them is a vector, do they have equal storage sizes, 5905 /// where the storage size is the number of elements times the element 5906 /// size? 5907 /// 5908 /// This will also return false if either of the types is neither a 5909 /// vector nor a real type. 5910 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5911 assert(destTy->isVectorType() || srcTy->isVectorType()); 5912 5913 // Disallow lax conversions between scalars and ExtVectors (these 5914 // conversions are allowed for other vector types because common headers 5915 // depend on them). Most scalar OP ExtVector cases are handled by the 5916 // splat path anyway, which does what we want (convert, not bitcast). 5917 // What this rules out for ExtVectors is crazy things like char4*float. 5918 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5919 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5920 5921 uint64_t srcLen, destLen; 5922 QualType srcEltTy, destEltTy; 5923 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5924 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5925 5926 // ASTContext::getTypeSize will return the size rounded up to a 5927 // power of 2, so instead of using that, we need to use the raw 5928 // element size multiplied by the element count. 5929 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5930 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5931 5932 return (srcLen * srcEltSize == destLen * destEltSize); 5933 } 5934 5935 /// Is this a legal conversion between two types, one of which is 5936 /// known to be a vector type? 5937 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5938 assert(destTy->isVectorType() || srcTy->isVectorType()); 5939 5940 if (!Context.getLangOpts().LaxVectorConversions) 5941 return false; 5942 return areLaxCompatibleVectorTypes(srcTy, destTy); 5943 } 5944 5945 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5946 CastKind &Kind) { 5947 assert(VectorTy->isVectorType() && "Not a vector type!"); 5948 5949 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5950 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5951 return Diag(R.getBegin(), 5952 Ty->isVectorType() ? 5953 diag::err_invalid_conversion_between_vectors : 5954 diag::err_invalid_conversion_between_vector_and_integer) 5955 << VectorTy << Ty << R; 5956 } else 5957 return Diag(R.getBegin(), 5958 diag::err_invalid_conversion_between_vector_and_scalar) 5959 << VectorTy << Ty << R; 5960 5961 Kind = CK_BitCast; 5962 return false; 5963 } 5964 5965 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5966 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5967 5968 if (DestElemTy == SplattedExpr->getType()) 5969 return SplattedExpr; 5970 5971 assert(DestElemTy->isFloatingType() || 5972 DestElemTy->isIntegralOrEnumerationType()); 5973 5974 CastKind CK; 5975 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5976 // OpenCL requires that we convert `true` boolean expressions to -1, but 5977 // only when splatting vectors. 5978 if (DestElemTy->isFloatingType()) { 5979 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5980 // in two steps: boolean to signed integral, then to floating. 5981 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5982 CK_BooleanToSignedIntegral); 5983 SplattedExpr = CastExprRes.get(); 5984 CK = CK_IntegralToFloating; 5985 } else { 5986 CK = CK_BooleanToSignedIntegral; 5987 } 5988 } else { 5989 ExprResult CastExprRes = SplattedExpr; 5990 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5991 if (CastExprRes.isInvalid()) 5992 return ExprError(); 5993 SplattedExpr = CastExprRes.get(); 5994 } 5995 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5996 } 5997 5998 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5999 Expr *CastExpr, CastKind &Kind) { 6000 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6001 6002 QualType SrcTy = CastExpr->getType(); 6003 6004 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6005 // an ExtVectorType. 6006 // In OpenCL, casts between vectors of different types are not allowed. 6007 // (See OpenCL 6.2). 6008 if (SrcTy->isVectorType()) { 6009 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 6010 || (getLangOpts().OpenCL && 6011 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 6012 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6013 << DestTy << SrcTy << R; 6014 return ExprError(); 6015 } 6016 Kind = CK_BitCast; 6017 return CastExpr; 6018 } 6019 6020 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6021 // conversion will take place first from scalar to elt type, and then 6022 // splat from elt type to vector. 6023 if (SrcTy->isPointerType()) 6024 return Diag(R.getBegin(), 6025 diag::err_invalid_conversion_between_vector_and_scalar) 6026 << DestTy << SrcTy << R; 6027 6028 Kind = CK_VectorSplat; 6029 return prepareVectorSplat(DestTy, CastExpr); 6030 } 6031 6032 ExprResult 6033 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6034 Declarator &D, ParsedType &Ty, 6035 SourceLocation RParenLoc, Expr *CastExpr) { 6036 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6037 "ActOnCastExpr(): missing type or expr"); 6038 6039 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6040 if (D.isInvalidType()) 6041 return ExprError(); 6042 6043 if (getLangOpts().CPlusPlus) { 6044 // Check that there are no default arguments (C++ only). 6045 CheckExtraCXXDefaultArguments(D); 6046 } else { 6047 // Make sure any TypoExprs have been dealt with. 6048 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6049 if (!Res.isUsable()) 6050 return ExprError(); 6051 CastExpr = Res.get(); 6052 } 6053 6054 checkUnusedDeclAttributes(D); 6055 6056 QualType castType = castTInfo->getType(); 6057 Ty = CreateParsedType(castType, castTInfo); 6058 6059 bool isVectorLiteral = false; 6060 6061 // Check for an altivec or OpenCL literal, 6062 // i.e. all the elements are integer constants. 6063 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6064 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6065 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6066 && castType->isVectorType() && (PE || PLE)) { 6067 if (PLE && PLE->getNumExprs() == 0) { 6068 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6069 return ExprError(); 6070 } 6071 if (PE || PLE->getNumExprs() == 1) { 6072 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6073 if (!E->getType()->isVectorType()) 6074 isVectorLiteral = true; 6075 } 6076 else 6077 isVectorLiteral = true; 6078 } 6079 6080 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6081 // then handle it as such. 6082 if (isVectorLiteral) 6083 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6084 6085 // If the Expr being casted is a ParenListExpr, handle it specially. 6086 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6087 // sequence of BinOp comma operators. 6088 if (isa<ParenListExpr>(CastExpr)) { 6089 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6090 if (Result.isInvalid()) return ExprError(); 6091 CastExpr = Result.get(); 6092 } 6093 6094 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6095 !getSourceManager().isInSystemMacro(LParenLoc)) 6096 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6097 6098 CheckTollFreeBridgeCast(castType, CastExpr); 6099 6100 CheckObjCBridgeRelatedCast(castType, CastExpr); 6101 6102 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6103 6104 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6105 } 6106 6107 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6108 SourceLocation RParenLoc, Expr *E, 6109 TypeSourceInfo *TInfo) { 6110 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6111 "Expected paren or paren list expression"); 6112 6113 Expr **exprs; 6114 unsigned numExprs; 6115 Expr *subExpr; 6116 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6117 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6118 LiteralLParenLoc = PE->getLParenLoc(); 6119 LiteralRParenLoc = PE->getRParenLoc(); 6120 exprs = PE->getExprs(); 6121 numExprs = PE->getNumExprs(); 6122 } else { // isa<ParenExpr> by assertion at function entrance 6123 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6124 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6125 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6126 exprs = &subExpr; 6127 numExprs = 1; 6128 } 6129 6130 QualType Ty = TInfo->getType(); 6131 assert(Ty->isVectorType() && "Expected vector type"); 6132 6133 SmallVector<Expr *, 8> initExprs; 6134 const VectorType *VTy = Ty->getAs<VectorType>(); 6135 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6136 6137 // '(...)' form of vector initialization in AltiVec: the number of 6138 // initializers must be one or must match the size of the vector. 6139 // If a single value is specified in the initializer then it will be 6140 // replicated to all the components of the vector 6141 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6142 // The number of initializers must be one or must match the size of the 6143 // vector. If a single value is specified in the initializer then it will 6144 // be replicated to all the components of the vector 6145 if (numExprs == 1) { 6146 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6147 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6148 if (Literal.isInvalid()) 6149 return ExprError(); 6150 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6151 PrepareScalarCast(Literal, ElemTy)); 6152 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6153 } 6154 else if (numExprs < numElems) { 6155 Diag(E->getExprLoc(), 6156 diag::err_incorrect_number_of_vector_initializers); 6157 return ExprError(); 6158 } 6159 else 6160 initExprs.append(exprs, exprs + numExprs); 6161 } 6162 else { 6163 // For OpenCL, when the number of initializers is a single value, 6164 // it will be replicated to all components of the vector. 6165 if (getLangOpts().OpenCL && 6166 VTy->getVectorKind() == VectorType::GenericVector && 6167 numExprs == 1) { 6168 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6169 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6170 if (Literal.isInvalid()) 6171 return ExprError(); 6172 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6173 PrepareScalarCast(Literal, ElemTy)); 6174 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6175 } 6176 6177 initExprs.append(exprs, exprs + numExprs); 6178 } 6179 // FIXME: This means that pretty-printing the final AST will produce curly 6180 // braces instead of the original commas. 6181 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6182 initExprs, LiteralRParenLoc); 6183 initE->setType(Ty); 6184 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6185 } 6186 6187 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6188 /// the ParenListExpr into a sequence of comma binary operators. 6189 ExprResult 6190 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6191 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6192 if (!E) 6193 return OrigExpr; 6194 6195 ExprResult Result(E->getExpr(0)); 6196 6197 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6198 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6199 E->getExpr(i)); 6200 6201 if (Result.isInvalid()) return ExprError(); 6202 6203 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6204 } 6205 6206 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6207 SourceLocation R, 6208 MultiExprArg Val) { 6209 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6210 return expr; 6211 } 6212 6213 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6214 /// constant and the other is not a pointer. Returns true if a diagnostic is 6215 /// emitted. 6216 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6217 SourceLocation QuestionLoc) { 6218 Expr *NullExpr = LHSExpr; 6219 Expr *NonPointerExpr = RHSExpr; 6220 Expr::NullPointerConstantKind NullKind = 6221 NullExpr->isNullPointerConstant(Context, 6222 Expr::NPC_ValueDependentIsNotNull); 6223 6224 if (NullKind == Expr::NPCK_NotNull) { 6225 NullExpr = RHSExpr; 6226 NonPointerExpr = LHSExpr; 6227 NullKind = 6228 NullExpr->isNullPointerConstant(Context, 6229 Expr::NPC_ValueDependentIsNotNull); 6230 } 6231 6232 if (NullKind == Expr::NPCK_NotNull) 6233 return false; 6234 6235 if (NullKind == Expr::NPCK_ZeroExpression) 6236 return false; 6237 6238 if (NullKind == Expr::NPCK_ZeroLiteral) { 6239 // In this case, check to make sure that we got here from a "NULL" 6240 // string in the source code. 6241 NullExpr = NullExpr->IgnoreParenImpCasts(); 6242 SourceLocation loc = NullExpr->getExprLoc(); 6243 if (!findMacroSpelling(loc, "NULL")) 6244 return false; 6245 } 6246 6247 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6248 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6249 << NonPointerExpr->getType() << DiagType 6250 << NonPointerExpr->getSourceRange(); 6251 return true; 6252 } 6253 6254 /// \brief Return false if the condition expression is valid, true otherwise. 6255 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6256 QualType CondTy = Cond->getType(); 6257 6258 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6259 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6260 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6261 << CondTy << Cond->getSourceRange(); 6262 return true; 6263 } 6264 6265 // C99 6.5.15p2 6266 if (CondTy->isScalarType()) return false; 6267 6268 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6269 << CondTy << Cond->getSourceRange(); 6270 return true; 6271 } 6272 6273 /// \brief Handle when one or both operands are void type. 6274 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6275 ExprResult &RHS) { 6276 Expr *LHSExpr = LHS.get(); 6277 Expr *RHSExpr = RHS.get(); 6278 6279 if (!LHSExpr->getType()->isVoidType()) 6280 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6281 << RHSExpr->getSourceRange(); 6282 if (!RHSExpr->getType()->isVoidType()) 6283 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6284 << LHSExpr->getSourceRange(); 6285 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6286 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6287 return S.Context.VoidTy; 6288 } 6289 6290 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6291 /// true otherwise. 6292 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6293 QualType PointerTy) { 6294 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6295 !NullExpr.get()->isNullPointerConstant(S.Context, 6296 Expr::NPC_ValueDependentIsNull)) 6297 return true; 6298 6299 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6300 return false; 6301 } 6302 6303 /// \brief Checks compatibility between two pointers and return the resulting 6304 /// type. 6305 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6306 ExprResult &RHS, 6307 SourceLocation Loc) { 6308 QualType LHSTy = LHS.get()->getType(); 6309 QualType RHSTy = RHS.get()->getType(); 6310 6311 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6312 // Two identical pointers types are always compatible. 6313 return LHSTy; 6314 } 6315 6316 QualType lhptee, rhptee; 6317 6318 // Get the pointee types. 6319 bool IsBlockPointer = false; 6320 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6321 lhptee = LHSBTy->getPointeeType(); 6322 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6323 IsBlockPointer = true; 6324 } else { 6325 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6326 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6327 } 6328 6329 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6330 // differently qualified versions of compatible types, the result type is 6331 // a pointer to an appropriately qualified version of the composite 6332 // type. 6333 6334 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6335 // clause doesn't make sense for our extensions. E.g. address space 2 should 6336 // be incompatible with address space 3: they may live on different devices or 6337 // anything. 6338 Qualifiers lhQual = lhptee.getQualifiers(); 6339 Qualifiers rhQual = rhptee.getQualifiers(); 6340 6341 unsigned ResultAddrSpace = 0; 6342 unsigned LAddrSpace = lhQual.getAddressSpace(); 6343 unsigned RAddrSpace = rhQual.getAddressSpace(); 6344 if (S.getLangOpts().OpenCL) { 6345 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6346 // spaces is disallowed. 6347 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6348 ResultAddrSpace = LAddrSpace; 6349 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6350 ResultAddrSpace = RAddrSpace; 6351 else { 6352 S.Diag(Loc, 6353 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6354 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6355 << RHS.get()->getSourceRange(); 6356 return QualType(); 6357 } 6358 } 6359 6360 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6361 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6362 lhQual.removeCVRQualifiers(); 6363 rhQual.removeCVRQualifiers(); 6364 6365 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6366 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6367 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6368 // qual types are compatible iff 6369 // * corresponded types are compatible 6370 // * CVR qualifiers are equal 6371 // * address spaces are equal 6372 // Thus for conditional operator we merge CVR and address space unqualified 6373 // pointees and if there is a composite type we return a pointer to it with 6374 // merged qualifiers. 6375 if (S.getLangOpts().OpenCL) { 6376 LHSCastKind = LAddrSpace == ResultAddrSpace 6377 ? CK_BitCast 6378 : CK_AddressSpaceConversion; 6379 RHSCastKind = RAddrSpace == ResultAddrSpace 6380 ? CK_BitCast 6381 : CK_AddressSpaceConversion; 6382 lhQual.removeAddressSpace(); 6383 rhQual.removeAddressSpace(); 6384 } 6385 6386 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6387 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6388 6389 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6390 6391 if (CompositeTy.isNull()) { 6392 // In this situation, we assume void* type. No especially good 6393 // reason, but this is what gcc does, and we do have to pick 6394 // to get a consistent AST. 6395 QualType incompatTy; 6396 incompatTy = S.Context.getPointerType( 6397 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6398 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6399 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6400 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6401 // for casts between types with incompatible address space qualifiers. 6402 // For the following code the compiler produces casts between global and 6403 // local address spaces of the corresponded innermost pointees: 6404 // local int *global *a; 6405 // global int *global *b; 6406 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6407 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6408 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6409 << RHS.get()->getSourceRange(); 6410 return incompatTy; 6411 } 6412 6413 // The pointer types are compatible. 6414 // In case of OpenCL ResultTy should have the address space qualifier 6415 // which is a superset of address spaces of both the 2nd and the 3rd 6416 // operands of the conditional operator. 6417 QualType ResultTy = [&, ResultAddrSpace]() { 6418 if (S.getLangOpts().OpenCL) { 6419 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6420 CompositeQuals.setAddressSpace(ResultAddrSpace); 6421 return S.Context 6422 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6423 .withCVRQualifiers(MergedCVRQual); 6424 } else 6425 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6426 }(); 6427 if (IsBlockPointer) 6428 ResultTy = S.Context.getBlockPointerType(ResultTy); 6429 else { 6430 ResultTy = S.Context.getPointerType(ResultTy); 6431 } 6432 6433 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6434 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6435 return ResultTy; 6436 } 6437 6438 /// \brief Return the resulting type when the operands are both block pointers. 6439 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6440 ExprResult &LHS, 6441 ExprResult &RHS, 6442 SourceLocation Loc) { 6443 QualType LHSTy = LHS.get()->getType(); 6444 QualType RHSTy = RHS.get()->getType(); 6445 6446 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6447 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6448 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6449 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6450 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6451 return destType; 6452 } 6453 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6454 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6455 << RHS.get()->getSourceRange(); 6456 return QualType(); 6457 } 6458 6459 // We have 2 block pointer types. 6460 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6461 } 6462 6463 /// \brief Return the resulting type when the operands are both pointers. 6464 static QualType 6465 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6466 ExprResult &RHS, 6467 SourceLocation Loc) { 6468 // get the pointer types 6469 QualType LHSTy = LHS.get()->getType(); 6470 QualType RHSTy = RHS.get()->getType(); 6471 6472 // get the "pointed to" types 6473 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6474 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6475 6476 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6477 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6478 // Figure out necessary qualifiers (C99 6.5.15p6) 6479 QualType destPointee 6480 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6481 QualType destType = S.Context.getPointerType(destPointee); 6482 // Add qualifiers if necessary. 6483 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6484 // Promote to void*. 6485 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6486 return destType; 6487 } 6488 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6489 QualType destPointee 6490 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6491 QualType destType = S.Context.getPointerType(destPointee); 6492 // Add qualifiers if necessary. 6493 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6494 // Promote to void*. 6495 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6496 return destType; 6497 } 6498 6499 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6500 } 6501 6502 /// \brief Return false if the first expression is not an integer and the second 6503 /// expression is not a pointer, true otherwise. 6504 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6505 Expr* PointerExpr, SourceLocation Loc, 6506 bool IsIntFirstExpr) { 6507 if (!PointerExpr->getType()->isPointerType() || 6508 !Int.get()->getType()->isIntegerType()) 6509 return false; 6510 6511 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6512 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6513 6514 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6515 << Expr1->getType() << Expr2->getType() 6516 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6517 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6518 CK_IntegralToPointer); 6519 return true; 6520 } 6521 6522 /// \brief Simple conversion between integer and floating point types. 6523 /// 6524 /// Used when handling the OpenCL conditional operator where the 6525 /// condition is a vector while the other operands are scalar. 6526 /// 6527 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6528 /// types are either integer or floating type. Between the two 6529 /// operands, the type with the higher rank is defined as the "result 6530 /// type". The other operand needs to be promoted to the same type. No 6531 /// other type promotion is allowed. We cannot use 6532 /// UsualArithmeticConversions() for this purpose, since it always 6533 /// promotes promotable types. 6534 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6535 ExprResult &RHS, 6536 SourceLocation QuestionLoc) { 6537 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6538 if (LHS.isInvalid()) 6539 return QualType(); 6540 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6541 if (RHS.isInvalid()) 6542 return QualType(); 6543 6544 // For conversion purposes, we ignore any qualifiers. 6545 // For example, "const float" and "float" are equivalent. 6546 QualType LHSType = 6547 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6548 QualType RHSType = 6549 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6550 6551 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6552 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6553 << LHSType << LHS.get()->getSourceRange(); 6554 return QualType(); 6555 } 6556 6557 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6558 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6559 << RHSType << RHS.get()->getSourceRange(); 6560 return QualType(); 6561 } 6562 6563 // If both types are identical, no conversion is needed. 6564 if (LHSType == RHSType) 6565 return LHSType; 6566 6567 // Now handle "real" floating types (i.e. float, double, long double). 6568 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6569 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6570 /*IsCompAssign = */ false); 6571 6572 // Finally, we have two differing integer types. 6573 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6574 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6575 } 6576 6577 /// \brief Convert scalar operands to a vector that matches the 6578 /// condition in length. 6579 /// 6580 /// Used when handling the OpenCL conditional operator where the 6581 /// condition is a vector while the other operands are scalar. 6582 /// 6583 /// We first compute the "result type" for the scalar operands 6584 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6585 /// into a vector of that type where the length matches the condition 6586 /// vector type. s6.11.6 requires that the element types of the result 6587 /// and the condition must have the same number of bits. 6588 static QualType 6589 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6590 QualType CondTy, SourceLocation QuestionLoc) { 6591 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6592 if (ResTy.isNull()) return QualType(); 6593 6594 const VectorType *CV = CondTy->getAs<VectorType>(); 6595 assert(CV); 6596 6597 // Determine the vector result type 6598 unsigned NumElements = CV->getNumElements(); 6599 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6600 6601 // Ensure that all types have the same number of bits 6602 if (S.Context.getTypeSize(CV->getElementType()) 6603 != S.Context.getTypeSize(ResTy)) { 6604 // Since VectorTy is created internally, it does not pretty print 6605 // with an OpenCL name. Instead, we just print a description. 6606 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6607 SmallString<64> Str; 6608 llvm::raw_svector_ostream OS(Str); 6609 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6610 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6611 << CondTy << OS.str(); 6612 return QualType(); 6613 } 6614 6615 // Convert operands to the vector result type 6616 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6617 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6618 6619 return VectorTy; 6620 } 6621 6622 /// \brief Return false if this is a valid OpenCL condition vector 6623 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6624 SourceLocation QuestionLoc) { 6625 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6626 // integral type. 6627 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6628 assert(CondTy); 6629 QualType EleTy = CondTy->getElementType(); 6630 if (EleTy->isIntegerType()) return false; 6631 6632 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6633 << Cond->getType() << Cond->getSourceRange(); 6634 return true; 6635 } 6636 6637 /// \brief Return false if the vector condition type and the vector 6638 /// result type are compatible. 6639 /// 6640 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6641 /// number of elements, and their element types have the same number 6642 /// of bits. 6643 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6644 SourceLocation QuestionLoc) { 6645 const VectorType *CV = CondTy->getAs<VectorType>(); 6646 const VectorType *RV = VecResTy->getAs<VectorType>(); 6647 assert(CV && RV); 6648 6649 if (CV->getNumElements() != RV->getNumElements()) { 6650 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6651 << CondTy << VecResTy; 6652 return true; 6653 } 6654 6655 QualType CVE = CV->getElementType(); 6656 QualType RVE = RV->getElementType(); 6657 6658 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6659 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6660 << CondTy << VecResTy; 6661 return true; 6662 } 6663 6664 return false; 6665 } 6666 6667 /// \brief Return the resulting type for the conditional operator in 6668 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6669 /// s6.3.i) when the condition is a vector type. 6670 static QualType 6671 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6672 ExprResult &LHS, ExprResult &RHS, 6673 SourceLocation QuestionLoc) { 6674 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6675 if (Cond.isInvalid()) 6676 return QualType(); 6677 QualType CondTy = Cond.get()->getType(); 6678 6679 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6680 return QualType(); 6681 6682 // If either operand is a vector then find the vector type of the 6683 // result as specified in OpenCL v1.1 s6.3.i. 6684 if (LHS.get()->getType()->isVectorType() || 6685 RHS.get()->getType()->isVectorType()) { 6686 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6687 /*isCompAssign*/false, 6688 /*AllowBothBool*/true, 6689 /*AllowBoolConversions*/false); 6690 if (VecResTy.isNull()) return QualType(); 6691 // The result type must match the condition type as specified in 6692 // OpenCL v1.1 s6.11.6. 6693 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6694 return QualType(); 6695 return VecResTy; 6696 } 6697 6698 // Both operands are scalar. 6699 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6700 } 6701 6702 /// \brief Return true if the Expr is block type 6703 static bool checkBlockType(Sema &S, const Expr *E) { 6704 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6705 QualType Ty = CE->getCallee()->getType(); 6706 if (Ty->isBlockPointerType()) { 6707 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6708 return true; 6709 } 6710 } 6711 return false; 6712 } 6713 6714 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6715 /// In that case, LHS = cond. 6716 /// C99 6.5.15 6717 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6718 ExprResult &RHS, ExprValueKind &VK, 6719 ExprObjectKind &OK, 6720 SourceLocation QuestionLoc) { 6721 6722 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6723 if (!LHSResult.isUsable()) return QualType(); 6724 LHS = LHSResult; 6725 6726 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6727 if (!RHSResult.isUsable()) return QualType(); 6728 RHS = RHSResult; 6729 6730 // C++ is sufficiently different to merit its own checker. 6731 if (getLangOpts().CPlusPlus) 6732 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6733 6734 VK = VK_RValue; 6735 OK = OK_Ordinary; 6736 6737 // The OpenCL operator with a vector condition is sufficiently 6738 // different to merit its own checker. 6739 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6740 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6741 6742 // First, check the condition. 6743 Cond = UsualUnaryConversions(Cond.get()); 6744 if (Cond.isInvalid()) 6745 return QualType(); 6746 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6747 return QualType(); 6748 6749 // Now check the two expressions. 6750 if (LHS.get()->getType()->isVectorType() || 6751 RHS.get()->getType()->isVectorType()) 6752 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6753 /*AllowBothBool*/true, 6754 /*AllowBoolConversions*/false); 6755 6756 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6757 if (LHS.isInvalid() || RHS.isInvalid()) 6758 return QualType(); 6759 6760 QualType LHSTy = LHS.get()->getType(); 6761 QualType RHSTy = RHS.get()->getType(); 6762 6763 // Diagnose attempts to convert between __float128 and long double where 6764 // such conversions currently can't be handled. 6765 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6766 Diag(QuestionLoc, 6767 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6768 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6769 return QualType(); 6770 } 6771 6772 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6773 // selection operator (?:). 6774 if (getLangOpts().OpenCL && 6775 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6776 return QualType(); 6777 } 6778 6779 // If both operands have arithmetic type, do the usual arithmetic conversions 6780 // to find a common type: C99 6.5.15p3,5. 6781 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6782 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6783 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6784 6785 return ResTy; 6786 } 6787 6788 // If both operands are the same structure or union type, the result is that 6789 // type. 6790 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6791 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6792 if (LHSRT->getDecl() == RHSRT->getDecl()) 6793 // "If both the operands have structure or union type, the result has 6794 // that type." This implies that CV qualifiers are dropped. 6795 return LHSTy.getUnqualifiedType(); 6796 // FIXME: Type of conditional expression must be complete in C mode. 6797 } 6798 6799 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6800 // The following || allows only one side to be void (a GCC-ism). 6801 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6802 return checkConditionalVoidType(*this, LHS, RHS); 6803 } 6804 6805 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6806 // the type of the other operand." 6807 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6808 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6809 6810 // All objective-c pointer type analysis is done here. 6811 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6812 QuestionLoc); 6813 if (LHS.isInvalid() || RHS.isInvalid()) 6814 return QualType(); 6815 if (!compositeType.isNull()) 6816 return compositeType; 6817 6818 6819 // Handle block pointer types. 6820 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6821 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6822 QuestionLoc); 6823 6824 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6825 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6826 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6827 QuestionLoc); 6828 6829 // GCC compatibility: soften pointer/integer mismatch. Note that 6830 // null pointers have been filtered out by this point. 6831 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6832 /*isIntFirstExpr=*/true)) 6833 return RHSTy; 6834 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6835 /*isIntFirstExpr=*/false)) 6836 return LHSTy; 6837 6838 // Emit a better diagnostic if one of the expressions is a null pointer 6839 // constant and the other is not a pointer type. In this case, the user most 6840 // likely forgot to take the address of the other expression. 6841 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6842 return QualType(); 6843 6844 // Otherwise, the operands are not compatible. 6845 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6846 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6847 << RHS.get()->getSourceRange(); 6848 return QualType(); 6849 } 6850 6851 /// FindCompositeObjCPointerType - Helper method to find composite type of 6852 /// two objective-c pointer types of the two input expressions. 6853 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6854 SourceLocation QuestionLoc) { 6855 QualType LHSTy = LHS.get()->getType(); 6856 QualType RHSTy = RHS.get()->getType(); 6857 6858 // Handle things like Class and struct objc_class*. Here we case the result 6859 // to the pseudo-builtin, because that will be implicitly cast back to the 6860 // redefinition type if an attempt is made to access its fields. 6861 if (LHSTy->isObjCClassType() && 6862 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6863 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6864 return LHSTy; 6865 } 6866 if (RHSTy->isObjCClassType() && 6867 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6868 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6869 return RHSTy; 6870 } 6871 // And the same for struct objc_object* / id 6872 if (LHSTy->isObjCIdType() && 6873 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6874 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6875 return LHSTy; 6876 } 6877 if (RHSTy->isObjCIdType() && 6878 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6879 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6880 return RHSTy; 6881 } 6882 // And the same for struct objc_selector* / SEL 6883 if (Context.isObjCSelType(LHSTy) && 6884 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6885 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6886 return LHSTy; 6887 } 6888 if (Context.isObjCSelType(RHSTy) && 6889 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6890 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6891 return RHSTy; 6892 } 6893 // Check constraints for Objective-C object pointers types. 6894 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6895 6896 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6897 // Two identical object pointer types are always compatible. 6898 return LHSTy; 6899 } 6900 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6901 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6902 QualType compositeType = LHSTy; 6903 6904 // If both operands are interfaces and either operand can be 6905 // assigned to the other, use that type as the composite 6906 // type. This allows 6907 // xxx ? (A*) a : (B*) b 6908 // where B is a subclass of A. 6909 // 6910 // Additionally, as for assignment, if either type is 'id' 6911 // allow silent coercion. Finally, if the types are 6912 // incompatible then make sure to use 'id' as the composite 6913 // type so the result is acceptable for sending messages to. 6914 6915 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6916 // It could return the composite type. 6917 if (!(compositeType = 6918 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6919 // Nothing more to do. 6920 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6921 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6922 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6923 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6924 } else if ((LHSTy->isObjCQualifiedIdType() || 6925 RHSTy->isObjCQualifiedIdType()) && 6926 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6927 // Need to handle "id<xx>" explicitly. 6928 // GCC allows qualified id and any Objective-C type to devolve to 6929 // id. Currently localizing to here until clear this should be 6930 // part of ObjCQualifiedIdTypesAreCompatible. 6931 compositeType = Context.getObjCIdType(); 6932 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6933 compositeType = Context.getObjCIdType(); 6934 } else { 6935 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6936 << LHSTy << RHSTy 6937 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6938 QualType incompatTy = Context.getObjCIdType(); 6939 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6940 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6941 return incompatTy; 6942 } 6943 // The object pointer types are compatible. 6944 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6945 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6946 return compositeType; 6947 } 6948 // Check Objective-C object pointer types and 'void *' 6949 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6950 if (getLangOpts().ObjCAutoRefCount) { 6951 // ARC forbids the implicit conversion of object pointers to 'void *', 6952 // so these types are not compatible. 6953 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6954 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6955 LHS = RHS = true; 6956 return QualType(); 6957 } 6958 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6959 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6960 QualType destPointee 6961 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6962 QualType destType = Context.getPointerType(destPointee); 6963 // Add qualifiers if necessary. 6964 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6965 // Promote to void*. 6966 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6967 return destType; 6968 } 6969 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6970 if (getLangOpts().ObjCAutoRefCount) { 6971 // ARC forbids the implicit conversion of object pointers to 'void *', 6972 // so these types are not compatible. 6973 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6974 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6975 LHS = RHS = true; 6976 return QualType(); 6977 } 6978 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6979 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6980 QualType destPointee 6981 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6982 QualType destType = Context.getPointerType(destPointee); 6983 // Add qualifiers if necessary. 6984 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6985 // Promote to void*. 6986 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6987 return destType; 6988 } 6989 return QualType(); 6990 } 6991 6992 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6993 /// ParenRange in parentheses. 6994 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6995 const PartialDiagnostic &Note, 6996 SourceRange ParenRange) { 6997 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6998 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6999 EndLoc.isValid()) { 7000 Self.Diag(Loc, Note) 7001 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7002 << FixItHint::CreateInsertion(EndLoc, ")"); 7003 } else { 7004 // We can't display the parentheses, so just show the bare note. 7005 Self.Diag(Loc, Note) << ParenRange; 7006 } 7007 } 7008 7009 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7010 return BinaryOperator::isAdditiveOp(Opc) || 7011 BinaryOperator::isMultiplicativeOp(Opc) || 7012 BinaryOperator::isShiftOp(Opc); 7013 } 7014 7015 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7016 /// expression, either using a built-in or overloaded operator, 7017 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7018 /// expression. 7019 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7020 Expr **RHSExprs) { 7021 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7022 E = E->IgnoreImpCasts(); 7023 E = E->IgnoreConversionOperator(); 7024 E = E->IgnoreImpCasts(); 7025 7026 // Built-in binary operator. 7027 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7028 if (IsArithmeticOp(OP->getOpcode())) { 7029 *Opcode = OP->getOpcode(); 7030 *RHSExprs = OP->getRHS(); 7031 return true; 7032 } 7033 } 7034 7035 // Overloaded operator. 7036 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7037 if (Call->getNumArgs() != 2) 7038 return false; 7039 7040 // Make sure this is really a binary operator that is safe to pass into 7041 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7042 OverloadedOperatorKind OO = Call->getOperator(); 7043 if (OO < OO_Plus || OO > OO_Arrow || 7044 OO == OO_PlusPlus || OO == OO_MinusMinus) 7045 return false; 7046 7047 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7048 if (IsArithmeticOp(OpKind)) { 7049 *Opcode = OpKind; 7050 *RHSExprs = Call->getArg(1); 7051 return true; 7052 } 7053 } 7054 7055 return false; 7056 } 7057 7058 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7059 /// or is a logical expression such as (x==y) which has int type, but is 7060 /// commonly interpreted as boolean. 7061 static bool ExprLooksBoolean(Expr *E) { 7062 E = E->IgnoreParenImpCasts(); 7063 7064 if (E->getType()->isBooleanType()) 7065 return true; 7066 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7067 return OP->isComparisonOp() || OP->isLogicalOp(); 7068 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7069 return OP->getOpcode() == UO_LNot; 7070 if (E->getType()->isPointerType()) 7071 return true; 7072 7073 return false; 7074 } 7075 7076 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7077 /// and binary operator are mixed in a way that suggests the programmer assumed 7078 /// the conditional operator has higher precedence, for example: 7079 /// "int x = a + someBinaryCondition ? 1 : 2". 7080 static void DiagnoseConditionalPrecedence(Sema &Self, 7081 SourceLocation OpLoc, 7082 Expr *Condition, 7083 Expr *LHSExpr, 7084 Expr *RHSExpr) { 7085 BinaryOperatorKind CondOpcode; 7086 Expr *CondRHS; 7087 7088 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7089 return; 7090 if (!ExprLooksBoolean(CondRHS)) 7091 return; 7092 7093 // The condition is an arithmetic binary expression, with a right- 7094 // hand side that looks boolean, so warn. 7095 7096 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7097 << Condition->getSourceRange() 7098 << BinaryOperator::getOpcodeStr(CondOpcode); 7099 7100 SuggestParentheses(Self, OpLoc, 7101 Self.PDiag(diag::note_precedence_silence) 7102 << BinaryOperator::getOpcodeStr(CondOpcode), 7103 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7104 7105 SuggestParentheses(Self, OpLoc, 7106 Self.PDiag(diag::note_precedence_conditional_first), 7107 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7108 } 7109 7110 /// Compute the nullability of a conditional expression. 7111 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7112 QualType LHSTy, QualType RHSTy, 7113 ASTContext &Ctx) { 7114 if (!ResTy->isAnyPointerType()) 7115 return ResTy; 7116 7117 auto GetNullability = [&Ctx](QualType Ty) { 7118 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7119 if (Kind) 7120 return *Kind; 7121 return NullabilityKind::Unspecified; 7122 }; 7123 7124 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7125 NullabilityKind MergedKind; 7126 7127 // Compute nullability of a binary conditional expression. 7128 if (IsBin) { 7129 if (LHSKind == NullabilityKind::NonNull) 7130 MergedKind = NullabilityKind::NonNull; 7131 else 7132 MergedKind = RHSKind; 7133 // Compute nullability of a normal conditional expression. 7134 } else { 7135 if (LHSKind == NullabilityKind::Nullable || 7136 RHSKind == NullabilityKind::Nullable) 7137 MergedKind = NullabilityKind::Nullable; 7138 else if (LHSKind == NullabilityKind::NonNull) 7139 MergedKind = RHSKind; 7140 else if (RHSKind == NullabilityKind::NonNull) 7141 MergedKind = LHSKind; 7142 else 7143 MergedKind = NullabilityKind::Unspecified; 7144 } 7145 7146 // Return if ResTy already has the correct nullability. 7147 if (GetNullability(ResTy) == MergedKind) 7148 return ResTy; 7149 7150 // Strip all nullability from ResTy. 7151 while (ResTy->getNullability(Ctx)) 7152 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7153 7154 // Create a new AttributedType with the new nullability kind. 7155 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7156 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7157 } 7158 7159 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7160 /// in the case of a the GNU conditional expr extension. 7161 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7162 SourceLocation ColonLoc, 7163 Expr *CondExpr, Expr *LHSExpr, 7164 Expr *RHSExpr) { 7165 if (!getLangOpts().CPlusPlus) { 7166 // C cannot handle TypoExpr nodes in the condition because it 7167 // doesn't handle dependent types properly, so make sure any TypoExprs have 7168 // been dealt with before checking the operands. 7169 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7170 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7171 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7172 7173 if (!CondResult.isUsable()) 7174 return ExprError(); 7175 7176 if (LHSExpr) { 7177 if (!LHSResult.isUsable()) 7178 return ExprError(); 7179 } 7180 7181 if (!RHSResult.isUsable()) 7182 return ExprError(); 7183 7184 CondExpr = CondResult.get(); 7185 LHSExpr = LHSResult.get(); 7186 RHSExpr = RHSResult.get(); 7187 } 7188 7189 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7190 // was the condition. 7191 OpaqueValueExpr *opaqueValue = nullptr; 7192 Expr *commonExpr = nullptr; 7193 if (!LHSExpr) { 7194 commonExpr = CondExpr; 7195 // Lower out placeholder types first. This is important so that we don't 7196 // try to capture a placeholder. This happens in few cases in C++; such 7197 // as Objective-C++'s dictionary subscripting syntax. 7198 if (commonExpr->hasPlaceholderType()) { 7199 ExprResult result = CheckPlaceholderExpr(commonExpr); 7200 if (!result.isUsable()) return ExprError(); 7201 commonExpr = result.get(); 7202 } 7203 // We usually want to apply unary conversions *before* saving, except 7204 // in the special case of a C++ l-value conditional. 7205 if (!(getLangOpts().CPlusPlus 7206 && !commonExpr->isTypeDependent() 7207 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7208 && commonExpr->isGLValue() 7209 && commonExpr->isOrdinaryOrBitFieldObject() 7210 && RHSExpr->isOrdinaryOrBitFieldObject() 7211 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7212 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7213 if (commonRes.isInvalid()) 7214 return ExprError(); 7215 commonExpr = commonRes.get(); 7216 } 7217 7218 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7219 commonExpr->getType(), 7220 commonExpr->getValueKind(), 7221 commonExpr->getObjectKind(), 7222 commonExpr); 7223 LHSExpr = CondExpr = opaqueValue; 7224 } 7225 7226 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7227 ExprValueKind VK = VK_RValue; 7228 ExprObjectKind OK = OK_Ordinary; 7229 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7230 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7231 VK, OK, QuestionLoc); 7232 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7233 RHS.isInvalid()) 7234 return ExprError(); 7235 7236 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7237 RHS.get()); 7238 7239 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7240 7241 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7242 Context); 7243 7244 if (!commonExpr) 7245 return new (Context) 7246 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7247 RHS.get(), result, VK, OK); 7248 7249 return new (Context) BinaryConditionalOperator( 7250 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7251 ColonLoc, result, VK, OK); 7252 } 7253 7254 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7255 // being closely modeled after the C99 spec:-). The odd characteristic of this 7256 // routine is it effectively iqnores the qualifiers on the top level pointee. 7257 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7258 // FIXME: add a couple examples in this comment. 7259 static Sema::AssignConvertType 7260 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7261 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7262 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7263 7264 // get the "pointed to" type (ignoring qualifiers at the top level) 7265 const Type *lhptee, *rhptee; 7266 Qualifiers lhq, rhq; 7267 std::tie(lhptee, lhq) = 7268 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7269 std::tie(rhptee, rhq) = 7270 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7271 7272 Sema::AssignConvertType ConvTy = Sema::Compatible; 7273 7274 // C99 6.5.16.1p1: This following citation is common to constraints 7275 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7276 // qualifiers of the type *pointed to* by the right; 7277 7278 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7279 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7280 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7281 // Ignore lifetime for further calculation. 7282 lhq.removeObjCLifetime(); 7283 rhq.removeObjCLifetime(); 7284 } 7285 7286 if (!lhq.compatiblyIncludes(rhq)) { 7287 // Treat address-space mismatches as fatal. TODO: address subspaces 7288 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7289 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7290 7291 // It's okay to add or remove GC or lifetime qualifiers when converting to 7292 // and from void*. 7293 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7294 .compatiblyIncludes( 7295 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7296 && (lhptee->isVoidType() || rhptee->isVoidType())) 7297 ; // keep old 7298 7299 // Treat lifetime mismatches as fatal. 7300 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7301 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7302 7303 // For GCC/MS compatibility, other qualifier mismatches are treated 7304 // as still compatible in C. 7305 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7306 } 7307 7308 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7309 // incomplete type and the other is a pointer to a qualified or unqualified 7310 // version of void... 7311 if (lhptee->isVoidType()) { 7312 if (rhptee->isIncompleteOrObjectType()) 7313 return ConvTy; 7314 7315 // As an extension, we allow cast to/from void* to function pointer. 7316 assert(rhptee->isFunctionType()); 7317 return Sema::FunctionVoidPointer; 7318 } 7319 7320 if (rhptee->isVoidType()) { 7321 if (lhptee->isIncompleteOrObjectType()) 7322 return ConvTy; 7323 7324 // As an extension, we allow cast to/from void* to function pointer. 7325 assert(lhptee->isFunctionType()); 7326 return Sema::FunctionVoidPointer; 7327 } 7328 7329 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7330 // unqualified versions of compatible types, ... 7331 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7332 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7333 // Check if the pointee types are compatible ignoring the sign. 7334 // We explicitly check for char so that we catch "char" vs 7335 // "unsigned char" on systems where "char" is unsigned. 7336 if (lhptee->isCharType()) 7337 ltrans = S.Context.UnsignedCharTy; 7338 else if (lhptee->hasSignedIntegerRepresentation()) 7339 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7340 7341 if (rhptee->isCharType()) 7342 rtrans = S.Context.UnsignedCharTy; 7343 else if (rhptee->hasSignedIntegerRepresentation()) 7344 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7345 7346 if (ltrans == rtrans) { 7347 // Types are compatible ignoring the sign. Qualifier incompatibility 7348 // takes priority over sign incompatibility because the sign 7349 // warning can be disabled. 7350 if (ConvTy != Sema::Compatible) 7351 return ConvTy; 7352 7353 return Sema::IncompatiblePointerSign; 7354 } 7355 7356 // If we are a multi-level pointer, it's possible that our issue is simply 7357 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7358 // the eventual target type is the same and the pointers have the same 7359 // level of indirection, this must be the issue. 7360 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7361 do { 7362 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7363 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7364 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7365 7366 if (lhptee == rhptee) 7367 return Sema::IncompatibleNestedPointerQualifiers; 7368 } 7369 7370 // General pointer incompatibility takes priority over qualifiers. 7371 return Sema::IncompatiblePointer; 7372 } 7373 if (!S.getLangOpts().CPlusPlus && 7374 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7375 return Sema::IncompatiblePointer; 7376 return ConvTy; 7377 } 7378 7379 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7380 /// block pointer types are compatible or whether a block and normal pointer 7381 /// are compatible. It is more restrict than comparing two function pointer 7382 // types. 7383 static Sema::AssignConvertType 7384 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7385 QualType RHSType) { 7386 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7387 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7388 7389 QualType lhptee, rhptee; 7390 7391 // get the "pointed to" type (ignoring qualifiers at the top level) 7392 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7393 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7394 7395 // In C++, the types have to match exactly. 7396 if (S.getLangOpts().CPlusPlus) 7397 return Sema::IncompatibleBlockPointer; 7398 7399 Sema::AssignConvertType ConvTy = Sema::Compatible; 7400 7401 // For blocks we enforce that qualifiers are identical. 7402 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7403 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7404 if (S.getLangOpts().OpenCL) { 7405 LQuals.removeAddressSpace(); 7406 RQuals.removeAddressSpace(); 7407 } 7408 if (LQuals != RQuals) 7409 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7410 7411 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7412 // assignment. 7413 // The current behavior is similar to C++ lambdas. A block might be 7414 // assigned to a variable iff its return type and parameters are compatible 7415 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7416 // an assignment. Presumably it should behave in way that a function pointer 7417 // assignment does in C, so for each parameter and return type: 7418 // * CVR and address space of LHS should be a superset of CVR and address 7419 // space of RHS. 7420 // * unqualified types should be compatible. 7421 if (S.getLangOpts().OpenCL) { 7422 if (!S.Context.typesAreBlockPointerCompatible( 7423 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7424 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7425 return Sema::IncompatibleBlockPointer; 7426 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7427 return Sema::IncompatibleBlockPointer; 7428 7429 return ConvTy; 7430 } 7431 7432 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7433 /// for assignment compatibility. 7434 static Sema::AssignConvertType 7435 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7436 QualType RHSType) { 7437 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7438 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7439 7440 if (LHSType->isObjCBuiltinType()) { 7441 // Class is not compatible with ObjC object pointers. 7442 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7443 !RHSType->isObjCQualifiedClassType()) 7444 return Sema::IncompatiblePointer; 7445 return Sema::Compatible; 7446 } 7447 if (RHSType->isObjCBuiltinType()) { 7448 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7449 !LHSType->isObjCQualifiedClassType()) 7450 return Sema::IncompatiblePointer; 7451 return Sema::Compatible; 7452 } 7453 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7454 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7455 7456 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7457 // make an exception for id<P> 7458 !LHSType->isObjCQualifiedIdType()) 7459 return Sema::CompatiblePointerDiscardsQualifiers; 7460 7461 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7462 return Sema::Compatible; 7463 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7464 return Sema::IncompatibleObjCQualifiedId; 7465 return Sema::IncompatiblePointer; 7466 } 7467 7468 Sema::AssignConvertType 7469 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7470 QualType LHSType, QualType RHSType) { 7471 // Fake up an opaque expression. We don't actually care about what 7472 // cast operations are required, so if CheckAssignmentConstraints 7473 // adds casts to this they'll be wasted, but fortunately that doesn't 7474 // usually happen on valid code. 7475 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7476 ExprResult RHSPtr = &RHSExpr; 7477 CastKind K = CK_Invalid; 7478 7479 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7480 } 7481 7482 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7483 /// has code to accommodate several GCC extensions when type checking 7484 /// pointers. Here are some objectionable examples that GCC considers warnings: 7485 /// 7486 /// int a, *pint; 7487 /// short *pshort; 7488 /// struct foo *pfoo; 7489 /// 7490 /// pint = pshort; // warning: assignment from incompatible pointer type 7491 /// a = pint; // warning: assignment makes integer from pointer without a cast 7492 /// pint = a; // warning: assignment makes pointer from integer without a cast 7493 /// pint = pfoo; // warning: assignment from incompatible pointer type 7494 /// 7495 /// As a result, the code for dealing with pointers is more complex than the 7496 /// C99 spec dictates. 7497 /// 7498 /// Sets 'Kind' for any result kind except Incompatible. 7499 Sema::AssignConvertType 7500 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7501 CastKind &Kind, bool ConvertRHS) { 7502 QualType RHSType = RHS.get()->getType(); 7503 QualType OrigLHSType = LHSType; 7504 7505 // Get canonical types. We're not formatting these types, just comparing 7506 // them. 7507 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7508 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7509 7510 // Common case: no conversion required. 7511 if (LHSType == RHSType) { 7512 Kind = CK_NoOp; 7513 return Compatible; 7514 } 7515 7516 // If we have an atomic type, try a non-atomic assignment, then just add an 7517 // atomic qualification step. 7518 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7519 Sema::AssignConvertType result = 7520 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7521 if (result != Compatible) 7522 return result; 7523 if (Kind != CK_NoOp && ConvertRHS) 7524 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7525 Kind = CK_NonAtomicToAtomic; 7526 return Compatible; 7527 } 7528 7529 // If the left-hand side is a reference type, then we are in a 7530 // (rare!) case where we've allowed the use of references in C, 7531 // e.g., as a parameter type in a built-in function. In this case, 7532 // just make sure that the type referenced is compatible with the 7533 // right-hand side type. The caller is responsible for adjusting 7534 // LHSType so that the resulting expression does not have reference 7535 // type. 7536 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7537 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7538 Kind = CK_LValueBitCast; 7539 return Compatible; 7540 } 7541 return Incompatible; 7542 } 7543 7544 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7545 // to the same ExtVector type. 7546 if (LHSType->isExtVectorType()) { 7547 if (RHSType->isExtVectorType()) 7548 return Incompatible; 7549 if (RHSType->isArithmeticType()) { 7550 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7551 if (ConvertRHS) 7552 RHS = prepareVectorSplat(LHSType, RHS.get()); 7553 Kind = CK_VectorSplat; 7554 return Compatible; 7555 } 7556 } 7557 7558 // Conversions to or from vector type. 7559 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7560 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7561 // Allow assignments of an AltiVec vector type to an equivalent GCC 7562 // vector type and vice versa 7563 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7564 Kind = CK_BitCast; 7565 return Compatible; 7566 } 7567 7568 // If we are allowing lax vector conversions, and LHS and RHS are both 7569 // vectors, the total size only needs to be the same. This is a bitcast; 7570 // no bits are changed but the result type is different. 7571 if (isLaxVectorConversion(RHSType, LHSType)) { 7572 Kind = CK_BitCast; 7573 return IncompatibleVectors; 7574 } 7575 } 7576 7577 // When the RHS comes from another lax conversion (e.g. binops between 7578 // scalars and vectors) the result is canonicalized as a vector. When the 7579 // LHS is also a vector, the lax is allowed by the condition above. Handle 7580 // the case where LHS is a scalar. 7581 if (LHSType->isScalarType()) { 7582 const VectorType *VecType = RHSType->getAs<VectorType>(); 7583 if (VecType && VecType->getNumElements() == 1 && 7584 isLaxVectorConversion(RHSType, LHSType)) { 7585 ExprResult *VecExpr = &RHS; 7586 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7587 Kind = CK_BitCast; 7588 return Compatible; 7589 } 7590 } 7591 7592 return Incompatible; 7593 } 7594 7595 // Diagnose attempts to convert between __float128 and long double where 7596 // such conversions currently can't be handled. 7597 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7598 return Incompatible; 7599 7600 // Arithmetic conversions. 7601 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7602 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7603 if (ConvertRHS) 7604 Kind = PrepareScalarCast(RHS, LHSType); 7605 return Compatible; 7606 } 7607 7608 // Conversions to normal pointers. 7609 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7610 // U* -> T* 7611 if (isa<PointerType>(RHSType)) { 7612 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7613 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7614 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7615 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7616 } 7617 7618 // int -> T* 7619 if (RHSType->isIntegerType()) { 7620 Kind = CK_IntegralToPointer; // FIXME: null? 7621 return IntToPointer; 7622 } 7623 7624 // C pointers are not compatible with ObjC object pointers, 7625 // with two exceptions: 7626 if (isa<ObjCObjectPointerType>(RHSType)) { 7627 // - conversions to void* 7628 if (LHSPointer->getPointeeType()->isVoidType()) { 7629 Kind = CK_BitCast; 7630 return Compatible; 7631 } 7632 7633 // - conversions from 'Class' to the redefinition type 7634 if (RHSType->isObjCClassType() && 7635 Context.hasSameType(LHSType, 7636 Context.getObjCClassRedefinitionType())) { 7637 Kind = CK_BitCast; 7638 return Compatible; 7639 } 7640 7641 Kind = CK_BitCast; 7642 return IncompatiblePointer; 7643 } 7644 7645 // U^ -> void* 7646 if (RHSType->getAs<BlockPointerType>()) { 7647 if (LHSPointer->getPointeeType()->isVoidType()) { 7648 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7649 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7650 ->getPointeeType() 7651 .getAddressSpace(); 7652 Kind = 7653 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7654 return Compatible; 7655 } 7656 } 7657 7658 return Incompatible; 7659 } 7660 7661 // Conversions to block pointers. 7662 if (isa<BlockPointerType>(LHSType)) { 7663 // U^ -> T^ 7664 if (RHSType->isBlockPointerType()) { 7665 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>() 7666 ->getPointeeType() 7667 .getAddressSpace(); 7668 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7669 ->getPointeeType() 7670 .getAddressSpace(); 7671 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7672 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7673 } 7674 7675 // int or null -> T^ 7676 if (RHSType->isIntegerType()) { 7677 Kind = CK_IntegralToPointer; // FIXME: null 7678 return IntToBlockPointer; 7679 } 7680 7681 // id -> T^ 7682 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7683 Kind = CK_AnyPointerToBlockPointerCast; 7684 return Compatible; 7685 } 7686 7687 // void* -> T^ 7688 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7689 if (RHSPT->getPointeeType()->isVoidType()) { 7690 Kind = CK_AnyPointerToBlockPointerCast; 7691 return Compatible; 7692 } 7693 7694 return Incompatible; 7695 } 7696 7697 // Conversions to Objective-C pointers. 7698 if (isa<ObjCObjectPointerType>(LHSType)) { 7699 // A* -> B* 7700 if (RHSType->isObjCObjectPointerType()) { 7701 Kind = CK_BitCast; 7702 Sema::AssignConvertType result = 7703 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7704 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7705 result == Compatible && 7706 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7707 result = IncompatibleObjCWeakRef; 7708 return result; 7709 } 7710 7711 // int or null -> A* 7712 if (RHSType->isIntegerType()) { 7713 Kind = CK_IntegralToPointer; // FIXME: null 7714 return IntToPointer; 7715 } 7716 7717 // In general, C pointers are not compatible with ObjC object pointers, 7718 // with two exceptions: 7719 if (isa<PointerType>(RHSType)) { 7720 Kind = CK_CPointerToObjCPointerCast; 7721 7722 // - conversions from 'void*' 7723 if (RHSType->isVoidPointerType()) { 7724 return Compatible; 7725 } 7726 7727 // - conversions to 'Class' from its redefinition type 7728 if (LHSType->isObjCClassType() && 7729 Context.hasSameType(RHSType, 7730 Context.getObjCClassRedefinitionType())) { 7731 return Compatible; 7732 } 7733 7734 return IncompatiblePointer; 7735 } 7736 7737 // Only under strict condition T^ is compatible with an Objective-C pointer. 7738 if (RHSType->isBlockPointerType() && 7739 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7740 if (ConvertRHS) 7741 maybeExtendBlockObject(RHS); 7742 Kind = CK_BlockPointerToObjCPointerCast; 7743 return Compatible; 7744 } 7745 7746 return Incompatible; 7747 } 7748 7749 // Conversions from pointers that are not covered by the above. 7750 if (isa<PointerType>(RHSType)) { 7751 // T* -> _Bool 7752 if (LHSType == Context.BoolTy) { 7753 Kind = CK_PointerToBoolean; 7754 return Compatible; 7755 } 7756 7757 // T* -> int 7758 if (LHSType->isIntegerType()) { 7759 Kind = CK_PointerToIntegral; 7760 return PointerToInt; 7761 } 7762 7763 return Incompatible; 7764 } 7765 7766 // Conversions from Objective-C pointers that are not covered by the above. 7767 if (isa<ObjCObjectPointerType>(RHSType)) { 7768 // T* -> _Bool 7769 if (LHSType == Context.BoolTy) { 7770 Kind = CK_PointerToBoolean; 7771 return Compatible; 7772 } 7773 7774 // T* -> int 7775 if (LHSType->isIntegerType()) { 7776 Kind = CK_PointerToIntegral; 7777 return PointerToInt; 7778 } 7779 7780 return Incompatible; 7781 } 7782 7783 // struct A -> struct B 7784 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7785 if (Context.typesAreCompatible(LHSType, RHSType)) { 7786 Kind = CK_NoOp; 7787 return Compatible; 7788 } 7789 } 7790 7791 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7792 Kind = CK_IntToOCLSampler; 7793 return Compatible; 7794 } 7795 7796 return Incompatible; 7797 } 7798 7799 /// \brief Constructs a transparent union from an expression that is 7800 /// used to initialize the transparent union. 7801 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7802 ExprResult &EResult, QualType UnionType, 7803 FieldDecl *Field) { 7804 // Build an initializer list that designates the appropriate member 7805 // of the transparent union. 7806 Expr *E = EResult.get(); 7807 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7808 E, SourceLocation()); 7809 Initializer->setType(UnionType); 7810 Initializer->setInitializedFieldInUnion(Field); 7811 7812 // Build a compound literal constructing a value of the transparent 7813 // union type from this initializer list. 7814 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7815 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7816 VK_RValue, Initializer, false); 7817 } 7818 7819 Sema::AssignConvertType 7820 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7821 ExprResult &RHS) { 7822 QualType RHSType = RHS.get()->getType(); 7823 7824 // If the ArgType is a Union type, we want to handle a potential 7825 // transparent_union GCC extension. 7826 const RecordType *UT = ArgType->getAsUnionType(); 7827 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7828 return Incompatible; 7829 7830 // The field to initialize within the transparent union. 7831 RecordDecl *UD = UT->getDecl(); 7832 FieldDecl *InitField = nullptr; 7833 // It's compatible if the expression matches any of the fields. 7834 for (auto *it : UD->fields()) { 7835 if (it->getType()->isPointerType()) { 7836 // If the transparent union contains a pointer type, we allow: 7837 // 1) void pointer 7838 // 2) null pointer constant 7839 if (RHSType->isPointerType()) 7840 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7841 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7842 InitField = it; 7843 break; 7844 } 7845 7846 if (RHS.get()->isNullPointerConstant(Context, 7847 Expr::NPC_ValueDependentIsNull)) { 7848 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7849 CK_NullToPointer); 7850 InitField = it; 7851 break; 7852 } 7853 } 7854 7855 CastKind Kind = CK_Invalid; 7856 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7857 == Compatible) { 7858 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7859 InitField = it; 7860 break; 7861 } 7862 } 7863 7864 if (!InitField) 7865 return Incompatible; 7866 7867 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7868 return Compatible; 7869 } 7870 7871 Sema::AssignConvertType 7872 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7873 bool Diagnose, 7874 bool DiagnoseCFAudited, 7875 bool ConvertRHS) { 7876 // We need to be able to tell the caller whether we diagnosed a problem, if 7877 // they ask us to issue diagnostics. 7878 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7879 7880 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7881 // we can't avoid *all* modifications at the moment, so we need some somewhere 7882 // to put the updated value. 7883 ExprResult LocalRHS = CallerRHS; 7884 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7885 7886 if (getLangOpts().CPlusPlus) { 7887 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7888 // C++ 5.17p3: If the left operand is not of class type, the 7889 // expression is implicitly converted (C++ 4) to the 7890 // cv-unqualified type of the left operand. 7891 QualType RHSType = RHS.get()->getType(); 7892 if (Diagnose) { 7893 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7894 AA_Assigning); 7895 } else { 7896 ImplicitConversionSequence ICS = 7897 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7898 /*SuppressUserConversions=*/false, 7899 /*AllowExplicit=*/false, 7900 /*InOverloadResolution=*/false, 7901 /*CStyle=*/false, 7902 /*AllowObjCWritebackConversion=*/false); 7903 if (ICS.isFailure()) 7904 return Incompatible; 7905 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7906 ICS, AA_Assigning); 7907 } 7908 if (RHS.isInvalid()) 7909 return Incompatible; 7910 Sema::AssignConvertType result = Compatible; 7911 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7912 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7913 result = IncompatibleObjCWeakRef; 7914 return result; 7915 } 7916 7917 // FIXME: Currently, we fall through and treat C++ classes like C 7918 // structures. 7919 // FIXME: We also fall through for atomics; not sure what should 7920 // happen there, though. 7921 } else if (RHS.get()->getType() == Context.OverloadTy) { 7922 // As a set of extensions to C, we support overloading on functions. These 7923 // functions need to be resolved here. 7924 DeclAccessPair DAP; 7925 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7926 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7927 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7928 else 7929 return Incompatible; 7930 } 7931 7932 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7933 // a null pointer constant. 7934 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7935 LHSType->isBlockPointerType()) && 7936 RHS.get()->isNullPointerConstant(Context, 7937 Expr::NPC_ValueDependentIsNull)) { 7938 if (Diagnose || ConvertRHS) { 7939 CastKind Kind; 7940 CXXCastPath Path; 7941 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7942 /*IgnoreBaseAccess=*/false, Diagnose); 7943 if (ConvertRHS) 7944 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7945 } 7946 return Compatible; 7947 } 7948 7949 // This check seems unnatural, however it is necessary to ensure the proper 7950 // conversion of functions/arrays. If the conversion were done for all 7951 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7952 // expressions that suppress this implicit conversion (&, sizeof). 7953 // 7954 // Suppress this for references: C++ 8.5.3p5. 7955 if (!LHSType->isReferenceType()) { 7956 // FIXME: We potentially allocate here even if ConvertRHS is false. 7957 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7958 if (RHS.isInvalid()) 7959 return Incompatible; 7960 } 7961 7962 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7963 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7964 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7965 if (PDecl && !PDecl->hasDefinition()) { 7966 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7967 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7968 } 7969 } 7970 7971 CastKind Kind = CK_Invalid; 7972 Sema::AssignConvertType result = 7973 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7974 7975 // C99 6.5.16.1p2: The value of the right operand is converted to the 7976 // type of the assignment expression. 7977 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7978 // so that we can use references in built-in functions even in C. 7979 // The getNonReferenceType() call makes sure that the resulting expression 7980 // does not have reference type. 7981 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7982 QualType Ty = LHSType.getNonLValueExprType(Context); 7983 Expr *E = RHS.get(); 7984 7985 // Check for various Objective-C errors. If we are not reporting 7986 // diagnostics and just checking for errors, e.g., during overload 7987 // resolution, return Incompatible to indicate the failure. 7988 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7989 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7990 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7991 if (!Diagnose) 7992 return Incompatible; 7993 } 7994 if (getLangOpts().ObjC1 && 7995 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7996 E->getType(), E, Diagnose) || 7997 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7998 if (!Diagnose) 7999 return Incompatible; 8000 // Replace the expression with a corrected version and continue so we 8001 // can find further errors. 8002 RHS = E; 8003 return Compatible; 8004 } 8005 8006 if (ConvertRHS) 8007 RHS = ImpCastExprToType(E, Ty, Kind); 8008 } 8009 return result; 8010 } 8011 8012 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8013 ExprResult &RHS) { 8014 Diag(Loc, diag::err_typecheck_invalid_operands) 8015 << LHS.get()->getType() << RHS.get()->getType() 8016 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8017 return QualType(); 8018 } 8019 8020 /// Try to convert a value of non-vector type to a vector type by converting 8021 /// the type to the element type of the vector and then performing a splat. 8022 /// If the language is OpenCL, we only use conversions that promote scalar 8023 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8024 /// for float->int. 8025 /// 8026 /// \param scalar - if non-null, actually perform the conversions 8027 /// \return true if the operation fails (but without diagnosing the failure) 8028 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8029 QualType scalarTy, 8030 QualType vectorEltTy, 8031 QualType vectorTy) { 8032 // The conversion to apply to the scalar before splatting it, 8033 // if necessary. 8034 CastKind scalarCast = CK_Invalid; 8035 8036 if (vectorEltTy->isIntegralType(S.Context)) { 8037 if (!scalarTy->isIntegralType(S.Context)) 8038 return true; 8039 if (S.getLangOpts().OpenCL && 8040 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 8041 return true; 8042 scalarCast = CK_IntegralCast; 8043 } else if (vectorEltTy->isRealFloatingType()) { 8044 if (scalarTy->isRealFloatingType()) { 8045 if (S.getLangOpts().OpenCL && 8046 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 8047 return true; 8048 scalarCast = CK_FloatingCast; 8049 } 8050 else if (scalarTy->isIntegralType(S.Context)) 8051 scalarCast = CK_IntegralToFloating; 8052 else 8053 return true; 8054 } else { 8055 return true; 8056 } 8057 8058 // Adjust scalar if desired. 8059 if (scalar) { 8060 if (scalarCast != CK_Invalid) 8061 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8062 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8063 } 8064 return false; 8065 } 8066 8067 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8068 SourceLocation Loc, bool IsCompAssign, 8069 bool AllowBothBool, 8070 bool AllowBoolConversions) { 8071 if (!IsCompAssign) { 8072 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8073 if (LHS.isInvalid()) 8074 return QualType(); 8075 } 8076 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8077 if (RHS.isInvalid()) 8078 return QualType(); 8079 8080 // For conversion purposes, we ignore any qualifiers. 8081 // For example, "const float" and "float" are equivalent. 8082 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8083 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8084 8085 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8086 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8087 assert(LHSVecType || RHSVecType); 8088 8089 // AltiVec-style "vector bool op vector bool" combinations are allowed 8090 // for some operators but not others. 8091 if (!AllowBothBool && 8092 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8093 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8094 return InvalidOperands(Loc, LHS, RHS); 8095 8096 // If the vector types are identical, return. 8097 if (Context.hasSameType(LHSType, RHSType)) 8098 return LHSType; 8099 8100 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8101 if (LHSVecType && RHSVecType && 8102 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8103 if (isa<ExtVectorType>(LHSVecType)) { 8104 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8105 return LHSType; 8106 } 8107 8108 if (!IsCompAssign) 8109 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8110 return RHSType; 8111 } 8112 8113 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8114 // can be mixed, with the result being the non-bool type. The non-bool 8115 // operand must have integer element type. 8116 if (AllowBoolConversions && LHSVecType && RHSVecType && 8117 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8118 (Context.getTypeSize(LHSVecType->getElementType()) == 8119 Context.getTypeSize(RHSVecType->getElementType()))) { 8120 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8121 LHSVecType->getElementType()->isIntegerType() && 8122 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8123 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8124 return LHSType; 8125 } 8126 if (!IsCompAssign && 8127 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8128 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8129 RHSVecType->getElementType()->isIntegerType()) { 8130 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8131 return RHSType; 8132 } 8133 } 8134 8135 // If there's an ext-vector type and a scalar, try to convert the scalar to 8136 // the vector element type and splat. 8137 // FIXME: this should also work for regular vector types as supported in GCC. 8138 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8139 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8140 LHSVecType->getElementType(), LHSType)) 8141 return LHSType; 8142 } 8143 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8144 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8145 LHSType, RHSVecType->getElementType(), 8146 RHSType)) 8147 return RHSType; 8148 } 8149 8150 // FIXME: The code below also handles conversion between vectors and 8151 // non-scalars, we should break this down into fine grained specific checks 8152 // and emit proper diagnostics. 8153 QualType VecType = LHSVecType ? LHSType : RHSType; 8154 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8155 QualType OtherType = LHSVecType ? RHSType : LHSType; 8156 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8157 if (isLaxVectorConversion(OtherType, VecType)) { 8158 // If we're allowing lax vector conversions, only the total (data) size 8159 // needs to be the same. For non compound assignment, if one of the types is 8160 // scalar, the result is always the vector type. 8161 if (!IsCompAssign) { 8162 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8163 return VecType; 8164 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8165 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8166 // type. Note that this is already done by non-compound assignments in 8167 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8168 // <1 x T> -> T. The result is also a vector type. 8169 } else if (OtherType->isExtVectorType() || 8170 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8171 ExprResult *RHSExpr = &RHS; 8172 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8173 return VecType; 8174 } 8175 } 8176 8177 // Okay, the expression is invalid. 8178 8179 // If there's a non-vector, non-real operand, diagnose that. 8180 if ((!RHSVecType && !RHSType->isRealType()) || 8181 (!LHSVecType && !LHSType->isRealType())) { 8182 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8183 << LHSType << RHSType 8184 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8185 return QualType(); 8186 } 8187 8188 // OpenCL V1.1 6.2.6.p1: 8189 // If the operands are of more than one vector type, then an error shall 8190 // occur. Implicit conversions between vector types are not permitted, per 8191 // section 6.2.1. 8192 if (getLangOpts().OpenCL && 8193 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8194 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8195 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8196 << RHSType; 8197 return QualType(); 8198 } 8199 8200 // Otherwise, use the generic diagnostic. 8201 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8202 << LHSType << RHSType 8203 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8204 return QualType(); 8205 } 8206 8207 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8208 // expression. These are mainly cases where the null pointer is used as an 8209 // integer instead of a pointer. 8210 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8211 SourceLocation Loc, bool IsCompare) { 8212 // The canonical way to check for a GNU null is with isNullPointerConstant, 8213 // but we use a bit of a hack here for speed; this is a relatively 8214 // hot path, and isNullPointerConstant is slow. 8215 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8216 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8217 8218 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8219 8220 // Avoid analyzing cases where the result will either be invalid (and 8221 // diagnosed as such) or entirely valid and not something to warn about. 8222 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8223 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8224 return; 8225 8226 // Comparison operations would not make sense with a null pointer no matter 8227 // what the other expression is. 8228 if (!IsCompare) { 8229 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8230 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8231 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8232 return; 8233 } 8234 8235 // The rest of the operations only make sense with a null pointer 8236 // if the other expression is a pointer. 8237 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8238 NonNullType->canDecayToPointerType()) 8239 return; 8240 8241 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8242 << LHSNull /* LHS is NULL */ << NonNullType 8243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8244 } 8245 8246 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8247 ExprResult &RHS, 8248 SourceLocation Loc, bool IsDiv) { 8249 // Check for division/remainder by zero. 8250 llvm::APSInt RHSValue; 8251 if (!RHS.get()->isValueDependent() && 8252 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8253 S.DiagRuntimeBehavior(Loc, RHS.get(), 8254 S.PDiag(diag::warn_remainder_division_by_zero) 8255 << IsDiv << RHS.get()->getSourceRange()); 8256 } 8257 8258 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8259 SourceLocation Loc, 8260 bool IsCompAssign, bool IsDiv) { 8261 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8262 8263 if (LHS.get()->getType()->isVectorType() || 8264 RHS.get()->getType()->isVectorType()) 8265 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8266 /*AllowBothBool*/getLangOpts().AltiVec, 8267 /*AllowBoolConversions*/false); 8268 8269 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8270 if (LHS.isInvalid() || RHS.isInvalid()) 8271 return QualType(); 8272 8273 8274 if (compType.isNull() || !compType->isArithmeticType()) 8275 return InvalidOperands(Loc, LHS, RHS); 8276 if (IsDiv) 8277 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8278 return compType; 8279 } 8280 8281 QualType Sema::CheckRemainderOperands( 8282 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8283 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8284 8285 if (LHS.get()->getType()->isVectorType() || 8286 RHS.get()->getType()->isVectorType()) { 8287 if (LHS.get()->getType()->hasIntegerRepresentation() && 8288 RHS.get()->getType()->hasIntegerRepresentation()) 8289 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8290 /*AllowBothBool*/getLangOpts().AltiVec, 8291 /*AllowBoolConversions*/false); 8292 return InvalidOperands(Loc, LHS, RHS); 8293 } 8294 8295 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8296 if (LHS.isInvalid() || RHS.isInvalid()) 8297 return QualType(); 8298 8299 if (compType.isNull() || !compType->isIntegerType()) 8300 return InvalidOperands(Loc, LHS, RHS); 8301 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8302 return compType; 8303 } 8304 8305 /// \brief Diagnose invalid arithmetic on two void pointers. 8306 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8307 Expr *LHSExpr, Expr *RHSExpr) { 8308 S.Diag(Loc, S.getLangOpts().CPlusPlus 8309 ? diag::err_typecheck_pointer_arith_void_type 8310 : diag::ext_gnu_void_ptr) 8311 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8312 << RHSExpr->getSourceRange(); 8313 } 8314 8315 /// \brief Diagnose invalid arithmetic on a void pointer. 8316 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8317 Expr *Pointer) { 8318 S.Diag(Loc, S.getLangOpts().CPlusPlus 8319 ? diag::err_typecheck_pointer_arith_void_type 8320 : diag::ext_gnu_void_ptr) 8321 << 0 /* one pointer */ << Pointer->getSourceRange(); 8322 } 8323 8324 /// \brief Diagnose invalid arithmetic on two function pointers. 8325 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8326 Expr *LHS, Expr *RHS) { 8327 assert(LHS->getType()->isAnyPointerType()); 8328 assert(RHS->getType()->isAnyPointerType()); 8329 S.Diag(Loc, S.getLangOpts().CPlusPlus 8330 ? diag::err_typecheck_pointer_arith_function_type 8331 : diag::ext_gnu_ptr_func_arith) 8332 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8333 // We only show the second type if it differs from the first. 8334 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8335 RHS->getType()) 8336 << RHS->getType()->getPointeeType() 8337 << LHS->getSourceRange() << RHS->getSourceRange(); 8338 } 8339 8340 /// \brief Diagnose invalid arithmetic on a function pointer. 8341 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8342 Expr *Pointer) { 8343 assert(Pointer->getType()->isAnyPointerType()); 8344 S.Diag(Loc, S.getLangOpts().CPlusPlus 8345 ? diag::err_typecheck_pointer_arith_function_type 8346 : diag::ext_gnu_ptr_func_arith) 8347 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8348 << 0 /* one pointer, so only one type */ 8349 << Pointer->getSourceRange(); 8350 } 8351 8352 /// \brief Emit error if Operand is incomplete pointer type 8353 /// 8354 /// \returns True if pointer has incomplete type 8355 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8356 Expr *Operand) { 8357 QualType ResType = Operand->getType(); 8358 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8359 ResType = ResAtomicType->getValueType(); 8360 8361 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8362 QualType PointeeTy = ResType->getPointeeType(); 8363 return S.RequireCompleteType(Loc, PointeeTy, 8364 diag::err_typecheck_arithmetic_incomplete_type, 8365 PointeeTy, Operand->getSourceRange()); 8366 } 8367 8368 /// \brief Check the validity of an arithmetic pointer operand. 8369 /// 8370 /// If the operand has pointer type, this code will check for pointer types 8371 /// which are invalid in arithmetic operations. These will be diagnosed 8372 /// appropriately, including whether or not the use is supported as an 8373 /// extension. 8374 /// 8375 /// \returns True when the operand is valid to use (even if as an extension). 8376 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8377 Expr *Operand) { 8378 QualType ResType = Operand->getType(); 8379 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8380 ResType = ResAtomicType->getValueType(); 8381 8382 if (!ResType->isAnyPointerType()) return true; 8383 8384 QualType PointeeTy = ResType->getPointeeType(); 8385 if (PointeeTy->isVoidType()) { 8386 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8387 return !S.getLangOpts().CPlusPlus; 8388 } 8389 if (PointeeTy->isFunctionType()) { 8390 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8391 return !S.getLangOpts().CPlusPlus; 8392 } 8393 8394 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8395 8396 return true; 8397 } 8398 8399 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8400 /// operands. 8401 /// 8402 /// This routine will diagnose any invalid arithmetic on pointer operands much 8403 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8404 /// for emitting a single diagnostic even for operations where both LHS and RHS 8405 /// are (potentially problematic) pointers. 8406 /// 8407 /// \returns True when the operand is valid to use (even if as an extension). 8408 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8409 Expr *LHSExpr, Expr *RHSExpr) { 8410 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8411 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8412 if (!isLHSPointer && !isRHSPointer) return true; 8413 8414 QualType LHSPointeeTy, RHSPointeeTy; 8415 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8416 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8417 8418 // if both are pointers check if operation is valid wrt address spaces 8419 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8420 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8421 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8422 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8423 S.Diag(Loc, 8424 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8425 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8426 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8427 return false; 8428 } 8429 } 8430 8431 // Check for arithmetic on pointers to incomplete types. 8432 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8433 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8434 if (isLHSVoidPtr || isRHSVoidPtr) { 8435 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8436 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8437 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8438 8439 return !S.getLangOpts().CPlusPlus; 8440 } 8441 8442 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8443 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8444 if (isLHSFuncPtr || isRHSFuncPtr) { 8445 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8446 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8447 RHSExpr); 8448 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8449 8450 return !S.getLangOpts().CPlusPlus; 8451 } 8452 8453 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8454 return false; 8455 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8456 return false; 8457 8458 return true; 8459 } 8460 8461 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8462 /// literal. 8463 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8464 Expr *LHSExpr, Expr *RHSExpr) { 8465 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8466 Expr* IndexExpr = RHSExpr; 8467 if (!StrExpr) { 8468 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8469 IndexExpr = LHSExpr; 8470 } 8471 8472 bool IsStringPlusInt = StrExpr && 8473 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8474 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8475 return; 8476 8477 llvm::APSInt index; 8478 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8479 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8480 if (index.isNonNegative() && 8481 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8482 index.isUnsigned())) 8483 return; 8484 } 8485 8486 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8487 Self.Diag(OpLoc, diag::warn_string_plus_int) 8488 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8489 8490 // Only print a fixit for "str" + int, not for int + "str". 8491 if (IndexExpr == RHSExpr) { 8492 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8493 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8494 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8495 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8496 << FixItHint::CreateInsertion(EndLoc, "]"); 8497 } else 8498 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8499 } 8500 8501 /// \brief Emit a warning when adding a char literal to a string. 8502 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8503 Expr *LHSExpr, Expr *RHSExpr) { 8504 const Expr *StringRefExpr = LHSExpr; 8505 const CharacterLiteral *CharExpr = 8506 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8507 8508 if (!CharExpr) { 8509 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8510 StringRefExpr = RHSExpr; 8511 } 8512 8513 if (!CharExpr || !StringRefExpr) 8514 return; 8515 8516 const QualType StringType = StringRefExpr->getType(); 8517 8518 // Return if not a PointerType. 8519 if (!StringType->isAnyPointerType()) 8520 return; 8521 8522 // Return if not a CharacterType. 8523 if (!StringType->getPointeeType()->isAnyCharacterType()) 8524 return; 8525 8526 ASTContext &Ctx = Self.getASTContext(); 8527 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8528 8529 const QualType CharType = CharExpr->getType(); 8530 if (!CharType->isAnyCharacterType() && 8531 CharType->isIntegerType() && 8532 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8533 Self.Diag(OpLoc, diag::warn_string_plus_char) 8534 << DiagRange << Ctx.CharTy; 8535 } else { 8536 Self.Diag(OpLoc, diag::warn_string_plus_char) 8537 << DiagRange << CharExpr->getType(); 8538 } 8539 8540 // Only print a fixit for str + char, not for char + str. 8541 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8542 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8543 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8544 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8545 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8546 << FixItHint::CreateInsertion(EndLoc, "]"); 8547 } else { 8548 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8549 } 8550 } 8551 8552 /// \brief Emit error when two pointers are incompatible. 8553 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8554 Expr *LHSExpr, Expr *RHSExpr) { 8555 assert(LHSExpr->getType()->isAnyPointerType()); 8556 assert(RHSExpr->getType()->isAnyPointerType()); 8557 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8558 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8559 << RHSExpr->getSourceRange(); 8560 } 8561 8562 // C99 6.5.6 8563 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8564 SourceLocation Loc, BinaryOperatorKind Opc, 8565 QualType* CompLHSTy) { 8566 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8567 8568 if (LHS.get()->getType()->isVectorType() || 8569 RHS.get()->getType()->isVectorType()) { 8570 QualType compType = CheckVectorOperands( 8571 LHS, RHS, Loc, CompLHSTy, 8572 /*AllowBothBool*/getLangOpts().AltiVec, 8573 /*AllowBoolConversions*/getLangOpts().ZVector); 8574 if (CompLHSTy) *CompLHSTy = compType; 8575 return compType; 8576 } 8577 8578 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8579 if (LHS.isInvalid() || RHS.isInvalid()) 8580 return QualType(); 8581 8582 // Diagnose "string literal" '+' int and string '+' "char literal". 8583 if (Opc == BO_Add) { 8584 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8585 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8586 } 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 // Type-checking. Ultimately the pointer's going to be in PExp; 8595 // note that we bias towards the LHS being the pointer. 8596 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8597 8598 bool isObjCPointer; 8599 if (PExp->getType()->isPointerType()) { 8600 isObjCPointer = false; 8601 } else if (PExp->getType()->isObjCObjectPointerType()) { 8602 isObjCPointer = true; 8603 } else { 8604 std::swap(PExp, IExp); 8605 if (PExp->getType()->isPointerType()) { 8606 isObjCPointer = false; 8607 } else if (PExp->getType()->isObjCObjectPointerType()) { 8608 isObjCPointer = true; 8609 } else { 8610 return InvalidOperands(Loc, LHS, RHS); 8611 } 8612 } 8613 assert(PExp->getType()->isAnyPointerType()); 8614 8615 if (!IExp->getType()->isIntegerType()) 8616 return InvalidOperands(Loc, LHS, RHS); 8617 8618 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8619 return QualType(); 8620 8621 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8622 return QualType(); 8623 8624 // Check array bounds for pointer arithemtic 8625 CheckArrayAccess(PExp, IExp); 8626 8627 if (CompLHSTy) { 8628 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8629 if (LHSTy.isNull()) { 8630 LHSTy = LHS.get()->getType(); 8631 if (LHSTy->isPromotableIntegerType()) 8632 LHSTy = Context.getPromotedIntegerType(LHSTy); 8633 } 8634 *CompLHSTy = LHSTy; 8635 } 8636 8637 return PExp->getType(); 8638 } 8639 8640 // C99 6.5.6 8641 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8642 SourceLocation Loc, 8643 QualType* CompLHSTy) { 8644 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8645 8646 if (LHS.get()->getType()->isVectorType() || 8647 RHS.get()->getType()->isVectorType()) { 8648 QualType compType = CheckVectorOperands( 8649 LHS, RHS, Loc, CompLHSTy, 8650 /*AllowBothBool*/getLangOpts().AltiVec, 8651 /*AllowBoolConversions*/getLangOpts().ZVector); 8652 if (CompLHSTy) *CompLHSTy = compType; 8653 return compType; 8654 } 8655 8656 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8657 if (LHS.isInvalid() || RHS.isInvalid()) 8658 return QualType(); 8659 8660 // Enforce type constraints: C99 6.5.6p3. 8661 8662 // Handle the common case first (both operands are arithmetic). 8663 if (!compType.isNull() && compType->isArithmeticType()) { 8664 if (CompLHSTy) *CompLHSTy = compType; 8665 return compType; 8666 } 8667 8668 // Either ptr - int or ptr - ptr. 8669 if (LHS.get()->getType()->isAnyPointerType()) { 8670 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8671 8672 // Diagnose bad cases where we step over interface counts. 8673 if (LHS.get()->getType()->isObjCObjectPointerType() && 8674 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8675 return QualType(); 8676 8677 // The result type of a pointer-int computation is the pointer type. 8678 if (RHS.get()->getType()->isIntegerType()) { 8679 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8680 return QualType(); 8681 8682 // Check array bounds for pointer arithemtic 8683 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8684 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8685 8686 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8687 return LHS.get()->getType(); 8688 } 8689 8690 // Handle pointer-pointer subtractions. 8691 if (const PointerType *RHSPTy 8692 = RHS.get()->getType()->getAs<PointerType>()) { 8693 QualType rpointee = RHSPTy->getPointeeType(); 8694 8695 if (getLangOpts().CPlusPlus) { 8696 // Pointee types must be the same: C++ [expr.add] 8697 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8698 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8699 } 8700 } else { 8701 // Pointee types must be compatible C99 6.5.6p3 8702 if (!Context.typesAreCompatible( 8703 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8704 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8705 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8706 return QualType(); 8707 } 8708 } 8709 8710 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8711 LHS.get(), RHS.get())) 8712 return QualType(); 8713 8714 // The pointee type may have zero size. As an extension, a structure or 8715 // union may have zero size or an array may have zero length. In this 8716 // case subtraction does not make sense. 8717 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8718 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8719 if (ElementSize.isZero()) { 8720 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8721 << rpointee.getUnqualifiedType() 8722 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8723 } 8724 } 8725 8726 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8727 return Context.getPointerDiffType(); 8728 } 8729 } 8730 8731 return InvalidOperands(Loc, LHS, RHS); 8732 } 8733 8734 static bool isScopedEnumerationType(QualType T) { 8735 if (const EnumType *ET = T->getAs<EnumType>()) 8736 return ET->getDecl()->isScoped(); 8737 return false; 8738 } 8739 8740 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8741 SourceLocation Loc, BinaryOperatorKind Opc, 8742 QualType LHSType) { 8743 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8744 // so skip remaining warnings as we don't want to modify values within Sema. 8745 if (S.getLangOpts().OpenCL) 8746 return; 8747 8748 llvm::APSInt Right; 8749 // Check right/shifter operand 8750 if (RHS.get()->isValueDependent() || 8751 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8752 return; 8753 8754 if (Right.isNegative()) { 8755 S.DiagRuntimeBehavior(Loc, RHS.get(), 8756 S.PDiag(diag::warn_shift_negative) 8757 << RHS.get()->getSourceRange()); 8758 return; 8759 } 8760 llvm::APInt LeftBits(Right.getBitWidth(), 8761 S.Context.getTypeSize(LHS.get()->getType())); 8762 if (Right.uge(LeftBits)) { 8763 S.DiagRuntimeBehavior(Loc, RHS.get(), 8764 S.PDiag(diag::warn_shift_gt_typewidth) 8765 << RHS.get()->getSourceRange()); 8766 return; 8767 } 8768 if (Opc != BO_Shl) 8769 return; 8770 8771 // When left shifting an ICE which is signed, we can check for overflow which 8772 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8773 // integers have defined behavior modulo one more than the maximum value 8774 // representable in the result type, so never warn for those. 8775 llvm::APSInt Left; 8776 if (LHS.get()->isValueDependent() || 8777 LHSType->hasUnsignedIntegerRepresentation() || 8778 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8779 return; 8780 8781 // If LHS does not have a signed type and non-negative value 8782 // then, the behavior is undefined. Warn about it. 8783 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8784 S.DiagRuntimeBehavior(Loc, LHS.get(), 8785 S.PDiag(diag::warn_shift_lhs_negative) 8786 << LHS.get()->getSourceRange()); 8787 return; 8788 } 8789 8790 llvm::APInt ResultBits = 8791 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8792 if (LeftBits.uge(ResultBits)) 8793 return; 8794 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8795 Result = Result.shl(Right); 8796 8797 // Print the bit representation of the signed integer as an unsigned 8798 // hexadecimal number. 8799 SmallString<40> HexResult; 8800 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8801 8802 // If we are only missing a sign bit, this is less likely to result in actual 8803 // bugs -- if the result is cast back to an unsigned type, it will have the 8804 // expected value. Thus we place this behind a different warning that can be 8805 // turned off separately if needed. 8806 if (LeftBits == ResultBits - 1) { 8807 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8808 << HexResult << LHSType 8809 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8810 return; 8811 } 8812 8813 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8814 << HexResult.str() << Result.getMinSignedBits() << LHSType 8815 << Left.getBitWidth() << LHS.get()->getSourceRange() 8816 << RHS.get()->getSourceRange(); 8817 } 8818 8819 /// \brief Return the resulting type when a vector is shifted 8820 /// by a scalar or vector shift amount. 8821 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8822 SourceLocation Loc, bool IsCompAssign) { 8823 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8824 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8825 !LHS.get()->getType()->isVectorType()) { 8826 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8827 << RHS.get()->getType() << LHS.get()->getType() 8828 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8829 return QualType(); 8830 } 8831 8832 if (!IsCompAssign) { 8833 LHS = S.UsualUnaryConversions(LHS.get()); 8834 if (LHS.isInvalid()) return QualType(); 8835 } 8836 8837 RHS = S.UsualUnaryConversions(RHS.get()); 8838 if (RHS.isInvalid()) return QualType(); 8839 8840 QualType LHSType = LHS.get()->getType(); 8841 // Note that LHS might be a scalar because the routine calls not only in 8842 // OpenCL case. 8843 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8844 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8845 8846 // Note that RHS might not be a vector. 8847 QualType RHSType = RHS.get()->getType(); 8848 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8849 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8850 8851 // The operands need to be integers. 8852 if (!LHSEleType->isIntegerType()) { 8853 S.Diag(Loc, diag::err_typecheck_expect_int) 8854 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8855 return QualType(); 8856 } 8857 8858 if (!RHSEleType->isIntegerType()) { 8859 S.Diag(Loc, diag::err_typecheck_expect_int) 8860 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8861 return QualType(); 8862 } 8863 8864 if (!LHSVecTy) { 8865 assert(RHSVecTy); 8866 if (IsCompAssign) 8867 return RHSType; 8868 if (LHSEleType != RHSEleType) { 8869 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8870 LHSEleType = RHSEleType; 8871 } 8872 QualType VecTy = 8873 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8874 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8875 LHSType = VecTy; 8876 } else if (RHSVecTy) { 8877 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8878 // are applied component-wise. So if RHS is a vector, then ensure 8879 // that the number of elements is the same as LHS... 8880 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8881 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8882 << LHS.get()->getType() << RHS.get()->getType() 8883 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8884 return QualType(); 8885 } 8886 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 8887 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 8888 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 8889 if (LHSBT != RHSBT && 8890 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 8891 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 8892 << LHS.get()->getType() << RHS.get()->getType() 8893 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8894 } 8895 } 8896 } else { 8897 // ...else expand RHS to match the number of elements in LHS. 8898 QualType VecTy = 8899 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8900 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8901 } 8902 8903 return LHSType; 8904 } 8905 8906 // C99 6.5.7 8907 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8908 SourceLocation Loc, BinaryOperatorKind Opc, 8909 bool IsCompAssign) { 8910 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8911 8912 // Vector shifts promote their scalar inputs to vector type. 8913 if (LHS.get()->getType()->isVectorType() || 8914 RHS.get()->getType()->isVectorType()) { 8915 if (LangOpts.ZVector) { 8916 // The shift operators for the z vector extensions work basically 8917 // like general shifts, except that neither the LHS nor the RHS is 8918 // allowed to be a "vector bool". 8919 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8920 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8921 return InvalidOperands(Loc, LHS, RHS); 8922 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8923 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8924 return InvalidOperands(Loc, LHS, RHS); 8925 } 8926 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8927 } 8928 8929 // Shifts don't perform usual arithmetic conversions, they just do integer 8930 // promotions on each operand. C99 6.5.7p3 8931 8932 // For the LHS, do usual unary conversions, but then reset them away 8933 // if this is a compound assignment. 8934 ExprResult OldLHS = LHS; 8935 LHS = UsualUnaryConversions(LHS.get()); 8936 if (LHS.isInvalid()) 8937 return QualType(); 8938 QualType LHSType = LHS.get()->getType(); 8939 if (IsCompAssign) LHS = OldLHS; 8940 8941 // The RHS is simpler. 8942 RHS = UsualUnaryConversions(RHS.get()); 8943 if (RHS.isInvalid()) 8944 return QualType(); 8945 QualType RHSType = RHS.get()->getType(); 8946 8947 // C99 6.5.7p2: Each of the operands shall have integer type. 8948 if (!LHSType->hasIntegerRepresentation() || 8949 !RHSType->hasIntegerRepresentation()) 8950 return InvalidOperands(Loc, LHS, RHS); 8951 8952 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8953 // hasIntegerRepresentation() above instead of this. 8954 if (isScopedEnumerationType(LHSType) || 8955 isScopedEnumerationType(RHSType)) { 8956 return InvalidOperands(Loc, LHS, RHS); 8957 } 8958 // Sanity-check shift operands 8959 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8960 8961 // "The type of the result is that of the promoted left operand." 8962 return LHSType; 8963 } 8964 8965 static bool IsWithinTemplateSpecialization(Decl *D) { 8966 if (DeclContext *DC = D->getDeclContext()) { 8967 if (isa<ClassTemplateSpecializationDecl>(DC)) 8968 return true; 8969 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8970 return FD->isFunctionTemplateSpecialization(); 8971 } 8972 return false; 8973 } 8974 8975 /// If two different enums are compared, raise a warning. 8976 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8977 Expr *RHS) { 8978 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8979 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8980 8981 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8982 if (!LHSEnumType) 8983 return; 8984 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8985 if (!RHSEnumType) 8986 return; 8987 8988 // Ignore anonymous enums. 8989 if (!LHSEnumType->getDecl()->getIdentifier()) 8990 return; 8991 if (!RHSEnumType->getDecl()->getIdentifier()) 8992 return; 8993 8994 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8995 return; 8996 8997 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8998 << LHSStrippedType << RHSStrippedType 8999 << LHS->getSourceRange() << RHS->getSourceRange(); 9000 } 9001 9002 /// \brief Diagnose bad pointer comparisons. 9003 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9004 ExprResult &LHS, ExprResult &RHS, 9005 bool IsError) { 9006 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9007 : diag::ext_typecheck_comparison_of_distinct_pointers) 9008 << LHS.get()->getType() << RHS.get()->getType() 9009 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9010 } 9011 9012 /// \brief Returns false if the pointers are converted to a composite type, 9013 /// true otherwise. 9014 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9015 ExprResult &LHS, ExprResult &RHS) { 9016 // C++ [expr.rel]p2: 9017 // [...] Pointer conversions (4.10) and qualification 9018 // conversions (4.4) are performed on pointer operands (or on 9019 // a pointer operand and a null pointer constant) to bring 9020 // them to their composite pointer type. [...] 9021 // 9022 // C++ [expr.eq]p1 uses the same notion for (in)equality 9023 // comparisons of pointers. 9024 9025 QualType LHSType = LHS.get()->getType(); 9026 QualType RHSType = RHS.get()->getType(); 9027 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9028 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9029 9030 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9031 if (T.isNull()) { 9032 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9033 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9034 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9035 else 9036 S.InvalidOperands(Loc, LHS, RHS); 9037 return true; 9038 } 9039 9040 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9041 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9042 return false; 9043 } 9044 9045 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9046 ExprResult &LHS, 9047 ExprResult &RHS, 9048 bool IsError) { 9049 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9050 : diag::ext_typecheck_comparison_of_fptr_to_void) 9051 << LHS.get()->getType() << RHS.get()->getType() 9052 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9053 } 9054 9055 static bool isObjCObjectLiteral(ExprResult &E) { 9056 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9057 case Stmt::ObjCArrayLiteralClass: 9058 case Stmt::ObjCDictionaryLiteralClass: 9059 case Stmt::ObjCStringLiteralClass: 9060 case Stmt::ObjCBoxedExprClass: 9061 return true; 9062 default: 9063 // Note that ObjCBoolLiteral is NOT an object literal! 9064 return false; 9065 } 9066 } 9067 9068 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9069 const ObjCObjectPointerType *Type = 9070 LHS->getType()->getAs<ObjCObjectPointerType>(); 9071 9072 // If this is not actually an Objective-C object, bail out. 9073 if (!Type) 9074 return false; 9075 9076 // Get the LHS object's interface type. 9077 QualType InterfaceType = Type->getPointeeType(); 9078 9079 // If the RHS isn't an Objective-C object, bail out. 9080 if (!RHS->getType()->isObjCObjectPointerType()) 9081 return false; 9082 9083 // Try to find the -isEqual: method. 9084 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9085 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9086 InterfaceType, 9087 /*instance=*/true); 9088 if (!Method) { 9089 if (Type->isObjCIdType()) { 9090 // For 'id', just check the global pool. 9091 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9092 /*receiverId=*/true); 9093 } else { 9094 // Check protocols. 9095 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9096 /*instance=*/true); 9097 } 9098 } 9099 9100 if (!Method) 9101 return false; 9102 9103 QualType T = Method->parameters()[0]->getType(); 9104 if (!T->isObjCObjectPointerType()) 9105 return false; 9106 9107 QualType R = Method->getReturnType(); 9108 if (!R->isScalarType()) 9109 return false; 9110 9111 return true; 9112 } 9113 9114 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9115 FromE = FromE->IgnoreParenImpCasts(); 9116 switch (FromE->getStmtClass()) { 9117 default: 9118 break; 9119 case Stmt::ObjCStringLiteralClass: 9120 // "string literal" 9121 return LK_String; 9122 case Stmt::ObjCArrayLiteralClass: 9123 // "array literal" 9124 return LK_Array; 9125 case Stmt::ObjCDictionaryLiteralClass: 9126 // "dictionary literal" 9127 return LK_Dictionary; 9128 case Stmt::BlockExprClass: 9129 return LK_Block; 9130 case Stmt::ObjCBoxedExprClass: { 9131 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9132 switch (Inner->getStmtClass()) { 9133 case Stmt::IntegerLiteralClass: 9134 case Stmt::FloatingLiteralClass: 9135 case Stmt::CharacterLiteralClass: 9136 case Stmt::ObjCBoolLiteralExprClass: 9137 case Stmt::CXXBoolLiteralExprClass: 9138 // "numeric literal" 9139 return LK_Numeric; 9140 case Stmt::ImplicitCastExprClass: { 9141 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9142 // Boolean literals can be represented by implicit casts. 9143 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9144 return LK_Numeric; 9145 break; 9146 } 9147 default: 9148 break; 9149 } 9150 return LK_Boxed; 9151 } 9152 } 9153 return LK_None; 9154 } 9155 9156 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9157 ExprResult &LHS, ExprResult &RHS, 9158 BinaryOperator::Opcode Opc){ 9159 Expr *Literal; 9160 Expr *Other; 9161 if (isObjCObjectLiteral(LHS)) { 9162 Literal = LHS.get(); 9163 Other = RHS.get(); 9164 } else { 9165 Literal = RHS.get(); 9166 Other = LHS.get(); 9167 } 9168 9169 // Don't warn on comparisons against nil. 9170 Other = Other->IgnoreParenCasts(); 9171 if (Other->isNullPointerConstant(S.getASTContext(), 9172 Expr::NPC_ValueDependentIsNotNull)) 9173 return; 9174 9175 // This should be kept in sync with warn_objc_literal_comparison. 9176 // LK_String should always be after the other literals, since it has its own 9177 // warning flag. 9178 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9179 assert(LiteralKind != Sema::LK_Block); 9180 if (LiteralKind == Sema::LK_None) { 9181 llvm_unreachable("Unknown Objective-C object literal kind"); 9182 } 9183 9184 if (LiteralKind == Sema::LK_String) 9185 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9186 << Literal->getSourceRange(); 9187 else 9188 S.Diag(Loc, diag::warn_objc_literal_comparison) 9189 << LiteralKind << Literal->getSourceRange(); 9190 9191 if (BinaryOperator::isEqualityOp(Opc) && 9192 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9193 SourceLocation Start = LHS.get()->getLocStart(); 9194 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9195 CharSourceRange OpRange = 9196 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9197 9198 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9199 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9200 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9201 << FixItHint::CreateInsertion(End, "]"); 9202 } 9203 } 9204 9205 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9206 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9207 ExprResult &RHS, SourceLocation Loc, 9208 BinaryOperatorKind Opc) { 9209 // Check that left hand side is !something. 9210 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9211 if (!UO || UO->getOpcode() != UO_LNot) return; 9212 9213 // Only check if the right hand side is non-bool arithmetic type. 9214 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9215 9216 // Make sure that the something in !something is not bool. 9217 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9218 if (SubExpr->isKnownToHaveBooleanValue()) return; 9219 9220 // Emit warning. 9221 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9222 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9223 << Loc << IsBitwiseOp; 9224 9225 // First note suggest !(x < y) 9226 SourceLocation FirstOpen = SubExpr->getLocStart(); 9227 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9228 FirstClose = S.getLocForEndOfToken(FirstClose); 9229 if (FirstClose.isInvalid()) 9230 FirstOpen = SourceLocation(); 9231 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9232 << IsBitwiseOp 9233 << FixItHint::CreateInsertion(FirstOpen, "(") 9234 << FixItHint::CreateInsertion(FirstClose, ")"); 9235 9236 // Second note suggests (!x) < y 9237 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9238 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9239 SecondClose = S.getLocForEndOfToken(SecondClose); 9240 if (SecondClose.isInvalid()) 9241 SecondOpen = SourceLocation(); 9242 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9243 << FixItHint::CreateInsertion(SecondOpen, "(") 9244 << FixItHint::CreateInsertion(SecondClose, ")"); 9245 } 9246 9247 // Get the decl for a simple expression: a reference to a variable, 9248 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9249 static ValueDecl *getCompareDecl(Expr *E) { 9250 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9251 return DR->getDecl(); 9252 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9253 if (Ivar->isFreeIvar()) 9254 return Ivar->getDecl(); 9255 } 9256 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9257 if (Mem->isImplicitAccess()) 9258 return Mem->getMemberDecl(); 9259 } 9260 return nullptr; 9261 } 9262 9263 // C99 6.5.8, C++ [expr.rel] 9264 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9265 SourceLocation Loc, BinaryOperatorKind Opc, 9266 bool IsRelational) { 9267 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9268 9269 // Handle vector comparisons separately. 9270 if (LHS.get()->getType()->isVectorType() || 9271 RHS.get()->getType()->isVectorType()) 9272 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9273 9274 QualType LHSType = LHS.get()->getType(); 9275 QualType RHSType = RHS.get()->getType(); 9276 9277 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9278 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9279 9280 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9281 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9282 9283 if (!LHSType->hasFloatingRepresentation() && 9284 !(LHSType->isBlockPointerType() && IsRelational) && 9285 !LHS.get()->getLocStart().isMacroID() && 9286 !RHS.get()->getLocStart().isMacroID() && 9287 !inTemplateInstantiation()) { 9288 // For non-floating point types, check for self-comparisons of the form 9289 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9290 // often indicate logic errors in the program. 9291 // 9292 // NOTE: Don't warn about comparison expressions resulting from macro 9293 // expansion. Also don't warn about comparisons which are only self 9294 // comparisons within a template specialization. The warnings should catch 9295 // obvious cases in the definition of the template anyways. The idea is to 9296 // warn when the typed comparison operator will always evaluate to the same 9297 // result. 9298 ValueDecl *DL = getCompareDecl(LHSStripped); 9299 ValueDecl *DR = getCompareDecl(RHSStripped); 9300 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9301 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9302 << 0 // self- 9303 << (Opc == BO_EQ 9304 || Opc == BO_LE 9305 || Opc == BO_GE)); 9306 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9307 !DL->getType()->isReferenceType() && 9308 !DR->getType()->isReferenceType()) { 9309 // what is it always going to eval to? 9310 char always_evals_to; 9311 switch(Opc) { 9312 case BO_EQ: // e.g. array1 == array2 9313 always_evals_to = 0; // false 9314 break; 9315 case BO_NE: // e.g. array1 != array2 9316 always_evals_to = 1; // true 9317 break; 9318 default: 9319 // best we can say is 'a constant' 9320 always_evals_to = 2; // e.g. array1 <= array2 9321 break; 9322 } 9323 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9324 << 1 // array 9325 << always_evals_to); 9326 } 9327 9328 if (isa<CastExpr>(LHSStripped)) 9329 LHSStripped = LHSStripped->IgnoreParenCasts(); 9330 if (isa<CastExpr>(RHSStripped)) 9331 RHSStripped = RHSStripped->IgnoreParenCasts(); 9332 9333 // Warn about comparisons against a string constant (unless the other 9334 // operand is null), the user probably wants strcmp. 9335 Expr *literalString = nullptr; 9336 Expr *literalStringStripped = nullptr; 9337 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9338 !RHSStripped->isNullPointerConstant(Context, 9339 Expr::NPC_ValueDependentIsNull)) { 9340 literalString = LHS.get(); 9341 literalStringStripped = LHSStripped; 9342 } else if ((isa<StringLiteral>(RHSStripped) || 9343 isa<ObjCEncodeExpr>(RHSStripped)) && 9344 !LHSStripped->isNullPointerConstant(Context, 9345 Expr::NPC_ValueDependentIsNull)) { 9346 literalString = RHS.get(); 9347 literalStringStripped = RHSStripped; 9348 } 9349 9350 if (literalString) { 9351 DiagRuntimeBehavior(Loc, nullptr, 9352 PDiag(diag::warn_stringcompare) 9353 << isa<ObjCEncodeExpr>(literalStringStripped) 9354 << literalString->getSourceRange()); 9355 } 9356 } 9357 9358 // C99 6.5.8p3 / C99 6.5.9p4 9359 UsualArithmeticConversions(LHS, RHS); 9360 if (LHS.isInvalid() || RHS.isInvalid()) 9361 return QualType(); 9362 9363 LHSType = LHS.get()->getType(); 9364 RHSType = RHS.get()->getType(); 9365 9366 // The result of comparisons is 'bool' in C++, 'int' in C. 9367 QualType ResultTy = Context.getLogicalOperationType(); 9368 9369 if (IsRelational) { 9370 if (LHSType->isRealType() && RHSType->isRealType()) 9371 return ResultTy; 9372 } else { 9373 // Check for comparisons of floating point operands using != and ==. 9374 if (LHSType->hasFloatingRepresentation()) 9375 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9376 9377 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9378 return ResultTy; 9379 } 9380 9381 const Expr::NullPointerConstantKind LHSNullKind = 9382 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9383 const Expr::NullPointerConstantKind RHSNullKind = 9384 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9385 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9386 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9387 9388 if (!IsRelational && LHSIsNull != RHSIsNull) { 9389 bool IsEquality = Opc == BO_EQ; 9390 if (RHSIsNull) 9391 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9392 RHS.get()->getSourceRange()); 9393 else 9394 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9395 LHS.get()->getSourceRange()); 9396 } 9397 9398 if ((LHSType->isIntegerType() && !LHSIsNull) || 9399 (RHSType->isIntegerType() && !RHSIsNull)) { 9400 // Skip normal pointer conversion checks in this case; we have better 9401 // diagnostics for this below. 9402 } else if (getLangOpts().CPlusPlus) { 9403 // Equality comparison of a function pointer to a void pointer is invalid, 9404 // but we allow it as an extension. 9405 // FIXME: If we really want to allow this, should it be part of composite 9406 // pointer type computation so it works in conditionals too? 9407 if (!IsRelational && 9408 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9409 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9410 // This is a gcc extension compatibility comparison. 9411 // In a SFINAE context, we treat this as a hard error to maintain 9412 // conformance with the C++ standard. 9413 diagnoseFunctionPointerToVoidComparison( 9414 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9415 9416 if (isSFINAEContext()) 9417 return QualType(); 9418 9419 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9420 return ResultTy; 9421 } 9422 9423 // C++ [expr.eq]p2: 9424 // If at least one operand is a pointer [...] bring them to their 9425 // composite pointer type. 9426 // C++ [expr.rel]p2: 9427 // If both operands are pointers, [...] bring them to their composite 9428 // pointer type. 9429 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9430 (IsRelational ? 2 : 1) && 9431 (!LangOpts.ObjCAutoRefCount || 9432 !(LHSType->isObjCObjectPointerType() || 9433 RHSType->isObjCObjectPointerType()))) { 9434 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9435 return QualType(); 9436 else 9437 return ResultTy; 9438 } 9439 } else if (LHSType->isPointerType() && 9440 RHSType->isPointerType()) { // C99 6.5.8p2 9441 // All of the following pointer-related warnings are GCC extensions, except 9442 // when handling null pointer constants. 9443 QualType LCanPointeeTy = 9444 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9445 QualType RCanPointeeTy = 9446 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9447 9448 // C99 6.5.9p2 and C99 6.5.8p2 9449 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9450 RCanPointeeTy.getUnqualifiedType())) { 9451 // Valid unless a relational comparison of function pointers 9452 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9453 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9454 << LHSType << RHSType << LHS.get()->getSourceRange() 9455 << RHS.get()->getSourceRange(); 9456 } 9457 } else if (!IsRelational && 9458 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9459 // Valid unless comparison between non-null pointer and function pointer 9460 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9461 && !LHSIsNull && !RHSIsNull) 9462 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9463 /*isError*/false); 9464 } else { 9465 // Invalid 9466 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9467 } 9468 if (LCanPointeeTy != RCanPointeeTy) { 9469 // Treat NULL constant as a special case in OpenCL. 9470 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9471 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9472 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9473 Diag(Loc, 9474 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9475 << LHSType << RHSType << 0 /* comparison */ 9476 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9477 } 9478 } 9479 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9480 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9481 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9482 : CK_BitCast; 9483 if (LHSIsNull && !RHSIsNull) 9484 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9485 else 9486 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9487 } 9488 return ResultTy; 9489 } 9490 9491 if (getLangOpts().CPlusPlus) { 9492 // C++ [expr.eq]p4: 9493 // Two operands of type std::nullptr_t or one operand of type 9494 // std::nullptr_t and the other a null pointer constant compare equal. 9495 if (!IsRelational && LHSIsNull && RHSIsNull) { 9496 if (LHSType->isNullPtrType()) { 9497 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9498 return ResultTy; 9499 } 9500 if (RHSType->isNullPtrType()) { 9501 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9502 return ResultTy; 9503 } 9504 } 9505 9506 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9507 // These aren't covered by the composite pointer type rules. 9508 if (!IsRelational && RHSType->isNullPtrType() && 9509 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9510 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9511 return ResultTy; 9512 } 9513 if (!IsRelational && LHSType->isNullPtrType() && 9514 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9515 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9516 return ResultTy; 9517 } 9518 9519 if (IsRelational && 9520 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9521 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9522 // HACK: Relational comparison of nullptr_t against a pointer type is 9523 // invalid per DR583, but we allow it within std::less<> and friends, 9524 // since otherwise common uses of it break. 9525 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9526 // friends to have std::nullptr_t overload candidates. 9527 DeclContext *DC = CurContext; 9528 if (isa<FunctionDecl>(DC)) 9529 DC = DC->getParent(); 9530 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9531 if (CTSD->isInStdNamespace() && 9532 llvm::StringSwitch<bool>(CTSD->getName()) 9533 .Cases("less", "less_equal", "greater", "greater_equal", true) 9534 .Default(false)) { 9535 if (RHSType->isNullPtrType()) 9536 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9537 else 9538 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9539 return ResultTy; 9540 } 9541 } 9542 } 9543 9544 // C++ [expr.eq]p2: 9545 // If at least one operand is a pointer to member, [...] bring them to 9546 // their composite pointer type. 9547 if (!IsRelational && 9548 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9549 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9550 return QualType(); 9551 else 9552 return ResultTy; 9553 } 9554 9555 // Handle scoped enumeration types specifically, since they don't promote 9556 // to integers. 9557 if (LHS.get()->getType()->isEnumeralType() && 9558 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9559 RHS.get()->getType())) 9560 return ResultTy; 9561 } 9562 9563 // Handle block pointer types. 9564 if (!IsRelational && LHSType->isBlockPointerType() && 9565 RHSType->isBlockPointerType()) { 9566 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9567 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9568 9569 if (!LHSIsNull && !RHSIsNull && 9570 !Context.typesAreCompatible(lpointee, rpointee)) { 9571 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9572 << LHSType << RHSType << LHS.get()->getSourceRange() 9573 << RHS.get()->getSourceRange(); 9574 } 9575 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9576 return ResultTy; 9577 } 9578 9579 // Allow block pointers to be compared with null pointer constants. 9580 if (!IsRelational 9581 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9582 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9583 if (!LHSIsNull && !RHSIsNull) { 9584 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9585 ->getPointeeType()->isVoidType()) 9586 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9587 ->getPointeeType()->isVoidType()))) 9588 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9589 << LHSType << RHSType << LHS.get()->getSourceRange() 9590 << RHS.get()->getSourceRange(); 9591 } 9592 if (LHSIsNull && !RHSIsNull) 9593 LHS = ImpCastExprToType(LHS.get(), RHSType, 9594 RHSType->isPointerType() ? CK_BitCast 9595 : CK_AnyPointerToBlockPointerCast); 9596 else 9597 RHS = ImpCastExprToType(RHS.get(), LHSType, 9598 LHSType->isPointerType() ? CK_BitCast 9599 : CK_AnyPointerToBlockPointerCast); 9600 return ResultTy; 9601 } 9602 9603 if (LHSType->isObjCObjectPointerType() || 9604 RHSType->isObjCObjectPointerType()) { 9605 const PointerType *LPT = LHSType->getAs<PointerType>(); 9606 const PointerType *RPT = RHSType->getAs<PointerType>(); 9607 if (LPT || RPT) { 9608 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9609 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9610 9611 if (!LPtrToVoid && !RPtrToVoid && 9612 !Context.typesAreCompatible(LHSType, RHSType)) { 9613 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9614 /*isError*/false); 9615 } 9616 if (LHSIsNull && !RHSIsNull) { 9617 Expr *E = LHS.get(); 9618 if (getLangOpts().ObjCAutoRefCount) 9619 CheckObjCConversion(SourceRange(), RHSType, E, 9620 CCK_ImplicitConversion); 9621 LHS = ImpCastExprToType(E, RHSType, 9622 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9623 } 9624 else { 9625 Expr *E = RHS.get(); 9626 if (getLangOpts().ObjCAutoRefCount) 9627 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9628 /*Diagnose=*/true, 9629 /*DiagnoseCFAudited=*/false, Opc); 9630 RHS = ImpCastExprToType(E, LHSType, 9631 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9632 } 9633 return ResultTy; 9634 } 9635 if (LHSType->isObjCObjectPointerType() && 9636 RHSType->isObjCObjectPointerType()) { 9637 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9638 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9639 /*isError*/false); 9640 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9641 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9642 9643 if (LHSIsNull && !RHSIsNull) 9644 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9645 else 9646 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9647 return ResultTy; 9648 } 9649 } 9650 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9651 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9652 unsigned DiagID = 0; 9653 bool isError = false; 9654 if (LangOpts.DebuggerSupport) { 9655 // Under a debugger, allow the comparison of pointers to integers, 9656 // since users tend to want to compare addresses. 9657 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9658 (RHSIsNull && RHSType->isIntegerType())) { 9659 if (IsRelational) { 9660 isError = getLangOpts().CPlusPlus; 9661 DiagID = 9662 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9663 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9664 } 9665 } else if (getLangOpts().CPlusPlus) { 9666 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9667 isError = true; 9668 } else if (IsRelational) 9669 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9670 else 9671 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9672 9673 if (DiagID) { 9674 Diag(Loc, DiagID) 9675 << LHSType << RHSType << LHS.get()->getSourceRange() 9676 << RHS.get()->getSourceRange(); 9677 if (isError) 9678 return QualType(); 9679 } 9680 9681 if (LHSType->isIntegerType()) 9682 LHS = ImpCastExprToType(LHS.get(), RHSType, 9683 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9684 else 9685 RHS = ImpCastExprToType(RHS.get(), LHSType, 9686 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9687 return ResultTy; 9688 } 9689 9690 // Handle block pointers. 9691 if (!IsRelational && RHSIsNull 9692 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9693 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9694 return ResultTy; 9695 } 9696 if (!IsRelational && LHSIsNull 9697 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9698 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9699 return ResultTy; 9700 } 9701 9702 if (getLangOpts().OpenCLVersion >= 200) { 9703 if (LHSIsNull && RHSType->isQueueT()) { 9704 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9705 return ResultTy; 9706 } 9707 9708 if (LHSType->isQueueT() && RHSIsNull) { 9709 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9710 return ResultTy; 9711 } 9712 } 9713 9714 return InvalidOperands(Loc, LHS, RHS); 9715 } 9716 9717 // Return a signed ext_vector_type that is of identical size and number of 9718 // elements. For floating point vectors, return an integer type of identical 9719 // size and number of elements. In the non ext_vector_type case, search from 9720 // the largest type to the smallest type to avoid cases where long long == long, 9721 // where long gets picked over long long. 9722 QualType Sema::GetSignedVectorType(QualType V) { 9723 const VectorType *VTy = V->getAs<VectorType>(); 9724 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9725 9726 if (isa<ExtVectorType>(VTy)) { 9727 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9728 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9729 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9730 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9731 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9732 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9733 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9734 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9735 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9736 "Unhandled vector element size in vector compare"); 9737 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9738 } 9739 9740 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 9741 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 9742 VectorType::GenericVector); 9743 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9744 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 9745 VectorType::GenericVector); 9746 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9747 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 9748 VectorType::GenericVector); 9749 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9750 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 9751 VectorType::GenericVector); 9752 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 9753 "Unhandled vector element size in vector compare"); 9754 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 9755 VectorType::GenericVector); 9756 } 9757 9758 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9759 /// operates on extended vector types. Instead of producing an IntTy result, 9760 /// like a scalar comparison, a vector comparison produces a vector of integer 9761 /// types. 9762 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9763 SourceLocation Loc, 9764 bool IsRelational) { 9765 // Check to make sure we're operating on vectors of the same type and width, 9766 // Allowing one side to be a scalar of element type. 9767 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9768 /*AllowBothBool*/true, 9769 /*AllowBoolConversions*/getLangOpts().ZVector); 9770 if (vType.isNull()) 9771 return vType; 9772 9773 QualType LHSType = LHS.get()->getType(); 9774 9775 // If AltiVec, the comparison results in a numeric type, i.e. 9776 // bool for C++, int for C 9777 if (getLangOpts().AltiVec && 9778 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9779 return Context.getLogicalOperationType(); 9780 9781 // For non-floating point types, check for self-comparisons of the form 9782 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9783 // often indicate logic errors in the program. 9784 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 9785 if (DeclRefExpr* DRL 9786 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9787 if (DeclRefExpr* DRR 9788 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9789 if (DRL->getDecl() == DRR->getDecl()) 9790 DiagRuntimeBehavior(Loc, nullptr, 9791 PDiag(diag::warn_comparison_always) 9792 << 0 // self- 9793 << 2 // "a constant" 9794 ); 9795 } 9796 9797 // Check for comparisons of floating point operands using != and ==. 9798 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9799 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9800 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9801 } 9802 9803 // Return a signed type for the vector. 9804 return GetSignedVectorType(vType); 9805 } 9806 9807 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9808 SourceLocation Loc) { 9809 // Ensure that either both operands are of the same vector type, or 9810 // one operand is of a vector type and the other is of its element type. 9811 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9812 /*AllowBothBool*/true, 9813 /*AllowBoolConversions*/false); 9814 if (vType.isNull()) 9815 return InvalidOperands(Loc, LHS, RHS); 9816 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9817 vType->hasFloatingRepresentation()) 9818 return InvalidOperands(Loc, LHS, RHS); 9819 9820 return GetSignedVectorType(LHS.get()->getType()); 9821 } 9822 9823 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 9824 SourceLocation Loc, 9825 BinaryOperatorKind Opc) { 9826 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9827 9828 bool IsCompAssign = 9829 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 9830 9831 if (LHS.get()->getType()->isVectorType() || 9832 RHS.get()->getType()->isVectorType()) { 9833 if (LHS.get()->getType()->hasIntegerRepresentation() && 9834 RHS.get()->getType()->hasIntegerRepresentation()) 9835 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9836 /*AllowBothBool*/true, 9837 /*AllowBoolConversions*/getLangOpts().ZVector); 9838 return InvalidOperands(Loc, LHS, RHS); 9839 } 9840 9841 if (Opc == BO_And) 9842 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9843 9844 ExprResult LHSResult = LHS, RHSResult = RHS; 9845 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9846 IsCompAssign); 9847 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9848 return QualType(); 9849 LHS = LHSResult.get(); 9850 RHS = RHSResult.get(); 9851 9852 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9853 return compType; 9854 return InvalidOperands(Loc, LHS, RHS); 9855 } 9856 9857 // C99 6.5.[13,14] 9858 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9859 SourceLocation Loc, 9860 BinaryOperatorKind Opc) { 9861 // Check vector operands differently. 9862 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9863 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9864 9865 // Diagnose cases where the user write a logical and/or but probably meant a 9866 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9867 // is a constant. 9868 if (LHS.get()->getType()->isIntegerType() && 9869 !LHS.get()->getType()->isBooleanType() && 9870 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9871 // Don't warn in macros or template instantiations. 9872 !Loc.isMacroID() && !inTemplateInstantiation()) { 9873 // If the RHS can be constant folded, and if it constant folds to something 9874 // that isn't 0 or 1 (which indicate a potential logical operation that 9875 // happened to fold to true/false) then warn. 9876 // Parens on the RHS are ignored. 9877 llvm::APSInt Result; 9878 if (RHS.get()->EvaluateAsInt(Result, Context)) 9879 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9880 !RHS.get()->getExprLoc().isMacroID()) || 9881 (Result != 0 && Result != 1)) { 9882 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9883 << RHS.get()->getSourceRange() 9884 << (Opc == BO_LAnd ? "&&" : "||"); 9885 // Suggest replacing the logical operator with the bitwise version 9886 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9887 << (Opc == BO_LAnd ? "&" : "|") 9888 << FixItHint::CreateReplacement(SourceRange( 9889 Loc, getLocForEndOfToken(Loc)), 9890 Opc == BO_LAnd ? "&" : "|"); 9891 if (Opc == BO_LAnd) 9892 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9893 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9894 << FixItHint::CreateRemoval( 9895 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9896 RHS.get()->getLocEnd())); 9897 } 9898 } 9899 9900 if (!Context.getLangOpts().CPlusPlus) { 9901 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9902 // not operate on the built-in scalar and vector float types. 9903 if (Context.getLangOpts().OpenCL && 9904 Context.getLangOpts().OpenCLVersion < 120) { 9905 if (LHS.get()->getType()->isFloatingType() || 9906 RHS.get()->getType()->isFloatingType()) 9907 return InvalidOperands(Loc, LHS, RHS); 9908 } 9909 9910 LHS = UsualUnaryConversions(LHS.get()); 9911 if (LHS.isInvalid()) 9912 return QualType(); 9913 9914 RHS = UsualUnaryConversions(RHS.get()); 9915 if (RHS.isInvalid()) 9916 return QualType(); 9917 9918 if (!LHS.get()->getType()->isScalarType() || 9919 !RHS.get()->getType()->isScalarType()) 9920 return InvalidOperands(Loc, LHS, RHS); 9921 9922 return Context.IntTy; 9923 } 9924 9925 // The following is safe because we only use this method for 9926 // non-overloadable operands. 9927 9928 // C++ [expr.log.and]p1 9929 // C++ [expr.log.or]p1 9930 // The operands are both contextually converted to type bool. 9931 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9932 if (LHSRes.isInvalid()) 9933 return InvalidOperands(Loc, LHS, RHS); 9934 LHS = LHSRes; 9935 9936 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9937 if (RHSRes.isInvalid()) 9938 return InvalidOperands(Loc, LHS, RHS); 9939 RHS = RHSRes; 9940 9941 // C++ [expr.log.and]p2 9942 // C++ [expr.log.or]p2 9943 // The result is a bool. 9944 return Context.BoolTy; 9945 } 9946 9947 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9948 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9949 if (!ME) return false; 9950 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9951 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 9952 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 9953 if (!Base) return false; 9954 return Base->getMethodDecl() != nullptr; 9955 } 9956 9957 /// Is the given expression (which must be 'const') a reference to a 9958 /// variable which was originally non-const, but which has become 9959 /// 'const' due to being captured within a block? 9960 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9961 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9962 assert(E->isLValue() && E->getType().isConstQualified()); 9963 E = E->IgnoreParens(); 9964 9965 // Must be a reference to a declaration from an enclosing scope. 9966 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9967 if (!DRE) return NCCK_None; 9968 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9969 9970 // The declaration must be a variable which is not declared 'const'. 9971 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9972 if (!var) return NCCK_None; 9973 if (var->getType().isConstQualified()) return NCCK_None; 9974 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9975 9976 // Decide whether the first capture was for a block or a lambda. 9977 DeclContext *DC = S.CurContext, *Prev = nullptr; 9978 // Decide whether the first capture was for a block or a lambda. 9979 while (DC) { 9980 // For init-capture, it is possible that the variable belongs to the 9981 // template pattern of the current context. 9982 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9983 if (var->isInitCapture() && 9984 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9985 break; 9986 if (DC == var->getDeclContext()) 9987 break; 9988 Prev = DC; 9989 DC = DC->getParent(); 9990 } 9991 // Unless we have an init-capture, we've gone one step too far. 9992 if (!var->isInitCapture()) 9993 DC = Prev; 9994 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9995 } 9996 9997 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9998 Ty = Ty.getNonReferenceType(); 9999 if (IsDereference && Ty->isPointerType()) 10000 Ty = Ty->getPointeeType(); 10001 return !Ty.isConstQualified(); 10002 } 10003 10004 /// Emit the "read-only variable not assignable" error and print notes to give 10005 /// more information about why the variable is not assignable, such as pointing 10006 /// to the declaration of a const variable, showing that a method is const, or 10007 /// that the function is returning a const reference. 10008 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10009 SourceLocation Loc) { 10010 // Update err_typecheck_assign_const and note_typecheck_assign_const 10011 // when this enum is changed. 10012 enum { 10013 ConstFunction, 10014 ConstVariable, 10015 ConstMember, 10016 ConstMethod, 10017 ConstUnknown, // Keep as last element 10018 }; 10019 10020 SourceRange ExprRange = E->getSourceRange(); 10021 10022 // Only emit one error on the first const found. All other consts will emit 10023 // a note to the error. 10024 bool DiagnosticEmitted = false; 10025 10026 // Track if the current expression is the result of a dereference, and if the 10027 // next checked expression is the result of a dereference. 10028 bool IsDereference = false; 10029 bool NextIsDereference = false; 10030 10031 // Loop to process MemberExpr chains. 10032 while (true) { 10033 IsDereference = NextIsDereference; 10034 10035 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10036 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10037 NextIsDereference = ME->isArrow(); 10038 const ValueDecl *VD = ME->getMemberDecl(); 10039 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10040 // Mutable fields can be modified even if the class is const. 10041 if (Field->isMutable()) { 10042 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10043 break; 10044 } 10045 10046 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10047 if (!DiagnosticEmitted) { 10048 S.Diag(Loc, diag::err_typecheck_assign_const) 10049 << ExprRange << ConstMember << false /*static*/ << Field 10050 << Field->getType(); 10051 DiagnosticEmitted = true; 10052 } 10053 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10054 << ConstMember << false /*static*/ << Field << Field->getType() 10055 << Field->getSourceRange(); 10056 } 10057 E = ME->getBase(); 10058 continue; 10059 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10060 if (VDecl->getType().isConstQualified()) { 10061 if (!DiagnosticEmitted) { 10062 S.Diag(Loc, diag::err_typecheck_assign_const) 10063 << ExprRange << ConstMember << true /*static*/ << VDecl 10064 << VDecl->getType(); 10065 DiagnosticEmitted = true; 10066 } 10067 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10068 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10069 << VDecl->getSourceRange(); 10070 } 10071 // Static fields do not inherit constness from parents. 10072 break; 10073 } 10074 break; 10075 } // End MemberExpr 10076 break; 10077 } 10078 10079 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10080 // Function calls 10081 const FunctionDecl *FD = CE->getDirectCallee(); 10082 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10083 if (!DiagnosticEmitted) { 10084 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10085 << ConstFunction << FD; 10086 DiagnosticEmitted = true; 10087 } 10088 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10089 diag::note_typecheck_assign_const) 10090 << ConstFunction << FD << FD->getReturnType() 10091 << FD->getReturnTypeSourceRange(); 10092 } 10093 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10094 // Point to variable declaration. 10095 if (const ValueDecl *VD = DRE->getDecl()) { 10096 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10097 if (!DiagnosticEmitted) { 10098 S.Diag(Loc, diag::err_typecheck_assign_const) 10099 << ExprRange << ConstVariable << VD << VD->getType(); 10100 DiagnosticEmitted = true; 10101 } 10102 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10103 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10104 } 10105 } 10106 } else if (isa<CXXThisExpr>(E)) { 10107 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10108 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10109 if (MD->isConst()) { 10110 if (!DiagnosticEmitted) { 10111 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10112 << ConstMethod << MD; 10113 DiagnosticEmitted = true; 10114 } 10115 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10116 << ConstMethod << MD << MD->getSourceRange(); 10117 } 10118 } 10119 } 10120 } 10121 10122 if (DiagnosticEmitted) 10123 return; 10124 10125 // Can't determine a more specific message, so display the generic error. 10126 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10127 } 10128 10129 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10130 /// emit an error and return true. If so, return false. 10131 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10132 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10133 10134 S.CheckShadowingDeclModification(E, Loc); 10135 10136 SourceLocation OrigLoc = Loc; 10137 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10138 &Loc); 10139 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10140 IsLV = Expr::MLV_InvalidMessageExpression; 10141 if (IsLV == Expr::MLV_Valid) 10142 return false; 10143 10144 unsigned DiagID = 0; 10145 bool NeedType = false; 10146 switch (IsLV) { // C99 6.5.16p2 10147 case Expr::MLV_ConstQualified: 10148 // Use a specialized diagnostic when we're assigning to an object 10149 // from an enclosing function or block. 10150 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10151 if (NCCK == NCCK_Block) 10152 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10153 else 10154 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10155 break; 10156 } 10157 10158 // In ARC, use some specialized diagnostics for occasions where we 10159 // infer 'const'. These are always pseudo-strong variables. 10160 if (S.getLangOpts().ObjCAutoRefCount) { 10161 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10162 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10163 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10164 10165 // Use the normal diagnostic if it's pseudo-__strong but the 10166 // user actually wrote 'const'. 10167 if (var->isARCPseudoStrong() && 10168 (!var->getTypeSourceInfo() || 10169 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10170 // There are two pseudo-strong cases: 10171 // - self 10172 ObjCMethodDecl *method = S.getCurMethodDecl(); 10173 if (method && var == method->getSelfDecl()) 10174 DiagID = method->isClassMethod() 10175 ? diag::err_typecheck_arc_assign_self_class_method 10176 : diag::err_typecheck_arc_assign_self; 10177 10178 // - fast enumeration variables 10179 else 10180 DiagID = diag::err_typecheck_arr_assign_enumeration; 10181 10182 SourceRange Assign; 10183 if (Loc != OrigLoc) 10184 Assign = SourceRange(OrigLoc, OrigLoc); 10185 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10186 // We need to preserve the AST regardless, so migration tool 10187 // can do its job. 10188 return false; 10189 } 10190 } 10191 } 10192 10193 // If none of the special cases above are triggered, then this is a 10194 // simple const assignment. 10195 if (DiagID == 0) { 10196 DiagnoseConstAssignment(S, E, Loc); 10197 return true; 10198 } 10199 10200 break; 10201 case Expr::MLV_ConstAddrSpace: 10202 DiagnoseConstAssignment(S, E, Loc); 10203 return true; 10204 case Expr::MLV_ArrayType: 10205 case Expr::MLV_ArrayTemporary: 10206 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10207 NeedType = true; 10208 break; 10209 case Expr::MLV_NotObjectType: 10210 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10211 NeedType = true; 10212 break; 10213 case Expr::MLV_LValueCast: 10214 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10215 break; 10216 case Expr::MLV_Valid: 10217 llvm_unreachable("did not take early return for MLV_Valid"); 10218 case Expr::MLV_InvalidExpression: 10219 case Expr::MLV_MemberFunction: 10220 case Expr::MLV_ClassTemporary: 10221 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10222 break; 10223 case Expr::MLV_IncompleteType: 10224 case Expr::MLV_IncompleteVoidType: 10225 return S.RequireCompleteType(Loc, E->getType(), 10226 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10227 case Expr::MLV_DuplicateVectorComponents: 10228 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10229 break; 10230 case Expr::MLV_NoSetterProperty: 10231 llvm_unreachable("readonly properties should be processed differently"); 10232 case Expr::MLV_InvalidMessageExpression: 10233 DiagID = diag::err_readonly_message_assignment; 10234 break; 10235 case Expr::MLV_SubObjCPropertySetting: 10236 DiagID = diag::err_no_subobject_property_setting; 10237 break; 10238 } 10239 10240 SourceRange Assign; 10241 if (Loc != OrigLoc) 10242 Assign = SourceRange(OrigLoc, OrigLoc); 10243 if (NeedType) 10244 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10245 else 10246 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10247 return true; 10248 } 10249 10250 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10251 SourceLocation Loc, 10252 Sema &Sema) { 10253 // C / C++ fields 10254 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10255 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10256 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10257 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10258 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10259 } 10260 10261 // Objective-C instance variables 10262 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10263 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10264 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10265 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10266 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10267 if (RL && RR && RL->getDecl() == RR->getDecl()) 10268 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10269 } 10270 } 10271 10272 // C99 6.5.16.1 10273 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10274 SourceLocation Loc, 10275 QualType CompoundType) { 10276 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10277 10278 // Verify that LHS is a modifiable lvalue, and emit error if not. 10279 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10280 return QualType(); 10281 10282 QualType LHSType = LHSExpr->getType(); 10283 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10284 CompoundType; 10285 // OpenCL v1.2 s6.1.1.1 p2: 10286 // The half data type can only be used to declare a pointer to a buffer that 10287 // contains half values 10288 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10289 LHSType->isHalfType()) { 10290 Diag(Loc, diag::err_opencl_half_load_store) << 1 10291 << LHSType.getUnqualifiedType(); 10292 return QualType(); 10293 } 10294 10295 AssignConvertType ConvTy; 10296 if (CompoundType.isNull()) { 10297 Expr *RHSCheck = RHS.get(); 10298 10299 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10300 10301 QualType LHSTy(LHSType); 10302 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10303 if (RHS.isInvalid()) 10304 return QualType(); 10305 // Special case of NSObject attributes on c-style pointer types. 10306 if (ConvTy == IncompatiblePointer && 10307 ((Context.isObjCNSObjectType(LHSType) && 10308 RHSType->isObjCObjectPointerType()) || 10309 (Context.isObjCNSObjectType(RHSType) && 10310 LHSType->isObjCObjectPointerType()))) 10311 ConvTy = Compatible; 10312 10313 if (ConvTy == Compatible && 10314 LHSType->isObjCObjectType()) 10315 Diag(Loc, diag::err_objc_object_assignment) 10316 << LHSType; 10317 10318 // If the RHS is a unary plus or minus, check to see if they = and + are 10319 // right next to each other. If so, the user may have typo'd "x =+ 4" 10320 // instead of "x += 4". 10321 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10322 RHSCheck = ICE->getSubExpr(); 10323 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10324 if ((UO->getOpcode() == UO_Plus || 10325 UO->getOpcode() == UO_Minus) && 10326 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10327 // Only if the two operators are exactly adjacent. 10328 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10329 // And there is a space or other character before the subexpr of the 10330 // unary +/-. We don't want to warn on "x=-1". 10331 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10332 UO->getSubExpr()->getLocStart().isFileID()) { 10333 Diag(Loc, diag::warn_not_compound_assign) 10334 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10335 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10336 } 10337 } 10338 10339 if (ConvTy == Compatible) { 10340 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10341 // Warn about retain cycles where a block captures the LHS, but 10342 // not if the LHS is a simple variable into which the block is 10343 // being stored...unless that variable can be captured by reference! 10344 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10345 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10346 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10347 checkRetainCycles(LHSExpr, RHS.get()); 10348 } 10349 10350 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10351 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10352 // It is safe to assign a weak reference into a strong variable. 10353 // Although this code can still have problems: 10354 // id x = self.weakProp; 10355 // id y = self.weakProp; 10356 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10357 // paths through the function. This should be revisited if 10358 // -Wrepeated-use-of-weak is made flow-sensitive. 10359 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10360 // variable, which will be valid for the current autorelease scope. 10361 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10362 RHS.get()->getLocStart())) 10363 getCurFunction()->markSafeWeakUse(RHS.get()); 10364 10365 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10366 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10367 } 10368 } 10369 } else { 10370 // Compound assignment "x += y" 10371 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10372 } 10373 10374 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10375 RHS.get(), AA_Assigning)) 10376 return QualType(); 10377 10378 CheckForNullPointerDereference(*this, LHSExpr); 10379 10380 // C99 6.5.16p3: The type of an assignment expression is the type of the 10381 // left operand unless the left operand has qualified type, in which case 10382 // it is the unqualified version of the type of the left operand. 10383 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10384 // is converted to the type of the assignment expression (above). 10385 // C++ 5.17p1: the type of the assignment expression is that of its left 10386 // operand. 10387 return (getLangOpts().CPlusPlus 10388 ? LHSType : LHSType.getUnqualifiedType()); 10389 } 10390 10391 // Only ignore explicit casts to void. 10392 static bool IgnoreCommaOperand(const Expr *E) { 10393 E = E->IgnoreParens(); 10394 10395 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10396 if (CE->getCastKind() == CK_ToVoid) { 10397 return true; 10398 } 10399 } 10400 10401 return false; 10402 } 10403 10404 // Look for instances where it is likely the comma operator is confused with 10405 // another operator. There is a whitelist of acceptable expressions for the 10406 // left hand side of the comma operator, otherwise emit a warning. 10407 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10408 // No warnings in macros 10409 if (Loc.isMacroID()) 10410 return; 10411 10412 // Don't warn in template instantiations. 10413 if (inTemplateInstantiation()) 10414 return; 10415 10416 // Scope isn't fine-grained enough to whitelist the specific cases, so 10417 // instead, skip more than needed, then call back into here with the 10418 // CommaVisitor in SemaStmt.cpp. 10419 // The whitelisted locations are the initialization and increment portions 10420 // of a for loop. The additional checks are on the condition of 10421 // if statements, do/while loops, and for loops. 10422 const unsigned ForIncrementFlags = 10423 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10424 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10425 const unsigned ScopeFlags = getCurScope()->getFlags(); 10426 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10427 (ScopeFlags & ForInitFlags) == ForInitFlags) 10428 return; 10429 10430 // If there are multiple comma operators used together, get the RHS of the 10431 // of the comma operator as the LHS. 10432 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10433 if (BO->getOpcode() != BO_Comma) 10434 break; 10435 LHS = BO->getRHS(); 10436 } 10437 10438 // Only allow some expressions on LHS to not warn. 10439 if (IgnoreCommaOperand(LHS)) 10440 return; 10441 10442 Diag(Loc, diag::warn_comma_operator); 10443 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10444 << LHS->getSourceRange() 10445 << FixItHint::CreateInsertion(LHS->getLocStart(), 10446 LangOpts.CPlusPlus ? "static_cast<void>(" 10447 : "(void)(") 10448 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10449 ")"); 10450 } 10451 10452 // C99 6.5.17 10453 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10454 SourceLocation Loc) { 10455 LHS = S.CheckPlaceholderExpr(LHS.get()); 10456 RHS = S.CheckPlaceholderExpr(RHS.get()); 10457 if (LHS.isInvalid() || RHS.isInvalid()) 10458 return QualType(); 10459 10460 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10461 // operands, but not unary promotions. 10462 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10463 10464 // So we treat the LHS as a ignored value, and in C++ we allow the 10465 // containing site to determine what should be done with the RHS. 10466 LHS = S.IgnoredValueConversions(LHS.get()); 10467 if (LHS.isInvalid()) 10468 return QualType(); 10469 10470 S.DiagnoseUnusedExprResult(LHS.get()); 10471 10472 if (!S.getLangOpts().CPlusPlus) { 10473 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10474 if (RHS.isInvalid()) 10475 return QualType(); 10476 if (!RHS.get()->getType()->isVoidType()) 10477 S.RequireCompleteType(Loc, RHS.get()->getType(), 10478 diag::err_incomplete_type); 10479 } 10480 10481 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10482 S.DiagnoseCommaOperator(LHS.get(), Loc); 10483 10484 return RHS.get()->getType(); 10485 } 10486 10487 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10488 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10489 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10490 ExprValueKind &VK, 10491 ExprObjectKind &OK, 10492 SourceLocation OpLoc, 10493 bool IsInc, bool IsPrefix) { 10494 if (Op->isTypeDependent()) 10495 return S.Context.DependentTy; 10496 10497 QualType ResType = Op->getType(); 10498 // Atomic types can be used for increment / decrement where the non-atomic 10499 // versions can, so ignore the _Atomic() specifier for the purpose of 10500 // checking. 10501 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10502 ResType = ResAtomicType->getValueType(); 10503 10504 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10505 10506 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10507 // Decrement of bool is not allowed. 10508 if (!IsInc) { 10509 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10510 return QualType(); 10511 } 10512 // Increment of bool sets it to true, but is deprecated. 10513 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10514 : diag::warn_increment_bool) 10515 << Op->getSourceRange(); 10516 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10517 // Error on enum increments and decrements in C++ mode 10518 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10519 return QualType(); 10520 } else if (ResType->isRealType()) { 10521 // OK! 10522 } else if (ResType->isPointerType()) { 10523 // C99 6.5.2.4p2, 6.5.6p2 10524 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10525 return QualType(); 10526 } else if (ResType->isObjCObjectPointerType()) { 10527 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10528 // Otherwise, we just need a complete type. 10529 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10530 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10531 return QualType(); 10532 } else if (ResType->isAnyComplexType()) { 10533 // C99 does not support ++/-- on complex types, we allow as an extension. 10534 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10535 << ResType << Op->getSourceRange(); 10536 } else if (ResType->isPlaceholderType()) { 10537 ExprResult PR = S.CheckPlaceholderExpr(Op); 10538 if (PR.isInvalid()) return QualType(); 10539 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10540 IsInc, IsPrefix); 10541 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10542 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10543 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10544 (ResType->getAs<VectorType>()->getVectorKind() != 10545 VectorType::AltiVecBool)) { 10546 // The z vector extensions allow ++ and -- for non-bool vectors. 10547 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10548 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10549 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10550 } else { 10551 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10552 << ResType << int(IsInc) << Op->getSourceRange(); 10553 return QualType(); 10554 } 10555 // At this point, we know we have a real, complex or pointer type. 10556 // Now make sure the operand is a modifiable lvalue. 10557 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10558 return QualType(); 10559 // In C++, a prefix increment is the same type as the operand. Otherwise 10560 // (in C or with postfix), the increment is the unqualified type of the 10561 // operand. 10562 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10563 VK = VK_LValue; 10564 OK = Op->getObjectKind(); 10565 return ResType; 10566 } else { 10567 VK = VK_RValue; 10568 return ResType.getUnqualifiedType(); 10569 } 10570 } 10571 10572 10573 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10574 /// This routine allows us to typecheck complex/recursive expressions 10575 /// where the declaration is needed for type checking. We only need to 10576 /// handle cases when the expression references a function designator 10577 /// or is an lvalue. Here are some examples: 10578 /// - &(x) => x 10579 /// - &*****f => f for f a function designator. 10580 /// - &s.xx => s 10581 /// - &s.zz[1].yy -> s, if zz is an array 10582 /// - *(x + 1) -> x, if x is an array 10583 /// - &"123"[2] -> 0 10584 /// - & __real__ x -> x 10585 static ValueDecl *getPrimaryDecl(Expr *E) { 10586 switch (E->getStmtClass()) { 10587 case Stmt::DeclRefExprClass: 10588 return cast<DeclRefExpr>(E)->getDecl(); 10589 case Stmt::MemberExprClass: 10590 // If this is an arrow operator, the address is an offset from 10591 // the base's value, so the object the base refers to is 10592 // irrelevant. 10593 if (cast<MemberExpr>(E)->isArrow()) 10594 return nullptr; 10595 // Otherwise, the expression refers to a part of the base 10596 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10597 case Stmt::ArraySubscriptExprClass: { 10598 // FIXME: This code shouldn't be necessary! We should catch the implicit 10599 // promotion of register arrays earlier. 10600 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10601 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10602 if (ICE->getSubExpr()->getType()->isArrayType()) 10603 return getPrimaryDecl(ICE->getSubExpr()); 10604 } 10605 return nullptr; 10606 } 10607 case Stmt::UnaryOperatorClass: { 10608 UnaryOperator *UO = cast<UnaryOperator>(E); 10609 10610 switch(UO->getOpcode()) { 10611 case UO_Real: 10612 case UO_Imag: 10613 case UO_Extension: 10614 return getPrimaryDecl(UO->getSubExpr()); 10615 default: 10616 return nullptr; 10617 } 10618 } 10619 case Stmt::ParenExprClass: 10620 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10621 case Stmt::ImplicitCastExprClass: 10622 // If the result of an implicit cast is an l-value, we care about 10623 // the sub-expression; otherwise, the result here doesn't matter. 10624 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10625 default: 10626 return nullptr; 10627 } 10628 } 10629 10630 namespace { 10631 enum { 10632 AO_Bit_Field = 0, 10633 AO_Vector_Element = 1, 10634 AO_Property_Expansion = 2, 10635 AO_Register_Variable = 3, 10636 AO_No_Error = 4 10637 }; 10638 } 10639 /// \brief Diagnose invalid operand for address of operations. 10640 /// 10641 /// \param Type The type of operand which cannot have its address taken. 10642 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10643 Expr *E, unsigned Type) { 10644 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10645 } 10646 10647 /// CheckAddressOfOperand - The operand of & must be either a function 10648 /// designator or an lvalue designating an object. If it is an lvalue, the 10649 /// object cannot be declared with storage class register or be a bit field. 10650 /// Note: The usual conversions are *not* applied to the operand of the & 10651 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10652 /// In C++, the operand might be an overloaded function name, in which case 10653 /// we allow the '&' but retain the overloaded-function type. 10654 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10655 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10656 if (PTy->getKind() == BuiltinType::Overload) { 10657 Expr *E = OrigOp.get()->IgnoreParens(); 10658 if (!isa<OverloadExpr>(E)) { 10659 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10660 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10661 << OrigOp.get()->getSourceRange(); 10662 return QualType(); 10663 } 10664 10665 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10666 if (isa<UnresolvedMemberExpr>(Ovl)) 10667 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10668 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10669 << OrigOp.get()->getSourceRange(); 10670 return QualType(); 10671 } 10672 10673 return Context.OverloadTy; 10674 } 10675 10676 if (PTy->getKind() == BuiltinType::UnknownAny) 10677 return Context.UnknownAnyTy; 10678 10679 if (PTy->getKind() == BuiltinType::BoundMember) { 10680 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10681 << OrigOp.get()->getSourceRange(); 10682 return QualType(); 10683 } 10684 10685 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10686 if (OrigOp.isInvalid()) return QualType(); 10687 } 10688 10689 if (OrigOp.get()->isTypeDependent()) 10690 return Context.DependentTy; 10691 10692 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10693 10694 // Make sure to ignore parentheses in subsequent checks 10695 Expr *op = OrigOp.get()->IgnoreParens(); 10696 10697 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10698 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10699 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10700 return QualType(); 10701 } 10702 10703 if (getLangOpts().C99) { 10704 // Implement C99-only parts of addressof rules. 10705 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10706 if (uOp->getOpcode() == UO_Deref) 10707 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10708 // (assuming the deref expression is valid). 10709 return uOp->getSubExpr()->getType(); 10710 } 10711 // Technically, there should be a check for array subscript 10712 // expressions here, but the result of one is always an lvalue anyway. 10713 } 10714 ValueDecl *dcl = getPrimaryDecl(op); 10715 10716 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10717 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10718 op->getLocStart())) 10719 return QualType(); 10720 10721 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10722 unsigned AddressOfError = AO_No_Error; 10723 10724 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10725 bool sfinae = (bool)isSFINAEContext(); 10726 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10727 : diag::ext_typecheck_addrof_temporary) 10728 << op->getType() << op->getSourceRange(); 10729 if (sfinae) 10730 return QualType(); 10731 // Materialize the temporary as an lvalue so that we can take its address. 10732 OrigOp = op = 10733 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10734 } else if (isa<ObjCSelectorExpr>(op)) { 10735 return Context.getPointerType(op->getType()); 10736 } else if (lval == Expr::LV_MemberFunction) { 10737 // If it's an instance method, make a member pointer. 10738 // The expression must have exactly the form &A::foo. 10739 10740 // If the underlying expression isn't a decl ref, give up. 10741 if (!isa<DeclRefExpr>(op)) { 10742 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10743 << OrigOp.get()->getSourceRange(); 10744 return QualType(); 10745 } 10746 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10747 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10748 10749 // The id-expression was parenthesized. 10750 if (OrigOp.get() != DRE) { 10751 Diag(OpLoc, diag::err_parens_pointer_member_function) 10752 << OrigOp.get()->getSourceRange(); 10753 10754 // The method was named without a qualifier. 10755 } else if (!DRE->getQualifier()) { 10756 if (MD->getParent()->getName().empty()) 10757 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10758 << op->getSourceRange(); 10759 else { 10760 SmallString<32> Str; 10761 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10762 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10763 << op->getSourceRange() 10764 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10765 } 10766 } 10767 10768 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10769 if (isa<CXXDestructorDecl>(MD)) 10770 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10771 10772 QualType MPTy = Context.getMemberPointerType( 10773 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10774 // Under the MS ABI, lock down the inheritance model now. 10775 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10776 (void)isCompleteType(OpLoc, MPTy); 10777 return MPTy; 10778 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10779 // C99 6.5.3.2p1 10780 // The operand must be either an l-value or a function designator 10781 if (!op->getType()->isFunctionType()) { 10782 // Use a special diagnostic for loads from property references. 10783 if (isa<PseudoObjectExpr>(op)) { 10784 AddressOfError = AO_Property_Expansion; 10785 } else { 10786 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10787 << op->getType() << op->getSourceRange(); 10788 return QualType(); 10789 } 10790 } 10791 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10792 // The operand cannot be a bit-field 10793 AddressOfError = AO_Bit_Field; 10794 } else if (op->getObjectKind() == OK_VectorComponent) { 10795 // The operand cannot be an element of a vector 10796 AddressOfError = AO_Vector_Element; 10797 } else if (dcl) { // C99 6.5.3.2p1 10798 // We have an lvalue with a decl. Make sure the decl is not declared 10799 // with the register storage-class specifier. 10800 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10801 // in C++ it is not error to take address of a register 10802 // variable (c++03 7.1.1P3) 10803 if (vd->getStorageClass() == SC_Register && 10804 !getLangOpts().CPlusPlus) { 10805 AddressOfError = AO_Register_Variable; 10806 } 10807 } else if (isa<MSPropertyDecl>(dcl)) { 10808 AddressOfError = AO_Property_Expansion; 10809 } else if (isa<FunctionTemplateDecl>(dcl)) { 10810 return Context.OverloadTy; 10811 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10812 // Okay: we can take the address of a field. 10813 // Could be a pointer to member, though, if there is an explicit 10814 // scope qualifier for the class. 10815 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10816 DeclContext *Ctx = dcl->getDeclContext(); 10817 if (Ctx && Ctx->isRecord()) { 10818 if (dcl->getType()->isReferenceType()) { 10819 Diag(OpLoc, 10820 diag::err_cannot_form_pointer_to_member_of_reference_type) 10821 << dcl->getDeclName() << dcl->getType(); 10822 return QualType(); 10823 } 10824 10825 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10826 Ctx = Ctx->getParent(); 10827 10828 QualType MPTy = Context.getMemberPointerType( 10829 op->getType(), 10830 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10831 // Under the MS ABI, lock down the inheritance model now. 10832 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10833 (void)isCompleteType(OpLoc, MPTy); 10834 return MPTy; 10835 } 10836 } 10837 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10838 !isa<BindingDecl>(dcl)) 10839 llvm_unreachable("Unknown/unexpected decl type"); 10840 } 10841 10842 if (AddressOfError != AO_No_Error) { 10843 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10844 return QualType(); 10845 } 10846 10847 if (lval == Expr::LV_IncompleteVoidType) { 10848 // Taking the address of a void variable is technically illegal, but we 10849 // allow it in cases which are otherwise valid. 10850 // Example: "extern void x; void* y = &x;". 10851 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10852 } 10853 10854 // If the operand has type "type", the result has type "pointer to type". 10855 if (op->getType()->isObjCObjectType()) 10856 return Context.getObjCObjectPointerType(op->getType()); 10857 10858 CheckAddressOfPackedMember(op); 10859 10860 return Context.getPointerType(op->getType()); 10861 } 10862 10863 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10864 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10865 if (!DRE) 10866 return; 10867 const Decl *D = DRE->getDecl(); 10868 if (!D) 10869 return; 10870 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10871 if (!Param) 10872 return; 10873 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10874 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10875 return; 10876 if (FunctionScopeInfo *FD = S.getCurFunction()) 10877 if (!FD->ModifiedNonNullParams.count(Param)) 10878 FD->ModifiedNonNullParams.insert(Param); 10879 } 10880 10881 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10882 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10883 SourceLocation OpLoc) { 10884 if (Op->isTypeDependent()) 10885 return S.Context.DependentTy; 10886 10887 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10888 if (ConvResult.isInvalid()) 10889 return QualType(); 10890 Op = ConvResult.get(); 10891 QualType OpTy = Op->getType(); 10892 QualType Result; 10893 10894 if (isa<CXXReinterpretCastExpr>(Op)) { 10895 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10896 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10897 Op->getSourceRange()); 10898 } 10899 10900 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10901 { 10902 Result = PT->getPointeeType(); 10903 } 10904 else if (const ObjCObjectPointerType *OPT = 10905 OpTy->getAs<ObjCObjectPointerType>()) 10906 Result = OPT->getPointeeType(); 10907 else { 10908 ExprResult PR = S.CheckPlaceholderExpr(Op); 10909 if (PR.isInvalid()) return QualType(); 10910 if (PR.get() != Op) 10911 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10912 } 10913 10914 if (Result.isNull()) { 10915 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10916 << OpTy << Op->getSourceRange(); 10917 return QualType(); 10918 } 10919 10920 // Note that per both C89 and C99, indirection is always legal, even if Result 10921 // is an incomplete type or void. It would be possible to warn about 10922 // dereferencing a void pointer, but it's completely well-defined, and such a 10923 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10924 // for pointers to 'void' but is fine for any other pointer type: 10925 // 10926 // C++ [expr.unary.op]p1: 10927 // [...] the expression to which [the unary * operator] is applied shall 10928 // be a pointer to an object type, or a pointer to a function type 10929 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10930 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10931 << OpTy << Op->getSourceRange(); 10932 10933 // Dereferences are usually l-values... 10934 VK = VK_LValue; 10935 10936 // ...except that certain expressions are never l-values in C. 10937 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10938 VK = VK_RValue; 10939 10940 return Result; 10941 } 10942 10943 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10944 BinaryOperatorKind Opc; 10945 switch (Kind) { 10946 default: llvm_unreachable("Unknown binop!"); 10947 case tok::periodstar: Opc = BO_PtrMemD; break; 10948 case tok::arrowstar: Opc = BO_PtrMemI; break; 10949 case tok::star: Opc = BO_Mul; break; 10950 case tok::slash: Opc = BO_Div; break; 10951 case tok::percent: Opc = BO_Rem; break; 10952 case tok::plus: Opc = BO_Add; break; 10953 case tok::minus: Opc = BO_Sub; break; 10954 case tok::lessless: Opc = BO_Shl; break; 10955 case tok::greatergreater: Opc = BO_Shr; break; 10956 case tok::lessequal: Opc = BO_LE; break; 10957 case tok::less: Opc = BO_LT; break; 10958 case tok::greaterequal: Opc = BO_GE; break; 10959 case tok::greater: Opc = BO_GT; break; 10960 case tok::exclaimequal: Opc = BO_NE; break; 10961 case tok::equalequal: Opc = BO_EQ; break; 10962 case tok::amp: Opc = BO_And; break; 10963 case tok::caret: Opc = BO_Xor; break; 10964 case tok::pipe: Opc = BO_Or; break; 10965 case tok::ampamp: Opc = BO_LAnd; break; 10966 case tok::pipepipe: Opc = BO_LOr; break; 10967 case tok::equal: Opc = BO_Assign; break; 10968 case tok::starequal: Opc = BO_MulAssign; break; 10969 case tok::slashequal: Opc = BO_DivAssign; break; 10970 case tok::percentequal: Opc = BO_RemAssign; break; 10971 case tok::plusequal: Opc = BO_AddAssign; break; 10972 case tok::minusequal: Opc = BO_SubAssign; break; 10973 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10974 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10975 case tok::ampequal: Opc = BO_AndAssign; break; 10976 case tok::caretequal: Opc = BO_XorAssign; break; 10977 case tok::pipeequal: Opc = BO_OrAssign; break; 10978 case tok::comma: Opc = BO_Comma; break; 10979 } 10980 return Opc; 10981 } 10982 10983 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10984 tok::TokenKind Kind) { 10985 UnaryOperatorKind Opc; 10986 switch (Kind) { 10987 default: llvm_unreachable("Unknown unary op!"); 10988 case tok::plusplus: Opc = UO_PreInc; break; 10989 case tok::minusminus: Opc = UO_PreDec; break; 10990 case tok::amp: Opc = UO_AddrOf; break; 10991 case tok::star: Opc = UO_Deref; break; 10992 case tok::plus: Opc = UO_Plus; break; 10993 case tok::minus: Opc = UO_Minus; break; 10994 case tok::tilde: Opc = UO_Not; break; 10995 case tok::exclaim: Opc = UO_LNot; break; 10996 case tok::kw___real: Opc = UO_Real; break; 10997 case tok::kw___imag: Opc = UO_Imag; break; 10998 case tok::kw___extension__: Opc = UO_Extension; break; 10999 } 11000 return Opc; 11001 } 11002 11003 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11004 /// This warning is only emitted for builtin assignment operations. It is also 11005 /// suppressed in the event of macro expansions. 11006 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11007 SourceLocation OpLoc) { 11008 if (S.inTemplateInstantiation()) 11009 return; 11010 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11011 return; 11012 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11013 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11014 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11015 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11016 if (!LHSDeclRef || !RHSDeclRef || 11017 LHSDeclRef->getLocation().isMacroID() || 11018 RHSDeclRef->getLocation().isMacroID()) 11019 return; 11020 const ValueDecl *LHSDecl = 11021 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11022 const ValueDecl *RHSDecl = 11023 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11024 if (LHSDecl != RHSDecl) 11025 return; 11026 if (LHSDecl->getType().isVolatileQualified()) 11027 return; 11028 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11029 if (RefTy->getPointeeType().isVolatileQualified()) 11030 return; 11031 11032 S.Diag(OpLoc, diag::warn_self_assignment) 11033 << LHSDeclRef->getType() 11034 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11035 } 11036 11037 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11038 /// is usually indicative of introspection within the Objective-C pointer. 11039 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11040 SourceLocation OpLoc) { 11041 if (!S.getLangOpts().ObjC1) 11042 return; 11043 11044 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11045 const Expr *LHS = L.get(); 11046 const Expr *RHS = R.get(); 11047 11048 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11049 ObjCPointerExpr = LHS; 11050 OtherExpr = RHS; 11051 } 11052 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11053 ObjCPointerExpr = RHS; 11054 OtherExpr = LHS; 11055 } 11056 11057 // This warning is deliberately made very specific to reduce false 11058 // positives with logic that uses '&' for hashing. This logic mainly 11059 // looks for code trying to introspect into tagged pointers, which 11060 // code should generally never do. 11061 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11062 unsigned Diag = diag::warn_objc_pointer_masking; 11063 // Determine if we are introspecting the result of performSelectorXXX. 11064 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11065 // Special case messages to -performSelector and friends, which 11066 // can return non-pointer values boxed in a pointer value. 11067 // Some clients may wish to silence warnings in this subcase. 11068 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11069 Selector S = ME->getSelector(); 11070 StringRef SelArg0 = S.getNameForSlot(0); 11071 if (SelArg0.startswith("performSelector")) 11072 Diag = diag::warn_objc_pointer_masking_performSelector; 11073 } 11074 11075 S.Diag(OpLoc, Diag) 11076 << ObjCPointerExpr->getSourceRange(); 11077 } 11078 } 11079 11080 static NamedDecl *getDeclFromExpr(Expr *E) { 11081 if (!E) 11082 return nullptr; 11083 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11084 return DRE->getDecl(); 11085 if (auto *ME = dyn_cast<MemberExpr>(E)) 11086 return ME->getMemberDecl(); 11087 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11088 return IRE->getDecl(); 11089 return nullptr; 11090 } 11091 11092 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11093 /// operator @p Opc at location @c TokLoc. This routine only supports 11094 /// built-in operations; ActOnBinOp handles overloaded operators. 11095 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11096 BinaryOperatorKind Opc, 11097 Expr *LHSExpr, Expr *RHSExpr) { 11098 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11099 // The syntax only allows initializer lists on the RHS of assignment, 11100 // so we don't need to worry about accepting invalid code for 11101 // non-assignment operators. 11102 // C++11 5.17p9: 11103 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11104 // of x = {} is x = T(). 11105 InitializationKind Kind = 11106 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11107 InitializedEntity Entity = 11108 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11109 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11110 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11111 if (Init.isInvalid()) 11112 return Init; 11113 RHSExpr = Init.get(); 11114 } 11115 11116 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11117 QualType ResultTy; // Result type of the binary operator. 11118 // The following two variables are used for compound assignment operators 11119 QualType CompLHSTy; // Type of LHS after promotions for computation 11120 QualType CompResultTy; // Type of computation result 11121 ExprValueKind VK = VK_RValue; 11122 ExprObjectKind OK = OK_Ordinary; 11123 11124 if (!getLangOpts().CPlusPlus) { 11125 // C cannot handle TypoExpr nodes on either side of a binop because it 11126 // doesn't handle dependent types properly, so make sure any TypoExprs have 11127 // been dealt with before checking the operands. 11128 LHS = CorrectDelayedTyposInExpr(LHSExpr); 11129 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 11130 if (Opc != BO_Assign) 11131 return ExprResult(E); 11132 // Avoid correcting the RHS to the same Expr as the LHS. 11133 Decl *D = getDeclFromExpr(E); 11134 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11135 }); 11136 if (!LHS.isUsable() || !RHS.isUsable()) 11137 return ExprError(); 11138 } 11139 11140 if (getLangOpts().OpenCL) { 11141 QualType LHSTy = LHSExpr->getType(); 11142 QualType RHSTy = RHSExpr->getType(); 11143 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11144 // the ATOMIC_VAR_INIT macro. 11145 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11146 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11147 if (BO_Assign == Opc) 11148 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11149 else 11150 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11151 return ExprError(); 11152 } 11153 11154 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11155 // only with a builtin functions and therefore should be disallowed here. 11156 if (LHSTy->isImageType() || RHSTy->isImageType() || 11157 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11158 LHSTy->isPipeType() || RHSTy->isPipeType() || 11159 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11160 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11161 return ExprError(); 11162 } 11163 } 11164 11165 switch (Opc) { 11166 case BO_Assign: 11167 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11168 if (getLangOpts().CPlusPlus && 11169 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11170 VK = LHS.get()->getValueKind(); 11171 OK = LHS.get()->getObjectKind(); 11172 } 11173 if (!ResultTy.isNull()) { 11174 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11175 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11176 } 11177 RecordModifiableNonNullParam(*this, LHS.get()); 11178 break; 11179 case BO_PtrMemD: 11180 case BO_PtrMemI: 11181 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11182 Opc == BO_PtrMemI); 11183 break; 11184 case BO_Mul: 11185 case BO_Div: 11186 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11187 Opc == BO_Div); 11188 break; 11189 case BO_Rem: 11190 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11191 break; 11192 case BO_Add: 11193 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11194 break; 11195 case BO_Sub: 11196 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11197 break; 11198 case BO_Shl: 11199 case BO_Shr: 11200 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11201 break; 11202 case BO_LE: 11203 case BO_LT: 11204 case BO_GE: 11205 case BO_GT: 11206 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11207 break; 11208 case BO_EQ: 11209 case BO_NE: 11210 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11211 break; 11212 case BO_And: 11213 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11214 case BO_Xor: 11215 case BO_Or: 11216 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11217 break; 11218 case BO_LAnd: 11219 case BO_LOr: 11220 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11221 break; 11222 case BO_MulAssign: 11223 case BO_DivAssign: 11224 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11225 Opc == BO_DivAssign); 11226 CompLHSTy = CompResultTy; 11227 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11228 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11229 break; 11230 case BO_RemAssign: 11231 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11232 CompLHSTy = CompResultTy; 11233 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11234 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11235 break; 11236 case BO_AddAssign: 11237 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11238 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11239 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11240 break; 11241 case BO_SubAssign: 11242 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11243 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11244 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11245 break; 11246 case BO_ShlAssign: 11247 case BO_ShrAssign: 11248 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11249 CompLHSTy = CompResultTy; 11250 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11251 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11252 break; 11253 case BO_AndAssign: 11254 case BO_OrAssign: // fallthrough 11255 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11256 case BO_XorAssign: 11257 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11258 CompLHSTy = CompResultTy; 11259 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11260 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11261 break; 11262 case BO_Comma: 11263 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11264 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11265 VK = RHS.get()->getValueKind(); 11266 OK = RHS.get()->getObjectKind(); 11267 } 11268 break; 11269 } 11270 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11271 return ExprError(); 11272 11273 // Check for array bounds violations for both sides of the BinaryOperator 11274 CheckArrayAccess(LHS.get()); 11275 CheckArrayAccess(RHS.get()); 11276 11277 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11278 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11279 &Context.Idents.get("object_setClass"), 11280 SourceLocation(), LookupOrdinaryName); 11281 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11282 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11283 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11284 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11285 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11286 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11287 } 11288 else 11289 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11290 } 11291 else if (const ObjCIvarRefExpr *OIRE = 11292 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11293 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11294 11295 if (CompResultTy.isNull()) 11296 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11297 OK, OpLoc, FPFeatures); 11298 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11299 OK_ObjCProperty) { 11300 VK = VK_LValue; 11301 OK = LHS.get()->getObjectKind(); 11302 } 11303 return new (Context) CompoundAssignOperator( 11304 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11305 OpLoc, FPFeatures); 11306 } 11307 11308 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11309 /// operators are mixed in a way that suggests that the programmer forgot that 11310 /// comparison operators have higher precedence. The most typical example of 11311 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11312 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11313 SourceLocation OpLoc, Expr *LHSExpr, 11314 Expr *RHSExpr) { 11315 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11316 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11317 11318 // Check that one of the sides is a comparison operator and the other isn't. 11319 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11320 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11321 if (isLeftComp == isRightComp) 11322 return; 11323 11324 // Bitwise operations are sometimes used as eager logical ops. 11325 // Don't diagnose this. 11326 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11327 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11328 if (isLeftBitwise || isRightBitwise) 11329 return; 11330 11331 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11332 OpLoc) 11333 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11334 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11335 SourceRange ParensRange = isLeftComp ? 11336 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11337 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11338 11339 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11340 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11341 SuggestParentheses(Self, OpLoc, 11342 Self.PDiag(diag::note_precedence_silence) << OpStr, 11343 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11344 SuggestParentheses(Self, OpLoc, 11345 Self.PDiag(diag::note_precedence_bitwise_first) 11346 << BinaryOperator::getOpcodeStr(Opc), 11347 ParensRange); 11348 } 11349 11350 /// \brief It accepts a '&&' expr that is inside a '||' one. 11351 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11352 /// in parentheses. 11353 static void 11354 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11355 BinaryOperator *Bop) { 11356 assert(Bop->getOpcode() == BO_LAnd); 11357 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11358 << Bop->getSourceRange() << OpLoc; 11359 SuggestParentheses(Self, Bop->getOperatorLoc(), 11360 Self.PDiag(diag::note_precedence_silence) 11361 << Bop->getOpcodeStr(), 11362 Bop->getSourceRange()); 11363 } 11364 11365 /// \brief Returns true if the given expression can be evaluated as a constant 11366 /// 'true'. 11367 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11368 bool Res; 11369 return !E->isValueDependent() && 11370 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11371 } 11372 11373 /// \brief Returns true if the given expression can be evaluated as a constant 11374 /// 'false'. 11375 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11376 bool Res; 11377 return !E->isValueDependent() && 11378 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11379 } 11380 11381 /// \brief Look for '&&' in the left hand of a '||' expr. 11382 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11383 Expr *LHSExpr, Expr *RHSExpr) { 11384 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11385 if (Bop->getOpcode() == BO_LAnd) { 11386 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11387 if (EvaluatesAsFalse(S, RHSExpr)) 11388 return; 11389 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11390 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11391 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11392 } else if (Bop->getOpcode() == BO_LOr) { 11393 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11394 // If it's "a || b && 1 || c" we didn't warn earlier for 11395 // "a || b && 1", but warn now. 11396 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11397 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11398 } 11399 } 11400 } 11401 } 11402 11403 /// \brief Look for '&&' in the right hand of a '||' expr. 11404 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11405 Expr *LHSExpr, Expr *RHSExpr) { 11406 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11407 if (Bop->getOpcode() == BO_LAnd) { 11408 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11409 if (EvaluatesAsFalse(S, LHSExpr)) 11410 return; 11411 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11412 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11413 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11414 } 11415 } 11416 } 11417 11418 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11419 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11420 /// the '&' expression in parentheses. 11421 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11422 SourceLocation OpLoc, Expr *SubExpr) { 11423 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11424 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11425 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11426 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11427 << Bop->getSourceRange() << OpLoc; 11428 SuggestParentheses(S, Bop->getOperatorLoc(), 11429 S.PDiag(diag::note_precedence_silence) 11430 << Bop->getOpcodeStr(), 11431 Bop->getSourceRange()); 11432 } 11433 } 11434 } 11435 11436 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11437 Expr *SubExpr, StringRef Shift) { 11438 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11439 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11440 StringRef Op = Bop->getOpcodeStr(); 11441 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11442 << Bop->getSourceRange() << OpLoc << Shift << Op; 11443 SuggestParentheses(S, Bop->getOperatorLoc(), 11444 S.PDiag(diag::note_precedence_silence) << Op, 11445 Bop->getSourceRange()); 11446 } 11447 } 11448 } 11449 11450 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11451 Expr *LHSExpr, Expr *RHSExpr) { 11452 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11453 if (!OCE) 11454 return; 11455 11456 FunctionDecl *FD = OCE->getDirectCallee(); 11457 if (!FD || !FD->isOverloadedOperator()) 11458 return; 11459 11460 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11461 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11462 return; 11463 11464 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11465 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11466 << (Kind == OO_LessLess); 11467 SuggestParentheses(S, OCE->getOperatorLoc(), 11468 S.PDiag(diag::note_precedence_silence) 11469 << (Kind == OO_LessLess ? "<<" : ">>"), 11470 OCE->getSourceRange()); 11471 SuggestParentheses(S, OpLoc, 11472 S.PDiag(diag::note_evaluate_comparison_first), 11473 SourceRange(OCE->getArg(1)->getLocStart(), 11474 RHSExpr->getLocEnd())); 11475 } 11476 11477 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11478 /// precedence. 11479 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11480 SourceLocation OpLoc, Expr *LHSExpr, 11481 Expr *RHSExpr){ 11482 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11483 if (BinaryOperator::isBitwiseOp(Opc)) 11484 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11485 11486 // Diagnose "arg1 & arg2 | arg3" 11487 if ((Opc == BO_Or || Opc == BO_Xor) && 11488 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11489 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11490 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11491 } 11492 11493 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11494 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11495 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11496 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11497 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11498 } 11499 11500 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11501 || Opc == BO_Shr) { 11502 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11503 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11504 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11505 } 11506 11507 // Warn on overloaded shift operators and comparisons, such as: 11508 // cout << 5 == 4; 11509 if (BinaryOperator::isComparisonOp(Opc)) 11510 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11511 } 11512 11513 // Binary Operators. 'Tok' is the token for the operator. 11514 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11515 tok::TokenKind Kind, 11516 Expr *LHSExpr, Expr *RHSExpr) { 11517 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11518 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11519 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11520 11521 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11522 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11523 11524 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11525 } 11526 11527 /// Build an overloaded binary operator expression in the given scope. 11528 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11529 BinaryOperatorKind Opc, 11530 Expr *LHS, Expr *RHS) { 11531 // Find all of the overloaded operators visible from this 11532 // point. We perform both an operator-name lookup from the local 11533 // scope and an argument-dependent lookup based on the types of 11534 // the arguments. 11535 UnresolvedSet<16> Functions; 11536 OverloadedOperatorKind OverOp 11537 = BinaryOperator::getOverloadedOperator(Opc); 11538 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11539 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11540 RHS->getType(), Functions); 11541 11542 // Build the (potentially-overloaded, potentially-dependent) 11543 // binary operation. 11544 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11545 } 11546 11547 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11548 BinaryOperatorKind Opc, 11549 Expr *LHSExpr, Expr *RHSExpr) { 11550 // We want to end up calling one of checkPseudoObjectAssignment 11551 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11552 // both expressions are overloadable or either is type-dependent), 11553 // or CreateBuiltinBinOp (in any other case). We also want to get 11554 // any placeholder types out of the way. 11555 11556 // Handle pseudo-objects in the LHS. 11557 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11558 // Assignments with a pseudo-object l-value need special analysis. 11559 if (pty->getKind() == BuiltinType::PseudoObject && 11560 BinaryOperator::isAssignmentOp(Opc)) 11561 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11562 11563 // Don't resolve overloads if the other type is overloadable. 11564 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 11565 // We can't actually test that if we still have a placeholder, 11566 // though. Fortunately, none of the exceptions we see in that 11567 // code below are valid when the LHS is an overload set. Note 11568 // that an overload set can be dependently-typed, but it never 11569 // instantiates to having an overloadable type. 11570 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11571 if (resolvedRHS.isInvalid()) return ExprError(); 11572 RHSExpr = resolvedRHS.get(); 11573 11574 if (RHSExpr->isTypeDependent() || 11575 RHSExpr->getType()->isOverloadableType()) 11576 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11577 } 11578 11579 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11580 if (LHS.isInvalid()) return ExprError(); 11581 LHSExpr = LHS.get(); 11582 } 11583 11584 // Handle pseudo-objects in the RHS. 11585 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11586 // An overload in the RHS can potentially be resolved by the type 11587 // being assigned to. 11588 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11589 if (getLangOpts().CPlusPlus && 11590 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 11591 LHSExpr->getType()->isOverloadableType())) 11592 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11593 11594 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11595 } 11596 11597 // Don't resolve overloads if the other type is overloadable. 11598 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 11599 LHSExpr->getType()->isOverloadableType()) 11600 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11601 11602 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11603 if (!resolvedRHS.isUsable()) return ExprError(); 11604 RHSExpr = resolvedRHS.get(); 11605 } 11606 11607 if (getLangOpts().CPlusPlus) { 11608 // If either expression is type-dependent, always build an 11609 // overloaded op. 11610 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11611 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11612 11613 // Otherwise, build an overloaded op if either expression has an 11614 // overloadable type. 11615 if (LHSExpr->getType()->isOverloadableType() || 11616 RHSExpr->getType()->isOverloadableType()) 11617 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11618 } 11619 11620 // Build a built-in binary operation. 11621 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11622 } 11623 11624 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11625 UnaryOperatorKind Opc, 11626 Expr *InputExpr) { 11627 ExprResult Input = InputExpr; 11628 ExprValueKind VK = VK_RValue; 11629 ExprObjectKind OK = OK_Ordinary; 11630 QualType resultType; 11631 if (getLangOpts().OpenCL) { 11632 QualType Ty = InputExpr->getType(); 11633 // The only legal unary operation for atomics is '&'. 11634 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11635 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11636 // only with a builtin functions and therefore should be disallowed here. 11637 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11638 || Ty->isBlockPointerType())) { 11639 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11640 << InputExpr->getType() 11641 << Input.get()->getSourceRange()); 11642 } 11643 } 11644 switch (Opc) { 11645 case UO_PreInc: 11646 case UO_PreDec: 11647 case UO_PostInc: 11648 case UO_PostDec: 11649 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11650 OpLoc, 11651 Opc == UO_PreInc || 11652 Opc == UO_PostInc, 11653 Opc == UO_PreInc || 11654 Opc == UO_PreDec); 11655 break; 11656 case UO_AddrOf: 11657 resultType = CheckAddressOfOperand(Input, OpLoc); 11658 RecordModifiableNonNullParam(*this, InputExpr); 11659 break; 11660 case UO_Deref: { 11661 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11662 if (Input.isInvalid()) return ExprError(); 11663 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11664 break; 11665 } 11666 case UO_Plus: 11667 case UO_Minus: 11668 Input = UsualUnaryConversions(Input.get()); 11669 if (Input.isInvalid()) return ExprError(); 11670 resultType = Input.get()->getType(); 11671 if (resultType->isDependentType()) 11672 break; 11673 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11674 break; 11675 else if (resultType->isVectorType() && 11676 // The z vector extensions don't allow + or - with bool vectors. 11677 (!Context.getLangOpts().ZVector || 11678 resultType->getAs<VectorType>()->getVectorKind() != 11679 VectorType::AltiVecBool)) 11680 break; 11681 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11682 Opc == UO_Plus && 11683 resultType->isPointerType()) 11684 break; 11685 11686 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11687 << resultType << Input.get()->getSourceRange()); 11688 11689 case UO_Not: // bitwise complement 11690 Input = UsualUnaryConversions(Input.get()); 11691 if (Input.isInvalid()) 11692 return ExprError(); 11693 resultType = Input.get()->getType(); 11694 if (resultType->isDependentType()) 11695 break; 11696 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11697 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11698 // C99 does not support '~' for complex conjugation. 11699 Diag(OpLoc, diag::ext_integer_complement_complex) 11700 << resultType << Input.get()->getSourceRange(); 11701 else if (resultType->hasIntegerRepresentation()) 11702 break; 11703 else if (resultType->isExtVectorType()) { 11704 if (Context.getLangOpts().OpenCL) { 11705 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11706 // on vector float types. 11707 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11708 if (!T->isIntegerType()) 11709 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11710 << resultType << Input.get()->getSourceRange()); 11711 } 11712 break; 11713 } else { 11714 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11715 << resultType << Input.get()->getSourceRange()); 11716 } 11717 break; 11718 11719 case UO_LNot: // logical negation 11720 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11721 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11722 if (Input.isInvalid()) return ExprError(); 11723 resultType = Input.get()->getType(); 11724 11725 // Though we still have to promote half FP to float... 11726 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11727 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11728 resultType = Context.FloatTy; 11729 } 11730 11731 if (resultType->isDependentType()) 11732 break; 11733 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11734 // C99 6.5.3.3p1: ok, fallthrough; 11735 if (Context.getLangOpts().CPlusPlus) { 11736 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11737 // operand contextually converted to bool. 11738 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11739 ScalarTypeToBooleanCastKind(resultType)); 11740 } else if (Context.getLangOpts().OpenCL && 11741 Context.getLangOpts().OpenCLVersion < 120) { 11742 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11743 // operate on scalar float types. 11744 if (!resultType->isIntegerType() && !resultType->isPointerType()) 11745 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11746 << resultType << Input.get()->getSourceRange()); 11747 } 11748 } else if (resultType->isExtVectorType()) { 11749 if (Context.getLangOpts().OpenCL && 11750 Context.getLangOpts().OpenCLVersion < 120) { 11751 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11752 // operate on vector float types. 11753 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11754 if (!T->isIntegerType()) 11755 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11756 << resultType << Input.get()->getSourceRange()); 11757 } 11758 // Vector logical not returns the signed variant of the operand type. 11759 resultType = GetSignedVectorType(resultType); 11760 break; 11761 } else { 11762 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11763 << resultType << Input.get()->getSourceRange()); 11764 } 11765 11766 // LNot always has type int. C99 6.5.3.3p5. 11767 // In C++, it's bool. C++ 5.3.1p8 11768 resultType = Context.getLogicalOperationType(); 11769 break; 11770 case UO_Real: 11771 case UO_Imag: 11772 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11773 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11774 // complex l-values to ordinary l-values and all other values to r-values. 11775 if (Input.isInvalid()) return ExprError(); 11776 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11777 if (Input.get()->getValueKind() != VK_RValue && 11778 Input.get()->getObjectKind() == OK_Ordinary) 11779 VK = Input.get()->getValueKind(); 11780 } else if (!getLangOpts().CPlusPlus) { 11781 // In C, a volatile scalar is read by __imag. In C++, it is not. 11782 Input = DefaultLvalueConversion(Input.get()); 11783 } 11784 break; 11785 case UO_Extension: 11786 case UO_Coawait: 11787 resultType = Input.get()->getType(); 11788 VK = Input.get()->getValueKind(); 11789 OK = Input.get()->getObjectKind(); 11790 break; 11791 } 11792 if (resultType.isNull() || Input.isInvalid()) 11793 return ExprError(); 11794 11795 // Check for array bounds violations in the operand of the UnaryOperator, 11796 // except for the '*' and '&' operators that have to be handled specially 11797 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11798 // that are explicitly defined as valid by the standard). 11799 if (Opc != UO_AddrOf && Opc != UO_Deref) 11800 CheckArrayAccess(Input.get()); 11801 11802 return new (Context) 11803 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11804 } 11805 11806 /// \brief Determine whether the given expression is a qualified member 11807 /// access expression, of a form that could be turned into a pointer to member 11808 /// with the address-of operator. 11809 static bool isQualifiedMemberAccess(Expr *E) { 11810 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11811 if (!DRE->getQualifier()) 11812 return false; 11813 11814 ValueDecl *VD = DRE->getDecl(); 11815 if (!VD->isCXXClassMember()) 11816 return false; 11817 11818 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11819 return true; 11820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11821 return Method->isInstance(); 11822 11823 return false; 11824 } 11825 11826 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11827 if (!ULE->getQualifier()) 11828 return false; 11829 11830 for (NamedDecl *D : ULE->decls()) { 11831 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11832 if (Method->isInstance()) 11833 return true; 11834 } else { 11835 // Overload set does not contain methods. 11836 break; 11837 } 11838 } 11839 11840 return false; 11841 } 11842 11843 return false; 11844 } 11845 11846 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11847 UnaryOperatorKind Opc, Expr *Input) { 11848 // First things first: handle placeholders so that the 11849 // overloaded-operator check considers the right type. 11850 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11851 // Increment and decrement of pseudo-object references. 11852 if (pty->getKind() == BuiltinType::PseudoObject && 11853 UnaryOperator::isIncrementDecrementOp(Opc)) 11854 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11855 11856 // extension is always a builtin operator. 11857 if (Opc == UO_Extension) 11858 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11859 11860 // & gets special logic for several kinds of placeholder. 11861 // The builtin code knows what to do. 11862 if (Opc == UO_AddrOf && 11863 (pty->getKind() == BuiltinType::Overload || 11864 pty->getKind() == BuiltinType::UnknownAny || 11865 pty->getKind() == BuiltinType::BoundMember)) 11866 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11867 11868 // Anything else needs to be handled now. 11869 ExprResult Result = CheckPlaceholderExpr(Input); 11870 if (Result.isInvalid()) return ExprError(); 11871 Input = Result.get(); 11872 } 11873 11874 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11875 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11876 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11877 // Find all of the overloaded operators visible from this 11878 // point. We perform both an operator-name lookup from the local 11879 // scope and an argument-dependent lookup based on the types of 11880 // the arguments. 11881 UnresolvedSet<16> Functions; 11882 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11883 if (S && OverOp != OO_None) 11884 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11885 Functions); 11886 11887 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11888 } 11889 11890 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11891 } 11892 11893 // Unary Operators. 'Tok' is the token for the operator. 11894 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11895 tok::TokenKind Op, Expr *Input) { 11896 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11897 } 11898 11899 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11900 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11901 LabelDecl *TheDecl) { 11902 TheDecl->markUsed(Context); 11903 // Create the AST node. The address of a label always has type 'void*'. 11904 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11905 Context.getPointerType(Context.VoidTy)); 11906 } 11907 11908 /// Given the last statement in a statement-expression, check whether 11909 /// the result is a producing expression (like a call to an 11910 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11911 /// release out of the full-expression. Otherwise, return null. 11912 /// Cannot fail. 11913 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11914 // Should always be wrapped with one of these. 11915 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11916 if (!cleanups) return nullptr; 11917 11918 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11919 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11920 return nullptr; 11921 11922 // Splice out the cast. This shouldn't modify any interesting 11923 // features of the statement. 11924 Expr *producer = cast->getSubExpr(); 11925 assert(producer->getType() == cast->getType()); 11926 assert(producer->getValueKind() == cast->getValueKind()); 11927 cleanups->setSubExpr(producer); 11928 return cleanups; 11929 } 11930 11931 void Sema::ActOnStartStmtExpr() { 11932 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11933 } 11934 11935 void Sema::ActOnStmtExprError() { 11936 // Note that function is also called by TreeTransform when leaving a 11937 // StmtExpr scope without rebuilding anything. 11938 11939 DiscardCleanupsInEvaluationContext(); 11940 PopExpressionEvaluationContext(); 11941 } 11942 11943 ExprResult 11944 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11945 SourceLocation RPLoc) { // "({..})" 11946 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11947 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11948 11949 if (hasAnyUnrecoverableErrorsInThisFunction()) 11950 DiscardCleanupsInEvaluationContext(); 11951 assert(!Cleanup.exprNeedsCleanups() && 11952 "cleanups within StmtExpr not correctly bound!"); 11953 PopExpressionEvaluationContext(); 11954 11955 // FIXME: there are a variety of strange constraints to enforce here, for 11956 // example, it is not possible to goto into a stmt expression apparently. 11957 // More semantic analysis is needed. 11958 11959 // If there are sub-stmts in the compound stmt, take the type of the last one 11960 // as the type of the stmtexpr. 11961 QualType Ty = Context.VoidTy; 11962 bool StmtExprMayBindToTemp = false; 11963 if (!Compound->body_empty()) { 11964 Stmt *LastStmt = Compound->body_back(); 11965 LabelStmt *LastLabelStmt = nullptr; 11966 // If LastStmt is a label, skip down through into the body. 11967 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11968 LastLabelStmt = Label; 11969 LastStmt = Label->getSubStmt(); 11970 } 11971 11972 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11973 // Do function/array conversion on the last expression, but not 11974 // lvalue-to-rvalue. However, initialize an unqualified type. 11975 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11976 if (LastExpr.isInvalid()) 11977 return ExprError(); 11978 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11979 11980 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11981 // In ARC, if the final expression ends in a consume, splice 11982 // the consume out and bind it later. In the alternate case 11983 // (when dealing with a retainable type), the result 11984 // initialization will create a produce. In both cases the 11985 // result will be +1, and we'll need to balance that out with 11986 // a bind. 11987 if (Expr *rebuiltLastStmt 11988 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11989 LastExpr = rebuiltLastStmt; 11990 } else { 11991 LastExpr = PerformCopyInitialization( 11992 InitializedEntity::InitializeResult(LPLoc, 11993 Ty, 11994 false), 11995 SourceLocation(), 11996 LastExpr); 11997 } 11998 11999 if (LastExpr.isInvalid()) 12000 return ExprError(); 12001 if (LastExpr.get() != nullptr) { 12002 if (!LastLabelStmt) 12003 Compound->setLastStmt(LastExpr.get()); 12004 else 12005 LastLabelStmt->setSubStmt(LastExpr.get()); 12006 StmtExprMayBindToTemp = true; 12007 } 12008 } 12009 } 12010 } 12011 12012 // FIXME: Check that expression type is complete/non-abstract; statement 12013 // expressions are not lvalues. 12014 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12015 if (StmtExprMayBindToTemp) 12016 return MaybeBindToTemporary(ResStmtExpr); 12017 return ResStmtExpr; 12018 } 12019 12020 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12021 TypeSourceInfo *TInfo, 12022 ArrayRef<OffsetOfComponent> Components, 12023 SourceLocation RParenLoc) { 12024 QualType ArgTy = TInfo->getType(); 12025 bool Dependent = ArgTy->isDependentType(); 12026 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12027 12028 // We must have at least one component that refers to the type, and the first 12029 // one is known to be a field designator. Verify that the ArgTy represents 12030 // a struct/union/class. 12031 if (!Dependent && !ArgTy->isRecordType()) 12032 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12033 << ArgTy << TypeRange); 12034 12035 // Type must be complete per C99 7.17p3 because a declaring a variable 12036 // with an incomplete type would be ill-formed. 12037 if (!Dependent 12038 && RequireCompleteType(BuiltinLoc, ArgTy, 12039 diag::err_offsetof_incomplete_type, TypeRange)) 12040 return ExprError(); 12041 12042 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 12043 // GCC extension, diagnose them. 12044 // FIXME: This diagnostic isn't actually visible because the location is in 12045 // a system header! 12046 if (Components.size() != 1) 12047 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 12048 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 12049 12050 bool DidWarnAboutNonPOD = false; 12051 QualType CurrentType = ArgTy; 12052 SmallVector<OffsetOfNode, 4> Comps; 12053 SmallVector<Expr*, 4> Exprs; 12054 for (const OffsetOfComponent &OC : Components) { 12055 if (OC.isBrackets) { 12056 // Offset of an array sub-field. TODO: Should we allow vector elements? 12057 if (!CurrentType->isDependentType()) { 12058 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12059 if(!AT) 12060 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12061 << CurrentType); 12062 CurrentType = AT->getElementType(); 12063 } else 12064 CurrentType = Context.DependentTy; 12065 12066 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12067 if (IdxRval.isInvalid()) 12068 return ExprError(); 12069 Expr *Idx = IdxRval.get(); 12070 12071 // The expression must be an integral expression. 12072 // FIXME: An integral constant expression? 12073 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12074 !Idx->getType()->isIntegerType()) 12075 return ExprError(Diag(Idx->getLocStart(), 12076 diag::err_typecheck_subscript_not_integer) 12077 << Idx->getSourceRange()); 12078 12079 // Record this array index. 12080 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12081 Exprs.push_back(Idx); 12082 continue; 12083 } 12084 12085 // Offset of a field. 12086 if (CurrentType->isDependentType()) { 12087 // We have the offset of a field, but we can't look into the dependent 12088 // type. Just record the identifier of the field. 12089 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12090 CurrentType = Context.DependentTy; 12091 continue; 12092 } 12093 12094 // We need to have a complete type to look into. 12095 if (RequireCompleteType(OC.LocStart, CurrentType, 12096 diag::err_offsetof_incomplete_type)) 12097 return ExprError(); 12098 12099 // Look for the designated field. 12100 const RecordType *RC = CurrentType->getAs<RecordType>(); 12101 if (!RC) 12102 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12103 << CurrentType); 12104 RecordDecl *RD = RC->getDecl(); 12105 12106 // C++ [lib.support.types]p5: 12107 // The macro offsetof accepts a restricted set of type arguments in this 12108 // International Standard. type shall be a POD structure or a POD union 12109 // (clause 9). 12110 // C++11 [support.types]p4: 12111 // If type is not a standard-layout class (Clause 9), the results are 12112 // undefined. 12113 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12114 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12115 unsigned DiagID = 12116 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12117 : diag::ext_offsetof_non_pod_type; 12118 12119 if (!IsSafe && !DidWarnAboutNonPOD && 12120 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12121 PDiag(DiagID) 12122 << SourceRange(Components[0].LocStart, OC.LocEnd) 12123 << CurrentType)) 12124 DidWarnAboutNonPOD = true; 12125 } 12126 12127 // Look for the field. 12128 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12129 LookupQualifiedName(R, RD); 12130 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12131 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12132 if (!MemberDecl) { 12133 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12134 MemberDecl = IndirectMemberDecl->getAnonField(); 12135 } 12136 12137 if (!MemberDecl) 12138 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12139 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12140 OC.LocEnd)); 12141 12142 // C99 7.17p3: 12143 // (If the specified member is a bit-field, the behavior is undefined.) 12144 // 12145 // We diagnose this as an error. 12146 if (MemberDecl->isBitField()) { 12147 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12148 << MemberDecl->getDeclName() 12149 << SourceRange(BuiltinLoc, RParenLoc); 12150 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12151 return ExprError(); 12152 } 12153 12154 RecordDecl *Parent = MemberDecl->getParent(); 12155 if (IndirectMemberDecl) 12156 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12157 12158 // If the member was found in a base class, introduce OffsetOfNodes for 12159 // the base class indirections. 12160 CXXBasePaths Paths; 12161 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12162 Paths)) { 12163 if (Paths.getDetectedVirtual()) { 12164 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12165 << MemberDecl->getDeclName() 12166 << SourceRange(BuiltinLoc, RParenLoc); 12167 return ExprError(); 12168 } 12169 12170 CXXBasePath &Path = Paths.front(); 12171 for (const CXXBasePathElement &B : Path) 12172 Comps.push_back(OffsetOfNode(B.Base)); 12173 } 12174 12175 if (IndirectMemberDecl) { 12176 for (auto *FI : IndirectMemberDecl->chain()) { 12177 assert(isa<FieldDecl>(FI)); 12178 Comps.push_back(OffsetOfNode(OC.LocStart, 12179 cast<FieldDecl>(FI), OC.LocEnd)); 12180 } 12181 } else 12182 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12183 12184 CurrentType = MemberDecl->getType().getNonReferenceType(); 12185 } 12186 12187 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12188 Comps, Exprs, RParenLoc); 12189 } 12190 12191 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12192 SourceLocation BuiltinLoc, 12193 SourceLocation TypeLoc, 12194 ParsedType ParsedArgTy, 12195 ArrayRef<OffsetOfComponent> Components, 12196 SourceLocation RParenLoc) { 12197 12198 TypeSourceInfo *ArgTInfo; 12199 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12200 if (ArgTy.isNull()) 12201 return ExprError(); 12202 12203 if (!ArgTInfo) 12204 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12205 12206 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12207 } 12208 12209 12210 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12211 Expr *CondExpr, 12212 Expr *LHSExpr, Expr *RHSExpr, 12213 SourceLocation RPLoc) { 12214 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12215 12216 ExprValueKind VK = VK_RValue; 12217 ExprObjectKind OK = OK_Ordinary; 12218 QualType resType; 12219 bool ValueDependent = false; 12220 bool CondIsTrue = false; 12221 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12222 resType = Context.DependentTy; 12223 ValueDependent = true; 12224 } else { 12225 // The conditional expression is required to be a constant expression. 12226 llvm::APSInt condEval(32); 12227 ExprResult CondICE 12228 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12229 diag::err_typecheck_choose_expr_requires_constant, false); 12230 if (CondICE.isInvalid()) 12231 return ExprError(); 12232 CondExpr = CondICE.get(); 12233 CondIsTrue = condEval.getZExtValue(); 12234 12235 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12236 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12237 12238 resType = ActiveExpr->getType(); 12239 ValueDependent = ActiveExpr->isValueDependent(); 12240 VK = ActiveExpr->getValueKind(); 12241 OK = ActiveExpr->getObjectKind(); 12242 } 12243 12244 return new (Context) 12245 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12246 CondIsTrue, resType->isDependentType(), ValueDependent); 12247 } 12248 12249 //===----------------------------------------------------------------------===// 12250 // Clang Extensions. 12251 //===----------------------------------------------------------------------===// 12252 12253 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12254 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12255 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12256 12257 if (LangOpts.CPlusPlus) { 12258 Decl *ManglingContextDecl; 12259 if (MangleNumberingContext *MCtx = 12260 getCurrentMangleNumberContext(Block->getDeclContext(), 12261 ManglingContextDecl)) { 12262 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12263 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12264 } 12265 } 12266 12267 PushBlockScope(CurScope, Block); 12268 CurContext->addDecl(Block); 12269 if (CurScope) 12270 PushDeclContext(CurScope, Block); 12271 else 12272 CurContext = Block; 12273 12274 getCurBlock()->HasImplicitReturnType = true; 12275 12276 // Enter a new evaluation context to insulate the block from any 12277 // cleanups from the enclosing full-expression. 12278 PushExpressionEvaluationContext( 12279 ExpressionEvaluationContext::PotentiallyEvaluated); 12280 } 12281 12282 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12283 Scope *CurScope) { 12284 assert(ParamInfo.getIdentifier() == nullptr && 12285 "block-id should have no identifier!"); 12286 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12287 BlockScopeInfo *CurBlock = getCurBlock(); 12288 12289 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12290 QualType T = Sig->getType(); 12291 12292 // FIXME: We should allow unexpanded parameter packs here, but that would, 12293 // in turn, make the block expression contain unexpanded parameter packs. 12294 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12295 // Drop the parameters. 12296 FunctionProtoType::ExtProtoInfo EPI; 12297 EPI.HasTrailingReturn = false; 12298 EPI.TypeQuals |= DeclSpec::TQ_const; 12299 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12300 Sig = Context.getTrivialTypeSourceInfo(T); 12301 } 12302 12303 // GetTypeForDeclarator always produces a function type for a block 12304 // literal signature. Furthermore, it is always a FunctionProtoType 12305 // unless the function was written with a typedef. 12306 assert(T->isFunctionType() && 12307 "GetTypeForDeclarator made a non-function block signature"); 12308 12309 // Look for an explicit signature in that function type. 12310 FunctionProtoTypeLoc ExplicitSignature; 12311 12312 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12313 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12314 12315 // Check whether that explicit signature was synthesized by 12316 // GetTypeForDeclarator. If so, don't save that as part of the 12317 // written signature. 12318 if (ExplicitSignature.getLocalRangeBegin() == 12319 ExplicitSignature.getLocalRangeEnd()) { 12320 // This would be much cheaper if we stored TypeLocs instead of 12321 // TypeSourceInfos. 12322 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12323 unsigned Size = Result.getFullDataSize(); 12324 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12325 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12326 12327 ExplicitSignature = FunctionProtoTypeLoc(); 12328 } 12329 } 12330 12331 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12332 CurBlock->FunctionType = T; 12333 12334 const FunctionType *Fn = T->getAs<FunctionType>(); 12335 QualType RetTy = Fn->getReturnType(); 12336 bool isVariadic = 12337 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12338 12339 CurBlock->TheDecl->setIsVariadic(isVariadic); 12340 12341 // Context.DependentTy is used as a placeholder for a missing block 12342 // return type. TODO: what should we do with declarators like: 12343 // ^ * { ... } 12344 // If the answer is "apply template argument deduction".... 12345 if (RetTy != Context.DependentTy) { 12346 CurBlock->ReturnType = RetTy; 12347 CurBlock->TheDecl->setBlockMissingReturnType(false); 12348 CurBlock->HasImplicitReturnType = false; 12349 } 12350 12351 // Push block parameters from the declarator if we had them. 12352 SmallVector<ParmVarDecl*, 8> Params; 12353 if (ExplicitSignature) { 12354 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12355 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12356 if (Param->getIdentifier() == nullptr && 12357 !Param->isImplicit() && 12358 !Param->isInvalidDecl() && 12359 !getLangOpts().CPlusPlus) 12360 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12361 Params.push_back(Param); 12362 } 12363 12364 // Fake up parameter variables if we have a typedef, like 12365 // ^ fntype { ... } 12366 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12367 for (const auto &I : Fn->param_types()) { 12368 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12369 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12370 Params.push_back(Param); 12371 } 12372 } 12373 12374 // Set the parameters on the block decl. 12375 if (!Params.empty()) { 12376 CurBlock->TheDecl->setParams(Params); 12377 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12378 /*CheckParameterNames=*/false); 12379 } 12380 12381 // Finally we can process decl attributes. 12382 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12383 12384 // Put the parameter variables in scope. 12385 for (auto AI : CurBlock->TheDecl->parameters()) { 12386 AI->setOwningFunction(CurBlock->TheDecl); 12387 12388 // If this has an identifier, add it to the scope stack. 12389 if (AI->getIdentifier()) { 12390 CheckShadow(CurBlock->TheScope, AI); 12391 12392 PushOnScopeChains(AI, CurBlock->TheScope); 12393 } 12394 } 12395 } 12396 12397 /// ActOnBlockError - If there is an error parsing a block, this callback 12398 /// is invoked to pop the information about the block from the action impl. 12399 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12400 // Leave the expression-evaluation context. 12401 DiscardCleanupsInEvaluationContext(); 12402 PopExpressionEvaluationContext(); 12403 12404 // Pop off CurBlock, handle nested blocks. 12405 PopDeclContext(); 12406 PopFunctionScopeInfo(); 12407 } 12408 12409 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12410 /// literal was successfully completed. ^(int x){...} 12411 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12412 Stmt *Body, Scope *CurScope) { 12413 // If blocks are disabled, emit an error. 12414 if (!LangOpts.Blocks) 12415 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12416 12417 // Leave the expression-evaluation context. 12418 if (hasAnyUnrecoverableErrorsInThisFunction()) 12419 DiscardCleanupsInEvaluationContext(); 12420 assert(!Cleanup.exprNeedsCleanups() && 12421 "cleanups within block not correctly bound!"); 12422 PopExpressionEvaluationContext(); 12423 12424 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12425 12426 if (BSI->HasImplicitReturnType) 12427 deduceClosureReturnType(*BSI); 12428 12429 PopDeclContext(); 12430 12431 QualType RetTy = Context.VoidTy; 12432 if (!BSI->ReturnType.isNull()) 12433 RetTy = BSI->ReturnType; 12434 12435 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12436 QualType BlockTy; 12437 12438 // Set the captured variables on the block. 12439 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12440 SmallVector<BlockDecl::Capture, 4> Captures; 12441 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12442 if (Cap.isThisCapture()) 12443 continue; 12444 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12445 Cap.isNested(), Cap.getInitExpr()); 12446 Captures.push_back(NewCap); 12447 } 12448 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12449 12450 // If the user wrote a function type in some form, try to use that. 12451 if (!BSI->FunctionType.isNull()) { 12452 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12453 12454 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12455 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12456 12457 // Turn protoless block types into nullary block types. 12458 if (isa<FunctionNoProtoType>(FTy)) { 12459 FunctionProtoType::ExtProtoInfo EPI; 12460 EPI.ExtInfo = Ext; 12461 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12462 12463 // Otherwise, if we don't need to change anything about the function type, 12464 // preserve its sugar structure. 12465 } else if (FTy->getReturnType() == RetTy && 12466 (!NoReturn || FTy->getNoReturnAttr())) { 12467 BlockTy = BSI->FunctionType; 12468 12469 // Otherwise, make the minimal modifications to the function type. 12470 } else { 12471 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12472 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12473 EPI.TypeQuals = 0; // FIXME: silently? 12474 EPI.ExtInfo = Ext; 12475 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12476 } 12477 12478 // If we don't have a function type, just build one from nothing. 12479 } else { 12480 FunctionProtoType::ExtProtoInfo EPI; 12481 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12482 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12483 } 12484 12485 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12486 BlockTy = Context.getBlockPointerType(BlockTy); 12487 12488 // If needed, diagnose invalid gotos and switches in the block. 12489 if (getCurFunction()->NeedsScopeChecking() && 12490 !PP.isCodeCompletionEnabled()) 12491 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12492 12493 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12494 12495 // Try to apply the named return value optimization. We have to check again 12496 // if we can do this, though, because blocks keep return statements around 12497 // to deduce an implicit return type. 12498 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12499 !BSI->TheDecl->isDependentContext()) 12500 computeNRVO(Body, BSI); 12501 12502 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12503 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12504 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12505 12506 // If the block isn't obviously global, i.e. it captures anything at 12507 // all, then we need to do a few things in the surrounding context: 12508 if (Result->getBlockDecl()->hasCaptures()) { 12509 // First, this expression has a new cleanup object. 12510 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12511 Cleanup.setExprNeedsCleanups(true); 12512 12513 // It also gets a branch-protected scope if any of the captured 12514 // variables needs destruction. 12515 for (const auto &CI : Result->getBlockDecl()->captures()) { 12516 const VarDecl *var = CI.getVariable(); 12517 if (var->getType().isDestructedType() != QualType::DK_none) { 12518 getCurFunction()->setHasBranchProtectedScope(); 12519 break; 12520 } 12521 } 12522 } 12523 12524 return Result; 12525 } 12526 12527 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12528 SourceLocation RPLoc) { 12529 TypeSourceInfo *TInfo; 12530 GetTypeFromParser(Ty, &TInfo); 12531 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12532 } 12533 12534 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12535 Expr *E, TypeSourceInfo *TInfo, 12536 SourceLocation RPLoc) { 12537 Expr *OrigExpr = E; 12538 bool IsMS = false; 12539 12540 // CUDA device code does not support varargs. 12541 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12542 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12543 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12544 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12545 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12546 } 12547 } 12548 12549 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12550 // as Microsoft ABI on an actual Microsoft platform, where 12551 // __builtin_ms_va_list and __builtin_va_list are the same.) 12552 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12553 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12554 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12555 if (Context.hasSameType(MSVaListType, E->getType())) { 12556 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12557 return ExprError(); 12558 IsMS = true; 12559 } 12560 } 12561 12562 // Get the va_list type 12563 QualType VaListType = Context.getBuiltinVaListType(); 12564 if (!IsMS) { 12565 if (VaListType->isArrayType()) { 12566 // Deal with implicit array decay; for example, on x86-64, 12567 // va_list is an array, but it's supposed to decay to 12568 // a pointer for va_arg. 12569 VaListType = Context.getArrayDecayedType(VaListType); 12570 // Make sure the input expression also decays appropriately. 12571 ExprResult Result = UsualUnaryConversions(E); 12572 if (Result.isInvalid()) 12573 return ExprError(); 12574 E = Result.get(); 12575 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12576 // If va_list is a record type and we are compiling in C++ mode, 12577 // check the argument using reference binding. 12578 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12579 Context, Context.getLValueReferenceType(VaListType), false); 12580 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12581 if (Init.isInvalid()) 12582 return ExprError(); 12583 E = Init.getAs<Expr>(); 12584 } else { 12585 // Otherwise, the va_list argument must be an l-value because 12586 // it is modified by va_arg. 12587 if (!E->isTypeDependent() && 12588 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12589 return ExprError(); 12590 } 12591 } 12592 12593 if (!IsMS && !E->isTypeDependent() && 12594 !Context.hasSameType(VaListType, E->getType())) 12595 return ExprError(Diag(E->getLocStart(), 12596 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12597 << OrigExpr->getType() << E->getSourceRange()); 12598 12599 if (!TInfo->getType()->isDependentType()) { 12600 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12601 diag::err_second_parameter_to_va_arg_incomplete, 12602 TInfo->getTypeLoc())) 12603 return ExprError(); 12604 12605 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12606 TInfo->getType(), 12607 diag::err_second_parameter_to_va_arg_abstract, 12608 TInfo->getTypeLoc())) 12609 return ExprError(); 12610 12611 if (!TInfo->getType().isPODType(Context)) { 12612 Diag(TInfo->getTypeLoc().getBeginLoc(), 12613 TInfo->getType()->isObjCLifetimeType() 12614 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12615 : diag::warn_second_parameter_to_va_arg_not_pod) 12616 << TInfo->getType() 12617 << TInfo->getTypeLoc().getSourceRange(); 12618 } 12619 12620 // Check for va_arg where arguments of the given type will be promoted 12621 // (i.e. this va_arg is guaranteed to have undefined behavior). 12622 QualType PromoteType; 12623 if (TInfo->getType()->isPromotableIntegerType()) { 12624 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12625 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12626 PromoteType = QualType(); 12627 } 12628 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12629 PromoteType = Context.DoubleTy; 12630 if (!PromoteType.isNull()) 12631 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12632 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12633 << TInfo->getType() 12634 << PromoteType 12635 << TInfo->getTypeLoc().getSourceRange()); 12636 } 12637 12638 QualType T = TInfo->getType().getNonLValueExprType(Context); 12639 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12640 } 12641 12642 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12643 // The type of __null will be int or long, depending on the size of 12644 // pointers on the target. 12645 QualType Ty; 12646 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12647 if (pw == Context.getTargetInfo().getIntWidth()) 12648 Ty = Context.IntTy; 12649 else if (pw == Context.getTargetInfo().getLongWidth()) 12650 Ty = Context.LongTy; 12651 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12652 Ty = Context.LongLongTy; 12653 else { 12654 llvm_unreachable("I don't know size of pointer!"); 12655 } 12656 12657 return new (Context) GNUNullExpr(Ty, TokenLoc); 12658 } 12659 12660 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12661 bool Diagnose) { 12662 if (!getLangOpts().ObjC1) 12663 return false; 12664 12665 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12666 if (!PT) 12667 return false; 12668 12669 if (!PT->isObjCIdType()) { 12670 // Check if the destination is the 'NSString' interface. 12671 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12672 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12673 return false; 12674 } 12675 12676 // Ignore any parens, implicit casts (should only be 12677 // array-to-pointer decays), and not-so-opaque values. The last is 12678 // important for making this trigger for property assignments. 12679 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12680 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12681 if (OV->getSourceExpr()) 12682 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12683 12684 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12685 if (!SL || !SL->isAscii()) 12686 return false; 12687 if (Diagnose) { 12688 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12689 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12690 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12691 } 12692 return true; 12693 } 12694 12695 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12696 const Expr *SrcExpr) { 12697 if (!DstType->isFunctionPointerType() || 12698 !SrcExpr->getType()->isFunctionType()) 12699 return false; 12700 12701 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12702 if (!DRE) 12703 return false; 12704 12705 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12706 if (!FD) 12707 return false; 12708 12709 return !S.checkAddressOfFunctionIsAvailable(FD, 12710 /*Complain=*/true, 12711 SrcExpr->getLocStart()); 12712 } 12713 12714 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12715 SourceLocation Loc, 12716 QualType DstType, QualType SrcType, 12717 Expr *SrcExpr, AssignmentAction Action, 12718 bool *Complained) { 12719 if (Complained) 12720 *Complained = false; 12721 12722 // Decode the result (notice that AST's are still created for extensions). 12723 bool CheckInferredResultType = false; 12724 bool isInvalid = false; 12725 unsigned DiagKind = 0; 12726 FixItHint Hint; 12727 ConversionFixItGenerator ConvHints; 12728 bool MayHaveConvFixit = false; 12729 bool MayHaveFunctionDiff = false; 12730 const ObjCInterfaceDecl *IFace = nullptr; 12731 const ObjCProtocolDecl *PDecl = nullptr; 12732 12733 switch (ConvTy) { 12734 case Compatible: 12735 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12736 return false; 12737 12738 case PointerToInt: 12739 DiagKind = diag::ext_typecheck_convert_pointer_int; 12740 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12741 MayHaveConvFixit = true; 12742 break; 12743 case IntToPointer: 12744 DiagKind = diag::ext_typecheck_convert_int_pointer; 12745 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12746 MayHaveConvFixit = true; 12747 break; 12748 case IncompatiblePointer: 12749 if (Action == AA_Passing_CFAudited) 12750 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12751 else if (SrcType->isFunctionPointerType() && 12752 DstType->isFunctionPointerType()) 12753 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12754 else 12755 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12756 12757 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12758 SrcType->isObjCObjectPointerType(); 12759 if (Hint.isNull() && !CheckInferredResultType) { 12760 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12761 } 12762 else if (CheckInferredResultType) { 12763 SrcType = SrcType.getUnqualifiedType(); 12764 DstType = DstType.getUnqualifiedType(); 12765 } 12766 MayHaveConvFixit = true; 12767 break; 12768 case IncompatiblePointerSign: 12769 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12770 break; 12771 case FunctionVoidPointer: 12772 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12773 break; 12774 case IncompatiblePointerDiscardsQualifiers: { 12775 // Perform array-to-pointer decay if necessary. 12776 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12777 12778 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12779 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12780 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12781 DiagKind = diag::err_typecheck_incompatible_address_space; 12782 break; 12783 12784 12785 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12786 DiagKind = diag::err_typecheck_incompatible_ownership; 12787 break; 12788 } 12789 12790 llvm_unreachable("unknown error case for discarding qualifiers!"); 12791 // fallthrough 12792 } 12793 case CompatiblePointerDiscardsQualifiers: 12794 // If the qualifiers lost were because we were applying the 12795 // (deprecated) C++ conversion from a string literal to a char* 12796 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12797 // Ideally, this check would be performed in 12798 // checkPointerTypesForAssignment. However, that would require a 12799 // bit of refactoring (so that the second argument is an 12800 // expression, rather than a type), which should be done as part 12801 // of a larger effort to fix checkPointerTypesForAssignment for 12802 // C++ semantics. 12803 if (getLangOpts().CPlusPlus && 12804 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12805 return false; 12806 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12807 break; 12808 case IncompatibleNestedPointerQualifiers: 12809 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12810 break; 12811 case IntToBlockPointer: 12812 DiagKind = diag::err_int_to_block_pointer; 12813 break; 12814 case IncompatibleBlockPointer: 12815 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12816 break; 12817 case IncompatibleObjCQualifiedId: { 12818 if (SrcType->isObjCQualifiedIdType()) { 12819 const ObjCObjectPointerType *srcOPT = 12820 SrcType->getAs<ObjCObjectPointerType>(); 12821 for (auto *srcProto : srcOPT->quals()) { 12822 PDecl = srcProto; 12823 break; 12824 } 12825 if (const ObjCInterfaceType *IFaceT = 12826 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12827 IFace = IFaceT->getDecl(); 12828 } 12829 else if (DstType->isObjCQualifiedIdType()) { 12830 const ObjCObjectPointerType *dstOPT = 12831 DstType->getAs<ObjCObjectPointerType>(); 12832 for (auto *dstProto : dstOPT->quals()) { 12833 PDecl = dstProto; 12834 break; 12835 } 12836 if (const ObjCInterfaceType *IFaceT = 12837 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12838 IFace = IFaceT->getDecl(); 12839 } 12840 DiagKind = diag::warn_incompatible_qualified_id; 12841 break; 12842 } 12843 case IncompatibleVectors: 12844 DiagKind = diag::warn_incompatible_vectors; 12845 break; 12846 case IncompatibleObjCWeakRef: 12847 DiagKind = diag::err_arc_weak_unavailable_assign; 12848 break; 12849 case Incompatible: 12850 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12851 if (Complained) 12852 *Complained = true; 12853 return true; 12854 } 12855 12856 DiagKind = diag::err_typecheck_convert_incompatible; 12857 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12858 MayHaveConvFixit = true; 12859 isInvalid = true; 12860 MayHaveFunctionDiff = true; 12861 break; 12862 } 12863 12864 QualType FirstType, SecondType; 12865 switch (Action) { 12866 case AA_Assigning: 12867 case AA_Initializing: 12868 // The destination type comes first. 12869 FirstType = DstType; 12870 SecondType = SrcType; 12871 break; 12872 12873 case AA_Returning: 12874 case AA_Passing: 12875 case AA_Passing_CFAudited: 12876 case AA_Converting: 12877 case AA_Sending: 12878 case AA_Casting: 12879 // The source type comes first. 12880 FirstType = SrcType; 12881 SecondType = DstType; 12882 break; 12883 } 12884 12885 PartialDiagnostic FDiag = PDiag(DiagKind); 12886 if (Action == AA_Passing_CFAudited) 12887 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12888 else 12889 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12890 12891 // If we can fix the conversion, suggest the FixIts. 12892 assert(ConvHints.isNull() || Hint.isNull()); 12893 if (!ConvHints.isNull()) { 12894 for (FixItHint &H : ConvHints.Hints) 12895 FDiag << H; 12896 } else { 12897 FDiag << Hint; 12898 } 12899 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12900 12901 if (MayHaveFunctionDiff) 12902 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12903 12904 Diag(Loc, FDiag); 12905 if (DiagKind == diag::warn_incompatible_qualified_id && 12906 PDecl && IFace && !IFace->hasDefinition()) 12907 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 12908 << IFace->getName() << PDecl->getName(); 12909 12910 if (SecondType == Context.OverloadTy) 12911 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12912 FirstType, /*TakingAddress=*/true); 12913 12914 if (CheckInferredResultType) 12915 EmitRelatedResultTypeNote(SrcExpr); 12916 12917 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12918 EmitRelatedResultTypeNoteForReturn(DstType); 12919 12920 if (Complained) 12921 *Complained = true; 12922 return isInvalid; 12923 } 12924 12925 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12926 llvm::APSInt *Result) { 12927 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12928 public: 12929 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12930 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12931 } 12932 } Diagnoser; 12933 12934 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12935 } 12936 12937 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12938 llvm::APSInt *Result, 12939 unsigned DiagID, 12940 bool AllowFold) { 12941 class IDDiagnoser : public VerifyICEDiagnoser { 12942 unsigned DiagID; 12943 12944 public: 12945 IDDiagnoser(unsigned DiagID) 12946 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12947 12948 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12949 S.Diag(Loc, DiagID) << SR; 12950 } 12951 } Diagnoser(DiagID); 12952 12953 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12954 } 12955 12956 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12957 SourceRange SR) { 12958 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12959 } 12960 12961 ExprResult 12962 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12963 VerifyICEDiagnoser &Diagnoser, 12964 bool AllowFold) { 12965 SourceLocation DiagLoc = E->getLocStart(); 12966 12967 if (getLangOpts().CPlusPlus11) { 12968 // C++11 [expr.const]p5: 12969 // If an expression of literal class type is used in a context where an 12970 // integral constant expression is required, then that class type shall 12971 // have a single non-explicit conversion function to an integral or 12972 // unscoped enumeration type 12973 ExprResult Converted; 12974 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12975 public: 12976 CXX11ConvertDiagnoser(bool Silent) 12977 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12978 Silent, true) {} 12979 12980 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12981 QualType T) override { 12982 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12983 } 12984 12985 SemaDiagnosticBuilder diagnoseIncomplete( 12986 Sema &S, SourceLocation Loc, QualType T) override { 12987 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12988 } 12989 12990 SemaDiagnosticBuilder diagnoseExplicitConv( 12991 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12992 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12993 } 12994 12995 SemaDiagnosticBuilder noteExplicitConv( 12996 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12997 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12998 << ConvTy->isEnumeralType() << ConvTy; 12999 } 13000 13001 SemaDiagnosticBuilder diagnoseAmbiguous( 13002 Sema &S, SourceLocation Loc, QualType T) override { 13003 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13004 } 13005 13006 SemaDiagnosticBuilder noteAmbiguous( 13007 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13008 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13009 << ConvTy->isEnumeralType() << ConvTy; 13010 } 13011 13012 SemaDiagnosticBuilder diagnoseConversion( 13013 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13014 llvm_unreachable("conversion functions are permitted"); 13015 } 13016 } ConvertDiagnoser(Diagnoser.Suppress); 13017 13018 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13019 ConvertDiagnoser); 13020 if (Converted.isInvalid()) 13021 return Converted; 13022 E = Converted.get(); 13023 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13024 return ExprError(); 13025 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13026 // An ICE must be of integral or unscoped enumeration type. 13027 if (!Diagnoser.Suppress) 13028 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13029 return ExprError(); 13030 } 13031 13032 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13033 // in the non-ICE case. 13034 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13035 if (Result) 13036 *Result = E->EvaluateKnownConstInt(Context); 13037 return E; 13038 } 13039 13040 Expr::EvalResult EvalResult; 13041 SmallVector<PartialDiagnosticAt, 8> Notes; 13042 EvalResult.Diag = &Notes; 13043 13044 // Try to evaluate the expression, and produce diagnostics explaining why it's 13045 // not a constant expression as a side-effect. 13046 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13047 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13048 13049 // In C++11, we can rely on diagnostics being produced for any expression 13050 // which is not a constant expression. If no diagnostics were produced, then 13051 // this is a constant expression. 13052 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13053 if (Result) 13054 *Result = EvalResult.Val.getInt(); 13055 return E; 13056 } 13057 13058 // If our only note is the usual "invalid subexpression" note, just point 13059 // the caret at its location rather than producing an essentially 13060 // redundant note. 13061 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13062 diag::note_invalid_subexpr_in_const_expr) { 13063 DiagLoc = Notes[0].first; 13064 Notes.clear(); 13065 } 13066 13067 if (!Folded || !AllowFold) { 13068 if (!Diagnoser.Suppress) { 13069 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13070 for (const PartialDiagnosticAt &Note : Notes) 13071 Diag(Note.first, Note.second); 13072 } 13073 13074 return ExprError(); 13075 } 13076 13077 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13078 for (const PartialDiagnosticAt &Note : Notes) 13079 Diag(Note.first, Note.second); 13080 13081 if (Result) 13082 *Result = EvalResult.Val.getInt(); 13083 return E; 13084 } 13085 13086 namespace { 13087 // Handle the case where we conclude a expression which we speculatively 13088 // considered to be unevaluated is actually evaluated. 13089 class TransformToPE : public TreeTransform<TransformToPE> { 13090 typedef TreeTransform<TransformToPE> BaseTransform; 13091 13092 public: 13093 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13094 13095 // Make sure we redo semantic analysis 13096 bool AlwaysRebuild() { return true; } 13097 13098 // Make sure we handle LabelStmts correctly. 13099 // FIXME: This does the right thing, but maybe we need a more general 13100 // fix to TreeTransform? 13101 StmtResult TransformLabelStmt(LabelStmt *S) { 13102 S->getDecl()->setStmt(nullptr); 13103 return BaseTransform::TransformLabelStmt(S); 13104 } 13105 13106 // We need to special-case DeclRefExprs referring to FieldDecls which 13107 // are not part of a member pointer formation; normal TreeTransforming 13108 // doesn't catch this case because of the way we represent them in the AST. 13109 // FIXME: This is a bit ugly; is it really the best way to handle this 13110 // case? 13111 // 13112 // Error on DeclRefExprs referring to FieldDecls. 13113 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13114 if (isa<FieldDecl>(E->getDecl()) && 13115 !SemaRef.isUnevaluatedContext()) 13116 return SemaRef.Diag(E->getLocation(), 13117 diag::err_invalid_non_static_member_use) 13118 << E->getDecl() << E->getSourceRange(); 13119 13120 return BaseTransform::TransformDeclRefExpr(E); 13121 } 13122 13123 // Exception: filter out member pointer formation 13124 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13125 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13126 return E; 13127 13128 return BaseTransform::TransformUnaryOperator(E); 13129 } 13130 13131 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13132 // Lambdas never need to be transformed. 13133 return E; 13134 } 13135 }; 13136 } 13137 13138 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13139 assert(isUnevaluatedContext() && 13140 "Should only transform unevaluated expressions"); 13141 ExprEvalContexts.back().Context = 13142 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13143 if (isUnevaluatedContext()) 13144 return E; 13145 return TransformToPE(*this).TransformExpr(E); 13146 } 13147 13148 void 13149 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13150 Decl *LambdaContextDecl, 13151 bool IsDecltype) { 13152 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13153 LambdaContextDecl, IsDecltype); 13154 Cleanup.reset(); 13155 if (!MaybeODRUseExprs.empty()) 13156 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13157 } 13158 13159 void 13160 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13161 ReuseLambdaContextDecl_t, 13162 bool IsDecltype) { 13163 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13164 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13165 } 13166 13167 void Sema::PopExpressionEvaluationContext() { 13168 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13169 unsigned NumTypos = Rec.NumTypos; 13170 13171 if (!Rec.Lambdas.empty()) { 13172 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13173 unsigned D; 13174 if (Rec.isUnevaluated()) { 13175 // C++11 [expr.prim.lambda]p2: 13176 // A lambda-expression shall not appear in an unevaluated operand 13177 // (Clause 5). 13178 D = diag::err_lambda_unevaluated_operand; 13179 } else { 13180 // C++1y [expr.const]p2: 13181 // A conditional-expression e is a core constant expression unless the 13182 // evaluation of e, following the rules of the abstract machine, would 13183 // evaluate [...] a lambda-expression. 13184 D = diag::err_lambda_in_constant_expression; 13185 } 13186 13187 // C++1z allows lambda expressions as core constant expressions. 13188 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13189 // 1607) from appearing within template-arguments and array-bounds that 13190 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13191 // unevaluated contexts) might lift some of these restrictions in a 13192 // future version. 13193 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z) 13194 for (const auto *L : Rec.Lambdas) 13195 Diag(L->getLocStart(), D); 13196 } else { 13197 // Mark the capture expressions odr-used. This was deferred 13198 // during lambda expression creation. 13199 for (auto *Lambda : Rec.Lambdas) { 13200 for (auto *C : Lambda->capture_inits()) 13201 MarkDeclarationsReferencedInExpr(C); 13202 } 13203 } 13204 } 13205 13206 // When are coming out of an unevaluated context, clear out any 13207 // temporaries that we may have created as part of the evaluation of 13208 // the expression in that context: they aren't relevant because they 13209 // will never be constructed. 13210 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13211 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13212 ExprCleanupObjects.end()); 13213 Cleanup = Rec.ParentCleanup; 13214 CleanupVarDeclMarking(); 13215 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13216 // Otherwise, merge the contexts together. 13217 } else { 13218 Cleanup.mergeFrom(Rec.ParentCleanup); 13219 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13220 Rec.SavedMaybeODRUseExprs.end()); 13221 } 13222 13223 // Pop the current expression evaluation context off the stack. 13224 ExprEvalContexts.pop_back(); 13225 13226 if (!ExprEvalContexts.empty()) 13227 ExprEvalContexts.back().NumTypos += NumTypos; 13228 else 13229 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13230 "last ExpressionEvaluationContextRecord"); 13231 } 13232 13233 void Sema::DiscardCleanupsInEvaluationContext() { 13234 ExprCleanupObjects.erase( 13235 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13236 ExprCleanupObjects.end()); 13237 Cleanup.reset(); 13238 MaybeODRUseExprs.clear(); 13239 } 13240 13241 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13242 if (!E->getType()->isVariablyModifiedType()) 13243 return E; 13244 return TransformToPotentiallyEvaluated(E); 13245 } 13246 13247 /// Are we within a context in which some evaluation could be performed (be it 13248 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13249 /// captured by C++'s idea of an "unevaluated context". 13250 static bool isEvaluatableContext(Sema &SemaRef) { 13251 switch (SemaRef.ExprEvalContexts.back().Context) { 13252 case Sema::ExpressionEvaluationContext::Unevaluated: 13253 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13254 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13255 // Expressions in this context are never evaluated. 13256 return false; 13257 13258 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13259 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13260 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13261 // Expressions in this context could be evaluated. 13262 return true; 13263 13264 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13265 // Referenced declarations will only be used if the construct in the 13266 // containing expression is used, at which point we'll be given another 13267 // turn to mark them. 13268 return false; 13269 } 13270 llvm_unreachable("Invalid context"); 13271 } 13272 13273 /// Are we within a context in which references to resolved functions or to 13274 /// variables result in odr-use? 13275 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13276 // An expression in a template is not really an expression until it's been 13277 // instantiated, so it doesn't trigger odr-use. 13278 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13279 return false; 13280 13281 switch (SemaRef.ExprEvalContexts.back().Context) { 13282 case Sema::ExpressionEvaluationContext::Unevaluated: 13283 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13284 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13285 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13286 return false; 13287 13288 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13289 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13290 return true; 13291 13292 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13293 return false; 13294 } 13295 llvm_unreachable("Invalid context"); 13296 } 13297 13298 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13299 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13300 return Func->isConstexpr() && 13301 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13302 } 13303 13304 /// \brief Mark a function referenced, and check whether it is odr-used 13305 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13306 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13307 bool MightBeOdrUse) { 13308 assert(Func && "No function?"); 13309 13310 Func->setReferenced(); 13311 13312 // C++11 [basic.def.odr]p3: 13313 // A function whose name appears as a potentially-evaluated expression is 13314 // odr-used if it is the unique lookup result or the selected member of a 13315 // set of overloaded functions [...]. 13316 // 13317 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13318 // can just check that here. 13319 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13320 13321 // Determine whether we require a function definition to exist, per 13322 // C++11 [temp.inst]p3: 13323 // Unless a function template specialization has been explicitly 13324 // instantiated or explicitly specialized, the function template 13325 // specialization is implicitly instantiated when the specialization is 13326 // referenced in a context that requires a function definition to exist. 13327 // 13328 // That is either when this is an odr-use, or when a usage of a constexpr 13329 // function occurs within an evaluatable context. 13330 bool NeedDefinition = 13331 OdrUse || (isEvaluatableContext(*this) && 13332 isImplicitlyDefinableConstexprFunction(Func)); 13333 13334 // C++14 [temp.expl.spec]p6: 13335 // If a template [...] is explicitly specialized then that specialization 13336 // shall be declared before the first use of that specialization that would 13337 // cause an implicit instantiation to take place, in every translation unit 13338 // in which such a use occurs 13339 if (NeedDefinition && 13340 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13341 Func->getMemberSpecializationInfo())) 13342 checkSpecializationVisibility(Loc, Func); 13343 13344 // C++14 [except.spec]p17: 13345 // An exception-specification is considered to be needed when: 13346 // - the function is odr-used or, if it appears in an unevaluated operand, 13347 // would be odr-used if the expression were potentially-evaluated; 13348 // 13349 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13350 // function is a pure virtual function we're calling, and in that case the 13351 // function was selected by overload resolution and we need to resolve its 13352 // exception specification for a different reason. 13353 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13354 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13355 ResolveExceptionSpec(Loc, FPT); 13356 13357 // If we don't need to mark the function as used, and we don't need to 13358 // try to provide a definition, there's nothing more to do. 13359 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13360 (!NeedDefinition || Func->getBody())) 13361 return; 13362 13363 // Note that this declaration has been used. 13364 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13365 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13366 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13367 if (Constructor->isDefaultConstructor()) { 13368 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13369 return; 13370 DefineImplicitDefaultConstructor(Loc, Constructor); 13371 } else if (Constructor->isCopyConstructor()) { 13372 DefineImplicitCopyConstructor(Loc, Constructor); 13373 } else if (Constructor->isMoveConstructor()) { 13374 DefineImplicitMoveConstructor(Loc, Constructor); 13375 } 13376 } else if (Constructor->getInheritedConstructor()) { 13377 DefineInheritingConstructor(Loc, Constructor); 13378 } 13379 } else if (CXXDestructorDecl *Destructor = 13380 dyn_cast<CXXDestructorDecl>(Func)) { 13381 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13382 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13383 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13384 return; 13385 DefineImplicitDestructor(Loc, Destructor); 13386 } 13387 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13388 MarkVTableUsed(Loc, Destructor->getParent()); 13389 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13390 if (MethodDecl->isOverloadedOperator() && 13391 MethodDecl->getOverloadedOperator() == OO_Equal) { 13392 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13393 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13394 if (MethodDecl->isCopyAssignmentOperator()) 13395 DefineImplicitCopyAssignment(Loc, MethodDecl); 13396 else if (MethodDecl->isMoveAssignmentOperator()) 13397 DefineImplicitMoveAssignment(Loc, MethodDecl); 13398 } 13399 } else if (isa<CXXConversionDecl>(MethodDecl) && 13400 MethodDecl->getParent()->isLambda()) { 13401 CXXConversionDecl *Conversion = 13402 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13403 if (Conversion->isLambdaToBlockPointerConversion()) 13404 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13405 else 13406 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13407 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13408 MarkVTableUsed(Loc, MethodDecl->getParent()); 13409 } 13410 13411 // Recursive functions should be marked when used from another function. 13412 // FIXME: Is this really right? 13413 if (CurContext == Func) return; 13414 13415 // Implicit instantiation of function templates and member functions of 13416 // class templates. 13417 if (Func->isImplicitlyInstantiable()) { 13418 bool AlreadyInstantiated = false; 13419 SourceLocation PointOfInstantiation = Loc; 13420 if (FunctionTemplateSpecializationInfo *SpecInfo 13421 = Func->getTemplateSpecializationInfo()) { 13422 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13423 SpecInfo->setPointOfInstantiation(Loc); 13424 else if (SpecInfo->getTemplateSpecializationKind() 13425 == TSK_ImplicitInstantiation) { 13426 AlreadyInstantiated = true; 13427 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13428 } 13429 } else if (MemberSpecializationInfo *MSInfo 13430 = Func->getMemberSpecializationInfo()) { 13431 if (MSInfo->getPointOfInstantiation().isInvalid()) 13432 MSInfo->setPointOfInstantiation(Loc); 13433 else if (MSInfo->getTemplateSpecializationKind() 13434 == TSK_ImplicitInstantiation) { 13435 AlreadyInstantiated = true; 13436 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13437 } 13438 } 13439 13440 if (!AlreadyInstantiated || Func->isConstexpr()) { 13441 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13442 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13443 CodeSynthesisContexts.size()) 13444 PendingLocalImplicitInstantiations.push_back( 13445 std::make_pair(Func, PointOfInstantiation)); 13446 else if (Func->isConstexpr()) 13447 // Do not defer instantiations of constexpr functions, to avoid the 13448 // expression evaluator needing to call back into Sema if it sees a 13449 // call to such a function. 13450 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13451 else { 13452 PendingInstantiations.push_back(std::make_pair(Func, 13453 PointOfInstantiation)); 13454 // Notify the consumer that a function was implicitly instantiated. 13455 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13456 } 13457 } 13458 } else { 13459 // Walk redefinitions, as some of them may be instantiable. 13460 for (auto i : Func->redecls()) { 13461 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13462 MarkFunctionReferenced(Loc, i, OdrUse); 13463 } 13464 } 13465 13466 if (!OdrUse) return; 13467 13468 // Keep track of used but undefined functions. 13469 if (!Func->isDefined()) { 13470 if (mightHaveNonExternalLinkage(Func)) 13471 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13472 else if (Func->getMostRecentDecl()->isInlined() && 13473 !LangOpts.GNUInline && 13474 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13475 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13476 } 13477 13478 Func->markUsed(Context); 13479 } 13480 13481 static void 13482 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13483 ValueDecl *var, DeclContext *DC) { 13484 DeclContext *VarDC = var->getDeclContext(); 13485 13486 // If the parameter still belongs to the translation unit, then 13487 // we're actually just using one parameter in the declaration of 13488 // the next. 13489 if (isa<ParmVarDecl>(var) && 13490 isa<TranslationUnitDecl>(VarDC)) 13491 return; 13492 13493 // For C code, don't diagnose about capture if we're not actually in code 13494 // right now; it's impossible to write a non-constant expression outside of 13495 // function context, so we'll get other (more useful) diagnostics later. 13496 // 13497 // For C++, things get a bit more nasty... it would be nice to suppress this 13498 // diagnostic for certain cases like using a local variable in an array bound 13499 // for a member of a local class, but the correct predicate is not obvious. 13500 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13501 return; 13502 13503 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13504 unsigned ContextKind = 3; // unknown 13505 if (isa<CXXMethodDecl>(VarDC) && 13506 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13507 ContextKind = 2; 13508 } else if (isa<FunctionDecl>(VarDC)) { 13509 ContextKind = 0; 13510 } else if (isa<BlockDecl>(VarDC)) { 13511 ContextKind = 1; 13512 } 13513 13514 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13515 << var << ValueKind << ContextKind << VarDC; 13516 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13517 << var; 13518 13519 // FIXME: Add additional diagnostic info about class etc. which prevents 13520 // capture. 13521 } 13522 13523 13524 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13525 bool &SubCapturesAreNested, 13526 QualType &CaptureType, 13527 QualType &DeclRefType) { 13528 // Check whether we've already captured it. 13529 if (CSI->CaptureMap.count(Var)) { 13530 // If we found a capture, any subcaptures are nested. 13531 SubCapturesAreNested = true; 13532 13533 // Retrieve the capture type for this variable. 13534 CaptureType = CSI->getCapture(Var).getCaptureType(); 13535 13536 // Compute the type of an expression that refers to this variable. 13537 DeclRefType = CaptureType.getNonReferenceType(); 13538 13539 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13540 // are mutable in the sense that user can change their value - they are 13541 // private instances of the captured declarations. 13542 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13543 if (Cap.isCopyCapture() && 13544 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13545 !(isa<CapturedRegionScopeInfo>(CSI) && 13546 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13547 DeclRefType.addConst(); 13548 return true; 13549 } 13550 return false; 13551 } 13552 13553 // Only block literals, captured statements, and lambda expressions can 13554 // capture; other scopes don't work. 13555 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13556 SourceLocation Loc, 13557 const bool Diagnose, Sema &S) { 13558 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13559 return getLambdaAwareParentOfDeclContext(DC); 13560 else if (Var->hasLocalStorage()) { 13561 if (Diagnose) 13562 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13563 } 13564 return nullptr; 13565 } 13566 13567 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13568 // certain types of variables (unnamed, variably modified types etc.) 13569 // so check for eligibility. 13570 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13571 SourceLocation Loc, 13572 const bool Diagnose, Sema &S) { 13573 13574 bool IsBlock = isa<BlockScopeInfo>(CSI); 13575 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13576 13577 // Lambdas are not allowed to capture unnamed variables 13578 // (e.g. anonymous unions). 13579 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13580 // assuming that's the intent. 13581 if (IsLambda && !Var->getDeclName()) { 13582 if (Diagnose) { 13583 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13584 S.Diag(Var->getLocation(), diag::note_declared_at); 13585 } 13586 return false; 13587 } 13588 13589 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13590 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13591 if (Diagnose) { 13592 S.Diag(Loc, diag::err_ref_vm_type); 13593 S.Diag(Var->getLocation(), diag::note_previous_decl) 13594 << Var->getDeclName(); 13595 } 13596 return false; 13597 } 13598 // Prohibit structs with flexible array members too. 13599 // We cannot capture what is in the tail end of the struct. 13600 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13601 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13602 if (Diagnose) { 13603 if (IsBlock) 13604 S.Diag(Loc, diag::err_ref_flexarray_type); 13605 else 13606 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13607 << Var->getDeclName(); 13608 S.Diag(Var->getLocation(), diag::note_previous_decl) 13609 << Var->getDeclName(); 13610 } 13611 return false; 13612 } 13613 } 13614 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13615 // Lambdas and captured statements are not allowed to capture __block 13616 // variables; they don't support the expected semantics. 13617 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13618 if (Diagnose) { 13619 S.Diag(Loc, diag::err_capture_block_variable) 13620 << Var->getDeclName() << !IsLambda; 13621 S.Diag(Var->getLocation(), diag::note_previous_decl) 13622 << Var->getDeclName(); 13623 } 13624 return false; 13625 } 13626 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 13627 if (S.getLangOpts().OpenCL && IsBlock && 13628 Var->getType()->isBlockPointerType()) { 13629 if (Diagnose) 13630 S.Diag(Loc, diag::err_opencl_block_ref_block); 13631 return false; 13632 } 13633 13634 return true; 13635 } 13636 13637 // Returns true if the capture by block was successful. 13638 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13639 SourceLocation Loc, 13640 const bool BuildAndDiagnose, 13641 QualType &CaptureType, 13642 QualType &DeclRefType, 13643 const bool Nested, 13644 Sema &S) { 13645 Expr *CopyExpr = nullptr; 13646 bool ByRef = false; 13647 13648 // Blocks are not allowed to capture arrays. 13649 if (CaptureType->isArrayType()) { 13650 if (BuildAndDiagnose) { 13651 S.Diag(Loc, diag::err_ref_array_type); 13652 S.Diag(Var->getLocation(), diag::note_previous_decl) 13653 << Var->getDeclName(); 13654 } 13655 return false; 13656 } 13657 13658 // Forbid the block-capture of autoreleasing variables. 13659 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13660 if (BuildAndDiagnose) { 13661 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13662 << /*block*/ 0; 13663 S.Diag(Var->getLocation(), diag::note_previous_decl) 13664 << Var->getDeclName(); 13665 } 13666 return false; 13667 } 13668 13669 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13670 if (const auto *PT = CaptureType->getAs<PointerType>()) { 13671 // This function finds out whether there is an AttributedType of kind 13672 // attr_objc_ownership in Ty. The existence of AttributedType of kind 13673 // attr_objc_ownership implies __autoreleasing was explicitly specified 13674 // rather than being added implicitly by the compiler. 13675 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 13676 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 13677 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 13678 return true; 13679 13680 // Peel off AttributedTypes that are not of kind objc_ownership. 13681 Ty = AttrTy->getModifiedType(); 13682 } 13683 13684 return false; 13685 }; 13686 13687 QualType PointeeTy = PT->getPointeeType(); 13688 13689 if (PointeeTy->getAs<ObjCObjectPointerType>() && 13690 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13691 !IsObjCOwnershipAttributedType(PointeeTy)) { 13692 if (BuildAndDiagnose) { 13693 SourceLocation VarLoc = Var->getLocation(); 13694 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13695 { 13696 auto AddAutoreleaseNote = 13697 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 13698 // Provide a fix-it for the '__autoreleasing' keyword at the 13699 // appropriate location in the variable's type. 13700 if (const auto *TSI = Var->getTypeSourceInfo()) { 13701 PointerTypeLoc PTL = 13702 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 13703 if (PTL) { 13704 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 13705 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 13706 S.getLangOpts()); 13707 if (Loc.isValid()) { 13708 StringRef CharAtLoc = Lexer::getSourceText( 13709 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 13710 S.getSourceManager(), S.getLangOpts()); 13711 AddAutoreleaseNote << FixItHint::CreateInsertion( 13712 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 13713 ? " __autoreleasing " 13714 : " __autoreleasing"); 13715 } 13716 } 13717 } 13718 } 13719 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13720 } 13721 } 13722 } 13723 13724 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13725 if (HasBlocksAttr || CaptureType->isReferenceType() || 13726 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13727 // Block capture by reference does not change the capture or 13728 // declaration reference types. 13729 ByRef = true; 13730 } else { 13731 // Block capture by copy introduces 'const'. 13732 CaptureType = CaptureType.getNonReferenceType().withConst(); 13733 DeclRefType = CaptureType; 13734 13735 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13736 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13737 // The capture logic needs the destructor, so make sure we mark it. 13738 // Usually this is unnecessary because most local variables have 13739 // their destructors marked at declaration time, but parameters are 13740 // an exception because it's technically only the call site that 13741 // actually requires the destructor. 13742 if (isa<ParmVarDecl>(Var)) 13743 S.FinalizeVarWithDestructor(Var, Record); 13744 13745 // Enter a new evaluation context to insulate the copy 13746 // full-expression. 13747 EnterExpressionEvaluationContext scope( 13748 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 13749 13750 // According to the blocks spec, the capture of a variable from 13751 // the stack requires a const copy constructor. This is not true 13752 // of the copy/move done to move a __block variable to the heap. 13753 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13754 DeclRefType.withConst(), 13755 VK_LValue, Loc); 13756 13757 ExprResult Result 13758 = S.PerformCopyInitialization( 13759 InitializedEntity::InitializeBlock(Var->getLocation(), 13760 CaptureType, false), 13761 Loc, DeclRef); 13762 13763 // Build a full-expression copy expression if initialization 13764 // succeeded and used a non-trivial constructor. Recover from 13765 // errors by pretending that the copy isn't necessary. 13766 if (!Result.isInvalid() && 13767 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13768 ->isTrivial()) { 13769 Result = S.MaybeCreateExprWithCleanups(Result); 13770 CopyExpr = Result.get(); 13771 } 13772 } 13773 } 13774 } 13775 13776 // Actually capture the variable. 13777 if (BuildAndDiagnose) 13778 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13779 SourceLocation(), CaptureType, CopyExpr); 13780 13781 return true; 13782 13783 } 13784 13785 13786 /// \brief Capture the given variable in the captured region. 13787 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13788 VarDecl *Var, 13789 SourceLocation Loc, 13790 const bool BuildAndDiagnose, 13791 QualType &CaptureType, 13792 QualType &DeclRefType, 13793 const bool RefersToCapturedVariable, 13794 Sema &S) { 13795 // By default, capture variables by reference. 13796 bool ByRef = true; 13797 // Using an LValue reference type is consistent with Lambdas (see below). 13798 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13799 if (S.IsOpenMPCapturedDecl(Var)) 13800 DeclRefType = DeclRefType.getUnqualifiedType(); 13801 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13802 } 13803 13804 if (ByRef) 13805 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13806 else 13807 CaptureType = DeclRefType; 13808 13809 Expr *CopyExpr = nullptr; 13810 if (BuildAndDiagnose) { 13811 // The current implementation assumes that all variables are captured 13812 // by references. Since there is no capture by copy, no expression 13813 // evaluation will be needed. 13814 RecordDecl *RD = RSI->TheRecordDecl; 13815 13816 FieldDecl *Field 13817 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13818 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13819 nullptr, false, ICIS_NoInit); 13820 Field->setImplicit(true); 13821 Field->setAccess(AS_private); 13822 RD->addDecl(Field); 13823 13824 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13825 DeclRefType, VK_LValue, Loc); 13826 Var->setReferenced(true); 13827 Var->markUsed(S.Context); 13828 } 13829 13830 // Actually capture the variable. 13831 if (BuildAndDiagnose) 13832 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13833 SourceLocation(), CaptureType, CopyExpr); 13834 13835 13836 return true; 13837 } 13838 13839 /// \brief Create a field within the lambda class for the variable 13840 /// being captured. 13841 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13842 QualType FieldType, QualType DeclRefType, 13843 SourceLocation Loc, 13844 bool RefersToCapturedVariable) { 13845 CXXRecordDecl *Lambda = LSI->Lambda; 13846 13847 // Build the non-static data member. 13848 FieldDecl *Field 13849 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13850 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13851 nullptr, false, ICIS_NoInit); 13852 Field->setImplicit(true); 13853 Field->setAccess(AS_private); 13854 Lambda->addDecl(Field); 13855 } 13856 13857 /// \brief Capture the given variable in the lambda. 13858 static bool captureInLambda(LambdaScopeInfo *LSI, 13859 VarDecl *Var, 13860 SourceLocation Loc, 13861 const bool BuildAndDiagnose, 13862 QualType &CaptureType, 13863 QualType &DeclRefType, 13864 const bool RefersToCapturedVariable, 13865 const Sema::TryCaptureKind Kind, 13866 SourceLocation EllipsisLoc, 13867 const bool IsTopScope, 13868 Sema &S) { 13869 13870 // Determine whether we are capturing by reference or by value. 13871 bool ByRef = false; 13872 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13873 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13874 } else { 13875 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13876 } 13877 13878 // Compute the type of the field that will capture this variable. 13879 if (ByRef) { 13880 // C++11 [expr.prim.lambda]p15: 13881 // An entity is captured by reference if it is implicitly or 13882 // explicitly captured but not captured by copy. It is 13883 // unspecified whether additional unnamed non-static data 13884 // members are declared in the closure type for entities 13885 // captured by reference. 13886 // 13887 // FIXME: It is not clear whether we want to build an lvalue reference 13888 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13889 // to do the former, while EDG does the latter. Core issue 1249 will 13890 // clarify, but for now we follow GCC because it's a more permissive and 13891 // easily defensible position. 13892 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13893 } else { 13894 // C++11 [expr.prim.lambda]p14: 13895 // For each entity captured by copy, an unnamed non-static 13896 // data member is declared in the closure type. The 13897 // declaration order of these members is unspecified. The type 13898 // of such a data member is the type of the corresponding 13899 // captured entity if the entity is not a reference to an 13900 // object, or the referenced type otherwise. [Note: If the 13901 // captured entity is a reference to a function, the 13902 // corresponding data member is also a reference to a 13903 // function. - end note ] 13904 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13905 if (!RefType->getPointeeType()->isFunctionType()) 13906 CaptureType = RefType->getPointeeType(); 13907 } 13908 13909 // Forbid the lambda copy-capture of autoreleasing variables. 13910 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13911 if (BuildAndDiagnose) { 13912 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13913 S.Diag(Var->getLocation(), diag::note_previous_decl) 13914 << Var->getDeclName(); 13915 } 13916 return false; 13917 } 13918 13919 // Make sure that by-copy captures are of a complete and non-abstract type. 13920 if (BuildAndDiagnose) { 13921 if (!CaptureType->isDependentType() && 13922 S.RequireCompleteType(Loc, CaptureType, 13923 diag::err_capture_of_incomplete_type, 13924 Var->getDeclName())) 13925 return false; 13926 13927 if (S.RequireNonAbstractType(Loc, CaptureType, 13928 diag::err_capture_of_abstract_type)) 13929 return false; 13930 } 13931 } 13932 13933 // Capture this variable in the lambda. 13934 if (BuildAndDiagnose) 13935 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13936 RefersToCapturedVariable); 13937 13938 // Compute the type of a reference to this captured variable. 13939 if (ByRef) 13940 DeclRefType = CaptureType.getNonReferenceType(); 13941 else { 13942 // C++ [expr.prim.lambda]p5: 13943 // The closure type for a lambda-expression has a public inline 13944 // function call operator [...]. This function call operator is 13945 // declared const (9.3.1) if and only if the lambda-expression's 13946 // parameter-declaration-clause is not followed by mutable. 13947 DeclRefType = CaptureType.getNonReferenceType(); 13948 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13949 DeclRefType.addConst(); 13950 } 13951 13952 // Add the capture. 13953 if (BuildAndDiagnose) 13954 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13955 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13956 13957 return true; 13958 } 13959 13960 bool Sema::tryCaptureVariable( 13961 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13962 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13963 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13964 // An init-capture is notionally from the context surrounding its 13965 // declaration, but its parent DC is the lambda class. 13966 DeclContext *VarDC = Var->getDeclContext(); 13967 if (Var->isInitCapture()) 13968 VarDC = VarDC->getParent(); 13969 13970 DeclContext *DC = CurContext; 13971 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13972 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13973 // We need to sync up the Declaration Context with the 13974 // FunctionScopeIndexToStopAt 13975 if (FunctionScopeIndexToStopAt) { 13976 unsigned FSIndex = FunctionScopes.size() - 1; 13977 while (FSIndex != MaxFunctionScopesIndex) { 13978 DC = getLambdaAwareParentOfDeclContext(DC); 13979 --FSIndex; 13980 } 13981 } 13982 13983 13984 // If the variable is declared in the current context, there is no need to 13985 // capture it. 13986 if (VarDC == DC) return true; 13987 13988 // Capture global variables if it is required to use private copy of this 13989 // variable. 13990 bool IsGlobal = !Var->hasLocalStorage(); 13991 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13992 return true; 13993 13994 // Walk up the stack to determine whether we can capture the variable, 13995 // performing the "simple" checks that don't depend on type. We stop when 13996 // we've either hit the declared scope of the variable or find an existing 13997 // capture of that variable. We start from the innermost capturing-entity 13998 // (the DC) and ensure that all intervening capturing-entities 13999 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14000 // declcontext can either capture the variable or have already captured 14001 // the variable. 14002 CaptureType = Var->getType(); 14003 DeclRefType = CaptureType.getNonReferenceType(); 14004 bool Nested = false; 14005 bool Explicit = (Kind != TryCapture_Implicit); 14006 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14007 do { 14008 // Only block literals, captured statements, and lambda expressions can 14009 // capture; other scopes don't work. 14010 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14011 ExprLoc, 14012 BuildAndDiagnose, 14013 *this); 14014 // We need to check for the parent *first* because, if we *have* 14015 // private-captured a global variable, we need to recursively capture it in 14016 // intermediate blocks, lambdas, etc. 14017 if (!ParentDC) { 14018 if (IsGlobal) { 14019 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14020 break; 14021 } 14022 return true; 14023 } 14024 14025 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14026 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14027 14028 14029 // Check whether we've already captured it. 14030 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14031 DeclRefType)) { 14032 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14033 break; 14034 } 14035 // If we are instantiating a generic lambda call operator body, 14036 // we do not want to capture new variables. What was captured 14037 // during either a lambdas transformation or initial parsing 14038 // should be used. 14039 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14040 if (BuildAndDiagnose) { 14041 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14042 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14043 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14044 Diag(Var->getLocation(), diag::note_previous_decl) 14045 << Var->getDeclName(); 14046 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14047 } else 14048 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14049 } 14050 return true; 14051 } 14052 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14053 // certain types of variables (unnamed, variably modified types etc.) 14054 // so check for eligibility. 14055 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14056 return true; 14057 14058 // Try to capture variable-length arrays types. 14059 if (Var->getType()->isVariablyModifiedType()) { 14060 // We're going to walk down into the type and look for VLA 14061 // expressions. 14062 QualType QTy = Var->getType(); 14063 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14064 QTy = PVD->getOriginalType(); 14065 captureVariablyModifiedType(Context, QTy, CSI); 14066 } 14067 14068 if (getLangOpts().OpenMP) { 14069 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14070 // OpenMP private variables should not be captured in outer scope, so 14071 // just break here. Similarly, global variables that are captured in a 14072 // target region should not be captured outside the scope of the region. 14073 if (RSI->CapRegionKind == CR_OpenMP) { 14074 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14075 // When we detect target captures we are looking from inside the 14076 // target region, therefore we need to propagate the capture from the 14077 // enclosing region. Therefore, the capture is not initially nested. 14078 if (IsTargetCap) 14079 FunctionScopesIndex--; 14080 14081 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 14082 Nested = !IsTargetCap; 14083 DeclRefType = DeclRefType.getUnqualifiedType(); 14084 CaptureType = Context.getLValueReferenceType(DeclRefType); 14085 break; 14086 } 14087 } 14088 } 14089 } 14090 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14091 // No capture-default, and this is not an explicit capture 14092 // so cannot capture this variable. 14093 if (BuildAndDiagnose) { 14094 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14095 Diag(Var->getLocation(), diag::note_previous_decl) 14096 << Var->getDeclName(); 14097 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14098 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14099 diag::note_lambda_decl); 14100 // FIXME: If we error out because an outer lambda can not implicitly 14101 // capture a variable that an inner lambda explicitly captures, we 14102 // should have the inner lambda do the explicit capture - because 14103 // it makes for cleaner diagnostics later. This would purely be done 14104 // so that the diagnostic does not misleadingly claim that a variable 14105 // can not be captured by a lambda implicitly even though it is captured 14106 // explicitly. Suggestion: 14107 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14108 // at the function head 14109 // - cache the StartingDeclContext - this must be a lambda 14110 // - captureInLambda in the innermost lambda the variable. 14111 } 14112 return true; 14113 } 14114 14115 FunctionScopesIndex--; 14116 DC = ParentDC; 14117 Explicit = false; 14118 } while (!VarDC->Equals(DC)); 14119 14120 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14121 // computing the type of the capture at each step, checking type-specific 14122 // requirements, and adding captures if requested. 14123 // If the variable had already been captured previously, we start capturing 14124 // at the lambda nested within that one. 14125 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14126 ++I) { 14127 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14128 14129 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14130 if (!captureInBlock(BSI, Var, ExprLoc, 14131 BuildAndDiagnose, CaptureType, 14132 DeclRefType, Nested, *this)) 14133 return true; 14134 Nested = true; 14135 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14136 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14137 BuildAndDiagnose, CaptureType, 14138 DeclRefType, Nested, *this)) 14139 return true; 14140 Nested = true; 14141 } else { 14142 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14143 if (!captureInLambda(LSI, Var, ExprLoc, 14144 BuildAndDiagnose, CaptureType, 14145 DeclRefType, Nested, Kind, EllipsisLoc, 14146 /*IsTopScope*/I == N - 1, *this)) 14147 return true; 14148 Nested = true; 14149 } 14150 } 14151 return false; 14152 } 14153 14154 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14155 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14156 QualType CaptureType; 14157 QualType DeclRefType; 14158 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14159 /*BuildAndDiagnose=*/true, CaptureType, 14160 DeclRefType, nullptr); 14161 } 14162 14163 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14164 QualType CaptureType; 14165 QualType DeclRefType; 14166 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14167 /*BuildAndDiagnose=*/false, CaptureType, 14168 DeclRefType, nullptr); 14169 } 14170 14171 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14172 QualType CaptureType; 14173 QualType DeclRefType; 14174 14175 // Determine whether we can capture this variable. 14176 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14177 /*BuildAndDiagnose=*/false, CaptureType, 14178 DeclRefType, nullptr)) 14179 return QualType(); 14180 14181 return DeclRefType; 14182 } 14183 14184 14185 14186 // If either the type of the variable or the initializer is dependent, 14187 // return false. Otherwise, determine whether the variable is a constant 14188 // expression. Use this if you need to know if a variable that might or 14189 // might not be dependent is truly a constant expression. 14190 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14191 ASTContext &Context) { 14192 14193 if (Var->getType()->isDependentType()) 14194 return false; 14195 const VarDecl *DefVD = nullptr; 14196 Var->getAnyInitializer(DefVD); 14197 if (!DefVD) 14198 return false; 14199 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14200 Expr *Init = cast<Expr>(Eval->Value); 14201 if (Init->isValueDependent()) 14202 return false; 14203 return IsVariableAConstantExpression(Var, Context); 14204 } 14205 14206 14207 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14208 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14209 // an object that satisfies the requirements for appearing in a 14210 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14211 // is immediately applied." This function handles the lvalue-to-rvalue 14212 // conversion part. 14213 MaybeODRUseExprs.erase(E->IgnoreParens()); 14214 14215 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14216 // to a variable that is a constant expression, and if so, identify it as 14217 // a reference to a variable that does not involve an odr-use of that 14218 // variable. 14219 if (LambdaScopeInfo *LSI = getCurLambda()) { 14220 Expr *SansParensExpr = E->IgnoreParens(); 14221 VarDecl *Var = nullptr; 14222 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14223 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14224 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14225 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14226 14227 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14228 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14229 } 14230 } 14231 14232 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14233 Res = CorrectDelayedTyposInExpr(Res); 14234 14235 if (!Res.isUsable()) 14236 return Res; 14237 14238 // If a constant-expression is a reference to a variable where we delay 14239 // deciding whether it is an odr-use, just assume we will apply the 14240 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14241 // (a non-type template argument), we have special handling anyway. 14242 UpdateMarkingForLValueToRValue(Res.get()); 14243 return Res; 14244 } 14245 14246 void Sema::CleanupVarDeclMarking() { 14247 for (Expr *E : MaybeODRUseExprs) { 14248 VarDecl *Var; 14249 SourceLocation Loc; 14250 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14251 Var = cast<VarDecl>(DRE->getDecl()); 14252 Loc = DRE->getLocation(); 14253 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14254 Var = cast<VarDecl>(ME->getMemberDecl()); 14255 Loc = ME->getMemberLoc(); 14256 } else { 14257 llvm_unreachable("Unexpected expression"); 14258 } 14259 14260 MarkVarDeclODRUsed(Var, Loc, *this, 14261 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14262 } 14263 14264 MaybeODRUseExprs.clear(); 14265 } 14266 14267 14268 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14269 VarDecl *Var, Expr *E) { 14270 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14271 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14272 Var->setReferenced(); 14273 14274 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14275 14276 bool OdrUseContext = isOdrUseContext(SemaRef); 14277 bool NeedDefinition = 14278 OdrUseContext || (isEvaluatableContext(SemaRef) && 14279 Var->isUsableInConstantExpressions(SemaRef.Context)); 14280 14281 VarTemplateSpecializationDecl *VarSpec = 14282 dyn_cast<VarTemplateSpecializationDecl>(Var); 14283 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14284 "Can't instantiate a partial template specialization."); 14285 14286 // If this might be a member specialization of a static data member, check 14287 // the specialization is visible. We already did the checks for variable 14288 // template specializations when we created them. 14289 if (NeedDefinition && TSK != TSK_Undeclared && 14290 !isa<VarTemplateSpecializationDecl>(Var)) 14291 SemaRef.checkSpecializationVisibility(Loc, Var); 14292 14293 // Perform implicit instantiation of static data members, static data member 14294 // templates of class templates, and variable template specializations. Delay 14295 // instantiations of variable templates, except for those that could be used 14296 // in a constant expression. 14297 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14298 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14299 14300 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14301 if (Var->getPointOfInstantiation().isInvalid()) { 14302 // This is a modification of an existing AST node. Notify listeners. 14303 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14304 L->StaticDataMemberInstantiated(Var); 14305 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14306 // Don't bother trying to instantiate it again, unless we might need 14307 // its initializer before we get to the end of the TU. 14308 TryInstantiating = false; 14309 } 14310 14311 if (Var->getPointOfInstantiation().isInvalid()) 14312 Var->setTemplateSpecializationKind(TSK, Loc); 14313 14314 if (TryInstantiating) { 14315 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14316 bool InstantiationDependent = false; 14317 bool IsNonDependent = 14318 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14319 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14320 : true; 14321 14322 // Do not instantiate specializations that are still type-dependent. 14323 if (IsNonDependent) { 14324 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14325 // Do not defer instantiations of variables which could be used in a 14326 // constant expression. 14327 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14328 } else { 14329 SemaRef.PendingInstantiations 14330 .push_back(std::make_pair(Var, PointOfInstantiation)); 14331 } 14332 } 14333 } 14334 } 14335 14336 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14337 // the requirements for appearing in a constant expression (5.19) and, if 14338 // it is an object, the lvalue-to-rvalue conversion (4.1) 14339 // is immediately applied." We check the first part here, and 14340 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14341 // Note that we use the C++11 definition everywhere because nothing in 14342 // C++03 depends on whether we get the C++03 version correct. The second 14343 // part does not apply to references, since they are not objects. 14344 if (OdrUseContext && E && 14345 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14346 // A reference initialized by a constant expression can never be 14347 // odr-used, so simply ignore it. 14348 if (!Var->getType()->isReferenceType()) 14349 SemaRef.MaybeODRUseExprs.insert(E); 14350 } else if (OdrUseContext) { 14351 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14352 /*MaxFunctionScopeIndex ptr*/ nullptr); 14353 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14354 // If this is a dependent context, we don't need to mark variables as 14355 // odr-used, but we may still need to track them for lambda capture. 14356 // FIXME: Do we also need to do this inside dependent typeid expressions 14357 // (which are modeled as unevaluated at this point)? 14358 const bool RefersToEnclosingScope = 14359 (SemaRef.CurContext != Var->getDeclContext() && 14360 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14361 if (RefersToEnclosingScope) { 14362 LambdaScopeInfo *const LSI = 14363 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14364 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14365 // If a variable could potentially be odr-used, defer marking it so 14366 // until we finish analyzing the full expression for any 14367 // lvalue-to-rvalue 14368 // or discarded value conversions that would obviate odr-use. 14369 // Add it to the list of potential captures that will be analyzed 14370 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14371 // unless the variable is a reference that was initialized by a constant 14372 // expression (this will never need to be captured or odr-used). 14373 assert(E && "Capture variable should be used in an expression."); 14374 if (!Var->getType()->isReferenceType() || 14375 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14376 LSI->addPotentialCapture(E->IgnoreParens()); 14377 } 14378 } 14379 } 14380 } 14381 14382 /// \brief Mark a variable referenced, and check whether it is odr-used 14383 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14384 /// used directly for normal expressions referring to VarDecl. 14385 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14386 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14387 } 14388 14389 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14390 Decl *D, Expr *E, bool MightBeOdrUse) { 14391 if (SemaRef.isInOpenMPDeclareTargetContext()) 14392 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14393 14394 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14395 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14396 return; 14397 } 14398 14399 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14400 14401 // If this is a call to a method via a cast, also mark the method in the 14402 // derived class used in case codegen can devirtualize the call. 14403 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14404 if (!ME) 14405 return; 14406 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14407 if (!MD) 14408 return; 14409 // Only attempt to devirtualize if this is truly a virtual call. 14410 bool IsVirtualCall = MD->isVirtual() && 14411 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14412 if (!IsVirtualCall) 14413 return; 14414 const Expr *Base = ME->getBase(); 14415 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14416 if (!MostDerivedClassDecl) 14417 return; 14418 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14419 if (!DM || DM->isPure()) 14420 return; 14421 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14422 } 14423 14424 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14425 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14426 // TODO: update this with DR# once a defect report is filed. 14427 // C++11 defect. The address of a pure member should not be an ODR use, even 14428 // if it's a qualified reference. 14429 bool OdrUse = true; 14430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14431 if (Method->isVirtual()) 14432 OdrUse = false; 14433 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14434 } 14435 14436 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14437 void Sema::MarkMemberReferenced(MemberExpr *E) { 14438 // C++11 [basic.def.odr]p2: 14439 // A non-overloaded function whose name appears as a potentially-evaluated 14440 // expression or a member of a set of candidate functions, if selected by 14441 // overload resolution when referred to from a potentially-evaluated 14442 // expression, is odr-used, unless it is a pure virtual function and its 14443 // name is not explicitly qualified. 14444 bool MightBeOdrUse = true; 14445 if (E->performsVirtualDispatch(getLangOpts())) { 14446 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14447 if (Method->isPure()) 14448 MightBeOdrUse = false; 14449 } 14450 SourceLocation Loc = E->getMemberLoc().isValid() ? 14451 E->getMemberLoc() : E->getLocStart(); 14452 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14453 } 14454 14455 /// \brief Perform marking for a reference to an arbitrary declaration. It 14456 /// marks the declaration referenced, and performs odr-use checking for 14457 /// functions and variables. This method should not be used when building a 14458 /// normal expression which refers to a variable. 14459 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14460 bool MightBeOdrUse) { 14461 if (MightBeOdrUse) { 14462 if (auto *VD = dyn_cast<VarDecl>(D)) { 14463 MarkVariableReferenced(Loc, VD); 14464 return; 14465 } 14466 } 14467 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14468 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14469 return; 14470 } 14471 D->setReferenced(); 14472 } 14473 14474 namespace { 14475 // Mark all of the declarations used by a type as referenced. 14476 // FIXME: Not fully implemented yet! We need to have a better understanding 14477 // of when we're entering a context we should not recurse into. 14478 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 14479 // TreeTransforms rebuilding the type in a new context. Rather than 14480 // duplicating the TreeTransform logic, we should consider reusing it here. 14481 // Currently that causes problems when rebuilding LambdaExprs. 14482 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14483 Sema &S; 14484 SourceLocation Loc; 14485 14486 public: 14487 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14488 14489 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14490 14491 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14492 }; 14493 } 14494 14495 bool MarkReferencedDecls::TraverseTemplateArgument( 14496 const TemplateArgument &Arg) { 14497 { 14498 // A non-type template argument is a constant-evaluated context. 14499 EnterExpressionEvaluationContext Evaluated( 14500 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 14501 if (Arg.getKind() == TemplateArgument::Declaration) { 14502 if (Decl *D = Arg.getAsDecl()) 14503 S.MarkAnyDeclReferenced(Loc, D, true); 14504 } else if (Arg.getKind() == TemplateArgument::Expression) { 14505 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 14506 } 14507 } 14508 14509 return Inherited::TraverseTemplateArgument(Arg); 14510 } 14511 14512 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14513 MarkReferencedDecls Marker(*this, Loc); 14514 Marker.TraverseType(T); 14515 } 14516 14517 namespace { 14518 /// \brief Helper class that marks all of the declarations referenced by 14519 /// potentially-evaluated subexpressions as "referenced". 14520 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14521 Sema &S; 14522 bool SkipLocalVariables; 14523 14524 public: 14525 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14526 14527 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14528 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14529 14530 void VisitDeclRefExpr(DeclRefExpr *E) { 14531 // If we were asked not to visit local variables, don't. 14532 if (SkipLocalVariables) { 14533 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14534 if (VD->hasLocalStorage()) 14535 return; 14536 } 14537 14538 S.MarkDeclRefReferenced(E); 14539 } 14540 14541 void VisitMemberExpr(MemberExpr *E) { 14542 S.MarkMemberReferenced(E); 14543 Inherited::VisitMemberExpr(E); 14544 } 14545 14546 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14547 S.MarkFunctionReferenced(E->getLocStart(), 14548 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14549 Visit(E->getSubExpr()); 14550 } 14551 14552 void VisitCXXNewExpr(CXXNewExpr *E) { 14553 if (E->getOperatorNew()) 14554 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14555 if (E->getOperatorDelete()) 14556 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14557 Inherited::VisitCXXNewExpr(E); 14558 } 14559 14560 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14561 if (E->getOperatorDelete()) 14562 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14563 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14564 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14565 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14566 S.MarkFunctionReferenced(E->getLocStart(), 14567 S.LookupDestructor(Record)); 14568 } 14569 14570 Inherited::VisitCXXDeleteExpr(E); 14571 } 14572 14573 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14574 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14575 Inherited::VisitCXXConstructExpr(E); 14576 } 14577 14578 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14579 Visit(E->getExpr()); 14580 } 14581 14582 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14583 Inherited::VisitImplicitCastExpr(E); 14584 14585 if (E->getCastKind() == CK_LValueToRValue) 14586 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14587 } 14588 }; 14589 } 14590 14591 /// \brief Mark any declarations that appear within this expression or any 14592 /// potentially-evaluated subexpressions as "referenced". 14593 /// 14594 /// \param SkipLocalVariables If true, don't mark local variables as 14595 /// 'referenced'. 14596 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14597 bool SkipLocalVariables) { 14598 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14599 } 14600 14601 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14602 /// of the program being compiled. 14603 /// 14604 /// This routine emits the given diagnostic when the code currently being 14605 /// type-checked is "potentially evaluated", meaning that there is a 14606 /// possibility that the code will actually be executable. Code in sizeof() 14607 /// expressions, code used only during overload resolution, etc., are not 14608 /// potentially evaluated. This routine will suppress such diagnostics or, 14609 /// in the absolutely nutty case of potentially potentially evaluated 14610 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14611 /// later. 14612 /// 14613 /// This routine should be used for all diagnostics that describe the run-time 14614 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14615 /// Failure to do so will likely result in spurious diagnostics or failures 14616 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14617 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14618 const PartialDiagnostic &PD) { 14619 switch (ExprEvalContexts.back().Context) { 14620 case ExpressionEvaluationContext::Unevaluated: 14621 case ExpressionEvaluationContext::UnevaluatedList: 14622 case ExpressionEvaluationContext::UnevaluatedAbstract: 14623 case ExpressionEvaluationContext::DiscardedStatement: 14624 // The argument will never be evaluated, so don't complain. 14625 break; 14626 14627 case ExpressionEvaluationContext::ConstantEvaluated: 14628 // Relevant diagnostics should be produced by constant evaluation. 14629 break; 14630 14631 case ExpressionEvaluationContext::PotentiallyEvaluated: 14632 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14633 if (Statement && getCurFunctionOrMethodDecl()) { 14634 FunctionScopes.back()->PossiblyUnreachableDiags. 14635 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14636 } 14637 else 14638 Diag(Loc, PD); 14639 14640 return true; 14641 } 14642 14643 return false; 14644 } 14645 14646 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14647 CallExpr *CE, FunctionDecl *FD) { 14648 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14649 return false; 14650 14651 // If we're inside a decltype's expression, don't check for a valid return 14652 // type or construct temporaries until we know whether this is the last call. 14653 if (ExprEvalContexts.back().IsDecltype) { 14654 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14655 return false; 14656 } 14657 14658 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14659 FunctionDecl *FD; 14660 CallExpr *CE; 14661 14662 public: 14663 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14664 : FD(FD), CE(CE) { } 14665 14666 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14667 if (!FD) { 14668 S.Diag(Loc, diag::err_call_incomplete_return) 14669 << T << CE->getSourceRange(); 14670 return; 14671 } 14672 14673 S.Diag(Loc, diag::err_call_function_incomplete_return) 14674 << CE->getSourceRange() << FD->getDeclName() << T; 14675 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14676 << FD->getDeclName(); 14677 } 14678 } Diagnoser(FD, CE); 14679 14680 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14681 return true; 14682 14683 return false; 14684 } 14685 14686 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14687 // will prevent this condition from triggering, which is what we want. 14688 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14689 SourceLocation Loc; 14690 14691 unsigned diagnostic = diag::warn_condition_is_assignment; 14692 bool IsOrAssign = false; 14693 14694 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14695 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14696 return; 14697 14698 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14699 14700 // Greylist some idioms by putting them into a warning subcategory. 14701 if (ObjCMessageExpr *ME 14702 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14703 Selector Sel = ME->getSelector(); 14704 14705 // self = [<foo> init...] 14706 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14707 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14708 14709 // <foo> = [<bar> nextObject] 14710 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14711 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14712 } 14713 14714 Loc = Op->getOperatorLoc(); 14715 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14716 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14717 return; 14718 14719 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14720 Loc = Op->getOperatorLoc(); 14721 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14722 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14723 else { 14724 // Not an assignment. 14725 return; 14726 } 14727 14728 Diag(Loc, diagnostic) << E->getSourceRange(); 14729 14730 SourceLocation Open = E->getLocStart(); 14731 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14732 Diag(Loc, diag::note_condition_assign_silence) 14733 << FixItHint::CreateInsertion(Open, "(") 14734 << FixItHint::CreateInsertion(Close, ")"); 14735 14736 if (IsOrAssign) 14737 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14738 << FixItHint::CreateReplacement(Loc, "!="); 14739 else 14740 Diag(Loc, diag::note_condition_assign_to_comparison) 14741 << FixItHint::CreateReplacement(Loc, "=="); 14742 } 14743 14744 /// \brief Redundant parentheses over an equality comparison can indicate 14745 /// that the user intended an assignment used as condition. 14746 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14747 // Don't warn if the parens came from a macro. 14748 SourceLocation parenLoc = ParenE->getLocStart(); 14749 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14750 return; 14751 // Don't warn for dependent expressions. 14752 if (ParenE->isTypeDependent()) 14753 return; 14754 14755 Expr *E = ParenE->IgnoreParens(); 14756 14757 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14758 if (opE->getOpcode() == BO_EQ && 14759 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14760 == Expr::MLV_Valid) { 14761 SourceLocation Loc = opE->getOperatorLoc(); 14762 14763 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14764 SourceRange ParenERange = ParenE->getSourceRange(); 14765 Diag(Loc, diag::note_equality_comparison_silence) 14766 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14767 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14768 Diag(Loc, diag::note_equality_comparison_to_assign) 14769 << FixItHint::CreateReplacement(Loc, "="); 14770 } 14771 } 14772 14773 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14774 bool IsConstexpr) { 14775 DiagnoseAssignmentAsCondition(E); 14776 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14777 DiagnoseEqualityWithExtraParens(parenE); 14778 14779 ExprResult result = CheckPlaceholderExpr(E); 14780 if (result.isInvalid()) return ExprError(); 14781 E = result.get(); 14782 14783 if (!E->isTypeDependent()) { 14784 if (getLangOpts().CPlusPlus) 14785 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14786 14787 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14788 if (ERes.isInvalid()) 14789 return ExprError(); 14790 E = ERes.get(); 14791 14792 QualType T = E->getType(); 14793 if (!T->isScalarType()) { // C99 6.8.4.1p1 14794 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14795 << T << E->getSourceRange(); 14796 return ExprError(); 14797 } 14798 CheckBoolLikeConversion(E, Loc); 14799 } 14800 14801 return E; 14802 } 14803 14804 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14805 Expr *SubExpr, ConditionKind CK) { 14806 // Empty conditions are valid in for-statements. 14807 if (!SubExpr) 14808 return ConditionResult(); 14809 14810 ExprResult Cond; 14811 switch (CK) { 14812 case ConditionKind::Boolean: 14813 Cond = CheckBooleanCondition(Loc, SubExpr); 14814 break; 14815 14816 case ConditionKind::ConstexprIf: 14817 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14818 break; 14819 14820 case ConditionKind::Switch: 14821 Cond = CheckSwitchCondition(Loc, SubExpr); 14822 break; 14823 } 14824 if (Cond.isInvalid()) 14825 return ConditionError(); 14826 14827 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14828 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14829 if (!FullExpr.get()) 14830 return ConditionError(); 14831 14832 return ConditionResult(*this, nullptr, FullExpr, 14833 CK == ConditionKind::ConstexprIf); 14834 } 14835 14836 namespace { 14837 /// A visitor for rebuilding a call to an __unknown_any expression 14838 /// to have an appropriate type. 14839 struct RebuildUnknownAnyFunction 14840 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14841 14842 Sema &S; 14843 14844 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14845 14846 ExprResult VisitStmt(Stmt *S) { 14847 llvm_unreachable("unexpected statement!"); 14848 } 14849 14850 ExprResult VisitExpr(Expr *E) { 14851 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14852 << E->getSourceRange(); 14853 return ExprError(); 14854 } 14855 14856 /// Rebuild an expression which simply semantically wraps another 14857 /// expression which it shares the type and value kind of. 14858 template <class T> ExprResult rebuildSugarExpr(T *E) { 14859 ExprResult SubResult = Visit(E->getSubExpr()); 14860 if (SubResult.isInvalid()) return ExprError(); 14861 14862 Expr *SubExpr = SubResult.get(); 14863 E->setSubExpr(SubExpr); 14864 E->setType(SubExpr->getType()); 14865 E->setValueKind(SubExpr->getValueKind()); 14866 assert(E->getObjectKind() == OK_Ordinary); 14867 return E; 14868 } 14869 14870 ExprResult VisitParenExpr(ParenExpr *E) { 14871 return rebuildSugarExpr(E); 14872 } 14873 14874 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14875 return rebuildSugarExpr(E); 14876 } 14877 14878 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14879 ExprResult SubResult = Visit(E->getSubExpr()); 14880 if (SubResult.isInvalid()) return ExprError(); 14881 14882 Expr *SubExpr = SubResult.get(); 14883 E->setSubExpr(SubExpr); 14884 E->setType(S.Context.getPointerType(SubExpr->getType())); 14885 assert(E->getValueKind() == VK_RValue); 14886 assert(E->getObjectKind() == OK_Ordinary); 14887 return E; 14888 } 14889 14890 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14891 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14892 14893 E->setType(VD->getType()); 14894 14895 assert(E->getValueKind() == VK_RValue); 14896 if (S.getLangOpts().CPlusPlus && 14897 !(isa<CXXMethodDecl>(VD) && 14898 cast<CXXMethodDecl>(VD)->isInstance())) 14899 E->setValueKind(VK_LValue); 14900 14901 return E; 14902 } 14903 14904 ExprResult VisitMemberExpr(MemberExpr *E) { 14905 return resolveDecl(E, E->getMemberDecl()); 14906 } 14907 14908 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14909 return resolveDecl(E, E->getDecl()); 14910 } 14911 }; 14912 } 14913 14914 /// Given a function expression of unknown-any type, try to rebuild it 14915 /// to have a function type. 14916 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14917 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14918 if (Result.isInvalid()) return ExprError(); 14919 return S.DefaultFunctionArrayConversion(Result.get()); 14920 } 14921 14922 namespace { 14923 /// A visitor for rebuilding an expression of type __unknown_anytype 14924 /// into one which resolves the type directly on the referring 14925 /// expression. Strict preservation of the original source 14926 /// structure is not a goal. 14927 struct RebuildUnknownAnyExpr 14928 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14929 14930 Sema &S; 14931 14932 /// The current destination type. 14933 QualType DestType; 14934 14935 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14936 : S(S), DestType(CastType) {} 14937 14938 ExprResult VisitStmt(Stmt *S) { 14939 llvm_unreachable("unexpected statement!"); 14940 } 14941 14942 ExprResult VisitExpr(Expr *E) { 14943 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14944 << E->getSourceRange(); 14945 return ExprError(); 14946 } 14947 14948 ExprResult VisitCallExpr(CallExpr *E); 14949 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14950 14951 /// Rebuild an expression which simply semantically wraps another 14952 /// expression which it shares the type and value kind of. 14953 template <class T> ExprResult rebuildSugarExpr(T *E) { 14954 ExprResult SubResult = Visit(E->getSubExpr()); 14955 if (SubResult.isInvalid()) return ExprError(); 14956 Expr *SubExpr = SubResult.get(); 14957 E->setSubExpr(SubExpr); 14958 E->setType(SubExpr->getType()); 14959 E->setValueKind(SubExpr->getValueKind()); 14960 assert(E->getObjectKind() == OK_Ordinary); 14961 return E; 14962 } 14963 14964 ExprResult VisitParenExpr(ParenExpr *E) { 14965 return rebuildSugarExpr(E); 14966 } 14967 14968 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14969 return rebuildSugarExpr(E); 14970 } 14971 14972 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14973 const PointerType *Ptr = DestType->getAs<PointerType>(); 14974 if (!Ptr) { 14975 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14976 << E->getSourceRange(); 14977 return ExprError(); 14978 } 14979 14980 if (isa<CallExpr>(E->getSubExpr())) { 14981 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 14982 << E->getSourceRange(); 14983 return ExprError(); 14984 } 14985 14986 assert(E->getValueKind() == VK_RValue); 14987 assert(E->getObjectKind() == OK_Ordinary); 14988 E->setType(DestType); 14989 14990 // Build the sub-expression as if it were an object of the pointee type. 14991 DestType = Ptr->getPointeeType(); 14992 ExprResult SubResult = Visit(E->getSubExpr()); 14993 if (SubResult.isInvalid()) return ExprError(); 14994 E->setSubExpr(SubResult.get()); 14995 return E; 14996 } 14997 14998 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14999 15000 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15001 15002 ExprResult VisitMemberExpr(MemberExpr *E) { 15003 return resolveDecl(E, E->getMemberDecl()); 15004 } 15005 15006 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15007 return resolveDecl(E, E->getDecl()); 15008 } 15009 }; 15010 } 15011 15012 /// Rebuilds a call expression which yielded __unknown_anytype. 15013 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15014 Expr *CalleeExpr = E->getCallee(); 15015 15016 enum FnKind { 15017 FK_MemberFunction, 15018 FK_FunctionPointer, 15019 FK_BlockPointer 15020 }; 15021 15022 FnKind Kind; 15023 QualType CalleeType = CalleeExpr->getType(); 15024 if (CalleeType == S.Context.BoundMemberTy) { 15025 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15026 Kind = FK_MemberFunction; 15027 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15028 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15029 CalleeType = Ptr->getPointeeType(); 15030 Kind = FK_FunctionPointer; 15031 } else { 15032 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15033 Kind = FK_BlockPointer; 15034 } 15035 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15036 15037 // Verify that this is a legal result type of a function. 15038 if (DestType->isArrayType() || DestType->isFunctionType()) { 15039 unsigned diagID = diag::err_func_returning_array_function; 15040 if (Kind == FK_BlockPointer) 15041 diagID = diag::err_block_returning_array_function; 15042 15043 S.Diag(E->getExprLoc(), diagID) 15044 << DestType->isFunctionType() << DestType; 15045 return ExprError(); 15046 } 15047 15048 // Otherwise, go ahead and set DestType as the call's result. 15049 E->setType(DestType.getNonLValueExprType(S.Context)); 15050 E->setValueKind(Expr::getValueKindForType(DestType)); 15051 assert(E->getObjectKind() == OK_Ordinary); 15052 15053 // Rebuild the function type, replacing the result type with DestType. 15054 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15055 if (Proto) { 15056 // __unknown_anytype(...) is a special case used by the debugger when 15057 // it has no idea what a function's signature is. 15058 // 15059 // We want to build this call essentially under the K&R 15060 // unprototyped rules, but making a FunctionNoProtoType in C++ 15061 // would foul up all sorts of assumptions. However, we cannot 15062 // simply pass all arguments as variadic arguments, nor can we 15063 // portably just call the function under a non-variadic type; see 15064 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15065 // However, it turns out that in practice it is generally safe to 15066 // call a function declared as "A foo(B,C,D);" under the prototype 15067 // "A foo(B,C,D,...);". The only known exception is with the 15068 // Windows ABI, where any variadic function is implicitly cdecl 15069 // regardless of its normal CC. Therefore we change the parameter 15070 // types to match the types of the arguments. 15071 // 15072 // This is a hack, but it is far superior to moving the 15073 // corresponding target-specific code from IR-gen to Sema/AST. 15074 15075 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15076 SmallVector<QualType, 8> ArgTypes; 15077 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15078 ArgTypes.reserve(E->getNumArgs()); 15079 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15080 Expr *Arg = E->getArg(i); 15081 QualType ArgType = Arg->getType(); 15082 if (E->isLValue()) { 15083 ArgType = S.Context.getLValueReferenceType(ArgType); 15084 } else if (E->isXValue()) { 15085 ArgType = S.Context.getRValueReferenceType(ArgType); 15086 } 15087 ArgTypes.push_back(ArgType); 15088 } 15089 ParamTypes = ArgTypes; 15090 } 15091 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15092 Proto->getExtProtoInfo()); 15093 } else { 15094 DestType = S.Context.getFunctionNoProtoType(DestType, 15095 FnType->getExtInfo()); 15096 } 15097 15098 // Rebuild the appropriate pointer-to-function type. 15099 switch (Kind) { 15100 case FK_MemberFunction: 15101 // Nothing to do. 15102 break; 15103 15104 case FK_FunctionPointer: 15105 DestType = S.Context.getPointerType(DestType); 15106 break; 15107 15108 case FK_BlockPointer: 15109 DestType = S.Context.getBlockPointerType(DestType); 15110 break; 15111 } 15112 15113 // Finally, we can recurse. 15114 ExprResult CalleeResult = Visit(CalleeExpr); 15115 if (!CalleeResult.isUsable()) return ExprError(); 15116 E->setCallee(CalleeResult.get()); 15117 15118 // Bind a temporary if necessary. 15119 return S.MaybeBindToTemporary(E); 15120 } 15121 15122 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15123 // Verify that this is a legal result type of a call. 15124 if (DestType->isArrayType() || DestType->isFunctionType()) { 15125 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15126 << DestType->isFunctionType() << DestType; 15127 return ExprError(); 15128 } 15129 15130 // Rewrite the method result type if available. 15131 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15132 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15133 Method->setReturnType(DestType); 15134 } 15135 15136 // Change the type of the message. 15137 E->setType(DestType.getNonReferenceType()); 15138 E->setValueKind(Expr::getValueKindForType(DestType)); 15139 15140 return S.MaybeBindToTemporary(E); 15141 } 15142 15143 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15144 // The only case we should ever see here is a function-to-pointer decay. 15145 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15146 assert(E->getValueKind() == VK_RValue); 15147 assert(E->getObjectKind() == OK_Ordinary); 15148 15149 E->setType(DestType); 15150 15151 // Rebuild the sub-expression as the pointee (function) type. 15152 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15153 15154 ExprResult Result = Visit(E->getSubExpr()); 15155 if (!Result.isUsable()) return ExprError(); 15156 15157 E->setSubExpr(Result.get()); 15158 return E; 15159 } else if (E->getCastKind() == CK_LValueToRValue) { 15160 assert(E->getValueKind() == VK_RValue); 15161 assert(E->getObjectKind() == OK_Ordinary); 15162 15163 assert(isa<BlockPointerType>(E->getType())); 15164 15165 E->setType(DestType); 15166 15167 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15168 DestType = S.Context.getLValueReferenceType(DestType); 15169 15170 ExprResult Result = Visit(E->getSubExpr()); 15171 if (!Result.isUsable()) return ExprError(); 15172 15173 E->setSubExpr(Result.get()); 15174 return E; 15175 } else { 15176 llvm_unreachable("Unhandled cast type!"); 15177 } 15178 } 15179 15180 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15181 ExprValueKind ValueKind = VK_LValue; 15182 QualType Type = DestType; 15183 15184 // We know how to make this work for certain kinds of decls: 15185 15186 // - functions 15187 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15188 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15189 DestType = Ptr->getPointeeType(); 15190 ExprResult Result = resolveDecl(E, VD); 15191 if (Result.isInvalid()) return ExprError(); 15192 return S.ImpCastExprToType(Result.get(), Type, 15193 CK_FunctionToPointerDecay, VK_RValue); 15194 } 15195 15196 if (!Type->isFunctionType()) { 15197 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15198 << VD << E->getSourceRange(); 15199 return ExprError(); 15200 } 15201 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15202 // We must match the FunctionDecl's type to the hack introduced in 15203 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15204 // type. See the lengthy commentary in that routine. 15205 QualType FDT = FD->getType(); 15206 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15207 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15208 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15209 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15210 SourceLocation Loc = FD->getLocation(); 15211 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15212 FD->getDeclContext(), 15213 Loc, Loc, FD->getNameInfo().getName(), 15214 DestType, FD->getTypeSourceInfo(), 15215 SC_None, false/*isInlineSpecified*/, 15216 FD->hasPrototype(), 15217 false/*isConstexprSpecified*/); 15218 15219 if (FD->getQualifier()) 15220 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15221 15222 SmallVector<ParmVarDecl*, 16> Params; 15223 for (const auto &AI : FT->param_types()) { 15224 ParmVarDecl *Param = 15225 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15226 Param->setScopeInfo(0, Params.size()); 15227 Params.push_back(Param); 15228 } 15229 NewFD->setParams(Params); 15230 DRE->setDecl(NewFD); 15231 VD = DRE->getDecl(); 15232 } 15233 } 15234 15235 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15236 if (MD->isInstance()) { 15237 ValueKind = VK_RValue; 15238 Type = S.Context.BoundMemberTy; 15239 } 15240 15241 // Function references aren't l-values in C. 15242 if (!S.getLangOpts().CPlusPlus) 15243 ValueKind = VK_RValue; 15244 15245 // - variables 15246 } else if (isa<VarDecl>(VD)) { 15247 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15248 Type = RefTy->getPointeeType(); 15249 } else if (Type->isFunctionType()) { 15250 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15251 << VD << E->getSourceRange(); 15252 return ExprError(); 15253 } 15254 15255 // - nothing else 15256 } else { 15257 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15258 << VD << E->getSourceRange(); 15259 return ExprError(); 15260 } 15261 15262 // Modifying the declaration like this is friendly to IR-gen but 15263 // also really dangerous. 15264 VD->setType(DestType); 15265 E->setType(Type); 15266 E->setValueKind(ValueKind); 15267 return E; 15268 } 15269 15270 /// Check a cast of an unknown-any type. We intentionally only 15271 /// trigger this for C-style casts. 15272 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15273 Expr *CastExpr, CastKind &CastKind, 15274 ExprValueKind &VK, CXXCastPath &Path) { 15275 // The type we're casting to must be either void or complete. 15276 if (!CastType->isVoidType() && 15277 RequireCompleteType(TypeRange.getBegin(), CastType, 15278 diag::err_typecheck_cast_to_incomplete)) 15279 return ExprError(); 15280 15281 // Rewrite the casted expression from scratch. 15282 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15283 if (!result.isUsable()) return ExprError(); 15284 15285 CastExpr = result.get(); 15286 VK = CastExpr->getValueKind(); 15287 CastKind = CK_NoOp; 15288 15289 return CastExpr; 15290 } 15291 15292 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15293 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15294 } 15295 15296 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15297 Expr *arg, QualType ¶mType) { 15298 // If the syntactic form of the argument is not an explicit cast of 15299 // any sort, just do default argument promotion. 15300 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15301 if (!castArg) { 15302 ExprResult result = DefaultArgumentPromotion(arg); 15303 if (result.isInvalid()) return ExprError(); 15304 paramType = result.get()->getType(); 15305 return result; 15306 } 15307 15308 // Otherwise, use the type that was written in the explicit cast. 15309 assert(!arg->hasPlaceholderType()); 15310 paramType = castArg->getTypeAsWritten(); 15311 15312 // Copy-initialize a parameter of that type. 15313 InitializedEntity entity = 15314 InitializedEntity::InitializeParameter(Context, paramType, 15315 /*consumed*/ false); 15316 return PerformCopyInitialization(entity, callLoc, arg); 15317 } 15318 15319 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15320 Expr *orig = E; 15321 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15322 while (true) { 15323 E = E->IgnoreParenImpCasts(); 15324 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15325 E = call->getCallee(); 15326 diagID = diag::err_uncasted_call_of_unknown_any; 15327 } else { 15328 break; 15329 } 15330 } 15331 15332 SourceLocation loc; 15333 NamedDecl *d; 15334 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15335 loc = ref->getLocation(); 15336 d = ref->getDecl(); 15337 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15338 loc = mem->getMemberLoc(); 15339 d = mem->getMemberDecl(); 15340 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15341 diagID = diag::err_uncasted_call_of_unknown_any; 15342 loc = msg->getSelectorStartLoc(); 15343 d = msg->getMethodDecl(); 15344 if (!d) { 15345 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15346 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15347 << orig->getSourceRange(); 15348 return ExprError(); 15349 } 15350 } else { 15351 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15352 << E->getSourceRange(); 15353 return ExprError(); 15354 } 15355 15356 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15357 15358 // Never recoverable. 15359 return ExprError(); 15360 } 15361 15362 /// Check for operands with placeholder types and complain if found. 15363 /// Returns true if there was an error and no recovery was possible. 15364 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15365 if (!getLangOpts().CPlusPlus) { 15366 // C cannot handle TypoExpr nodes on either side of a binop because it 15367 // doesn't handle dependent types properly, so make sure any TypoExprs have 15368 // been dealt with before checking the operands. 15369 ExprResult Result = CorrectDelayedTyposInExpr(E); 15370 if (!Result.isUsable()) return ExprError(); 15371 E = Result.get(); 15372 } 15373 15374 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15375 if (!placeholderType) return E; 15376 15377 switch (placeholderType->getKind()) { 15378 15379 // Overloaded expressions. 15380 case BuiltinType::Overload: { 15381 // Try to resolve a single function template specialization. 15382 // This is obligatory. 15383 ExprResult Result = E; 15384 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15385 return Result; 15386 15387 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15388 // leaves Result unchanged on failure. 15389 Result = E; 15390 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15391 return Result; 15392 15393 // If that failed, try to recover with a call. 15394 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15395 /*complain*/ true); 15396 return Result; 15397 } 15398 15399 // Bound member functions. 15400 case BuiltinType::BoundMember: { 15401 ExprResult result = E; 15402 const Expr *BME = E->IgnoreParens(); 15403 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15404 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15405 if (isa<CXXPseudoDestructorExpr>(BME)) { 15406 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15407 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15408 if (ME->getMemberNameInfo().getName().getNameKind() == 15409 DeclarationName::CXXDestructorName) 15410 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15411 } 15412 tryToRecoverWithCall(result, PD, 15413 /*complain*/ true); 15414 return result; 15415 } 15416 15417 // ARC unbridged casts. 15418 case BuiltinType::ARCUnbridgedCast: { 15419 Expr *realCast = stripARCUnbridgedCast(E); 15420 diagnoseARCUnbridgedCast(realCast); 15421 return realCast; 15422 } 15423 15424 // Expressions of unknown type. 15425 case BuiltinType::UnknownAny: 15426 return diagnoseUnknownAnyExpr(*this, E); 15427 15428 // Pseudo-objects. 15429 case BuiltinType::PseudoObject: 15430 return checkPseudoObjectRValue(E); 15431 15432 case BuiltinType::BuiltinFn: { 15433 // Accept __noop without parens by implicitly converting it to a call expr. 15434 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15435 if (DRE) { 15436 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15437 if (FD->getBuiltinID() == Builtin::BI__noop) { 15438 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15439 CK_BuiltinFnToFnPtr).get(); 15440 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15441 VK_RValue, SourceLocation()); 15442 } 15443 } 15444 15445 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15446 return ExprError(); 15447 } 15448 15449 // Expressions of unknown type. 15450 case BuiltinType::OMPArraySection: 15451 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15452 return ExprError(); 15453 15454 // Everything else should be impossible. 15455 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15456 case BuiltinType::Id: 15457 #include "clang/Basic/OpenCLImageTypes.def" 15458 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15459 #define PLACEHOLDER_TYPE(Id, SingletonId) 15460 #include "clang/AST/BuiltinTypes.def" 15461 break; 15462 } 15463 15464 llvm_unreachable("invalid placeholder type!"); 15465 } 15466 15467 bool Sema::CheckCaseExpression(Expr *E) { 15468 if (E->isTypeDependent()) 15469 return true; 15470 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15471 return E->getType()->isIntegralOrEnumerationType(); 15472 return false; 15473 } 15474 15475 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15476 ExprResult 15477 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15478 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15479 "Unknown Objective-C Boolean value!"); 15480 QualType BoolT = Context.ObjCBuiltinBoolTy; 15481 if (!Context.getBOOLDecl()) { 15482 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15483 Sema::LookupOrdinaryName); 15484 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15485 NamedDecl *ND = Result.getFoundDecl(); 15486 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15487 Context.setBOOLDecl(TD); 15488 } 15489 } 15490 if (Context.getBOOLDecl()) 15491 BoolT = Context.getBOOLType(); 15492 return new (Context) 15493 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15494 } 15495 15496 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15497 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15498 SourceLocation RParen) { 15499 15500 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15501 15502 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15503 [&](const AvailabilitySpec &Spec) { 15504 return Spec.getPlatform() == Platform; 15505 }); 15506 15507 VersionTuple Version; 15508 if (Spec != AvailSpecs.end()) 15509 Version = Spec->getVersion(); 15510 15511 return new (Context) 15512 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15513 } 15514