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 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1776 UnusedPrivateFields.remove(FD); 1777 // Just in case we're building an illegal pointer-to-member. 1778 if (FD->isBitField()) 1779 E->setObjectKind(OK_BitField); 1780 } 1781 1782 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1783 // designates a bit-field. 1784 if (auto *BD = dyn_cast<BindingDecl>(D)) 1785 if (auto *BE = BD->getBinding()) 1786 E->setObjectKind(BE->getObjectKind()); 1787 1788 return E; 1789 } 1790 1791 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1792 /// possibly a list of template arguments. 1793 /// 1794 /// If this produces template arguments, it is permitted to call 1795 /// DecomposeTemplateName. 1796 /// 1797 /// This actually loses a lot of source location information for 1798 /// non-standard name kinds; we should consider preserving that in 1799 /// some way. 1800 void 1801 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1802 TemplateArgumentListInfo &Buffer, 1803 DeclarationNameInfo &NameInfo, 1804 const TemplateArgumentListInfo *&TemplateArgs) { 1805 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1806 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1807 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1808 1809 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1810 Id.TemplateId->NumArgs); 1811 translateTemplateArguments(TemplateArgsPtr, Buffer); 1812 1813 TemplateName TName = Id.TemplateId->Template.get(); 1814 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1815 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1816 TemplateArgs = &Buffer; 1817 } else { 1818 NameInfo = GetNameFromUnqualifiedId(Id); 1819 TemplateArgs = nullptr; 1820 } 1821 } 1822 1823 static void emitEmptyLookupTypoDiagnostic( 1824 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1825 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1826 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1827 DeclContext *Ctx = 1828 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1829 if (!TC) { 1830 // Emit a special diagnostic for failed member lookups. 1831 // FIXME: computing the declaration context might fail here (?) 1832 if (Ctx) 1833 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1834 << SS.getRange(); 1835 else 1836 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1837 return; 1838 } 1839 1840 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1841 bool DroppedSpecifier = 1842 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1843 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1844 ? diag::note_implicit_param_decl 1845 : diag::note_previous_decl; 1846 if (!Ctx) 1847 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1848 SemaRef.PDiag(NoteID)); 1849 else 1850 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1851 << Typo << Ctx << DroppedSpecifier 1852 << SS.getRange(), 1853 SemaRef.PDiag(NoteID)); 1854 } 1855 1856 /// Diagnose an empty lookup. 1857 /// 1858 /// \return false if new lookup candidates were found 1859 bool 1860 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1861 std::unique_ptr<CorrectionCandidateCallback> CCC, 1862 TemplateArgumentListInfo *ExplicitTemplateArgs, 1863 ArrayRef<Expr *> Args, TypoExpr **Out) { 1864 DeclarationName Name = R.getLookupName(); 1865 1866 unsigned diagnostic = diag::err_undeclared_var_use; 1867 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1868 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1869 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1870 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1871 diagnostic = diag::err_undeclared_use; 1872 diagnostic_suggest = diag::err_undeclared_use_suggest; 1873 } 1874 1875 // If the original lookup was an unqualified lookup, fake an 1876 // unqualified lookup. This is useful when (for example) the 1877 // original lookup would not have found something because it was a 1878 // dependent name. 1879 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1880 while (DC) { 1881 if (isa<CXXRecordDecl>(DC)) { 1882 LookupQualifiedName(R, DC); 1883 1884 if (!R.empty()) { 1885 // Don't give errors about ambiguities in this lookup. 1886 R.suppressDiagnostics(); 1887 1888 // During a default argument instantiation the CurContext points 1889 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1890 // function parameter list, hence add an explicit check. 1891 bool isDefaultArgument = 1892 !CodeSynthesisContexts.empty() && 1893 CodeSynthesisContexts.back().Kind == 1894 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1895 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1896 bool isInstance = CurMethod && 1897 CurMethod->isInstance() && 1898 DC == CurMethod->getParent() && !isDefaultArgument; 1899 1900 // Give a code modification hint to insert 'this->'. 1901 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1902 // Actually quite difficult! 1903 if (getLangOpts().MSVCCompat) 1904 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1905 if (isInstance) { 1906 Diag(R.getNameLoc(), diagnostic) << Name 1907 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1908 CheckCXXThisCapture(R.getNameLoc()); 1909 } else { 1910 Diag(R.getNameLoc(), diagnostic) << Name; 1911 } 1912 1913 // Do we really want to note all of these? 1914 for (NamedDecl *D : R) 1915 Diag(D->getLocation(), diag::note_dependent_var_use); 1916 1917 // Return true if we are inside a default argument instantiation 1918 // and the found name refers to an instance member function, otherwise 1919 // the function calling DiagnoseEmptyLookup will try to create an 1920 // implicit member call and this is wrong for default argument. 1921 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1922 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1923 return true; 1924 } 1925 1926 // Tell the callee to try to recover. 1927 return false; 1928 } 1929 1930 R.clear(); 1931 } 1932 1933 // In Microsoft mode, if we are performing lookup from within a friend 1934 // function definition declared at class scope then we must set 1935 // DC to the lexical parent to be able to search into the parent 1936 // class. 1937 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1938 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1939 DC->getLexicalParent()->isRecord()) 1940 DC = DC->getLexicalParent(); 1941 else 1942 DC = DC->getParent(); 1943 } 1944 1945 // We didn't find anything, so try to correct for a typo. 1946 TypoCorrection Corrected; 1947 if (S && Out) { 1948 SourceLocation TypoLoc = R.getNameLoc(); 1949 assert(!ExplicitTemplateArgs && 1950 "Diagnosing an empty lookup with explicit template args!"); 1951 *Out = CorrectTypoDelayed( 1952 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1953 [=](const TypoCorrection &TC) { 1954 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1955 diagnostic, diagnostic_suggest); 1956 }, 1957 nullptr, CTK_ErrorRecovery); 1958 if (*Out) 1959 return true; 1960 } else if (S && (Corrected = 1961 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1962 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1963 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1964 bool DroppedSpecifier = 1965 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1966 R.setLookupName(Corrected.getCorrection()); 1967 1968 bool AcceptableWithRecovery = false; 1969 bool AcceptableWithoutRecovery = false; 1970 NamedDecl *ND = Corrected.getFoundDecl(); 1971 if (ND) { 1972 if (Corrected.isOverloaded()) { 1973 OverloadCandidateSet OCS(R.getNameLoc(), 1974 OverloadCandidateSet::CSK_Normal); 1975 OverloadCandidateSet::iterator Best; 1976 for (NamedDecl *CD : Corrected) { 1977 if (FunctionTemplateDecl *FTD = 1978 dyn_cast<FunctionTemplateDecl>(CD)) 1979 AddTemplateOverloadCandidate( 1980 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1981 Args, OCS); 1982 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1983 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1984 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1985 Args, OCS); 1986 } 1987 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1988 case OR_Success: 1989 ND = Best->FoundDecl; 1990 Corrected.setCorrectionDecl(ND); 1991 break; 1992 default: 1993 // FIXME: Arbitrarily pick the first declaration for the note. 1994 Corrected.setCorrectionDecl(ND); 1995 break; 1996 } 1997 } 1998 R.addDecl(ND); 1999 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2000 CXXRecordDecl *Record = nullptr; 2001 if (Corrected.getCorrectionSpecifier()) { 2002 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2003 Record = Ty->getAsCXXRecordDecl(); 2004 } 2005 if (!Record) 2006 Record = cast<CXXRecordDecl>( 2007 ND->getDeclContext()->getRedeclContext()); 2008 R.setNamingClass(Record); 2009 } 2010 2011 auto *UnderlyingND = ND->getUnderlyingDecl(); 2012 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2013 isa<FunctionTemplateDecl>(UnderlyingND); 2014 // FIXME: If we ended up with a typo for a type name or 2015 // Objective-C class name, we're in trouble because the parser 2016 // is in the wrong place to recover. Suggest the typo 2017 // correction, but don't make it a fix-it since we're not going 2018 // to recover well anyway. 2019 AcceptableWithoutRecovery = 2020 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2021 } else { 2022 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2023 // because we aren't able to recover. 2024 AcceptableWithoutRecovery = true; 2025 } 2026 2027 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2028 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2029 ? diag::note_implicit_param_decl 2030 : diag::note_previous_decl; 2031 if (SS.isEmpty()) 2032 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2033 PDiag(NoteID), AcceptableWithRecovery); 2034 else 2035 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2036 << Name << computeDeclContext(SS, false) 2037 << DroppedSpecifier << SS.getRange(), 2038 PDiag(NoteID), AcceptableWithRecovery); 2039 2040 // Tell the callee whether to try to recover. 2041 return !AcceptableWithRecovery; 2042 } 2043 } 2044 R.clear(); 2045 2046 // Emit a special diagnostic for failed member lookups. 2047 // FIXME: computing the declaration context might fail here (?) 2048 if (!SS.isEmpty()) { 2049 Diag(R.getNameLoc(), diag::err_no_member) 2050 << Name << computeDeclContext(SS, false) 2051 << SS.getRange(); 2052 return true; 2053 } 2054 2055 // Give up, we can't recover. 2056 Diag(R.getNameLoc(), diagnostic) << Name; 2057 return true; 2058 } 2059 2060 /// In Microsoft mode, if we are inside a template class whose parent class has 2061 /// dependent base classes, and we can't resolve an unqualified identifier, then 2062 /// assume the identifier is a member of a dependent base class. We can only 2063 /// recover successfully in static methods, instance methods, and other contexts 2064 /// where 'this' is available. This doesn't precisely match MSVC's 2065 /// instantiation model, but it's close enough. 2066 static Expr * 2067 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2068 DeclarationNameInfo &NameInfo, 2069 SourceLocation TemplateKWLoc, 2070 const TemplateArgumentListInfo *TemplateArgs) { 2071 // Only try to recover from lookup into dependent bases in static methods or 2072 // contexts where 'this' is available. 2073 QualType ThisType = S.getCurrentThisType(); 2074 const CXXRecordDecl *RD = nullptr; 2075 if (!ThisType.isNull()) 2076 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2077 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2078 RD = MD->getParent(); 2079 if (!RD || !RD->hasAnyDependentBases()) 2080 return nullptr; 2081 2082 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2083 // is available, suggest inserting 'this->' as a fixit. 2084 SourceLocation Loc = NameInfo.getLoc(); 2085 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2086 DB << NameInfo.getName() << RD; 2087 2088 if (!ThisType.isNull()) { 2089 DB << FixItHint::CreateInsertion(Loc, "this->"); 2090 return CXXDependentScopeMemberExpr::Create( 2091 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2092 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2093 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2094 } 2095 2096 // Synthesize a fake NNS that points to the derived class. This will 2097 // perform name lookup during template instantiation. 2098 CXXScopeSpec SS; 2099 auto *NNS = 2100 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2101 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2102 return DependentScopeDeclRefExpr::Create( 2103 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2104 TemplateArgs); 2105 } 2106 2107 ExprResult 2108 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2109 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2110 bool HasTrailingLParen, bool IsAddressOfOperand, 2111 std::unique_ptr<CorrectionCandidateCallback> CCC, 2112 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2113 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2114 "cannot be direct & operand and have a trailing lparen"); 2115 if (SS.isInvalid()) 2116 return ExprError(); 2117 2118 TemplateArgumentListInfo TemplateArgsBuffer; 2119 2120 // Decompose the UnqualifiedId into the following data. 2121 DeclarationNameInfo NameInfo; 2122 const TemplateArgumentListInfo *TemplateArgs; 2123 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2124 2125 DeclarationName Name = NameInfo.getName(); 2126 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2127 SourceLocation NameLoc = NameInfo.getLoc(); 2128 2129 // C++ [temp.dep.expr]p3: 2130 // An id-expression is type-dependent if it contains: 2131 // -- an identifier that was declared with a dependent type, 2132 // (note: handled after lookup) 2133 // -- a template-id that is dependent, 2134 // (note: handled in BuildTemplateIdExpr) 2135 // -- a conversion-function-id that specifies a dependent type, 2136 // -- a nested-name-specifier that contains a class-name that 2137 // names a dependent type. 2138 // Determine whether this is a member of an unknown specialization; 2139 // we need to handle these differently. 2140 bool DependentID = false; 2141 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2142 Name.getCXXNameType()->isDependentType()) { 2143 DependentID = true; 2144 } else if (SS.isSet()) { 2145 if (DeclContext *DC = computeDeclContext(SS, false)) { 2146 if (RequireCompleteDeclContext(SS, DC)) 2147 return ExprError(); 2148 } else { 2149 DependentID = true; 2150 } 2151 } 2152 2153 if (DependentID) 2154 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2155 IsAddressOfOperand, TemplateArgs); 2156 2157 // Perform the required lookup. 2158 LookupResult R(*this, NameInfo, 2159 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2160 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2161 if (TemplateArgs) { 2162 // Lookup the template name again to correctly establish the context in 2163 // which it was found. This is really unfortunate as we already did the 2164 // lookup to determine that it was a template name in the first place. If 2165 // this becomes a performance hit, we can work harder to preserve those 2166 // results until we get here but it's likely not worth it. 2167 bool MemberOfUnknownSpecialization; 2168 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2169 MemberOfUnknownSpecialization); 2170 2171 if (MemberOfUnknownSpecialization || 2172 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2173 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2174 IsAddressOfOperand, TemplateArgs); 2175 } else { 2176 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2177 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2178 2179 // If the result might be in a dependent base class, this is a dependent 2180 // id-expression. 2181 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2182 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2183 IsAddressOfOperand, TemplateArgs); 2184 2185 // If this reference is in an Objective-C method, then we need to do 2186 // some special Objective-C lookup, too. 2187 if (IvarLookupFollowUp) { 2188 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2189 if (E.isInvalid()) 2190 return ExprError(); 2191 2192 if (Expr *Ex = E.getAs<Expr>()) 2193 return Ex; 2194 } 2195 } 2196 2197 if (R.isAmbiguous()) 2198 return ExprError(); 2199 2200 // This could be an implicitly declared function reference (legal in C90, 2201 // extension in C99, forbidden in C++). 2202 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2203 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2204 if (D) R.addDecl(D); 2205 } 2206 2207 // Determine whether this name might be a candidate for 2208 // argument-dependent lookup. 2209 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2210 2211 if (R.empty() && !ADL) { 2212 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2213 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2214 TemplateKWLoc, TemplateArgs)) 2215 return E; 2216 } 2217 2218 // Don't diagnose an empty lookup for inline assembly. 2219 if (IsInlineAsmIdentifier) 2220 return ExprError(); 2221 2222 // If this name wasn't predeclared and if this is not a function 2223 // call, diagnose the problem. 2224 TypoExpr *TE = nullptr; 2225 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2226 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2227 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2228 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2229 "Typo correction callback misconfigured"); 2230 if (CCC) { 2231 // Make sure the callback knows what the typo being diagnosed is. 2232 CCC->setTypoName(II); 2233 if (SS.isValid()) 2234 CCC->setTypoNNS(SS.getScopeRep()); 2235 } 2236 if (DiagnoseEmptyLookup(S, SS, R, 2237 CCC ? std::move(CCC) : std::move(DefaultValidator), 2238 nullptr, None, &TE)) { 2239 if (TE && KeywordReplacement) { 2240 auto &State = getTypoExprState(TE); 2241 auto BestTC = State.Consumer->getNextCorrection(); 2242 if (BestTC.isKeyword()) { 2243 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2244 if (State.DiagHandler) 2245 State.DiagHandler(BestTC); 2246 KeywordReplacement->startToken(); 2247 KeywordReplacement->setKind(II->getTokenID()); 2248 KeywordReplacement->setIdentifierInfo(II); 2249 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2250 // Clean up the state associated with the TypoExpr, since it has 2251 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2252 clearDelayedTypo(TE); 2253 // Signal that a correction to a keyword was performed by returning a 2254 // valid-but-null ExprResult. 2255 return (Expr*)nullptr; 2256 } 2257 State.Consumer->resetCorrectionStream(); 2258 } 2259 return TE ? TE : ExprError(); 2260 } 2261 2262 assert(!R.empty() && 2263 "DiagnoseEmptyLookup returned false but added no results"); 2264 2265 // If we found an Objective-C instance variable, let 2266 // LookupInObjCMethod build the appropriate expression to 2267 // reference the ivar. 2268 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2269 R.clear(); 2270 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2271 // In a hopelessly buggy code, Objective-C instance variable 2272 // lookup fails and no expression will be built to reference it. 2273 if (!E.isInvalid() && !E.get()) 2274 return ExprError(); 2275 return E; 2276 } 2277 } 2278 2279 // This is guaranteed from this point on. 2280 assert(!R.empty() || ADL); 2281 2282 // Check whether this might be a C++ implicit instance member access. 2283 // C++ [class.mfct.non-static]p3: 2284 // When an id-expression that is not part of a class member access 2285 // syntax and not used to form a pointer to member is used in the 2286 // body of a non-static member function of class X, if name lookup 2287 // resolves the name in the id-expression to a non-static non-type 2288 // member of some class C, the id-expression is transformed into a 2289 // class member access expression using (*this) as the 2290 // postfix-expression to the left of the . operator. 2291 // 2292 // But we don't actually need to do this for '&' operands if R 2293 // resolved to a function or overloaded function set, because the 2294 // expression is ill-formed if it actually works out to be a 2295 // non-static member function: 2296 // 2297 // C++ [expr.ref]p4: 2298 // Otherwise, if E1.E2 refers to a non-static member function. . . 2299 // [t]he expression can be used only as the left-hand operand of a 2300 // member function call. 2301 // 2302 // There are other safeguards against such uses, but it's important 2303 // to get this right here so that we don't end up making a 2304 // spuriously dependent expression if we're inside a dependent 2305 // instance method. 2306 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2307 bool MightBeImplicitMember; 2308 if (!IsAddressOfOperand) 2309 MightBeImplicitMember = true; 2310 else if (!SS.isEmpty()) 2311 MightBeImplicitMember = false; 2312 else if (R.isOverloadedResult()) 2313 MightBeImplicitMember = false; 2314 else if (R.isUnresolvableResult()) 2315 MightBeImplicitMember = true; 2316 else 2317 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2318 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2319 isa<MSPropertyDecl>(R.getFoundDecl()); 2320 2321 if (MightBeImplicitMember) 2322 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2323 R, TemplateArgs, S); 2324 } 2325 2326 if (TemplateArgs || TemplateKWLoc.isValid()) { 2327 2328 // In C++1y, if this is a variable template id, then check it 2329 // in BuildTemplateIdExpr(). 2330 // The single lookup result must be a variable template declaration. 2331 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2332 Id.TemplateId->Kind == TNK_Var_template) { 2333 assert(R.getAsSingle<VarTemplateDecl>() && 2334 "There should only be one declaration found."); 2335 } 2336 2337 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2338 } 2339 2340 return BuildDeclarationNameExpr(SS, R, ADL); 2341 } 2342 2343 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2344 /// declaration name, generally during template instantiation. 2345 /// There's a large number of things which don't need to be done along 2346 /// this path. 2347 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2348 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2349 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2350 DeclContext *DC = computeDeclContext(SS, false); 2351 if (!DC) 2352 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2353 NameInfo, /*TemplateArgs=*/nullptr); 2354 2355 if (RequireCompleteDeclContext(SS, DC)) 2356 return ExprError(); 2357 2358 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2359 LookupQualifiedName(R, DC); 2360 2361 if (R.isAmbiguous()) 2362 return ExprError(); 2363 2364 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2365 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2366 NameInfo, /*TemplateArgs=*/nullptr); 2367 2368 if (R.empty()) { 2369 Diag(NameInfo.getLoc(), diag::err_no_member) 2370 << NameInfo.getName() << DC << SS.getRange(); 2371 return ExprError(); 2372 } 2373 2374 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2375 // Diagnose a missing typename if this resolved unambiguously to a type in 2376 // a dependent context. If we can recover with a type, downgrade this to 2377 // a warning in Microsoft compatibility mode. 2378 unsigned DiagID = diag::err_typename_missing; 2379 if (RecoveryTSI && getLangOpts().MSVCCompat) 2380 DiagID = diag::ext_typename_missing; 2381 SourceLocation Loc = SS.getBeginLoc(); 2382 auto D = Diag(Loc, DiagID); 2383 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2384 << SourceRange(Loc, NameInfo.getEndLoc()); 2385 2386 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2387 // context. 2388 if (!RecoveryTSI) 2389 return ExprError(); 2390 2391 // Only issue the fixit if we're prepared to recover. 2392 D << FixItHint::CreateInsertion(Loc, "typename "); 2393 2394 // Recover by pretending this was an elaborated type. 2395 QualType Ty = Context.getTypeDeclType(TD); 2396 TypeLocBuilder TLB; 2397 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2398 2399 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2400 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2401 QTL.setElaboratedKeywordLoc(SourceLocation()); 2402 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2403 2404 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2405 2406 return ExprEmpty(); 2407 } 2408 2409 // Defend against this resolving to an implicit member access. We usually 2410 // won't get here if this might be a legitimate a class member (we end up in 2411 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2412 // a pointer-to-member or in an unevaluated context in C++11. 2413 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2414 return BuildPossibleImplicitMemberExpr(SS, 2415 /*TemplateKWLoc=*/SourceLocation(), 2416 R, /*TemplateArgs=*/nullptr, S); 2417 2418 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2419 } 2420 2421 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2422 /// detected that we're currently inside an ObjC method. Perform some 2423 /// additional lookup. 2424 /// 2425 /// Ideally, most of this would be done by lookup, but there's 2426 /// actually quite a lot of extra work involved. 2427 /// 2428 /// Returns a null sentinel to indicate trivial success. 2429 ExprResult 2430 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2431 IdentifierInfo *II, bool AllowBuiltinCreation) { 2432 SourceLocation Loc = Lookup.getNameLoc(); 2433 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2434 2435 // Check for error condition which is already reported. 2436 if (!CurMethod) 2437 return ExprError(); 2438 2439 // There are two cases to handle here. 1) scoped lookup could have failed, 2440 // in which case we should look for an ivar. 2) scoped lookup could have 2441 // found a decl, but that decl is outside the current instance method (i.e. 2442 // a global variable). In these two cases, we do a lookup for an ivar with 2443 // this name, if the lookup sucedes, we replace it our current decl. 2444 2445 // If we're in a class method, we don't normally want to look for 2446 // ivars. But if we don't find anything else, and there's an 2447 // ivar, that's an error. 2448 bool IsClassMethod = CurMethod->isClassMethod(); 2449 2450 bool LookForIvars; 2451 if (Lookup.empty()) 2452 LookForIvars = true; 2453 else if (IsClassMethod) 2454 LookForIvars = false; 2455 else 2456 LookForIvars = (Lookup.isSingleResult() && 2457 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2458 ObjCInterfaceDecl *IFace = nullptr; 2459 if (LookForIvars) { 2460 IFace = CurMethod->getClassInterface(); 2461 ObjCInterfaceDecl *ClassDeclared; 2462 ObjCIvarDecl *IV = nullptr; 2463 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2464 // Diagnose using an ivar in a class method. 2465 if (IsClassMethod) 2466 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2467 << IV->getDeclName()); 2468 2469 // If we're referencing an invalid decl, just return this as a silent 2470 // error node. The error diagnostic was already emitted on the decl. 2471 if (IV->isInvalidDecl()) 2472 return ExprError(); 2473 2474 // Check if referencing a field with __attribute__((deprecated)). 2475 if (DiagnoseUseOfDecl(IV, Loc)) 2476 return ExprError(); 2477 2478 // Diagnose the use of an ivar outside of the declaring class. 2479 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2480 !declaresSameEntity(ClassDeclared, IFace) && 2481 !getLangOpts().DebuggerSupport) 2482 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2483 2484 // FIXME: This should use a new expr for a direct reference, don't 2485 // turn this into Self->ivar, just return a BareIVarExpr or something. 2486 IdentifierInfo &II = Context.Idents.get("self"); 2487 UnqualifiedId SelfName; 2488 SelfName.setIdentifier(&II, SourceLocation()); 2489 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2490 CXXScopeSpec SelfScopeSpec; 2491 SourceLocation TemplateKWLoc; 2492 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2493 SelfName, false, false); 2494 if (SelfExpr.isInvalid()) 2495 return ExprError(); 2496 2497 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2498 if (SelfExpr.isInvalid()) 2499 return ExprError(); 2500 2501 MarkAnyDeclReferenced(Loc, IV, true); 2502 2503 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2504 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2505 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2506 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2507 2508 ObjCIvarRefExpr *Result = new (Context) 2509 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2510 IV->getLocation(), SelfExpr.get(), true, true); 2511 2512 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2513 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2514 recordUseOfEvaluatedWeak(Result); 2515 } 2516 if (getLangOpts().ObjCAutoRefCount) { 2517 if (CurContext->isClosure()) 2518 Diag(Loc, diag::warn_implicitly_retains_self) 2519 << FixItHint::CreateInsertion(Loc, "self->"); 2520 } 2521 2522 return Result; 2523 } 2524 } else if (CurMethod->isInstanceMethod()) { 2525 // We should warn if a local variable hides an ivar. 2526 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2527 ObjCInterfaceDecl *ClassDeclared; 2528 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2529 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2530 declaresSameEntity(IFace, ClassDeclared)) 2531 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2532 } 2533 } 2534 } else if (Lookup.isSingleResult() && 2535 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2536 // If accessing a stand-alone ivar in a class method, this is an error. 2537 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2538 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2539 << IV->getDeclName()); 2540 } 2541 2542 if (Lookup.empty() && II && AllowBuiltinCreation) { 2543 // FIXME. Consolidate this with similar code in LookupName. 2544 if (unsigned BuiltinID = II->getBuiltinID()) { 2545 if (!(getLangOpts().CPlusPlus && 2546 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2547 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2548 S, Lookup.isForRedeclaration(), 2549 Lookup.getNameLoc()); 2550 if (D) Lookup.addDecl(D); 2551 } 2552 } 2553 } 2554 // Sentinel value saying that we didn't do anything special. 2555 return ExprResult((Expr *)nullptr); 2556 } 2557 2558 /// \brief Cast a base object to a member's actual type. 2559 /// 2560 /// Logically this happens in three phases: 2561 /// 2562 /// * First we cast from the base type to the naming class. 2563 /// The naming class is the class into which we were looking 2564 /// when we found the member; it's the qualifier type if a 2565 /// qualifier was provided, and otherwise it's the base type. 2566 /// 2567 /// * Next we cast from the naming class to the declaring class. 2568 /// If the member we found was brought into a class's scope by 2569 /// a using declaration, this is that class; otherwise it's 2570 /// the class declaring the member. 2571 /// 2572 /// * Finally we cast from the declaring class to the "true" 2573 /// declaring class of the member. This conversion does not 2574 /// obey access control. 2575 ExprResult 2576 Sema::PerformObjectMemberConversion(Expr *From, 2577 NestedNameSpecifier *Qualifier, 2578 NamedDecl *FoundDecl, 2579 NamedDecl *Member) { 2580 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2581 if (!RD) 2582 return From; 2583 2584 QualType DestRecordType; 2585 QualType DestType; 2586 QualType FromRecordType; 2587 QualType FromType = From->getType(); 2588 bool PointerConversions = false; 2589 if (isa<FieldDecl>(Member)) { 2590 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2591 2592 if (FromType->getAs<PointerType>()) { 2593 DestType = Context.getPointerType(DestRecordType); 2594 FromRecordType = FromType->getPointeeType(); 2595 PointerConversions = true; 2596 } else { 2597 DestType = DestRecordType; 2598 FromRecordType = FromType; 2599 } 2600 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2601 if (Method->isStatic()) 2602 return From; 2603 2604 DestType = Method->getThisType(Context); 2605 DestRecordType = DestType->getPointeeType(); 2606 2607 if (FromType->getAs<PointerType>()) { 2608 FromRecordType = FromType->getPointeeType(); 2609 PointerConversions = true; 2610 } else { 2611 FromRecordType = FromType; 2612 DestType = DestRecordType; 2613 } 2614 } else { 2615 // No conversion necessary. 2616 return From; 2617 } 2618 2619 if (DestType->isDependentType() || FromType->isDependentType()) 2620 return From; 2621 2622 // If the unqualified types are the same, no conversion is necessary. 2623 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2624 return From; 2625 2626 SourceRange FromRange = From->getSourceRange(); 2627 SourceLocation FromLoc = FromRange.getBegin(); 2628 2629 ExprValueKind VK = From->getValueKind(); 2630 2631 // C++ [class.member.lookup]p8: 2632 // [...] Ambiguities can often be resolved by qualifying a name with its 2633 // class name. 2634 // 2635 // If the member was a qualified name and the qualified referred to a 2636 // specific base subobject type, we'll cast to that intermediate type 2637 // first and then to the object in which the member is declared. That allows 2638 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2639 // 2640 // class Base { public: int x; }; 2641 // class Derived1 : public Base { }; 2642 // class Derived2 : public Base { }; 2643 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2644 // 2645 // void VeryDerived::f() { 2646 // x = 17; // error: ambiguous base subobjects 2647 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2648 // } 2649 if (Qualifier && Qualifier->getAsType()) { 2650 QualType QType = QualType(Qualifier->getAsType(), 0); 2651 assert(QType->isRecordType() && "lookup done with non-record type"); 2652 2653 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2654 2655 // In C++98, the qualifier type doesn't actually have to be a base 2656 // type of the object type, in which case we just ignore it. 2657 // Otherwise build the appropriate casts. 2658 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2659 CXXCastPath BasePath; 2660 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2661 FromLoc, FromRange, &BasePath)) 2662 return ExprError(); 2663 2664 if (PointerConversions) 2665 QType = Context.getPointerType(QType); 2666 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2667 VK, &BasePath).get(); 2668 2669 FromType = QType; 2670 FromRecordType = QRecordType; 2671 2672 // If the qualifier type was the same as the destination type, 2673 // we're done. 2674 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2675 return From; 2676 } 2677 } 2678 2679 bool IgnoreAccess = false; 2680 2681 // If we actually found the member through a using declaration, cast 2682 // down to the using declaration's type. 2683 // 2684 // Pointer equality is fine here because only one declaration of a 2685 // class ever has member declarations. 2686 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2687 assert(isa<UsingShadowDecl>(FoundDecl)); 2688 QualType URecordType = Context.getTypeDeclType( 2689 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2690 2691 // We only need to do this if the naming-class to declaring-class 2692 // conversion is non-trivial. 2693 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2694 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2695 CXXCastPath BasePath; 2696 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2697 FromLoc, FromRange, &BasePath)) 2698 return ExprError(); 2699 2700 QualType UType = URecordType; 2701 if (PointerConversions) 2702 UType = Context.getPointerType(UType); 2703 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2704 VK, &BasePath).get(); 2705 FromType = UType; 2706 FromRecordType = URecordType; 2707 } 2708 2709 // We don't do access control for the conversion from the 2710 // declaring class to the true declaring class. 2711 IgnoreAccess = true; 2712 } 2713 2714 CXXCastPath BasePath; 2715 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2716 FromLoc, FromRange, &BasePath, 2717 IgnoreAccess)) 2718 return ExprError(); 2719 2720 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2721 VK, &BasePath); 2722 } 2723 2724 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2725 const LookupResult &R, 2726 bool HasTrailingLParen) { 2727 // Only when used directly as the postfix-expression of a call. 2728 if (!HasTrailingLParen) 2729 return false; 2730 2731 // Never if a scope specifier was provided. 2732 if (SS.isSet()) 2733 return false; 2734 2735 // Only in C++ or ObjC++. 2736 if (!getLangOpts().CPlusPlus) 2737 return false; 2738 2739 // Turn off ADL when we find certain kinds of declarations during 2740 // normal lookup: 2741 for (NamedDecl *D : R) { 2742 // C++0x [basic.lookup.argdep]p3: 2743 // -- a declaration of a class member 2744 // Since using decls preserve this property, we check this on the 2745 // original decl. 2746 if (D->isCXXClassMember()) 2747 return false; 2748 2749 // C++0x [basic.lookup.argdep]p3: 2750 // -- a block-scope function declaration that is not a 2751 // using-declaration 2752 // NOTE: we also trigger this for function templates (in fact, we 2753 // don't check the decl type at all, since all other decl types 2754 // turn off ADL anyway). 2755 if (isa<UsingShadowDecl>(D)) 2756 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2757 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2758 return false; 2759 2760 // C++0x [basic.lookup.argdep]p3: 2761 // -- a declaration that is neither a function or a function 2762 // template 2763 // And also for builtin functions. 2764 if (isa<FunctionDecl>(D)) { 2765 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2766 2767 // But also builtin functions. 2768 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2769 return false; 2770 } else if (!isa<FunctionTemplateDecl>(D)) 2771 return false; 2772 } 2773 2774 return true; 2775 } 2776 2777 2778 /// Diagnoses obvious problems with the use of the given declaration 2779 /// as an expression. This is only actually called for lookups that 2780 /// were not overloaded, and it doesn't promise that the declaration 2781 /// will in fact be used. 2782 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2783 if (D->isInvalidDecl()) 2784 return true; 2785 2786 if (isa<TypedefNameDecl>(D)) { 2787 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2788 return true; 2789 } 2790 2791 if (isa<ObjCInterfaceDecl>(D)) { 2792 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2793 return true; 2794 } 2795 2796 if (isa<NamespaceDecl>(D)) { 2797 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2798 return true; 2799 } 2800 2801 return false; 2802 } 2803 2804 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2805 LookupResult &R, bool NeedsADL, 2806 bool AcceptInvalidDecl) { 2807 // If this is a single, fully-resolved result and we don't need ADL, 2808 // just build an ordinary singleton decl ref. 2809 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2810 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2811 R.getRepresentativeDecl(), nullptr, 2812 AcceptInvalidDecl); 2813 2814 // We only need to check the declaration if there's exactly one 2815 // result, because in the overloaded case the results can only be 2816 // functions and function templates. 2817 if (R.isSingleResult() && 2818 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2819 return ExprError(); 2820 2821 // Otherwise, just build an unresolved lookup expression. Suppress 2822 // any lookup-related diagnostics; we'll hash these out later, when 2823 // we've picked a target. 2824 R.suppressDiagnostics(); 2825 2826 UnresolvedLookupExpr *ULE 2827 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2828 SS.getWithLocInContext(Context), 2829 R.getLookupNameInfo(), 2830 NeedsADL, R.isOverloadedResult(), 2831 R.begin(), R.end()); 2832 2833 return ULE; 2834 } 2835 2836 static void 2837 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2838 ValueDecl *var, DeclContext *DC); 2839 2840 /// \brief Complete semantic analysis for a reference to the given declaration. 2841 ExprResult Sema::BuildDeclarationNameExpr( 2842 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2843 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2844 bool AcceptInvalidDecl) { 2845 assert(D && "Cannot refer to a NULL declaration"); 2846 assert(!isa<FunctionTemplateDecl>(D) && 2847 "Cannot refer unambiguously to a function template"); 2848 2849 SourceLocation Loc = NameInfo.getLoc(); 2850 if (CheckDeclInExpr(*this, Loc, D)) 2851 return ExprError(); 2852 2853 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2854 // Specifically diagnose references to class templates that are missing 2855 // a template argument list. 2856 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2857 << Template << SS.getRange(); 2858 Diag(Template->getLocation(), diag::note_template_decl_here); 2859 return ExprError(); 2860 } 2861 2862 // Make sure that we're referring to a value. 2863 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2864 if (!VD) { 2865 Diag(Loc, diag::err_ref_non_value) 2866 << D << SS.getRange(); 2867 Diag(D->getLocation(), diag::note_declared_at); 2868 return ExprError(); 2869 } 2870 2871 // Check whether this declaration can be used. Note that we suppress 2872 // this check when we're going to perform argument-dependent lookup 2873 // on this function name, because this might not be the function 2874 // that overload resolution actually selects. 2875 if (DiagnoseUseOfDecl(VD, Loc)) 2876 return ExprError(); 2877 2878 // Only create DeclRefExpr's for valid Decl's. 2879 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2880 return ExprError(); 2881 2882 // Handle members of anonymous structs and unions. If we got here, 2883 // and the reference is to a class member indirect field, then this 2884 // must be the subject of a pointer-to-member expression. 2885 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2886 if (!indirectField->isCXXClassMember()) 2887 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2888 indirectField); 2889 2890 { 2891 QualType type = VD->getType(); 2892 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2893 // C++ [except.spec]p17: 2894 // An exception-specification is considered to be needed when: 2895 // - in an expression, the function is the unique lookup result or 2896 // the selected member of a set of overloaded functions. 2897 ResolveExceptionSpec(Loc, FPT); 2898 type = VD->getType(); 2899 } 2900 ExprValueKind valueKind = VK_RValue; 2901 2902 switch (D->getKind()) { 2903 // Ignore all the non-ValueDecl kinds. 2904 #define ABSTRACT_DECL(kind) 2905 #define VALUE(type, base) 2906 #define DECL(type, base) \ 2907 case Decl::type: 2908 #include "clang/AST/DeclNodes.inc" 2909 llvm_unreachable("invalid value decl kind"); 2910 2911 // These shouldn't make it here. 2912 case Decl::ObjCAtDefsField: 2913 case Decl::ObjCIvar: 2914 llvm_unreachable("forming non-member reference to ivar?"); 2915 2916 // Enum constants are always r-values and never references. 2917 // Unresolved using declarations are dependent. 2918 case Decl::EnumConstant: 2919 case Decl::UnresolvedUsingValue: 2920 case Decl::OMPDeclareReduction: 2921 valueKind = VK_RValue; 2922 break; 2923 2924 // Fields and indirect fields that got here must be for 2925 // pointer-to-member expressions; we just call them l-values for 2926 // internal consistency, because this subexpression doesn't really 2927 // exist in the high-level semantics. 2928 case Decl::Field: 2929 case Decl::IndirectField: 2930 assert(getLangOpts().CPlusPlus && 2931 "building reference to field in C?"); 2932 2933 // These can't have reference type in well-formed programs, but 2934 // for internal consistency we do this anyway. 2935 type = type.getNonReferenceType(); 2936 valueKind = VK_LValue; 2937 break; 2938 2939 // Non-type template parameters are either l-values or r-values 2940 // depending on the type. 2941 case Decl::NonTypeTemplateParm: { 2942 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2943 type = reftype->getPointeeType(); 2944 valueKind = VK_LValue; // even if the parameter is an r-value reference 2945 break; 2946 } 2947 2948 // For non-references, we need to strip qualifiers just in case 2949 // the template parameter was declared as 'const int' or whatever. 2950 valueKind = VK_RValue; 2951 type = type.getUnqualifiedType(); 2952 break; 2953 } 2954 2955 case Decl::Var: 2956 case Decl::VarTemplateSpecialization: 2957 case Decl::VarTemplatePartialSpecialization: 2958 case Decl::Decomposition: 2959 case Decl::OMPCapturedExpr: 2960 // In C, "extern void blah;" is valid and is an r-value. 2961 if (!getLangOpts().CPlusPlus && 2962 !type.hasQualifiers() && 2963 type->isVoidType()) { 2964 valueKind = VK_RValue; 2965 break; 2966 } 2967 // fallthrough 2968 2969 case Decl::ImplicitParam: 2970 case Decl::ParmVar: { 2971 // These are always l-values. 2972 valueKind = VK_LValue; 2973 type = type.getNonReferenceType(); 2974 2975 // FIXME: Does the addition of const really only apply in 2976 // potentially-evaluated contexts? Since the variable isn't actually 2977 // captured in an unevaluated context, it seems that the answer is no. 2978 if (!isUnevaluatedContext()) { 2979 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2980 if (!CapturedType.isNull()) 2981 type = CapturedType; 2982 } 2983 2984 break; 2985 } 2986 2987 case Decl::Binding: { 2988 // These are always lvalues. 2989 valueKind = VK_LValue; 2990 type = type.getNonReferenceType(); 2991 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2992 // decides how that's supposed to work. 2993 auto *BD = cast<BindingDecl>(VD); 2994 if (BD->getDeclContext()->isFunctionOrMethod() && 2995 BD->getDeclContext() != CurContext) 2996 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2997 break; 2998 } 2999 3000 case Decl::Function: { 3001 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3002 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3003 type = Context.BuiltinFnTy; 3004 valueKind = VK_RValue; 3005 break; 3006 } 3007 } 3008 3009 const FunctionType *fty = type->castAs<FunctionType>(); 3010 3011 // If we're referring to a function with an __unknown_anytype 3012 // result type, make the entire expression __unknown_anytype. 3013 if (fty->getReturnType() == Context.UnknownAnyTy) { 3014 type = Context.UnknownAnyTy; 3015 valueKind = VK_RValue; 3016 break; 3017 } 3018 3019 // Functions are l-values in C++. 3020 if (getLangOpts().CPlusPlus) { 3021 valueKind = VK_LValue; 3022 break; 3023 } 3024 3025 // C99 DR 316 says that, if a function type comes from a 3026 // function definition (without a prototype), that type is only 3027 // used for checking compatibility. Therefore, when referencing 3028 // the function, we pretend that we don't have the full function 3029 // type. 3030 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3031 isa<FunctionProtoType>(fty)) 3032 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3033 fty->getExtInfo()); 3034 3035 // Functions are r-values in C. 3036 valueKind = VK_RValue; 3037 break; 3038 } 3039 3040 case Decl::CXXDeductionGuide: 3041 llvm_unreachable("building reference to deduction guide"); 3042 3043 case Decl::MSProperty: 3044 valueKind = VK_LValue; 3045 break; 3046 3047 case Decl::CXXMethod: 3048 // If we're referring to a method with an __unknown_anytype 3049 // result type, make the entire expression __unknown_anytype. 3050 // This should only be possible with a type written directly. 3051 if (const FunctionProtoType *proto 3052 = dyn_cast<FunctionProtoType>(VD->getType())) 3053 if (proto->getReturnType() == Context.UnknownAnyTy) { 3054 type = Context.UnknownAnyTy; 3055 valueKind = VK_RValue; 3056 break; 3057 } 3058 3059 // C++ methods are l-values if static, r-values if non-static. 3060 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3061 valueKind = VK_LValue; 3062 break; 3063 } 3064 // fallthrough 3065 3066 case Decl::CXXConversion: 3067 case Decl::CXXDestructor: 3068 case Decl::CXXConstructor: 3069 valueKind = VK_RValue; 3070 break; 3071 } 3072 3073 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3074 TemplateArgs); 3075 } 3076 } 3077 3078 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3079 SmallString<32> &Target) { 3080 Target.resize(CharByteWidth * (Source.size() + 1)); 3081 char *ResultPtr = &Target[0]; 3082 const llvm::UTF8 *ErrorPtr; 3083 bool success = 3084 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3085 (void)success; 3086 assert(success); 3087 Target.resize(ResultPtr - &Target[0]); 3088 } 3089 3090 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3091 PredefinedExpr::IdentType IT) { 3092 // Pick the current block, lambda, captured statement or function. 3093 Decl *currentDecl = nullptr; 3094 if (const BlockScopeInfo *BSI = getCurBlock()) 3095 currentDecl = BSI->TheDecl; 3096 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3097 currentDecl = LSI->CallOperator; 3098 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3099 currentDecl = CSI->TheCapturedDecl; 3100 else 3101 currentDecl = getCurFunctionOrMethodDecl(); 3102 3103 if (!currentDecl) { 3104 Diag(Loc, diag::ext_predef_outside_function); 3105 currentDecl = Context.getTranslationUnitDecl(); 3106 } 3107 3108 QualType ResTy; 3109 StringLiteral *SL = nullptr; 3110 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3111 ResTy = Context.DependentTy; 3112 else { 3113 // Pre-defined identifiers are of type char[x], where x is the length of 3114 // the string. 3115 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3116 unsigned Length = Str.length(); 3117 3118 llvm::APInt LengthI(32, Length + 1); 3119 if (IT == PredefinedExpr::LFunction) { 3120 ResTy = Context.WideCharTy.withConst(); 3121 SmallString<32> RawChars; 3122 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3123 Str, RawChars); 3124 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3125 /*IndexTypeQuals*/ 0); 3126 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3127 /*Pascal*/ false, ResTy, Loc); 3128 } else { 3129 ResTy = Context.CharTy.withConst(); 3130 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3131 /*IndexTypeQuals*/ 0); 3132 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3133 /*Pascal*/ false, ResTy, Loc); 3134 } 3135 } 3136 3137 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3138 } 3139 3140 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3141 PredefinedExpr::IdentType IT; 3142 3143 switch (Kind) { 3144 default: llvm_unreachable("Unknown simple primary expr!"); 3145 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3146 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3147 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3148 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3149 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3150 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3151 } 3152 3153 return BuildPredefinedExpr(Loc, IT); 3154 } 3155 3156 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3157 SmallString<16> CharBuffer; 3158 bool Invalid = false; 3159 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3160 if (Invalid) 3161 return ExprError(); 3162 3163 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3164 PP, Tok.getKind()); 3165 if (Literal.hadError()) 3166 return ExprError(); 3167 3168 QualType Ty; 3169 if (Literal.isWide()) 3170 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3171 else if (Literal.isUTF16()) 3172 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3173 else if (Literal.isUTF32()) 3174 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3175 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3176 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3177 else 3178 Ty = Context.CharTy; // 'x' -> char in C++ 3179 3180 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3181 if (Literal.isWide()) 3182 Kind = CharacterLiteral::Wide; 3183 else if (Literal.isUTF16()) 3184 Kind = CharacterLiteral::UTF16; 3185 else if (Literal.isUTF32()) 3186 Kind = CharacterLiteral::UTF32; 3187 else if (Literal.isUTF8()) 3188 Kind = CharacterLiteral::UTF8; 3189 3190 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3191 Tok.getLocation()); 3192 3193 if (Literal.getUDSuffix().empty()) 3194 return Lit; 3195 3196 // We're building a user-defined literal. 3197 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3198 SourceLocation UDSuffixLoc = 3199 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3200 3201 // Make sure we're allowed user-defined literals here. 3202 if (!UDLScope) 3203 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3204 3205 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3206 // operator "" X (ch) 3207 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3208 Lit, Tok.getLocation()); 3209 } 3210 3211 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3212 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3213 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3214 Context.IntTy, Loc); 3215 } 3216 3217 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3218 QualType Ty, SourceLocation Loc) { 3219 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3220 3221 using llvm::APFloat; 3222 APFloat Val(Format); 3223 3224 APFloat::opStatus result = Literal.GetFloatValue(Val); 3225 3226 // Overflow is always an error, but underflow is only an error if 3227 // we underflowed to zero (APFloat reports denormals as underflow). 3228 if ((result & APFloat::opOverflow) || 3229 ((result & APFloat::opUnderflow) && Val.isZero())) { 3230 unsigned diagnostic; 3231 SmallString<20> buffer; 3232 if (result & APFloat::opOverflow) { 3233 diagnostic = diag::warn_float_overflow; 3234 APFloat::getLargest(Format).toString(buffer); 3235 } else { 3236 diagnostic = diag::warn_float_underflow; 3237 APFloat::getSmallest(Format).toString(buffer); 3238 } 3239 3240 S.Diag(Loc, diagnostic) 3241 << Ty 3242 << StringRef(buffer.data(), buffer.size()); 3243 } 3244 3245 bool isExact = (result == APFloat::opOK); 3246 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3247 } 3248 3249 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3250 assert(E && "Invalid expression"); 3251 3252 if (E->isValueDependent()) 3253 return false; 3254 3255 QualType QT = E->getType(); 3256 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3257 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3258 return true; 3259 } 3260 3261 llvm::APSInt ValueAPS; 3262 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3263 3264 if (R.isInvalid()) 3265 return true; 3266 3267 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3268 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3269 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3270 << ValueAPS.toString(10) << ValueIsPositive; 3271 return true; 3272 } 3273 3274 return false; 3275 } 3276 3277 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3278 // Fast path for a single digit (which is quite common). A single digit 3279 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3280 if (Tok.getLength() == 1) { 3281 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3282 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3283 } 3284 3285 SmallString<128> SpellingBuffer; 3286 // NumericLiteralParser wants to overread by one character. Add padding to 3287 // the buffer in case the token is copied to the buffer. If getSpelling() 3288 // returns a StringRef to the memory buffer, it should have a null char at 3289 // the EOF, so it is also safe. 3290 SpellingBuffer.resize(Tok.getLength() + 1); 3291 3292 // Get the spelling of the token, which eliminates trigraphs, etc. 3293 bool Invalid = false; 3294 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3295 if (Invalid) 3296 return ExprError(); 3297 3298 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3299 if (Literal.hadError) 3300 return ExprError(); 3301 3302 if (Literal.hasUDSuffix()) { 3303 // We're building a user-defined literal. 3304 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3305 SourceLocation UDSuffixLoc = 3306 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3307 3308 // Make sure we're allowed user-defined literals here. 3309 if (!UDLScope) 3310 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3311 3312 QualType CookedTy; 3313 if (Literal.isFloatingLiteral()) { 3314 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3315 // long double, the literal is treated as a call of the form 3316 // operator "" X (f L) 3317 CookedTy = Context.LongDoubleTy; 3318 } else { 3319 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3320 // unsigned long long, the literal is treated as a call of the form 3321 // operator "" X (n ULL) 3322 CookedTy = Context.UnsignedLongLongTy; 3323 } 3324 3325 DeclarationName OpName = 3326 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3327 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3328 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3329 3330 SourceLocation TokLoc = Tok.getLocation(); 3331 3332 // Perform literal operator lookup to determine if we're building a raw 3333 // literal or a cooked one. 3334 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3335 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3336 /*AllowRaw*/true, /*AllowTemplate*/true, 3337 /*AllowStringTemplate*/false)) { 3338 case LOLR_Error: 3339 return ExprError(); 3340 3341 case LOLR_Cooked: { 3342 Expr *Lit; 3343 if (Literal.isFloatingLiteral()) { 3344 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3345 } else { 3346 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3347 if (Literal.GetIntegerValue(ResultVal)) 3348 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3349 << /* Unsigned */ 1; 3350 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3351 Tok.getLocation()); 3352 } 3353 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3354 } 3355 3356 case LOLR_Raw: { 3357 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3358 // literal is treated as a call of the form 3359 // operator "" X ("n") 3360 unsigned Length = Literal.getUDSuffixOffset(); 3361 QualType StrTy = Context.getConstantArrayType( 3362 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3363 ArrayType::Normal, 0); 3364 Expr *Lit = StringLiteral::Create( 3365 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3366 /*Pascal*/false, StrTy, &TokLoc, 1); 3367 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3368 } 3369 3370 case LOLR_Template: { 3371 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3372 // template), L is treated as a call fo the form 3373 // operator "" X <'c1', 'c2', ... 'ck'>() 3374 // where n is the source character sequence c1 c2 ... ck. 3375 TemplateArgumentListInfo ExplicitArgs; 3376 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3377 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3378 llvm::APSInt Value(CharBits, CharIsUnsigned); 3379 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3380 Value = TokSpelling[I]; 3381 TemplateArgument Arg(Context, Value, Context.CharTy); 3382 TemplateArgumentLocInfo ArgInfo; 3383 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3384 } 3385 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3386 &ExplicitArgs); 3387 } 3388 case LOLR_StringTemplate: 3389 llvm_unreachable("unexpected literal operator lookup result"); 3390 } 3391 } 3392 3393 Expr *Res; 3394 3395 if (Literal.isFloatingLiteral()) { 3396 QualType Ty; 3397 if (Literal.isHalf){ 3398 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3399 Ty = Context.HalfTy; 3400 else { 3401 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3402 return ExprError(); 3403 } 3404 } else if (Literal.isFloat) 3405 Ty = Context.FloatTy; 3406 else if (Literal.isLong) 3407 Ty = Context.LongDoubleTy; 3408 else if (Literal.isFloat128) 3409 Ty = Context.Float128Ty; 3410 else 3411 Ty = Context.DoubleTy; 3412 3413 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3414 3415 if (Ty == Context.DoubleTy) { 3416 if (getLangOpts().SinglePrecisionConstants) { 3417 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3418 if (BTy->getKind() != BuiltinType::Float) { 3419 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3420 } 3421 } else if (getLangOpts().OpenCL && 3422 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3423 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3424 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3425 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3426 } 3427 } 3428 } else if (!Literal.isIntegerLiteral()) { 3429 return ExprError(); 3430 } else { 3431 QualType Ty; 3432 3433 // 'long long' is a C99 or C++11 feature. 3434 if (!getLangOpts().C99 && Literal.isLongLong) { 3435 if (getLangOpts().CPlusPlus) 3436 Diag(Tok.getLocation(), 3437 getLangOpts().CPlusPlus11 ? 3438 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3439 else 3440 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3441 } 3442 3443 // Get the value in the widest-possible width. 3444 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3445 llvm::APInt ResultVal(MaxWidth, 0); 3446 3447 if (Literal.GetIntegerValue(ResultVal)) { 3448 // If this value didn't fit into uintmax_t, error and force to ull. 3449 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3450 << /* Unsigned */ 1; 3451 Ty = Context.UnsignedLongLongTy; 3452 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3453 "long long is not intmax_t?"); 3454 } else { 3455 // If this value fits into a ULL, try to figure out what else it fits into 3456 // according to the rules of C99 6.4.4.1p5. 3457 3458 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3459 // be an unsigned int. 3460 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3461 3462 // Check from smallest to largest, picking the smallest type we can. 3463 unsigned Width = 0; 3464 3465 // Microsoft specific integer suffixes are explicitly sized. 3466 if (Literal.MicrosoftInteger) { 3467 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3468 Width = 8; 3469 Ty = Context.CharTy; 3470 } else { 3471 Width = Literal.MicrosoftInteger; 3472 Ty = Context.getIntTypeForBitwidth(Width, 3473 /*Signed=*/!Literal.isUnsigned); 3474 } 3475 } 3476 3477 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3478 // Are int/unsigned possibilities? 3479 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3480 3481 // Does it fit in a unsigned int? 3482 if (ResultVal.isIntN(IntSize)) { 3483 // Does it fit in a signed int? 3484 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3485 Ty = Context.IntTy; 3486 else if (AllowUnsigned) 3487 Ty = Context.UnsignedIntTy; 3488 Width = IntSize; 3489 } 3490 } 3491 3492 // Are long/unsigned long possibilities? 3493 if (Ty.isNull() && !Literal.isLongLong) { 3494 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3495 3496 // Does it fit in a unsigned long? 3497 if (ResultVal.isIntN(LongSize)) { 3498 // Does it fit in a signed long? 3499 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3500 Ty = Context.LongTy; 3501 else if (AllowUnsigned) 3502 Ty = Context.UnsignedLongTy; 3503 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3504 // is compatible. 3505 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3506 const unsigned LongLongSize = 3507 Context.getTargetInfo().getLongLongWidth(); 3508 Diag(Tok.getLocation(), 3509 getLangOpts().CPlusPlus 3510 ? Literal.isLong 3511 ? diag::warn_old_implicitly_unsigned_long_cxx 3512 : /*C++98 UB*/ diag:: 3513 ext_old_implicitly_unsigned_long_cxx 3514 : diag::warn_old_implicitly_unsigned_long) 3515 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3516 : /*will be ill-formed*/ 1); 3517 Ty = Context.UnsignedLongTy; 3518 } 3519 Width = LongSize; 3520 } 3521 } 3522 3523 // Check long long if needed. 3524 if (Ty.isNull()) { 3525 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3526 3527 // Does it fit in a unsigned long long? 3528 if (ResultVal.isIntN(LongLongSize)) { 3529 // Does it fit in a signed long long? 3530 // To be compatible with MSVC, hex integer literals ending with the 3531 // LL or i64 suffix are always signed in Microsoft mode. 3532 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3533 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3534 Ty = Context.LongLongTy; 3535 else if (AllowUnsigned) 3536 Ty = Context.UnsignedLongLongTy; 3537 Width = LongLongSize; 3538 } 3539 } 3540 3541 // If we still couldn't decide a type, we probably have something that 3542 // does not fit in a signed long long, but has no U suffix. 3543 if (Ty.isNull()) { 3544 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3545 Ty = Context.UnsignedLongLongTy; 3546 Width = Context.getTargetInfo().getLongLongWidth(); 3547 } 3548 3549 if (ResultVal.getBitWidth() != Width) 3550 ResultVal = ResultVal.trunc(Width); 3551 } 3552 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3553 } 3554 3555 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3556 if (Literal.isImaginary) 3557 Res = new (Context) ImaginaryLiteral(Res, 3558 Context.getComplexType(Res->getType())); 3559 3560 return Res; 3561 } 3562 3563 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3564 assert(E && "ActOnParenExpr() missing expr"); 3565 return new (Context) ParenExpr(L, R, E); 3566 } 3567 3568 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3569 SourceLocation Loc, 3570 SourceRange ArgRange) { 3571 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3572 // scalar or vector data type argument..." 3573 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3574 // type (C99 6.2.5p18) or void. 3575 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3576 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3577 << T << ArgRange; 3578 return true; 3579 } 3580 3581 assert((T->isVoidType() || !T->isIncompleteType()) && 3582 "Scalar types should always be complete"); 3583 return false; 3584 } 3585 3586 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3587 SourceLocation Loc, 3588 SourceRange ArgRange, 3589 UnaryExprOrTypeTrait TraitKind) { 3590 // Invalid types must be hard errors for SFINAE in C++. 3591 if (S.LangOpts.CPlusPlus) 3592 return true; 3593 3594 // C99 6.5.3.4p1: 3595 if (T->isFunctionType() && 3596 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3597 // sizeof(function)/alignof(function) is allowed as an extension. 3598 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3599 << TraitKind << ArgRange; 3600 return false; 3601 } 3602 3603 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3604 // this is an error (OpenCL v1.1 s6.3.k) 3605 if (T->isVoidType()) { 3606 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3607 : diag::ext_sizeof_alignof_void_type; 3608 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3609 return false; 3610 } 3611 3612 return true; 3613 } 3614 3615 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3616 SourceLocation Loc, 3617 SourceRange ArgRange, 3618 UnaryExprOrTypeTrait TraitKind) { 3619 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3620 // runtime doesn't allow it. 3621 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3622 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3623 << T << (TraitKind == UETT_SizeOf) 3624 << ArgRange; 3625 return true; 3626 } 3627 3628 return false; 3629 } 3630 3631 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3632 /// pointer type is equal to T) and emit a warning if it is. 3633 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3634 Expr *E) { 3635 // Don't warn if the operation changed the type. 3636 if (T != E->getType()) 3637 return; 3638 3639 // Now look for array decays. 3640 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3641 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3642 return; 3643 3644 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3645 << ICE->getType() 3646 << ICE->getSubExpr()->getType(); 3647 } 3648 3649 /// \brief Check the constraints on expression operands to unary type expression 3650 /// and type traits. 3651 /// 3652 /// Completes any types necessary and validates the constraints on the operand 3653 /// expression. The logic mostly mirrors the type-based overload, but may modify 3654 /// the expression as it completes the type for that expression through template 3655 /// instantiation, etc. 3656 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3657 UnaryExprOrTypeTrait ExprKind) { 3658 QualType ExprTy = E->getType(); 3659 assert(!ExprTy->isReferenceType()); 3660 3661 if (ExprKind == UETT_VecStep) 3662 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3663 E->getSourceRange()); 3664 3665 // Whitelist some types as extensions 3666 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3667 E->getSourceRange(), ExprKind)) 3668 return false; 3669 3670 // 'alignof' applied to an expression only requires the base element type of 3671 // the expression to be complete. 'sizeof' requires the expression's type to 3672 // be complete (and will attempt to complete it if it's an array of unknown 3673 // bound). 3674 if (ExprKind == UETT_AlignOf) { 3675 if (RequireCompleteType(E->getExprLoc(), 3676 Context.getBaseElementType(E->getType()), 3677 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3678 E->getSourceRange())) 3679 return true; 3680 } else { 3681 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3682 ExprKind, E->getSourceRange())) 3683 return true; 3684 } 3685 3686 // Completing the expression's type may have changed it. 3687 ExprTy = E->getType(); 3688 assert(!ExprTy->isReferenceType()); 3689 3690 if (ExprTy->isFunctionType()) { 3691 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3692 << ExprKind << E->getSourceRange(); 3693 return true; 3694 } 3695 3696 // The operand for sizeof and alignof is in an unevaluated expression context, 3697 // so side effects could result in unintended consequences. 3698 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3699 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3700 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3701 3702 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3703 E->getSourceRange(), ExprKind)) 3704 return true; 3705 3706 if (ExprKind == UETT_SizeOf) { 3707 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3708 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3709 QualType OType = PVD->getOriginalType(); 3710 QualType Type = PVD->getType(); 3711 if (Type->isPointerType() && OType->isArrayType()) { 3712 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3713 << Type << OType; 3714 Diag(PVD->getLocation(), diag::note_declared_at); 3715 } 3716 } 3717 } 3718 3719 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3720 // decays into a pointer and returns an unintended result. This is most 3721 // likely a typo for "sizeof(array) op x". 3722 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3723 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3724 BO->getLHS()); 3725 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3726 BO->getRHS()); 3727 } 3728 } 3729 3730 return false; 3731 } 3732 3733 /// \brief Check the constraints on operands to unary expression and type 3734 /// traits. 3735 /// 3736 /// This will complete any types necessary, and validate the various constraints 3737 /// on those operands. 3738 /// 3739 /// The UsualUnaryConversions() function is *not* called by this routine. 3740 /// C99 6.3.2.1p[2-4] all state: 3741 /// Except when it is the operand of the sizeof operator ... 3742 /// 3743 /// C++ [expr.sizeof]p4 3744 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3745 /// standard conversions are not applied to the operand of sizeof. 3746 /// 3747 /// This policy is followed for all of the unary trait expressions. 3748 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3749 SourceLocation OpLoc, 3750 SourceRange ExprRange, 3751 UnaryExprOrTypeTrait ExprKind) { 3752 if (ExprType->isDependentType()) 3753 return false; 3754 3755 // C++ [expr.sizeof]p2: 3756 // When applied to a reference or a reference type, the result 3757 // is the size of the referenced type. 3758 // C++11 [expr.alignof]p3: 3759 // When alignof is applied to a reference type, the result 3760 // shall be the alignment of the referenced type. 3761 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3762 ExprType = Ref->getPointeeType(); 3763 3764 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3765 // When alignof or _Alignof is applied to an array type, the result 3766 // is the alignment of the element type. 3767 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3768 ExprType = Context.getBaseElementType(ExprType); 3769 3770 if (ExprKind == UETT_VecStep) 3771 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3772 3773 // Whitelist some types as extensions 3774 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3775 ExprKind)) 3776 return false; 3777 3778 if (RequireCompleteType(OpLoc, ExprType, 3779 diag::err_sizeof_alignof_incomplete_type, 3780 ExprKind, ExprRange)) 3781 return true; 3782 3783 if (ExprType->isFunctionType()) { 3784 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3785 << ExprKind << ExprRange; 3786 return true; 3787 } 3788 3789 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3790 ExprKind)) 3791 return true; 3792 3793 return false; 3794 } 3795 3796 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3797 E = E->IgnoreParens(); 3798 3799 // Cannot know anything else if the expression is dependent. 3800 if (E->isTypeDependent()) 3801 return false; 3802 3803 if (E->getObjectKind() == OK_BitField) { 3804 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3805 << 1 << E->getSourceRange(); 3806 return true; 3807 } 3808 3809 ValueDecl *D = nullptr; 3810 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3811 D = DRE->getDecl(); 3812 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3813 D = ME->getMemberDecl(); 3814 } 3815 3816 // If it's a field, require the containing struct to have a 3817 // complete definition so that we can compute the layout. 3818 // 3819 // This can happen in C++11 onwards, either by naming the member 3820 // in a way that is not transformed into a member access expression 3821 // (in an unevaluated operand, for instance), or by naming the member 3822 // in a trailing-return-type. 3823 // 3824 // For the record, since __alignof__ on expressions is a GCC 3825 // extension, GCC seems to permit this but always gives the 3826 // nonsensical answer 0. 3827 // 3828 // We don't really need the layout here --- we could instead just 3829 // directly check for all the appropriate alignment-lowing 3830 // attributes --- but that would require duplicating a lot of 3831 // logic that just isn't worth duplicating for such a marginal 3832 // use-case. 3833 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3834 // Fast path this check, since we at least know the record has a 3835 // definition if we can find a member of it. 3836 if (!FD->getParent()->isCompleteDefinition()) { 3837 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3838 << E->getSourceRange(); 3839 return true; 3840 } 3841 3842 // Otherwise, if it's a field, and the field doesn't have 3843 // reference type, then it must have a complete type (or be a 3844 // flexible array member, which we explicitly want to 3845 // white-list anyway), which makes the following checks trivial. 3846 if (!FD->getType()->isReferenceType()) 3847 return false; 3848 } 3849 3850 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3851 } 3852 3853 bool Sema::CheckVecStepExpr(Expr *E) { 3854 E = E->IgnoreParens(); 3855 3856 // Cannot know anything else if the expression is dependent. 3857 if (E->isTypeDependent()) 3858 return false; 3859 3860 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3861 } 3862 3863 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3864 CapturingScopeInfo *CSI) { 3865 assert(T->isVariablyModifiedType()); 3866 assert(CSI != nullptr); 3867 3868 // We're going to walk down into the type and look for VLA expressions. 3869 do { 3870 const Type *Ty = T.getTypePtr(); 3871 switch (Ty->getTypeClass()) { 3872 #define TYPE(Class, Base) 3873 #define ABSTRACT_TYPE(Class, Base) 3874 #define NON_CANONICAL_TYPE(Class, Base) 3875 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3876 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3877 #include "clang/AST/TypeNodes.def" 3878 T = QualType(); 3879 break; 3880 // These types are never variably-modified. 3881 case Type::Builtin: 3882 case Type::Complex: 3883 case Type::Vector: 3884 case Type::ExtVector: 3885 case Type::Record: 3886 case Type::Enum: 3887 case Type::Elaborated: 3888 case Type::TemplateSpecialization: 3889 case Type::ObjCObject: 3890 case Type::ObjCInterface: 3891 case Type::ObjCObjectPointer: 3892 case Type::ObjCTypeParam: 3893 case Type::Pipe: 3894 llvm_unreachable("type class is never variably-modified!"); 3895 case Type::Adjusted: 3896 T = cast<AdjustedType>(Ty)->getOriginalType(); 3897 break; 3898 case Type::Decayed: 3899 T = cast<DecayedType>(Ty)->getPointeeType(); 3900 break; 3901 case Type::Pointer: 3902 T = cast<PointerType>(Ty)->getPointeeType(); 3903 break; 3904 case Type::BlockPointer: 3905 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3906 break; 3907 case Type::LValueReference: 3908 case Type::RValueReference: 3909 T = cast<ReferenceType>(Ty)->getPointeeType(); 3910 break; 3911 case Type::MemberPointer: 3912 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3913 break; 3914 case Type::ConstantArray: 3915 case Type::IncompleteArray: 3916 // Losing element qualification here is fine. 3917 T = cast<ArrayType>(Ty)->getElementType(); 3918 break; 3919 case Type::VariableArray: { 3920 // Losing element qualification here is fine. 3921 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3922 3923 // Unknown size indication requires no size computation. 3924 // Otherwise, evaluate and record it. 3925 if (auto Size = VAT->getSizeExpr()) { 3926 if (!CSI->isVLATypeCaptured(VAT)) { 3927 RecordDecl *CapRecord = nullptr; 3928 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3929 CapRecord = LSI->Lambda; 3930 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3931 CapRecord = CRSI->TheRecordDecl; 3932 } 3933 if (CapRecord) { 3934 auto ExprLoc = Size->getExprLoc(); 3935 auto SizeType = Context.getSizeType(); 3936 // Build the non-static data member. 3937 auto Field = 3938 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3939 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3940 /*BW*/ nullptr, /*Mutable*/ false, 3941 /*InitStyle*/ ICIS_NoInit); 3942 Field->setImplicit(true); 3943 Field->setAccess(AS_private); 3944 Field->setCapturedVLAType(VAT); 3945 CapRecord->addDecl(Field); 3946 3947 CSI->addVLATypeCapture(ExprLoc, SizeType); 3948 } 3949 } 3950 } 3951 T = VAT->getElementType(); 3952 break; 3953 } 3954 case Type::FunctionProto: 3955 case Type::FunctionNoProto: 3956 T = cast<FunctionType>(Ty)->getReturnType(); 3957 break; 3958 case Type::Paren: 3959 case Type::TypeOf: 3960 case Type::UnaryTransform: 3961 case Type::Attributed: 3962 case Type::SubstTemplateTypeParm: 3963 case Type::PackExpansion: 3964 // Keep walking after single level desugaring. 3965 T = T.getSingleStepDesugaredType(Context); 3966 break; 3967 case Type::Typedef: 3968 T = cast<TypedefType>(Ty)->desugar(); 3969 break; 3970 case Type::Decltype: 3971 T = cast<DecltypeType>(Ty)->desugar(); 3972 break; 3973 case Type::Auto: 3974 case Type::DeducedTemplateSpecialization: 3975 T = cast<DeducedType>(Ty)->getDeducedType(); 3976 break; 3977 case Type::TypeOfExpr: 3978 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3979 break; 3980 case Type::Atomic: 3981 T = cast<AtomicType>(Ty)->getValueType(); 3982 break; 3983 } 3984 } while (!T.isNull() && T->isVariablyModifiedType()); 3985 } 3986 3987 /// \brief Build a sizeof or alignof expression given a type operand. 3988 ExprResult 3989 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3990 SourceLocation OpLoc, 3991 UnaryExprOrTypeTrait ExprKind, 3992 SourceRange R) { 3993 if (!TInfo) 3994 return ExprError(); 3995 3996 QualType T = TInfo->getType(); 3997 3998 if (!T->isDependentType() && 3999 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4000 return ExprError(); 4001 4002 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4003 if (auto *TT = T->getAs<TypedefType>()) { 4004 for (auto I = FunctionScopes.rbegin(), 4005 E = std::prev(FunctionScopes.rend()); 4006 I != E; ++I) { 4007 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4008 if (CSI == nullptr) 4009 break; 4010 DeclContext *DC = nullptr; 4011 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4012 DC = LSI->CallOperator; 4013 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4014 DC = CRSI->TheCapturedDecl; 4015 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4016 DC = BSI->TheDecl; 4017 if (DC) { 4018 if (DC->containsDecl(TT->getDecl())) 4019 break; 4020 captureVariablyModifiedType(Context, T, CSI); 4021 } 4022 } 4023 } 4024 } 4025 4026 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4027 return new (Context) UnaryExprOrTypeTraitExpr( 4028 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4029 } 4030 4031 /// \brief Build a sizeof or alignof expression given an expression 4032 /// operand. 4033 ExprResult 4034 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4035 UnaryExprOrTypeTrait ExprKind) { 4036 ExprResult PE = CheckPlaceholderExpr(E); 4037 if (PE.isInvalid()) 4038 return ExprError(); 4039 4040 E = PE.get(); 4041 4042 // Verify that the operand is valid. 4043 bool isInvalid = false; 4044 if (E->isTypeDependent()) { 4045 // Delay type-checking for type-dependent expressions. 4046 } else if (ExprKind == UETT_AlignOf) { 4047 isInvalid = CheckAlignOfExpr(*this, E); 4048 } else if (ExprKind == UETT_VecStep) { 4049 isInvalid = CheckVecStepExpr(E); 4050 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4051 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4052 isInvalid = true; 4053 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4054 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4055 isInvalid = true; 4056 } else { 4057 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4058 } 4059 4060 if (isInvalid) 4061 return ExprError(); 4062 4063 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4064 PE = TransformToPotentiallyEvaluated(E); 4065 if (PE.isInvalid()) return ExprError(); 4066 E = PE.get(); 4067 } 4068 4069 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4070 return new (Context) UnaryExprOrTypeTraitExpr( 4071 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4072 } 4073 4074 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4075 /// expr and the same for @c alignof and @c __alignof 4076 /// Note that the ArgRange is invalid if isType is false. 4077 ExprResult 4078 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4079 UnaryExprOrTypeTrait ExprKind, bool IsType, 4080 void *TyOrEx, SourceRange ArgRange) { 4081 // If error parsing type, ignore. 4082 if (!TyOrEx) return ExprError(); 4083 4084 if (IsType) { 4085 TypeSourceInfo *TInfo; 4086 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4087 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4088 } 4089 4090 Expr *ArgEx = (Expr *)TyOrEx; 4091 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4092 return Result; 4093 } 4094 4095 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4096 bool IsReal) { 4097 if (V.get()->isTypeDependent()) 4098 return S.Context.DependentTy; 4099 4100 // _Real and _Imag are only l-values for normal l-values. 4101 if (V.get()->getObjectKind() != OK_Ordinary) { 4102 V = S.DefaultLvalueConversion(V.get()); 4103 if (V.isInvalid()) 4104 return QualType(); 4105 } 4106 4107 // These operators return the element type of a complex type. 4108 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4109 return CT->getElementType(); 4110 4111 // Otherwise they pass through real integer and floating point types here. 4112 if (V.get()->getType()->isArithmeticType()) 4113 return V.get()->getType(); 4114 4115 // Test for placeholders. 4116 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4117 if (PR.isInvalid()) return QualType(); 4118 if (PR.get() != V.get()) { 4119 V = PR; 4120 return CheckRealImagOperand(S, V, Loc, IsReal); 4121 } 4122 4123 // Reject anything else. 4124 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4125 << (IsReal ? "__real" : "__imag"); 4126 return QualType(); 4127 } 4128 4129 4130 4131 ExprResult 4132 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4133 tok::TokenKind Kind, Expr *Input) { 4134 UnaryOperatorKind Opc; 4135 switch (Kind) { 4136 default: llvm_unreachable("Unknown unary op!"); 4137 case tok::plusplus: Opc = UO_PostInc; break; 4138 case tok::minusminus: Opc = UO_PostDec; break; 4139 } 4140 4141 // Since this might is a postfix expression, get rid of ParenListExprs. 4142 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4143 if (Result.isInvalid()) return ExprError(); 4144 Input = Result.get(); 4145 4146 return BuildUnaryOp(S, OpLoc, Opc, Input); 4147 } 4148 4149 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4150 /// 4151 /// \return true on error 4152 static bool checkArithmeticOnObjCPointer(Sema &S, 4153 SourceLocation opLoc, 4154 Expr *op) { 4155 assert(op->getType()->isObjCObjectPointerType()); 4156 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4157 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4158 return false; 4159 4160 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4161 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4162 << op->getSourceRange(); 4163 return true; 4164 } 4165 4166 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4167 auto *BaseNoParens = Base->IgnoreParens(); 4168 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4169 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4170 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4171 } 4172 4173 ExprResult 4174 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4175 Expr *idx, SourceLocation rbLoc) { 4176 if (base && !base->getType().isNull() && 4177 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4178 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4179 /*Length=*/nullptr, rbLoc); 4180 4181 // Since this might be a postfix expression, get rid of ParenListExprs. 4182 if (isa<ParenListExpr>(base)) { 4183 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4184 if (result.isInvalid()) return ExprError(); 4185 base = result.get(); 4186 } 4187 4188 // Handle any non-overload placeholder types in the base and index 4189 // expressions. We can't handle overloads here because the other 4190 // operand might be an overloadable type, in which case the overload 4191 // resolution for the operator overload should get the first crack 4192 // at the overload. 4193 bool IsMSPropertySubscript = false; 4194 if (base->getType()->isNonOverloadPlaceholderType()) { 4195 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4196 if (!IsMSPropertySubscript) { 4197 ExprResult result = CheckPlaceholderExpr(base); 4198 if (result.isInvalid()) 4199 return ExprError(); 4200 base = result.get(); 4201 } 4202 } 4203 if (idx->getType()->isNonOverloadPlaceholderType()) { 4204 ExprResult result = CheckPlaceholderExpr(idx); 4205 if (result.isInvalid()) return ExprError(); 4206 idx = result.get(); 4207 } 4208 4209 // Build an unanalyzed expression if either operand is type-dependent. 4210 if (getLangOpts().CPlusPlus && 4211 (base->isTypeDependent() || idx->isTypeDependent())) { 4212 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4213 VK_LValue, OK_Ordinary, rbLoc); 4214 } 4215 4216 // MSDN, property (C++) 4217 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4218 // This attribute can also be used in the declaration of an empty array in a 4219 // class or structure definition. For example: 4220 // __declspec(property(get=GetX, put=PutX)) int x[]; 4221 // The above statement indicates that x[] can be used with one or more array 4222 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4223 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4224 if (IsMSPropertySubscript) { 4225 // Build MS property subscript expression if base is MS property reference 4226 // or MS property subscript. 4227 return new (Context) MSPropertySubscriptExpr( 4228 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4229 } 4230 4231 // Use C++ overloaded-operator rules if either operand has record 4232 // type. The spec says to do this if either type is *overloadable*, 4233 // but enum types can't declare subscript operators or conversion 4234 // operators, so there's nothing interesting for overload resolution 4235 // to do if there aren't any record types involved. 4236 // 4237 // ObjC pointers have their own subscripting logic that is not tied 4238 // to overload resolution and so should not take this path. 4239 if (getLangOpts().CPlusPlus && 4240 (base->getType()->isRecordType() || 4241 (!base->getType()->isObjCObjectPointerType() && 4242 idx->getType()->isRecordType()))) { 4243 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4244 } 4245 4246 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4247 } 4248 4249 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4250 Expr *LowerBound, 4251 SourceLocation ColonLoc, Expr *Length, 4252 SourceLocation RBLoc) { 4253 if (Base->getType()->isPlaceholderType() && 4254 !Base->getType()->isSpecificPlaceholderType( 4255 BuiltinType::OMPArraySection)) { 4256 ExprResult Result = CheckPlaceholderExpr(Base); 4257 if (Result.isInvalid()) 4258 return ExprError(); 4259 Base = Result.get(); 4260 } 4261 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4262 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4263 if (Result.isInvalid()) 4264 return ExprError(); 4265 Result = DefaultLvalueConversion(Result.get()); 4266 if (Result.isInvalid()) 4267 return ExprError(); 4268 LowerBound = Result.get(); 4269 } 4270 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4271 ExprResult Result = CheckPlaceholderExpr(Length); 4272 if (Result.isInvalid()) 4273 return ExprError(); 4274 Result = DefaultLvalueConversion(Result.get()); 4275 if (Result.isInvalid()) 4276 return ExprError(); 4277 Length = Result.get(); 4278 } 4279 4280 // Build an unanalyzed expression if either operand is type-dependent. 4281 if (Base->isTypeDependent() || 4282 (LowerBound && 4283 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4284 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4285 return new (Context) 4286 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4287 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4288 } 4289 4290 // Perform default conversions. 4291 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4292 QualType ResultTy; 4293 if (OriginalTy->isAnyPointerType()) { 4294 ResultTy = OriginalTy->getPointeeType(); 4295 } else if (OriginalTy->isArrayType()) { 4296 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4297 } else { 4298 return ExprError( 4299 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4300 << Base->getSourceRange()); 4301 } 4302 // C99 6.5.2.1p1 4303 if (LowerBound) { 4304 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4305 LowerBound); 4306 if (Res.isInvalid()) 4307 return ExprError(Diag(LowerBound->getExprLoc(), 4308 diag::err_omp_typecheck_section_not_integer) 4309 << 0 << LowerBound->getSourceRange()); 4310 LowerBound = Res.get(); 4311 4312 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4313 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4314 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4315 << 0 << LowerBound->getSourceRange(); 4316 } 4317 if (Length) { 4318 auto Res = 4319 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4320 if (Res.isInvalid()) 4321 return ExprError(Diag(Length->getExprLoc(), 4322 diag::err_omp_typecheck_section_not_integer) 4323 << 1 << Length->getSourceRange()); 4324 Length = Res.get(); 4325 4326 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4327 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4328 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4329 << 1 << Length->getSourceRange(); 4330 } 4331 4332 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4333 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4334 // type. Note that functions are not objects, and that (in C99 parlance) 4335 // incomplete types are not object types. 4336 if (ResultTy->isFunctionType()) { 4337 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4338 << ResultTy << Base->getSourceRange(); 4339 return ExprError(); 4340 } 4341 4342 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4343 diag::err_omp_section_incomplete_type, Base)) 4344 return ExprError(); 4345 4346 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4347 llvm::APSInt LowerBoundValue; 4348 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4349 // OpenMP 4.5, [2.4 Array Sections] 4350 // The array section must be a subset of the original array. 4351 if (LowerBoundValue.isNegative()) { 4352 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4353 << LowerBound->getSourceRange(); 4354 return ExprError(); 4355 } 4356 } 4357 } 4358 4359 if (Length) { 4360 llvm::APSInt LengthValue; 4361 if (Length->EvaluateAsInt(LengthValue, Context)) { 4362 // OpenMP 4.5, [2.4 Array Sections] 4363 // The length must evaluate to non-negative integers. 4364 if (LengthValue.isNegative()) { 4365 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4366 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4367 << Length->getSourceRange(); 4368 return ExprError(); 4369 } 4370 } 4371 } else if (ColonLoc.isValid() && 4372 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4373 !OriginalTy->isVariableArrayType()))) { 4374 // OpenMP 4.5, [2.4 Array Sections] 4375 // When the size of the array dimension is not known, the length must be 4376 // specified explicitly. 4377 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4378 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4379 return ExprError(); 4380 } 4381 4382 if (!Base->getType()->isSpecificPlaceholderType( 4383 BuiltinType::OMPArraySection)) { 4384 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4385 if (Result.isInvalid()) 4386 return ExprError(); 4387 Base = Result.get(); 4388 } 4389 return new (Context) 4390 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4391 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4392 } 4393 4394 ExprResult 4395 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4396 Expr *Idx, SourceLocation RLoc) { 4397 Expr *LHSExp = Base; 4398 Expr *RHSExp = Idx; 4399 4400 ExprValueKind VK = VK_LValue; 4401 ExprObjectKind OK = OK_Ordinary; 4402 4403 // Per C++ core issue 1213, the result is an xvalue if either operand is 4404 // a non-lvalue array, and an lvalue otherwise. 4405 if (getLangOpts().CPlusPlus11 && 4406 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4407 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4408 VK = VK_XValue; 4409 4410 // Perform default conversions. 4411 if (!LHSExp->getType()->getAs<VectorType>()) { 4412 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4413 if (Result.isInvalid()) 4414 return ExprError(); 4415 LHSExp = Result.get(); 4416 } 4417 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4418 if (Result.isInvalid()) 4419 return ExprError(); 4420 RHSExp = Result.get(); 4421 4422 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4423 4424 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4425 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4426 // in the subscript position. As a result, we need to derive the array base 4427 // and index from the expression types. 4428 Expr *BaseExpr, *IndexExpr; 4429 QualType ResultType; 4430 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4431 BaseExpr = LHSExp; 4432 IndexExpr = RHSExp; 4433 ResultType = Context.DependentTy; 4434 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4435 BaseExpr = LHSExp; 4436 IndexExpr = RHSExp; 4437 ResultType = PTy->getPointeeType(); 4438 } else if (const ObjCObjectPointerType *PTy = 4439 LHSTy->getAs<ObjCObjectPointerType>()) { 4440 BaseExpr = LHSExp; 4441 IndexExpr = RHSExp; 4442 4443 // Use custom logic if this should be the pseudo-object subscript 4444 // expression. 4445 if (!LangOpts.isSubscriptPointerArithmetic()) 4446 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4447 nullptr); 4448 4449 ResultType = PTy->getPointeeType(); 4450 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4451 // Handle the uncommon case of "123[Ptr]". 4452 BaseExpr = RHSExp; 4453 IndexExpr = LHSExp; 4454 ResultType = PTy->getPointeeType(); 4455 } else if (const ObjCObjectPointerType *PTy = 4456 RHSTy->getAs<ObjCObjectPointerType>()) { 4457 // Handle the uncommon case of "123[Ptr]". 4458 BaseExpr = RHSExp; 4459 IndexExpr = LHSExp; 4460 ResultType = PTy->getPointeeType(); 4461 if (!LangOpts.isSubscriptPointerArithmetic()) { 4462 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4463 << ResultType << BaseExpr->getSourceRange(); 4464 return ExprError(); 4465 } 4466 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4467 BaseExpr = LHSExp; // vectors: V[123] 4468 IndexExpr = RHSExp; 4469 VK = LHSExp->getValueKind(); 4470 if (VK != VK_RValue) 4471 OK = OK_VectorComponent; 4472 4473 // FIXME: need to deal with const... 4474 ResultType = VTy->getElementType(); 4475 } else if (LHSTy->isArrayType()) { 4476 // If we see an array that wasn't promoted by 4477 // DefaultFunctionArrayLvalueConversion, it must be an array that 4478 // wasn't promoted because of the C90 rule that doesn't 4479 // allow promoting non-lvalue arrays. Warn, then 4480 // force the promotion here. 4481 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4482 LHSExp->getSourceRange(); 4483 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4484 CK_ArrayToPointerDecay).get(); 4485 LHSTy = LHSExp->getType(); 4486 4487 BaseExpr = LHSExp; 4488 IndexExpr = RHSExp; 4489 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4490 } else if (RHSTy->isArrayType()) { 4491 // Same as previous, except for 123[f().a] case 4492 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4493 RHSExp->getSourceRange(); 4494 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4495 CK_ArrayToPointerDecay).get(); 4496 RHSTy = RHSExp->getType(); 4497 4498 BaseExpr = RHSExp; 4499 IndexExpr = LHSExp; 4500 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4501 } else { 4502 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4503 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4504 } 4505 // C99 6.5.2.1p1 4506 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4507 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4508 << IndexExpr->getSourceRange()); 4509 4510 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4511 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4512 && !IndexExpr->isTypeDependent()) 4513 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4514 4515 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4516 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4517 // type. Note that Functions are not objects, and that (in C99 parlance) 4518 // incomplete types are not object types. 4519 if (ResultType->isFunctionType()) { 4520 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4521 << ResultType << BaseExpr->getSourceRange(); 4522 return ExprError(); 4523 } 4524 4525 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4526 // GNU extension: subscripting on pointer to void 4527 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4528 << BaseExpr->getSourceRange(); 4529 4530 // C forbids expressions of unqualified void type from being l-values. 4531 // See IsCForbiddenLValueType. 4532 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4533 } else if (!ResultType->isDependentType() && 4534 RequireCompleteType(LLoc, ResultType, 4535 diag::err_subscript_incomplete_type, BaseExpr)) 4536 return ExprError(); 4537 4538 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4539 !ResultType.isCForbiddenLValueType()); 4540 4541 return new (Context) 4542 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4543 } 4544 4545 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4546 ParmVarDecl *Param) { 4547 if (Param->hasUnparsedDefaultArg()) { 4548 Diag(CallLoc, 4549 diag::err_use_of_default_argument_to_function_declared_later) << 4550 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4551 Diag(UnparsedDefaultArgLocs[Param], 4552 diag::note_default_argument_declared_here); 4553 return true; 4554 } 4555 4556 if (Param->hasUninstantiatedDefaultArg()) { 4557 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4558 4559 EnterExpressionEvaluationContext EvalContext( 4560 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4561 4562 // Instantiate the expression. 4563 MultiLevelTemplateArgumentList MutiLevelArgList 4564 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4565 4566 InstantiatingTemplate Inst(*this, CallLoc, Param, 4567 MutiLevelArgList.getInnermost()); 4568 if (Inst.isInvalid()) 4569 return true; 4570 if (Inst.isAlreadyInstantiating()) { 4571 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4572 Param->setInvalidDecl(); 4573 return true; 4574 } 4575 4576 ExprResult Result; 4577 { 4578 // C++ [dcl.fct.default]p5: 4579 // The names in the [default argument] expression are bound, and 4580 // the semantic constraints are checked, at the point where the 4581 // default argument expression appears. 4582 ContextRAII SavedContext(*this, FD); 4583 LocalInstantiationScope Local(*this); 4584 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4585 /*DirectInit*/false); 4586 } 4587 if (Result.isInvalid()) 4588 return true; 4589 4590 // Check the expression as an initializer for the parameter. 4591 InitializedEntity Entity 4592 = InitializedEntity::InitializeParameter(Context, Param); 4593 InitializationKind Kind 4594 = InitializationKind::CreateCopy(Param->getLocation(), 4595 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4596 Expr *ResultE = Result.getAs<Expr>(); 4597 4598 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4599 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4600 if (Result.isInvalid()) 4601 return true; 4602 4603 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4604 Param->getOuterLocStart()); 4605 if (Result.isInvalid()) 4606 return true; 4607 4608 // Remember the instantiated default argument. 4609 Param->setDefaultArg(Result.getAs<Expr>()); 4610 if (ASTMutationListener *L = getASTMutationListener()) { 4611 L->DefaultArgumentInstantiated(Param); 4612 } 4613 } 4614 4615 // If the default argument expression is not set yet, we are building it now. 4616 if (!Param->hasInit()) { 4617 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4618 Param->setInvalidDecl(); 4619 return true; 4620 } 4621 4622 // If the default expression creates temporaries, we need to 4623 // push them to the current stack of expression temporaries so they'll 4624 // be properly destroyed. 4625 // FIXME: We should really be rebuilding the default argument with new 4626 // bound temporaries; see the comment in PR5810. 4627 // We don't need to do that with block decls, though, because 4628 // blocks in default argument expression can never capture anything. 4629 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4630 // Set the "needs cleanups" bit regardless of whether there are 4631 // any explicit objects. 4632 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4633 4634 // Append all the objects to the cleanup list. Right now, this 4635 // should always be a no-op, because blocks in default argument 4636 // expressions should never be able to capture anything. 4637 assert(!Init->getNumObjects() && 4638 "default argument expression has capturing blocks?"); 4639 } 4640 4641 // We already type-checked the argument, so we know it works. 4642 // Just mark all of the declarations in this potentially-evaluated expression 4643 // as being "referenced". 4644 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4645 /*SkipLocalVariables=*/true); 4646 return false; 4647 } 4648 4649 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4650 FunctionDecl *FD, ParmVarDecl *Param) { 4651 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4652 return ExprError(); 4653 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4654 } 4655 4656 Sema::VariadicCallType 4657 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4658 Expr *Fn) { 4659 if (Proto && Proto->isVariadic()) { 4660 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4661 return VariadicConstructor; 4662 else if (Fn && Fn->getType()->isBlockPointerType()) 4663 return VariadicBlock; 4664 else if (FDecl) { 4665 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4666 if (Method->isInstance()) 4667 return VariadicMethod; 4668 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4669 return VariadicMethod; 4670 return VariadicFunction; 4671 } 4672 return VariadicDoesNotApply; 4673 } 4674 4675 namespace { 4676 class FunctionCallCCC : public FunctionCallFilterCCC { 4677 public: 4678 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4679 unsigned NumArgs, MemberExpr *ME) 4680 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4681 FunctionName(FuncName) {} 4682 4683 bool ValidateCandidate(const TypoCorrection &candidate) override { 4684 if (!candidate.getCorrectionSpecifier() || 4685 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4686 return false; 4687 } 4688 4689 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4690 } 4691 4692 private: 4693 const IdentifierInfo *const FunctionName; 4694 }; 4695 } 4696 4697 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4698 FunctionDecl *FDecl, 4699 ArrayRef<Expr *> Args) { 4700 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4701 DeclarationName FuncName = FDecl->getDeclName(); 4702 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4703 4704 if (TypoCorrection Corrected = S.CorrectTypo( 4705 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4706 S.getScopeForContext(S.CurContext), nullptr, 4707 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4708 Args.size(), ME), 4709 Sema::CTK_ErrorRecovery)) { 4710 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4711 if (Corrected.isOverloaded()) { 4712 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4713 OverloadCandidateSet::iterator Best; 4714 for (NamedDecl *CD : Corrected) { 4715 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4716 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4717 OCS); 4718 } 4719 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4720 case OR_Success: 4721 ND = Best->FoundDecl; 4722 Corrected.setCorrectionDecl(ND); 4723 break; 4724 default: 4725 break; 4726 } 4727 } 4728 ND = ND->getUnderlyingDecl(); 4729 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4730 return Corrected; 4731 } 4732 } 4733 return TypoCorrection(); 4734 } 4735 4736 /// ConvertArgumentsForCall - Converts the arguments specified in 4737 /// Args/NumArgs to the parameter types of the function FDecl with 4738 /// function prototype Proto. Call is the call expression itself, and 4739 /// Fn is the function expression. For a C++ member function, this 4740 /// routine does not attempt to convert the object argument. Returns 4741 /// true if the call is ill-formed. 4742 bool 4743 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4744 FunctionDecl *FDecl, 4745 const FunctionProtoType *Proto, 4746 ArrayRef<Expr *> Args, 4747 SourceLocation RParenLoc, 4748 bool IsExecConfig) { 4749 // Bail out early if calling a builtin with custom typechecking. 4750 if (FDecl) 4751 if (unsigned ID = FDecl->getBuiltinID()) 4752 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4753 return false; 4754 4755 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4756 // assignment, to the types of the corresponding parameter, ... 4757 unsigned NumParams = Proto->getNumParams(); 4758 bool Invalid = false; 4759 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4760 unsigned FnKind = Fn->getType()->isBlockPointerType() 4761 ? 1 /* block */ 4762 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4763 : 0 /* function */); 4764 4765 // If too few arguments are available (and we don't have default 4766 // arguments for the remaining parameters), don't make the call. 4767 if (Args.size() < NumParams) { 4768 if (Args.size() < MinArgs) { 4769 TypoCorrection TC; 4770 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4771 unsigned diag_id = 4772 MinArgs == NumParams && !Proto->isVariadic() 4773 ? diag::err_typecheck_call_too_few_args_suggest 4774 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4775 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4776 << static_cast<unsigned>(Args.size()) 4777 << TC.getCorrectionRange()); 4778 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4779 Diag(RParenLoc, 4780 MinArgs == NumParams && !Proto->isVariadic() 4781 ? diag::err_typecheck_call_too_few_args_one 4782 : diag::err_typecheck_call_too_few_args_at_least_one) 4783 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4784 else 4785 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4786 ? diag::err_typecheck_call_too_few_args 4787 : diag::err_typecheck_call_too_few_args_at_least) 4788 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4789 << Fn->getSourceRange(); 4790 4791 // Emit the location of the prototype. 4792 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4793 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4794 << FDecl; 4795 4796 return true; 4797 } 4798 Call->setNumArgs(Context, NumParams); 4799 } 4800 4801 // If too many are passed and not variadic, error on the extras and drop 4802 // them. 4803 if (Args.size() > NumParams) { 4804 if (!Proto->isVariadic()) { 4805 TypoCorrection TC; 4806 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4807 unsigned diag_id = 4808 MinArgs == NumParams && !Proto->isVariadic() 4809 ? diag::err_typecheck_call_too_many_args_suggest 4810 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4811 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4812 << static_cast<unsigned>(Args.size()) 4813 << TC.getCorrectionRange()); 4814 } else if (NumParams == 1 && FDecl && 4815 FDecl->getParamDecl(0)->getDeclName()) 4816 Diag(Args[NumParams]->getLocStart(), 4817 MinArgs == NumParams 4818 ? diag::err_typecheck_call_too_many_args_one 4819 : diag::err_typecheck_call_too_many_args_at_most_one) 4820 << FnKind << FDecl->getParamDecl(0) 4821 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4822 << SourceRange(Args[NumParams]->getLocStart(), 4823 Args.back()->getLocEnd()); 4824 else 4825 Diag(Args[NumParams]->getLocStart(), 4826 MinArgs == NumParams 4827 ? diag::err_typecheck_call_too_many_args 4828 : diag::err_typecheck_call_too_many_args_at_most) 4829 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4830 << Fn->getSourceRange() 4831 << SourceRange(Args[NumParams]->getLocStart(), 4832 Args.back()->getLocEnd()); 4833 4834 // Emit the location of the prototype. 4835 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4836 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4837 << FDecl; 4838 4839 // This deletes the extra arguments. 4840 Call->setNumArgs(Context, NumParams); 4841 return true; 4842 } 4843 } 4844 SmallVector<Expr *, 8> AllArgs; 4845 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4846 4847 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4848 Proto, 0, Args, AllArgs, CallType); 4849 if (Invalid) 4850 return true; 4851 unsigned TotalNumArgs = AllArgs.size(); 4852 for (unsigned i = 0; i < TotalNumArgs; ++i) 4853 Call->setArg(i, AllArgs[i]); 4854 4855 return false; 4856 } 4857 4858 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4859 const FunctionProtoType *Proto, 4860 unsigned FirstParam, ArrayRef<Expr *> Args, 4861 SmallVectorImpl<Expr *> &AllArgs, 4862 VariadicCallType CallType, bool AllowExplicit, 4863 bool IsListInitialization) { 4864 unsigned NumParams = Proto->getNumParams(); 4865 bool Invalid = false; 4866 size_t ArgIx = 0; 4867 // Continue to check argument types (even if we have too few/many args). 4868 for (unsigned i = FirstParam; i < NumParams; i++) { 4869 QualType ProtoArgType = Proto->getParamType(i); 4870 4871 Expr *Arg; 4872 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4873 if (ArgIx < Args.size()) { 4874 Arg = Args[ArgIx++]; 4875 4876 if (RequireCompleteType(Arg->getLocStart(), 4877 ProtoArgType, 4878 diag::err_call_incomplete_argument, Arg)) 4879 return true; 4880 4881 // Strip the unbridged-cast placeholder expression off, if applicable. 4882 bool CFAudited = false; 4883 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4884 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4885 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4886 Arg = stripARCUnbridgedCast(Arg); 4887 else if (getLangOpts().ObjCAutoRefCount && 4888 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4889 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4890 CFAudited = true; 4891 4892 InitializedEntity Entity = 4893 Param ? InitializedEntity::InitializeParameter(Context, Param, 4894 ProtoArgType) 4895 : InitializedEntity::InitializeParameter( 4896 Context, ProtoArgType, Proto->isParamConsumed(i)); 4897 4898 // Remember that parameter belongs to a CF audited API. 4899 if (CFAudited) 4900 Entity.setParameterCFAudited(); 4901 4902 ExprResult ArgE = PerformCopyInitialization( 4903 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4904 if (ArgE.isInvalid()) 4905 return true; 4906 4907 Arg = ArgE.getAs<Expr>(); 4908 } else { 4909 assert(Param && "can't use default arguments without a known callee"); 4910 4911 ExprResult ArgExpr = 4912 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4913 if (ArgExpr.isInvalid()) 4914 return true; 4915 4916 Arg = ArgExpr.getAs<Expr>(); 4917 } 4918 4919 // Check for array bounds violations for each argument to the call. This 4920 // check only triggers warnings when the argument isn't a more complex Expr 4921 // with its own checking, such as a BinaryOperator. 4922 CheckArrayAccess(Arg); 4923 4924 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4925 CheckStaticArrayArgument(CallLoc, Param, Arg); 4926 4927 AllArgs.push_back(Arg); 4928 } 4929 4930 // If this is a variadic call, handle args passed through "...". 4931 if (CallType != VariadicDoesNotApply) { 4932 // Assume that extern "C" functions with variadic arguments that 4933 // return __unknown_anytype aren't *really* variadic. 4934 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4935 FDecl->isExternC()) { 4936 for (Expr *A : Args.slice(ArgIx)) { 4937 QualType paramType; // ignored 4938 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4939 Invalid |= arg.isInvalid(); 4940 AllArgs.push_back(arg.get()); 4941 } 4942 4943 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4944 } else { 4945 for (Expr *A : Args.slice(ArgIx)) { 4946 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4947 Invalid |= Arg.isInvalid(); 4948 AllArgs.push_back(Arg.get()); 4949 } 4950 } 4951 4952 // Check for array bounds violations. 4953 for (Expr *A : Args.slice(ArgIx)) 4954 CheckArrayAccess(A); 4955 } 4956 return Invalid; 4957 } 4958 4959 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4960 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4961 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4962 TL = DTL.getOriginalLoc(); 4963 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4964 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4965 << ATL.getLocalSourceRange(); 4966 } 4967 4968 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4969 /// array parameter, check that it is non-null, and that if it is formed by 4970 /// array-to-pointer decay, the underlying array is sufficiently large. 4971 /// 4972 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4973 /// array type derivation, then for each call to the function, the value of the 4974 /// corresponding actual argument shall provide access to the first element of 4975 /// an array with at least as many elements as specified by the size expression. 4976 void 4977 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4978 ParmVarDecl *Param, 4979 const Expr *ArgExpr) { 4980 // Static array parameters are not supported in C++. 4981 if (!Param || getLangOpts().CPlusPlus) 4982 return; 4983 4984 QualType OrigTy = Param->getOriginalType(); 4985 4986 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4987 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4988 return; 4989 4990 if (ArgExpr->isNullPointerConstant(Context, 4991 Expr::NPC_NeverValueDependent)) { 4992 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4993 DiagnoseCalleeStaticArrayParam(*this, Param); 4994 return; 4995 } 4996 4997 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4998 if (!CAT) 4999 return; 5000 5001 const ConstantArrayType *ArgCAT = 5002 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5003 if (!ArgCAT) 5004 return; 5005 5006 if (ArgCAT->getSize().ult(CAT->getSize())) { 5007 Diag(CallLoc, diag::warn_static_array_too_small) 5008 << ArgExpr->getSourceRange() 5009 << (unsigned) ArgCAT->getSize().getZExtValue() 5010 << (unsigned) CAT->getSize().getZExtValue(); 5011 DiagnoseCalleeStaticArrayParam(*this, Param); 5012 } 5013 } 5014 5015 /// Given a function expression of unknown-any type, try to rebuild it 5016 /// to have a function type. 5017 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5018 5019 /// Is the given type a placeholder that we need to lower out 5020 /// immediately during argument processing? 5021 static bool isPlaceholderToRemoveAsArg(QualType type) { 5022 // Placeholders are never sugared. 5023 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5024 if (!placeholder) return false; 5025 5026 switch (placeholder->getKind()) { 5027 // Ignore all the non-placeholder types. 5028 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5029 case BuiltinType::Id: 5030 #include "clang/Basic/OpenCLImageTypes.def" 5031 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5032 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5033 #include "clang/AST/BuiltinTypes.def" 5034 return false; 5035 5036 // We cannot lower out overload sets; they might validly be resolved 5037 // by the call machinery. 5038 case BuiltinType::Overload: 5039 return false; 5040 5041 // Unbridged casts in ARC can be handled in some call positions and 5042 // should be left in place. 5043 case BuiltinType::ARCUnbridgedCast: 5044 return false; 5045 5046 // Pseudo-objects should be converted as soon as possible. 5047 case BuiltinType::PseudoObject: 5048 return true; 5049 5050 // The debugger mode could theoretically but currently does not try 5051 // to resolve unknown-typed arguments based on known parameter types. 5052 case BuiltinType::UnknownAny: 5053 return true; 5054 5055 // These are always invalid as call arguments and should be reported. 5056 case BuiltinType::BoundMember: 5057 case BuiltinType::BuiltinFn: 5058 case BuiltinType::OMPArraySection: 5059 return true; 5060 5061 } 5062 llvm_unreachable("bad builtin type kind"); 5063 } 5064 5065 /// Check an argument list for placeholders that we won't try to 5066 /// handle later. 5067 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5068 // Apply this processing to all the arguments at once instead of 5069 // dying at the first failure. 5070 bool hasInvalid = false; 5071 for (size_t i = 0, e = args.size(); i != e; i++) { 5072 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5073 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5074 if (result.isInvalid()) hasInvalid = true; 5075 else args[i] = result.get(); 5076 } else if (hasInvalid) { 5077 (void)S.CorrectDelayedTyposInExpr(args[i]); 5078 } 5079 } 5080 return hasInvalid; 5081 } 5082 5083 /// If a builtin function has a pointer argument with no explicit address 5084 /// space, then it should be able to accept a pointer to any address 5085 /// space as input. In order to do this, we need to replace the 5086 /// standard builtin declaration with one that uses the same address space 5087 /// as the call. 5088 /// 5089 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5090 /// it does not contain any pointer arguments without 5091 /// an address space qualifer. Otherwise the rewritten 5092 /// FunctionDecl is returned. 5093 /// TODO: Handle pointer return types. 5094 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5095 const FunctionDecl *FDecl, 5096 MultiExprArg ArgExprs) { 5097 5098 QualType DeclType = FDecl->getType(); 5099 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5100 5101 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5102 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5103 return nullptr; 5104 5105 bool NeedsNewDecl = false; 5106 unsigned i = 0; 5107 SmallVector<QualType, 8> OverloadParams; 5108 5109 for (QualType ParamType : FT->param_types()) { 5110 5111 // Convert array arguments to pointer to simplify type lookup. 5112 ExprResult ArgRes = 5113 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5114 if (ArgRes.isInvalid()) 5115 return nullptr; 5116 Expr *Arg = ArgRes.get(); 5117 QualType ArgType = Arg->getType(); 5118 if (!ParamType->isPointerType() || 5119 ParamType.getQualifiers().hasAddressSpace() || 5120 !ArgType->isPointerType() || 5121 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5122 OverloadParams.push_back(ParamType); 5123 continue; 5124 } 5125 5126 NeedsNewDecl = true; 5127 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5128 5129 QualType PointeeType = ParamType->getPointeeType(); 5130 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5131 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5132 } 5133 5134 if (!NeedsNewDecl) 5135 return nullptr; 5136 5137 FunctionProtoType::ExtProtoInfo EPI; 5138 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5139 OverloadParams, EPI); 5140 DeclContext *Parent = Context.getTranslationUnitDecl(); 5141 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5142 FDecl->getLocation(), 5143 FDecl->getLocation(), 5144 FDecl->getIdentifier(), 5145 OverloadTy, 5146 /*TInfo=*/nullptr, 5147 SC_Extern, false, 5148 /*hasPrototype=*/true); 5149 SmallVector<ParmVarDecl*, 16> Params; 5150 FT = cast<FunctionProtoType>(OverloadTy); 5151 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5152 QualType ParamType = FT->getParamType(i); 5153 ParmVarDecl *Parm = 5154 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5155 SourceLocation(), nullptr, ParamType, 5156 /*TInfo=*/nullptr, SC_None, nullptr); 5157 Parm->setScopeInfo(0, i); 5158 Params.push_back(Parm); 5159 } 5160 OverloadDecl->setParams(Params); 5161 return OverloadDecl; 5162 } 5163 5164 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5165 FunctionDecl *Callee, 5166 MultiExprArg ArgExprs) { 5167 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5168 // similar attributes) really don't like it when functions are called with an 5169 // invalid number of args. 5170 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5171 /*PartialOverloading=*/false) && 5172 !Callee->isVariadic()) 5173 return; 5174 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5175 return; 5176 5177 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5178 S.Diag(Fn->getLocStart(), 5179 isa<CXXMethodDecl>(Callee) 5180 ? diag::err_ovl_no_viable_member_function_in_call 5181 : diag::err_ovl_no_viable_function_in_call) 5182 << Callee << Callee->getSourceRange(); 5183 S.Diag(Callee->getLocation(), 5184 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5185 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5186 return; 5187 } 5188 } 5189 5190 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5191 /// This provides the location of the left/right parens and a list of comma 5192 /// locations. 5193 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5194 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5195 Expr *ExecConfig, bool IsExecConfig) { 5196 // Since this might be a postfix expression, get rid of ParenListExprs. 5197 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5198 if (Result.isInvalid()) return ExprError(); 5199 Fn = Result.get(); 5200 5201 if (checkArgsForPlaceholders(*this, ArgExprs)) 5202 return ExprError(); 5203 5204 if (getLangOpts().CPlusPlus) { 5205 // If this is a pseudo-destructor expression, build the call immediately. 5206 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5207 if (!ArgExprs.empty()) { 5208 // Pseudo-destructor calls should not have any arguments. 5209 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5210 << FixItHint::CreateRemoval( 5211 SourceRange(ArgExprs.front()->getLocStart(), 5212 ArgExprs.back()->getLocEnd())); 5213 } 5214 5215 return new (Context) 5216 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5217 } 5218 if (Fn->getType() == Context.PseudoObjectTy) { 5219 ExprResult result = CheckPlaceholderExpr(Fn); 5220 if (result.isInvalid()) return ExprError(); 5221 Fn = result.get(); 5222 } 5223 5224 // Determine whether this is a dependent call inside a C++ template, 5225 // in which case we won't do any semantic analysis now. 5226 bool Dependent = false; 5227 if (Fn->isTypeDependent()) 5228 Dependent = true; 5229 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5230 Dependent = true; 5231 5232 if (Dependent) { 5233 if (ExecConfig) { 5234 return new (Context) CUDAKernelCallExpr( 5235 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5236 Context.DependentTy, VK_RValue, RParenLoc); 5237 } else { 5238 return new (Context) CallExpr( 5239 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5240 } 5241 } 5242 5243 // Determine whether this is a call to an object (C++ [over.call.object]). 5244 if (Fn->getType()->isRecordType()) 5245 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5246 RParenLoc); 5247 5248 if (Fn->getType() == Context.UnknownAnyTy) { 5249 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5250 if (result.isInvalid()) return ExprError(); 5251 Fn = result.get(); 5252 } 5253 5254 if (Fn->getType() == Context.BoundMemberTy) { 5255 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5256 RParenLoc); 5257 } 5258 } 5259 5260 // Check for overloaded calls. This can happen even in C due to extensions. 5261 if (Fn->getType() == Context.OverloadTy) { 5262 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5263 5264 // We aren't supposed to apply this logic for if there'Scope an '&' 5265 // involved. 5266 if (!find.HasFormOfMemberPointer) { 5267 OverloadExpr *ovl = find.Expression; 5268 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5269 return BuildOverloadedCallExpr( 5270 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5271 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5272 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5273 RParenLoc); 5274 } 5275 } 5276 5277 // If we're directly calling a function, get the appropriate declaration. 5278 if (Fn->getType() == Context.UnknownAnyTy) { 5279 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5280 if (result.isInvalid()) return ExprError(); 5281 Fn = result.get(); 5282 } 5283 5284 Expr *NakedFn = Fn->IgnoreParens(); 5285 5286 bool CallingNDeclIndirectly = false; 5287 NamedDecl *NDecl = nullptr; 5288 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5289 if (UnOp->getOpcode() == UO_AddrOf) { 5290 CallingNDeclIndirectly = true; 5291 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5292 } 5293 } 5294 5295 if (isa<DeclRefExpr>(NakedFn)) { 5296 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5297 5298 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5299 if (FDecl && FDecl->getBuiltinID()) { 5300 // Rewrite the function decl for this builtin by replacing parameters 5301 // with no explicit address space with the address space of the arguments 5302 // in ArgExprs. 5303 if ((FDecl = 5304 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5305 NDecl = FDecl; 5306 Fn = DeclRefExpr::Create( 5307 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5308 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5309 } 5310 } 5311 } else if (isa<MemberExpr>(NakedFn)) 5312 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5313 5314 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5315 if (CallingNDeclIndirectly && 5316 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5317 Fn->getLocStart())) 5318 return ExprError(); 5319 5320 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5321 return ExprError(); 5322 5323 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5324 } 5325 5326 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5327 ExecConfig, IsExecConfig); 5328 } 5329 5330 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5331 /// 5332 /// __builtin_astype( value, dst type ) 5333 /// 5334 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5335 SourceLocation BuiltinLoc, 5336 SourceLocation RParenLoc) { 5337 ExprValueKind VK = VK_RValue; 5338 ExprObjectKind OK = OK_Ordinary; 5339 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5340 QualType SrcTy = E->getType(); 5341 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5342 return ExprError(Diag(BuiltinLoc, 5343 diag::err_invalid_astype_of_different_size) 5344 << DstTy 5345 << SrcTy 5346 << E->getSourceRange()); 5347 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5348 } 5349 5350 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5351 /// provided arguments. 5352 /// 5353 /// __builtin_convertvector( value, dst type ) 5354 /// 5355 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5356 SourceLocation BuiltinLoc, 5357 SourceLocation RParenLoc) { 5358 TypeSourceInfo *TInfo; 5359 GetTypeFromParser(ParsedDestTy, &TInfo); 5360 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5361 } 5362 5363 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5364 /// i.e. an expression not of \p OverloadTy. The expression should 5365 /// unary-convert to an expression of function-pointer or 5366 /// block-pointer type. 5367 /// 5368 /// \param NDecl the declaration being called, if available 5369 ExprResult 5370 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5371 SourceLocation LParenLoc, 5372 ArrayRef<Expr *> Args, 5373 SourceLocation RParenLoc, 5374 Expr *Config, bool IsExecConfig) { 5375 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5376 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5377 5378 // Functions with 'interrupt' attribute cannot be called directly. 5379 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5380 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5381 return ExprError(); 5382 } 5383 5384 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5385 // so there's some risk when calling out to non-interrupt handler functions 5386 // that the callee might not preserve them. This is easy to diagnose here, 5387 // but can be very challenging to debug. 5388 if (auto *Caller = getCurFunctionDecl()) 5389 if (Caller->hasAttr<ARMInterruptAttr>()) 5390 if (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()) 5391 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5392 5393 // Promote the function operand. 5394 // We special-case function promotion here because we only allow promoting 5395 // builtin functions to function pointers in the callee of a call. 5396 ExprResult Result; 5397 if (BuiltinID && 5398 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5399 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5400 CK_BuiltinFnToFnPtr).get(); 5401 } else { 5402 Result = CallExprUnaryConversions(Fn); 5403 } 5404 if (Result.isInvalid()) 5405 return ExprError(); 5406 Fn = Result.get(); 5407 5408 // Make the call expr early, before semantic checks. This guarantees cleanup 5409 // of arguments and function on error. 5410 CallExpr *TheCall; 5411 if (Config) 5412 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5413 cast<CallExpr>(Config), Args, 5414 Context.BoolTy, VK_RValue, 5415 RParenLoc); 5416 else 5417 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5418 VK_RValue, RParenLoc); 5419 5420 if (!getLangOpts().CPlusPlus) { 5421 // C cannot always handle TypoExpr nodes in builtin calls and direct 5422 // function calls as their argument checking don't necessarily handle 5423 // dependent types properly, so make sure any TypoExprs have been 5424 // dealt with. 5425 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5426 if (!Result.isUsable()) return ExprError(); 5427 TheCall = dyn_cast<CallExpr>(Result.get()); 5428 if (!TheCall) return Result; 5429 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5430 } 5431 5432 // Bail out early if calling a builtin with custom typechecking. 5433 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5434 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5435 5436 retry: 5437 const FunctionType *FuncT; 5438 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5439 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5440 // have type pointer to function". 5441 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5442 if (!FuncT) 5443 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5444 << Fn->getType() << Fn->getSourceRange()); 5445 } else if (const BlockPointerType *BPT = 5446 Fn->getType()->getAs<BlockPointerType>()) { 5447 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5448 } else { 5449 // Handle calls to expressions of unknown-any type. 5450 if (Fn->getType() == Context.UnknownAnyTy) { 5451 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5452 if (rewrite.isInvalid()) return ExprError(); 5453 Fn = rewrite.get(); 5454 TheCall->setCallee(Fn); 5455 goto retry; 5456 } 5457 5458 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5459 << Fn->getType() << Fn->getSourceRange()); 5460 } 5461 5462 if (getLangOpts().CUDA) { 5463 if (Config) { 5464 // CUDA: Kernel calls must be to global functions 5465 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5466 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5467 << FDecl->getName() << Fn->getSourceRange()); 5468 5469 // CUDA: Kernel function must have 'void' return type 5470 if (!FuncT->getReturnType()->isVoidType()) 5471 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5472 << Fn->getType() << Fn->getSourceRange()); 5473 } else { 5474 // CUDA: Calls to global functions must be configured 5475 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5476 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5477 << FDecl->getName() << Fn->getSourceRange()); 5478 } 5479 } 5480 5481 // Check for a valid return type 5482 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5483 FDecl)) 5484 return ExprError(); 5485 5486 // We know the result type of the call, set it. 5487 TheCall->setType(FuncT->getCallResultType(Context)); 5488 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5489 5490 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5491 if (Proto) { 5492 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5493 IsExecConfig)) 5494 return ExprError(); 5495 } else { 5496 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5497 5498 if (FDecl) { 5499 // Check if we have too few/too many template arguments, based 5500 // on our knowledge of the function definition. 5501 const FunctionDecl *Def = nullptr; 5502 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5503 Proto = Def->getType()->getAs<FunctionProtoType>(); 5504 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5505 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5506 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5507 } 5508 5509 // If the function we're calling isn't a function prototype, but we have 5510 // a function prototype from a prior declaratiom, use that prototype. 5511 if (!FDecl->hasPrototype()) 5512 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5513 } 5514 5515 // Promote the arguments (C99 6.5.2.2p6). 5516 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5517 Expr *Arg = Args[i]; 5518 5519 if (Proto && i < Proto->getNumParams()) { 5520 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5521 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5522 ExprResult ArgE = 5523 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5524 if (ArgE.isInvalid()) 5525 return true; 5526 5527 Arg = ArgE.getAs<Expr>(); 5528 5529 } else { 5530 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5531 5532 if (ArgE.isInvalid()) 5533 return true; 5534 5535 Arg = ArgE.getAs<Expr>(); 5536 } 5537 5538 if (RequireCompleteType(Arg->getLocStart(), 5539 Arg->getType(), 5540 diag::err_call_incomplete_argument, Arg)) 5541 return ExprError(); 5542 5543 TheCall->setArg(i, Arg); 5544 } 5545 } 5546 5547 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5548 if (!Method->isStatic()) 5549 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5550 << Fn->getSourceRange()); 5551 5552 // Check for sentinels 5553 if (NDecl) 5554 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5555 5556 // Do special checking on direct calls to functions. 5557 if (FDecl) { 5558 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5559 return ExprError(); 5560 5561 if (BuiltinID) 5562 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5563 } else if (NDecl) { 5564 if (CheckPointerCall(NDecl, TheCall, Proto)) 5565 return ExprError(); 5566 } else { 5567 if (CheckOtherCall(TheCall, Proto)) 5568 return ExprError(); 5569 } 5570 5571 return MaybeBindToTemporary(TheCall); 5572 } 5573 5574 ExprResult 5575 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5576 SourceLocation RParenLoc, Expr *InitExpr) { 5577 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5578 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5579 5580 TypeSourceInfo *TInfo; 5581 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5582 if (!TInfo) 5583 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5584 5585 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5586 } 5587 5588 ExprResult 5589 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5590 SourceLocation RParenLoc, Expr *LiteralExpr) { 5591 QualType literalType = TInfo->getType(); 5592 5593 if (literalType->isArrayType()) { 5594 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5595 diag::err_illegal_decl_array_incomplete_type, 5596 SourceRange(LParenLoc, 5597 LiteralExpr->getSourceRange().getEnd()))) 5598 return ExprError(); 5599 if (literalType->isVariableArrayType()) 5600 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5601 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5602 } else if (!literalType->isDependentType() && 5603 RequireCompleteType(LParenLoc, literalType, 5604 diag::err_typecheck_decl_incomplete_type, 5605 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5606 return ExprError(); 5607 5608 InitializedEntity Entity 5609 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5610 InitializationKind Kind 5611 = InitializationKind::CreateCStyleCast(LParenLoc, 5612 SourceRange(LParenLoc, RParenLoc), 5613 /*InitList=*/true); 5614 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5615 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5616 &literalType); 5617 if (Result.isInvalid()) 5618 return ExprError(); 5619 LiteralExpr = Result.get(); 5620 5621 bool isFileScope = !CurContext->isFunctionOrMethod(); 5622 if (isFileScope && 5623 !LiteralExpr->isTypeDependent() && 5624 !LiteralExpr->isValueDependent() && 5625 !literalType->isDependentType()) { // 6.5.2.5p3 5626 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5627 return ExprError(); 5628 } 5629 5630 // In C, compound literals are l-values for some reason. 5631 // For GCC compatibility, in C++, file-scope array compound literals with 5632 // constant initializers are also l-values, and compound literals are 5633 // otherwise prvalues. 5634 // 5635 // (GCC also treats C++ list-initialized file-scope array prvalues with 5636 // constant initializers as l-values, but that's non-conforming, so we don't 5637 // follow it there.) 5638 // 5639 // FIXME: It would be better to handle the lvalue cases as materializing and 5640 // lifetime-extending a temporary object, but our materialized temporaries 5641 // representation only supports lifetime extension from a variable, not "out 5642 // of thin air". 5643 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5644 // is bound to the result of applying array-to-pointer decay to the compound 5645 // literal. 5646 // FIXME: GCC supports compound literals of reference type, which should 5647 // obviously have a value kind derived from the kind of reference involved. 5648 ExprValueKind VK = 5649 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5650 ? VK_RValue 5651 : VK_LValue; 5652 5653 return MaybeBindToTemporary( 5654 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5655 VK, LiteralExpr, isFileScope)); 5656 } 5657 5658 ExprResult 5659 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5660 SourceLocation RBraceLoc) { 5661 // Immediately handle non-overload placeholders. Overloads can be 5662 // resolved contextually, but everything else here can't. 5663 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5664 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5665 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5666 5667 // Ignore failures; dropping the entire initializer list because 5668 // of one failure would be terrible for indexing/etc. 5669 if (result.isInvalid()) continue; 5670 5671 InitArgList[I] = result.get(); 5672 } 5673 } 5674 5675 // Semantic analysis for initializers is done by ActOnDeclarator() and 5676 // CheckInitializer() - it requires knowledge of the object being intialized. 5677 5678 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5679 RBraceLoc); 5680 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5681 return E; 5682 } 5683 5684 /// Do an explicit extend of the given block pointer if we're in ARC. 5685 void Sema::maybeExtendBlockObject(ExprResult &E) { 5686 assert(E.get()->getType()->isBlockPointerType()); 5687 assert(E.get()->isRValue()); 5688 5689 // Only do this in an r-value context. 5690 if (!getLangOpts().ObjCAutoRefCount) return; 5691 5692 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5693 CK_ARCExtendBlockObject, E.get(), 5694 /*base path*/ nullptr, VK_RValue); 5695 Cleanup.setExprNeedsCleanups(true); 5696 } 5697 5698 /// Prepare a conversion of the given expression to an ObjC object 5699 /// pointer type. 5700 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5701 QualType type = E.get()->getType(); 5702 if (type->isObjCObjectPointerType()) { 5703 return CK_BitCast; 5704 } else if (type->isBlockPointerType()) { 5705 maybeExtendBlockObject(E); 5706 return CK_BlockPointerToObjCPointerCast; 5707 } else { 5708 assert(type->isPointerType()); 5709 return CK_CPointerToObjCPointerCast; 5710 } 5711 } 5712 5713 /// Prepares for a scalar cast, performing all the necessary stages 5714 /// except the final cast and returning the kind required. 5715 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5716 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5717 // Also, callers should have filtered out the invalid cases with 5718 // pointers. Everything else should be possible. 5719 5720 QualType SrcTy = Src.get()->getType(); 5721 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5722 return CK_NoOp; 5723 5724 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5725 case Type::STK_MemberPointer: 5726 llvm_unreachable("member pointer type in C"); 5727 5728 case Type::STK_CPointer: 5729 case Type::STK_BlockPointer: 5730 case Type::STK_ObjCObjectPointer: 5731 switch (DestTy->getScalarTypeKind()) { 5732 case Type::STK_CPointer: { 5733 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5734 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5735 if (SrcAS != DestAS) 5736 return CK_AddressSpaceConversion; 5737 return CK_BitCast; 5738 } 5739 case Type::STK_BlockPointer: 5740 return (SrcKind == Type::STK_BlockPointer 5741 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5742 case Type::STK_ObjCObjectPointer: 5743 if (SrcKind == Type::STK_ObjCObjectPointer) 5744 return CK_BitCast; 5745 if (SrcKind == Type::STK_CPointer) 5746 return CK_CPointerToObjCPointerCast; 5747 maybeExtendBlockObject(Src); 5748 return CK_BlockPointerToObjCPointerCast; 5749 case Type::STK_Bool: 5750 return CK_PointerToBoolean; 5751 case Type::STK_Integral: 5752 return CK_PointerToIntegral; 5753 case Type::STK_Floating: 5754 case Type::STK_FloatingComplex: 5755 case Type::STK_IntegralComplex: 5756 case Type::STK_MemberPointer: 5757 llvm_unreachable("illegal cast from pointer"); 5758 } 5759 llvm_unreachable("Should have returned before this"); 5760 5761 case Type::STK_Bool: // casting from bool is like casting from an integer 5762 case Type::STK_Integral: 5763 switch (DestTy->getScalarTypeKind()) { 5764 case Type::STK_CPointer: 5765 case Type::STK_ObjCObjectPointer: 5766 case Type::STK_BlockPointer: 5767 if (Src.get()->isNullPointerConstant(Context, 5768 Expr::NPC_ValueDependentIsNull)) 5769 return CK_NullToPointer; 5770 return CK_IntegralToPointer; 5771 case Type::STK_Bool: 5772 return CK_IntegralToBoolean; 5773 case Type::STK_Integral: 5774 return CK_IntegralCast; 5775 case Type::STK_Floating: 5776 return CK_IntegralToFloating; 5777 case Type::STK_IntegralComplex: 5778 Src = ImpCastExprToType(Src.get(), 5779 DestTy->castAs<ComplexType>()->getElementType(), 5780 CK_IntegralCast); 5781 return CK_IntegralRealToComplex; 5782 case Type::STK_FloatingComplex: 5783 Src = ImpCastExprToType(Src.get(), 5784 DestTy->castAs<ComplexType>()->getElementType(), 5785 CK_IntegralToFloating); 5786 return CK_FloatingRealToComplex; 5787 case Type::STK_MemberPointer: 5788 llvm_unreachable("member pointer type in C"); 5789 } 5790 llvm_unreachable("Should have returned before this"); 5791 5792 case Type::STK_Floating: 5793 switch (DestTy->getScalarTypeKind()) { 5794 case Type::STK_Floating: 5795 return CK_FloatingCast; 5796 case Type::STK_Bool: 5797 return CK_FloatingToBoolean; 5798 case Type::STK_Integral: 5799 return CK_FloatingToIntegral; 5800 case Type::STK_FloatingComplex: 5801 Src = ImpCastExprToType(Src.get(), 5802 DestTy->castAs<ComplexType>()->getElementType(), 5803 CK_FloatingCast); 5804 return CK_FloatingRealToComplex; 5805 case Type::STK_IntegralComplex: 5806 Src = ImpCastExprToType(Src.get(), 5807 DestTy->castAs<ComplexType>()->getElementType(), 5808 CK_FloatingToIntegral); 5809 return CK_IntegralRealToComplex; 5810 case Type::STK_CPointer: 5811 case Type::STK_ObjCObjectPointer: 5812 case Type::STK_BlockPointer: 5813 llvm_unreachable("valid float->pointer cast?"); 5814 case Type::STK_MemberPointer: 5815 llvm_unreachable("member pointer type in C"); 5816 } 5817 llvm_unreachable("Should have returned before this"); 5818 5819 case Type::STK_FloatingComplex: 5820 switch (DestTy->getScalarTypeKind()) { 5821 case Type::STK_FloatingComplex: 5822 return CK_FloatingComplexCast; 5823 case Type::STK_IntegralComplex: 5824 return CK_FloatingComplexToIntegralComplex; 5825 case Type::STK_Floating: { 5826 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5827 if (Context.hasSameType(ET, DestTy)) 5828 return CK_FloatingComplexToReal; 5829 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5830 return CK_FloatingCast; 5831 } 5832 case Type::STK_Bool: 5833 return CK_FloatingComplexToBoolean; 5834 case Type::STK_Integral: 5835 Src = ImpCastExprToType(Src.get(), 5836 SrcTy->castAs<ComplexType>()->getElementType(), 5837 CK_FloatingComplexToReal); 5838 return CK_FloatingToIntegral; 5839 case Type::STK_CPointer: 5840 case Type::STK_ObjCObjectPointer: 5841 case Type::STK_BlockPointer: 5842 llvm_unreachable("valid complex float->pointer cast?"); 5843 case Type::STK_MemberPointer: 5844 llvm_unreachable("member pointer type in C"); 5845 } 5846 llvm_unreachable("Should have returned before this"); 5847 5848 case Type::STK_IntegralComplex: 5849 switch (DestTy->getScalarTypeKind()) { 5850 case Type::STK_FloatingComplex: 5851 return CK_IntegralComplexToFloatingComplex; 5852 case Type::STK_IntegralComplex: 5853 return CK_IntegralComplexCast; 5854 case Type::STK_Integral: { 5855 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5856 if (Context.hasSameType(ET, DestTy)) 5857 return CK_IntegralComplexToReal; 5858 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5859 return CK_IntegralCast; 5860 } 5861 case Type::STK_Bool: 5862 return CK_IntegralComplexToBoolean; 5863 case Type::STK_Floating: 5864 Src = ImpCastExprToType(Src.get(), 5865 SrcTy->castAs<ComplexType>()->getElementType(), 5866 CK_IntegralComplexToReal); 5867 return CK_IntegralToFloating; 5868 case Type::STK_CPointer: 5869 case Type::STK_ObjCObjectPointer: 5870 case Type::STK_BlockPointer: 5871 llvm_unreachable("valid complex int->pointer cast?"); 5872 case Type::STK_MemberPointer: 5873 llvm_unreachable("member pointer type in C"); 5874 } 5875 llvm_unreachable("Should have returned before this"); 5876 } 5877 5878 llvm_unreachable("Unhandled scalar cast"); 5879 } 5880 5881 static bool breakDownVectorType(QualType type, uint64_t &len, 5882 QualType &eltType) { 5883 // Vectors are simple. 5884 if (const VectorType *vecType = type->getAs<VectorType>()) { 5885 len = vecType->getNumElements(); 5886 eltType = vecType->getElementType(); 5887 assert(eltType->isScalarType()); 5888 return true; 5889 } 5890 5891 // We allow lax conversion to and from non-vector types, but only if 5892 // they're real types (i.e. non-complex, non-pointer scalar types). 5893 if (!type->isRealType()) return false; 5894 5895 len = 1; 5896 eltType = type; 5897 return true; 5898 } 5899 5900 /// Are the two types lax-compatible vector types? That is, given 5901 /// that one of them is a vector, do they have equal storage sizes, 5902 /// where the storage size is the number of elements times the element 5903 /// size? 5904 /// 5905 /// This will also return false if either of the types is neither a 5906 /// vector nor a real type. 5907 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5908 assert(destTy->isVectorType() || srcTy->isVectorType()); 5909 5910 // Disallow lax conversions between scalars and ExtVectors (these 5911 // conversions are allowed for other vector types because common headers 5912 // depend on them). Most scalar OP ExtVector cases are handled by the 5913 // splat path anyway, which does what we want (convert, not bitcast). 5914 // What this rules out for ExtVectors is crazy things like char4*float. 5915 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5916 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5917 5918 uint64_t srcLen, destLen; 5919 QualType srcEltTy, destEltTy; 5920 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5921 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5922 5923 // ASTContext::getTypeSize will return the size rounded up to a 5924 // power of 2, so instead of using that, we need to use the raw 5925 // element size multiplied by the element count. 5926 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5927 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5928 5929 return (srcLen * srcEltSize == destLen * destEltSize); 5930 } 5931 5932 /// Is this a legal conversion between two types, one of which is 5933 /// known to be a vector type? 5934 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5935 assert(destTy->isVectorType() || srcTy->isVectorType()); 5936 5937 if (!Context.getLangOpts().LaxVectorConversions) 5938 return false; 5939 return areLaxCompatibleVectorTypes(srcTy, destTy); 5940 } 5941 5942 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5943 CastKind &Kind) { 5944 assert(VectorTy->isVectorType() && "Not a vector type!"); 5945 5946 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5947 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5948 return Diag(R.getBegin(), 5949 Ty->isVectorType() ? 5950 diag::err_invalid_conversion_between_vectors : 5951 diag::err_invalid_conversion_between_vector_and_integer) 5952 << VectorTy << Ty << R; 5953 } else 5954 return Diag(R.getBegin(), 5955 diag::err_invalid_conversion_between_vector_and_scalar) 5956 << VectorTy << Ty << R; 5957 5958 Kind = CK_BitCast; 5959 return false; 5960 } 5961 5962 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5963 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5964 5965 if (DestElemTy == SplattedExpr->getType()) 5966 return SplattedExpr; 5967 5968 assert(DestElemTy->isFloatingType() || 5969 DestElemTy->isIntegralOrEnumerationType()); 5970 5971 CastKind CK; 5972 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5973 // OpenCL requires that we convert `true` boolean expressions to -1, but 5974 // only when splatting vectors. 5975 if (DestElemTy->isFloatingType()) { 5976 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5977 // in two steps: boolean to signed integral, then to floating. 5978 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5979 CK_BooleanToSignedIntegral); 5980 SplattedExpr = CastExprRes.get(); 5981 CK = CK_IntegralToFloating; 5982 } else { 5983 CK = CK_BooleanToSignedIntegral; 5984 } 5985 } else { 5986 ExprResult CastExprRes = SplattedExpr; 5987 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5988 if (CastExprRes.isInvalid()) 5989 return ExprError(); 5990 SplattedExpr = CastExprRes.get(); 5991 } 5992 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5993 } 5994 5995 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5996 Expr *CastExpr, CastKind &Kind) { 5997 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5998 5999 QualType SrcTy = CastExpr->getType(); 6000 6001 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6002 // an ExtVectorType. 6003 // In OpenCL, casts between vectors of different types are not allowed. 6004 // (See OpenCL 6.2). 6005 if (SrcTy->isVectorType()) { 6006 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 6007 || (getLangOpts().OpenCL && 6008 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 6009 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6010 << DestTy << SrcTy << R; 6011 return ExprError(); 6012 } 6013 Kind = CK_BitCast; 6014 return CastExpr; 6015 } 6016 6017 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6018 // conversion will take place first from scalar to elt type, and then 6019 // splat from elt type to vector. 6020 if (SrcTy->isPointerType()) 6021 return Diag(R.getBegin(), 6022 diag::err_invalid_conversion_between_vector_and_scalar) 6023 << DestTy << SrcTy << R; 6024 6025 Kind = CK_VectorSplat; 6026 return prepareVectorSplat(DestTy, CastExpr); 6027 } 6028 6029 ExprResult 6030 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6031 Declarator &D, ParsedType &Ty, 6032 SourceLocation RParenLoc, Expr *CastExpr) { 6033 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6034 "ActOnCastExpr(): missing type or expr"); 6035 6036 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6037 if (D.isInvalidType()) 6038 return ExprError(); 6039 6040 if (getLangOpts().CPlusPlus) { 6041 // Check that there are no default arguments (C++ only). 6042 CheckExtraCXXDefaultArguments(D); 6043 } else { 6044 // Make sure any TypoExprs have been dealt with. 6045 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6046 if (!Res.isUsable()) 6047 return ExprError(); 6048 CastExpr = Res.get(); 6049 } 6050 6051 checkUnusedDeclAttributes(D); 6052 6053 QualType castType = castTInfo->getType(); 6054 Ty = CreateParsedType(castType, castTInfo); 6055 6056 bool isVectorLiteral = false; 6057 6058 // Check for an altivec or OpenCL literal, 6059 // i.e. all the elements are integer constants. 6060 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6061 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6062 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6063 && castType->isVectorType() && (PE || PLE)) { 6064 if (PLE && PLE->getNumExprs() == 0) { 6065 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6066 return ExprError(); 6067 } 6068 if (PE || PLE->getNumExprs() == 1) { 6069 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6070 if (!E->getType()->isVectorType()) 6071 isVectorLiteral = true; 6072 } 6073 else 6074 isVectorLiteral = true; 6075 } 6076 6077 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6078 // then handle it as such. 6079 if (isVectorLiteral) 6080 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6081 6082 // If the Expr being casted is a ParenListExpr, handle it specially. 6083 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6084 // sequence of BinOp comma operators. 6085 if (isa<ParenListExpr>(CastExpr)) { 6086 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6087 if (Result.isInvalid()) return ExprError(); 6088 CastExpr = Result.get(); 6089 } 6090 6091 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6092 !getSourceManager().isInSystemMacro(LParenLoc)) 6093 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6094 6095 CheckTollFreeBridgeCast(castType, CastExpr); 6096 6097 CheckObjCBridgeRelatedCast(castType, CastExpr); 6098 6099 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6100 6101 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6102 } 6103 6104 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6105 SourceLocation RParenLoc, Expr *E, 6106 TypeSourceInfo *TInfo) { 6107 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6108 "Expected paren or paren list expression"); 6109 6110 Expr **exprs; 6111 unsigned numExprs; 6112 Expr *subExpr; 6113 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6114 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6115 LiteralLParenLoc = PE->getLParenLoc(); 6116 LiteralRParenLoc = PE->getRParenLoc(); 6117 exprs = PE->getExprs(); 6118 numExprs = PE->getNumExprs(); 6119 } else { // isa<ParenExpr> by assertion at function entrance 6120 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6121 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6122 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6123 exprs = &subExpr; 6124 numExprs = 1; 6125 } 6126 6127 QualType Ty = TInfo->getType(); 6128 assert(Ty->isVectorType() && "Expected vector type"); 6129 6130 SmallVector<Expr *, 8> initExprs; 6131 const VectorType *VTy = Ty->getAs<VectorType>(); 6132 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6133 6134 // '(...)' form of vector initialization in AltiVec: the number of 6135 // initializers must be one or must match the size of the vector. 6136 // If a single value is specified in the initializer then it will be 6137 // replicated to all the components of the vector 6138 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6139 // The number of initializers must be one or must match the size of the 6140 // vector. If a single value is specified in the initializer then it will 6141 // be replicated to all the components of the vector 6142 if (numExprs == 1) { 6143 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6144 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6145 if (Literal.isInvalid()) 6146 return ExprError(); 6147 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6148 PrepareScalarCast(Literal, ElemTy)); 6149 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6150 } 6151 else if (numExprs < numElems) { 6152 Diag(E->getExprLoc(), 6153 diag::err_incorrect_number_of_vector_initializers); 6154 return ExprError(); 6155 } 6156 else 6157 initExprs.append(exprs, exprs + numExprs); 6158 } 6159 else { 6160 // For OpenCL, when the number of initializers is a single value, 6161 // it will be replicated to all components of the vector. 6162 if (getLangOpts().OpenCL && 6163 VTy->getVectorKind() == VectorType::GenericVector && 6164 numExprs == 1) { 6165 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6166 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6167 if (Literal.isInvalid()) 6168 return ExprError(); 6169 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6170 PrepareScalarCast(Literal, ElemTy)); 6171 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6172 } 6173 6174 initExprs.append(exprs, exprs + numExprs); 6175 } 6176 // FIXME: This means that pretty-printing the final AST will produce curly 6177 // braces instead of the original commas. 6178 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6179 initExprs, LiteralRParenLoc); 6180 initE->setType(Ty); 6181 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6182 } 6183 6184 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6185 /// the ParenListExpr into a sequence of comma binary operators. 6186 ExprResult 6187 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6188 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6189 if (!E) 6190 return OrigExpr; 6191 6192 ExprResult Result(E->getExpr(0)); 6193 6194 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6195 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6196 E->getExpr(i)); 6197 6198 if (Result.isInvalid()) return ExprError(); 6199 6200 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6201 } 6202 6203 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6204 SourceLocation R, 6205 MultiExprArg Val) { 6206 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6207 return expr; 6208 } 6209 6210 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6211 /// constant and the other is not a pointer. Returns true if a diagnostic is 6212 /// emitted. 6213 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6214 SourceLocation QuestionLoc) { 6215 Expr *NullExpr = LHSExpr; 6216 Expr *NonPointerExpr = RHSExpr; 6217 Expr::NullPointerConstantKind NullKind = 6218 NullExpr->isNullPointerConstant(Context, 6219 Expr::NPC_ValueDependentIsNotNull); 6220 6221 if (NullKind == Expr::NPCK_NotNull) { 6222 NullExpr = RHSExpr; 6223 NonPointerExpr = LHSExpr; 6224 NullKind = 6225 NullExpr->isNullPointerConstant(Context, 6226 Expr::NPC_ValueDependentIsNotNull); 6227 } 6228 6229 if (NullKind == Expr::NPCK_NotNull) 6230 return false; 6231 6232 if (NullKind == Expr::NPCK_ZeroExpression) 6233 return false; 6234 6235 if (NullKind == Expr::NPCK_ZeroLiteral) { 6236 // In this case, check to make sure that we got here from a "NULL" 6237 // string in the source code. 6238 NullExpr = NullExpr->IgnoreParenImpCasts(); 6239 SourceLocation loc = NullExpr->getExprLoc(); 6240 if (!findMacroSpelling(loc, "NULL")) 6241 return false; 6242 } 6243 6244 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6245 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6246 << NonPointerExpr->getType() << DiagType 6247 << NonPointerExpr->getSourceRange(); 6248 return true; 6249 } 6250 6251 /// \brief Return false if the condition expression is valid, true otherwise. 6252 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6253 QualType CondTy = Cond->getType(); 6254 6255 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6256 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6257 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6258 << CondTy << Cond->getSourceRange(); 6259 return true; 6260 } 6261 6262 // C99 6.5.15p2 6263 if (CondTy->isScalarType()) return false; 6264 6265 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6266 << CondTy << Cond->getSourceRange(); 6267 return true; 6268 } 6269 6270 /// \brief Handle when one or both operands are void type. 6271 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6272 ExprResult &RHS) { 6273 Expr *LHSExpr = LHS.get(); 6274 Expr *RHSExpr = RHS.get(); 6275 6276 if (!LHSExpr->getType()->isVoidType()) 6277 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6278 << RHSExpr->getSourceRange(); 6279 if (!RHSExpr->getType()->isVoidType()) 6280 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6281 << LHSExpr->getSourceRange(); 6282 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6283 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6284 return S.Context.VoidTy; 6285 } 6286 6287 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6288 /// true otherwise. 6289 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6290 QualType PointerTy) { 6291 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6292 !NullExpr.get()->isNullPointerConstant(S.Context, 6293 Expr::NPC_ValueDependentIsNull)) 6294 return true; 6295 6296 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6297 return false; 6298 } 6299 6300 /// \brief Checks compatibility between two pointers and return the resulting 6301 /// type. 6302 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6303 ExprResult &RHS, 6304 SourceLocation Loc) { 6305 QualType LHSTy = LHS.get()->getType(); 6306 QualType RHSTy = RHS.get()->getType(); 6307 6308 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6309 // Two identical pointers types are always compatible. 6310 return LHSTy; 6311 } 6312 6313 QualType lhptee, rhptee; 6314 6315 // Get the pointee types. 6316 bool IsBlockPointer = false; 6317 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6318 lhptee = LHSBTy->getPointeeType(); 6319 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6320 IsBlockPointer = true; 6321 } else { 6322 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6323 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6324 } 6325 6326 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6327 // differently qualified versions of compatible types, the result type is 6328 // a pointer to an appropriately qualified version of the composite 6329 // type. 6330 6331 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6332 // clause doesn't make sense for our extensions. E.g. address space 2 should 6333 // be incompatible with address space 3: they may live on different devices or 6334 // anything. 6335 Qualifiers lhQual = lhptee.getQualifiers(); 6336 Qualifiers rhQual = rhptee.getQualifiers(); 6337 6338 unsigned ResultAddrSpace = 0; 6339 unsigned LAddrSpace = lhQual.getAddressSpace(); 6340 unsigned RAddrSpace = rhQual.getAddressSpace(); 6341 if (S.getLangOpts().OpenCL) { 6342 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6343 // spaces is disallowed. 6344 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6345 ResultAddrSpace = LAddrSpace; 6346 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6347 ResultAddrSpace = RAddrSpace; 6348 else { 6349 S.Diag(Loc, 6350 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6351 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6352 << RHS.get()->getSourceRange(); 6353 return QualType(); 6354 } 6355 } 6356 6357 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6358 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6359 lhQual.removeCVRQualifiers(); 6360 rhQual.removeCVRQualifiers(); 6361 6362 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6363 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6364 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6365 // qual types are compatible iff 6366 // * corresponded types are compatible 6367 // * CVR qualifiers are equal 6368 // * address spaces are equal 6369 // Thus for conditional operator we merge CVR and address space unqualified 6370 // pointees and if there is a composite type we return a pointer to it with 6371 // merged qualifiers. 6372 if (S.getLangOpts().OpenCL) { 6373 LHSCastKind = LAddrSpace == ResultAddrSpace 6374 ? CK_BitCast 6375 : CK_AddressSpaceConversion; 6376 RHSCastKind = RAddrSpace == ResultAddrSpace 6377 ? CK_BitCast 6378 : CK_AddressSpaceConversion; 6379 lhQual.removeAddressSpace(); 6380 rhQual.removeAddressSpace(); 6381 } 6382 6383 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6384 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6385 6386 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6387 6388 if (CompositeTy.isNull()) { 6389 // In this situation, we assume void* type. No especially good 6390 // reason, but this is what gcc does, and we do have to pick 6391 // to get a consistent AST. 6392 QualType incompatTy; 6393 incompatTy = S.Context.getPointerType( 6394 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6395 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6396 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6397 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6398 // for casts between types with incompatible address space qualifiers. 6399 // For the following code the compiler produces casts between global and 6400 // local address spaces of the corresponded innermost pointees: 6401 // local int *global *a; 6402 // global int *global *b; 6403 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6404 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6405 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6406 << RHS.get()->getSourceRange(); 6407 return incompatTy; 6408 } 6409 6410 // The pointer types are compatible. 6411 // In case of OpenCL ResultTy should have the address space qualifier 6412 // which is a superset of address spaces of both the 2nd and the 3rd 6413 // operands of the conditional operator. 6414 QualType ResultTy = [&, ResultAddrSpace]() { 6415 if (S.getLangOpts().OpenCL) { 6416 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6417 CompositeQuals.setAddressSpace(ResultAddrSpace); 6418 return S.Context 6419 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6420 .withCVRQualifiers(MergedCVRQual); 6421 } else 6422 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6423 }(); 6424 if (IsBlockPointer) 6425 ResultTy = S.Context.getBlockPointerType(ResultTy); 6426 else { 6427 ResultTy = S.Context.getPointerType(ResultTy); 6428 } 6429 6430 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6431 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6432 return ResultTy; 6433 } 6434 6435 /// \brief Return the resulting type when the operands are both block pointers. 6436 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6437 ExprResult &LHS, 6438 ExprResult &RHS, 6439 SourceLocation Loc) { 6440 QualType LHSTy = LHS.get()->getType(); 6441 QualType RHSTy = RHS.get()->getType(); 6442 6443 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6444 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6445 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6446 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6447 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6448 return destType; 6449 } 6450 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6451 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6452 << RHS.get()->getSourceRange(); 6453 return QualType(); 6454 } 6455 6456 // We have 2 block pointer types. 6457 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6458 } 6459 6460 /// \brief Return the resulting type when the operands are both pointers. 6461 static QualType 6462 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6463 ExprResult &RHS, 6464 SourceLocation Loc) { 6465 // get the pointer types 6466 QualType LHSTy = LHS.get()->getType(); 6467 QualType RHSTy = RHS.get()->getType(); 6468 6469 // get the "pointed to" types 6470 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6471 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6472 6473 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6474 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6475 // Figure out necessary qualifiers (C99 6.5.15p6) 6476 QualType destPointee 6477 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6478 QualType destType = S.Context.getPointerType(destPointee); 6479 // Add qualifiers if necessary. 6480 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6481 // Promote to void*. 6482 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6483 return destType; 6484 } 6485 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6486 QualType destPointee 6487 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6488 QualType destType = S.Context.getPointerType(destPointee); 6489 // Add qualifiers if necessary. 6490 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6491 // Promote to void*. 6492 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6493 return destType; 6494 } 6495 6496 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6497 } 6498 6499 /// \brief Return false if the first expression is not an integer and the second 6500 /// expression is not a pointer, true otherwise. 6501 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6502 Expr* PointerExpr, SourceLocation Loc, 6503 bool IsIntFirstExpr) { 6504 if (!PointerExpr->getType()->isPointerType() || 6505 !Int.get()->getType()->isIntegerType()) 6506 return false; 6507 6508 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6509 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6510 6511 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6512 << Expr1->getType() << Expr2->getType() 6513 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6514 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6515 CK_IntegralToPointer); 6516 return true; 6517 } 6518 6519 /// \brief Simple conversion between integer and floating point types. 6520 /// 6521 /// Used when handling the OpenCL conditional operator where the 6522 /// condition is a vector while the other operands are scalar. 6523 /// 6524 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6525 /// types are either integer or floating type. Between the two 6526 /// operands, the type with the higher rank is defined as the "result 6527 /// type". The other operand needs to be promoted to the same type. No 6528 /// other type promotion is allowed. We cannot use 6529 /// UsualArithmeticConversions() for this purpose, since it always 6530 /// promotes promotable types. 6531 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6532 ExprResult &RHS, 6533 SourceLocation QuestionLoc) { 6534 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6535 if (LHS.isInvalid()) 6536 return QualType(); 6537 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6538 if (RHS.isInvalid()) 6539 return QualType(); 6540 6541 // For conversion purposes, we ignore any qualifiers. 6542 // For example, "const float" and "float" are equivalent. 6543 QualType LHSType = 6544 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6545 QualType RHSType = 6546 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6547 6548 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6549 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6550 << LHSType << LHS.get()->getSourceRange(); 6551 return QualType(); 6552 } 6553 6554 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6555 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6556 << RHSType << RHS.get()->getSourceRange(); 6557 return QualType(); 6558 } 6559 6560 // If both types are identical, no conversion is needed. 6561 if (LHSType == RHSType) 6562 return LHSType; 6563 6564 // Now handle "real" floating types (i.e. float, double, long double). 6565 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6566 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6567 /*IsCompAssign = */ false); 6568 6569 // Finally, we have two differing integer types. 6570 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6571 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6572 } 6573 6574 /// \brief Convert scalar operands to a vector that matches the 6575 /// condition in length. 6576 /// 6577 /// Used when handling the OpenCL conditional operator where the 6578 /// condition is a vector while the other operands are scalar. 6579 /// 6580 /// We first compute the "result type" for the scalar operands 6581 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6582 /// into a vector of that type where the length matches the condition 6583 /// vector type. s6.11.6 requires that the element types of the result 6584 /// and the condition must have the same number of bits. 6585 static QualType 6586 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6587 QualType CondTy, SourceLocation QuestionLoc) { 6588 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6589 if (ResTy.isNull()) return QualType(); 6590 6591 const VectorType *CV = CondTy->getAs<VectorType>(); 6592 assert(CV); 6593 6594 // Determine the vector result type 6595 unsigned NumElements = CV->getNumElements(); 6596 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6597 6598 // Ensure that all types have the same number of bits 6599 if (S.Context.getTypeSize(CV->getElementType()) 6600 != S.Context.getTypeSize(ResTy)) { 6601 // Since VectorTy is created internally, it does not pretty print 6602 // with an OpenCL name. Instead, we just print a description. 6603 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6604 SmallString<64> Str; 6605 llvm::raw_svector_ostream OS(Str); 6606 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6607 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6608 << CondTy << OS.str(); 6609 return QualType(); 6610 } 6611 6612 // Convert operands to the vector result type 6613 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6614 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6615 6616 return VectorTy; 6617 } 6618 6619 /// \brief Return false if this is a valid OpenCL condition vector 6620 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6621 SourceLocation QuestionLoc) { 6622 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6623 // integral type. 6624 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6625 assert(CondTy); 6626 QualType EleTy = CondTy->getElementType(); 6627 if (EleTy->isIntegerType()) return false; 6628 6629 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6630 << Cond->getType() << Cond->getSourceRange(); 6631 return true; 6632 } 6633 6634 /// \brief Return false if the vector condition type and the vector 6635 /// result type are compatible. 6636 /// 6637 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6638 /// number of elements, and their element types have the same number 6639 /// of bits. 6640 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6641 SourceLocation QuestionLoc) { 6642 const VectorType *CV = CondTy->getAs<VectorType>(); 6643 const VectorType *RV = VecResTy->getAs<VectorType>(); 6644 assert(CV && RV); 6645 6646 if (CV->getNumElements() != RV->getNumElements()) { 6647 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6648 << CondTy << VecResTy; 6649 return true; 6650 } 6651 6652 QualType CVE = CV->getElementType(); 6653 QualType RVE = RV->getElementType(); 6654 6655 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6656 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6657 << CondTy << VecResTy; 6658 return true; 6659 } 6660 6661 return false; 6662 } 6663 6664 /// \brief Return the resulting type for the conditional operator in 6665 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6666 /// s6.3.i) when the condition is a vector type. 6667 static QualType 6668 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6669 ExprResult &LHS, ExprResult &RHS, 6670 SourceLocation QuestionLoc) { 6671 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6672 if (Cond.isInvalid()) 6673 return QualType(); 6674 QualType CondTy = Cond.get()->getType(); 6675 6676 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6677 return QualType(); 6678 6679 // If either operand is a vector then find the vector type of the 6680 // result as specified in OpenCL v1.1 s6.3.i. 6681 if (LHS.get()->getType()->isVectorType() || 6682 RHS.get()->getType()->isVectorType()) { 6683 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6684 /*isCompAssign*/false, 6685 /*AllowBothBool*/true, 6686 /*AllowBoolConversions*/false); 6687 if (VecResTy.isNull()) return QualType(); 6688 // The result type must match the condition type as specified in 6689 // OpenCL v1.1 s6.11.6. 6690 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6691 return QualType(); 6692 return VecResTy; 6693 } 6694 6695 // Both operands are scalar. 6696 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6697 } 6698 6699 /// \brief Return true if the Expr is block type 6700 static bool checkBlockType(Sema &S, const Expr *E) { 6701 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6702 QualType Ty = CE->getCallee()->getType(); 6703 if (Ty->isBlockPointerType()) { 6704 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6705 return true; 6706 } 6707 } 6708 return false; 6709 } 6710 6711 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6712 /// In that case, LHS = cond. 6713 /// C99 6.5.15 6714 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6715 ExprResult &RHS, ExprValueKind &VK, 6716 ExprObjectKind &OK, 6717 SourceLocation QuestionLoc) { 6718 6719 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6720 if (!LHSResult.isUsable()) return QualType(); 6721 LHS = LHSResult; 6722 6723 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6724 if (!RHSResult.isUsable()) return QualType(); 6725 RHS = RHSResult; 6726 6727 // C++ is sufficiently different to merit its own checker. 6728 if (getLangOpts().CPlusPlus) 6729 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6730 6731 VK = VK_RValue; 6732 OK = OK_Ordinary; 6733 6734 // The OpenCL operator with a vector condition is sufficiently 6735 // different to merit its own checker. 6736 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6737 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6738 6739 // First, check the condition. 6740 Cond = UsualUnaryConversions(Cond.get()); 6741 if (Cond.isInvalid()) 6742 return QualType(); 6743 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6744 return QualType(); 6745 6746 // Now check the two expressions. 6747 if (LHS.get()->getType()->isVectorType() || 6748 RHS.get()->getType()->isVectorType()) 6749 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6750 /*AllowBothBool*/true, 6751 /*AllowBoolConversions*/false); 6752 6753 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6754 if (LHS.isInvalid() || RHS.isInvalid()) 6755 return QualType(); 6756 6757 QualType LHSTy = LHS.get()->getType(); 6758 QualType RHSTy = RHS.get()->getType(); 6759 6760 // Diagnose attempts to convert between __float128 and long double where 6761 // such conversions currently can't be handled. 6762 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6763 Diag(QuestionLoc, 6764 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6765 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6766 return QualType(); 6767 } 6768 6769 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6770 // selection operator (?:). 6771 if (getLangOpts().OpenCL && 6772 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6773 return QualType(); 6774 } 6775 6776 // If both operands have arithmetic type, do the usual arithmetic conversions 6777 // to find a common type: C99 6.5.15p3,5. 6778 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6779 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6780 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6781 6782 return ResTy; 6783 } 6784 6785 // If both operands are the same structure or union type, the result is that 6786 // type. 6787 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6788 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6789 if (LHSRT->getDecl() == RHSRT->getDecl()) 6790 // "If both the operands have structure or union type, the result has 6791 // that type." This implies that CV qualifiers are dropped. 6792 return LHSTy.getUnqualifiedType(); 6793 // FIXME: Type of conditional expression must be complete in C mode. 6794 } 6795 6796 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6797 // The following || allows only one side to be void (a GCC-ism). 6798 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6799 return checkConditionalVoidType(*this, LHS, RHS); 6800 } 6801 6802 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6803 // the type of the other operand." 6804 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6805 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6806 6807 // All objective-c pointer type analysis is done here. 6808 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6809 QuestionLoc); 6810 if (LHS.isInvalid() || RHS.isInvalid()) 6811 return QualType(); 6812 if (!compositeType.isNull()) 6813 return compositeType; 6814 6815 6816 // Handle block pointer types. 6817 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6818 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6819 QuestionLoc); 6820 6821 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6822 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6823 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6824 QuestionLoc); 6825 6826 // GCC compatibility: soften pointer/integer mismatch. Note that 6827 // null pointers have been filtered out by this point. 6828 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6829 /*isIntFirstExpr=*/true)) 6830 return RHSTy; 6831 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6832 /*isIntFirstExpr=*/false)) 6833 return LHSTy; 6834 6835 // Emit a better diagnostic if one of the expressions is a null pointer 6836 // constant and the other is not a pointer type. In this case, the user most 6837 // likely forgot to take the address of the other expression. 6838 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6839 return QualType(); 6840 6841 // Otherwise, the operands are not compatible. 6842 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6843 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6844 << RHS.get()->getSourceRange(); 6845 return QualType(); 6846 } 6847 6848 /// FindCompositeObjCPointerType - Helper method to find composite type of 6849 /// two objective-c pointer types of the two input expressions. 6850 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6851 SourceLocation QuestionLoc) { 6852 QualType LHSTy = LHS.get()->getType(); 6853 QualType RHSTy = RHS.get()->getType(); 6854 6855 // Handle things like Class and struct objc_class*. Here we case the result 6856 // to the pseudo-builtin, because that will be implicitly cast back to the 6857 // redefinition type if an attempt is made to access its fields. 6858 if (LHSTy->isObjCClassType() && 6859 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6860 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6861 return LHSTy; 6862 } 6863 if (RHSTy->isObjCClassType() && 6864 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6865 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6866 return RHSTy; 6867 } 6868 // And the same for struct objc_object* / id 6869 if (LHSTy->isObjCIdType() && 6870 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6871 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6872 return LHSTy; 6873 } 6874 if (RHSTy->isObjCIdType() && 6875 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6876 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6877 return RHSTy; 6878 } 6879 // And the same for struct objc_selector* / SEL 6880 if (Context.isObjCSelType(LHSTy) && 6881 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6882 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6883 return LHSTy; 6884 } 6885 if (Context.isObjCSelType(RHSTy) && 6886 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6887 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6888 return RHSTy; 6889 } 6890 // Check constraints for Objective-C object pointers types. 6891 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6892 6893 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6894 // Two identical object pointer types are always compatible. 6895 return LHSTy; 6896 } 6897 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6898 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6899 QualType compositeType = LHSTy; 6900 6901 // If both operands are interfaces and either operand can be 6902 // assigned to the other, use that type as the composite 6903 // type. This allows 6904 // xxx ? (A*) a : (B*) b 6905 // where B is a subclass of A. 6906 // 6907 // Additionally, as for assignment, if either type is 'id' 6908 // allow silent coercion. Finally, if the types are 6909 // incompatible then make sure to use 'id' as the composite 6910 // type so the result is acceptable for sending messages to. 6911 6912 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6913 // It could return the composite type. 6914 if (!(compositeType = 6915 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6916 // Nothing more to do. 6917 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6918 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6919 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6920 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6921 } else if ((LHSTy->isObjCQualifiedIdType() || 6922 RHSTy->isObjCQualifiedIdType()) && 6923 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6924 // Need to handle "id<xx>" explicitly. 6925 // GCC allows qualified id and any Objective-C type to devolve to 6926 // id. Currently localizing to here until clear this should be 6927 // part of ObjCQualifiedIdTypesAreCompatible. 6928 compositeType = Context.getObjCIdType(); 6929 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6930 compositeType = Context.getObjCIdType(); 6931 } else { 6932 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6933 << LHSTy << RHSTy 6934 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6935 QualType incompatTy = Context.getObjCIdType(); 6936 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6937 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6938 return incompatTy; 6939 } 6940 // The object pointer types are compatible. 6941 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6942 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6943 return compositeType; 6944 } 6945 // Check Objective-C object pointer types and 'void *' 6946 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6947 if (getLangOpts().ObjCAutoRefCount) { 6948 // ARC forbids the implicit conversion of object pointers to 'void *', 6949 // so these types are not compatible. 6950 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6951 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6952 LHS = RHS = true; 6953 return QualType(); 6954 } 6955 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6956 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6957 QualType destPointee 6958 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6959 QualType destType = Context.getPointerType(destPointee); 6960 // Add qualifiers if necessary. 6961 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6962 // Promote to void*. 6963 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6964 return destType; 6965 } 6966 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6967 if (getLangOpts().ObjCAutoRefCount) { 6968 // ARC forbids the implicit conversion of object pointers to 'void *', 6969 // so these types are not compatible. 6970 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6971 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6972 LHS = RHS = true; 6973 return QualType(); 6974 } 6975 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6976 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6977 QualType destPointee 6978 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6979 QualType destType = Context.getPointerType(destPointee); 6980 // Add qualifiers if necessary. 6981 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6982 // Promote to void*. 6983 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6984 return destType; 6985 } 6986 return QualType(); 6987 } 6988 6989 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6990 /// ParenRange in parentheses. 6991 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6992 const PartialDiagnostic &Note, 6993 SourceRange ParenRange) { 6994 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6995 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6996 EndLoc.isValid()) { 6997 Self.Diag(Loc, Note) 6998 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6999 << FixItHint::CreateInsertion(EndLoc, ")"); 7000 } else { 7001 // We can't display the parentheses, so just show the bare note. 7002 Self.Diag(Loc, Note) << ParenRange; 7003 } 7004 } 7005 7006 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7007 return BinaryOperator::isAdditiveOp(Opc) || 7008 BinaryOperator::isMultiplicativeOp(Opc) || 7009 BinaryOperator::isShiftOp(Opc); 7010 } 7011 7012 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7013 /// expression, either using a built-in or overloaded operator, 7014 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7015 /// expression. 7016 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7017 Expr **RHSExprs) { 7018 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7019 E = E->IgnoreImpCasts(); 7020 E = E->IgnoreConversionOperator(); 7021 E = E->IgnoreImpCasts(); 7022 7023 // Built-in binary operator. 7024 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7025 if (IsArithmeticOp(OP->getOpcode())) { 7026 *Opcode = OP->getOpcode(); 7027 *RHSExprs = OP->getRHS(); 7028 return true; 7029 } 7030 } 7031 7032 // Overloaded operator. 7033 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7034 if (Call->getNumArgs() != 2) 7035 return false; 7036 7037 // Make sure this is really a binary operator that is safe to pass into 7038 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7039 OverloadedOperatorKind OO = Call->getOperator(); 7040 if (OO < OO_Plus || OO > OO_Arrow || 7041 OO == OO_PlusPlus || OO == OO_MinusMinus) 7042 return false; 7043 7044 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7045 if (IsArithmeticOp(OpKind)) { 7046 *Opcode = OpKind; 7047 *RHSExprs = Call->getArg(1); 7048 return true; 7049 } 7050 } 7051 7052 return false; 7053 } 7054 7055 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7056 /// or is a logical expression such as (x==y) which has int type, but is 7057 /// commonly interpreted as boolean. 7058 static bool ExprLooksBoolean(Expr *E) { 7059 E = E->IgnoreParenImpCasts(); 7060 7061 if (E->getType()->isBooleanType()) 7062 return true; 7063 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7064 return OP->isComparisonOp() || OP->isLogicalOp(); 7065 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7066 return OP->getOpcode() == UO_LNot; 7067 if (E->getType()->isPointerType()) 7068 return true; 7069 7070 return false; 7071 } 7072 7073 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7074 /// and binary operator are mixed in a way that suggests the programmer assumed 7075 /// the conditional operator has higher precedence, for example: 7076 /// "int x = a + someBinaryCondition ? 1 : 2". 7077 static void DiagnoseConditionalPrecedence(Sema &Self, 7078 SourceLocation OpLoc, 7079 Expr *Condition, 7080 Expr *LHSExpr, 7081 Expr *RHSExpr) { 7082 BinaryOperatorKind CondOpcode; 7083 Expr *CondRHS; 7084 7085 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7086 return; 7087 if (!ExprLooksBoolean(CondRHS)) 7088 return; 7089 7090 // The condition is an arithmetic binary expression, with a right- 7091 // hand side that looks boolean, so warn. 7092 7093 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7094 << Condition->getSourceRange() 7095 << BinaryOperator::getOpcodeStr(CondOpcode); 7096 7097 SuggestParentheses(Self, OpLoc, 7098 Self.PDiag(diag::note_precedence_silence) 7099 << BinaryOperator::getOpcodeStr(CondOpcode), 7100 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7101 7102 SuggestParentheses(Self, OpLoc, 7103 Self.PDiag(diag::note_precedence_conditional_first), 7104 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7105 } 7106 7107 /// Compute the nullability of a conditional expression. 7108 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7109 QualType LHSTy, QualType RHSTy, 7110 ASTContext &Ctx) { 7111 if (!ResTy->isAnyPointerType()) 7112 return ResTy; 7113 7114 auto GetNullability = [&Ctx](QualType Ty) { 7115 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7116 if (Kind) 7117 return *Kind; 7118 return NullabilityKind::Unspecified; 7119 }; 7120 7121 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7122 NullabilityKind MergedKind; 7123 7124 // Compute nullability of a binary conditional expression. 7125 if (IsBin) { 7126 if (LHSKind == NullabilityKind::NonNull) 7127 MergedKind = NullabilityKind::NonNull; 7128 else 7129 MergedKind = RHSKind; 7130 // Compute nullability of a normal conditional expression. 7131 } else { 7132 if (LHSKind == NullabilityKind::Nullable || 7133 RHSKind == NullabilityKind::Nullable) 7134 MergedKind = NullabilityKind::Nullable; 7135 else if (LHSKind == NullabilityKind::NonNull) 7136 MergedKind = RHSKind; 7137 else if (RHSKind == NullabilityKind::NonNull) 7138 MergedKind = LHSKind; 7139 else 7140 MergedKind = NullabilityKind::Unspecified; 7141 } 7142 7143 // Return if ResTy already has the correct nullability. 7144 if (GetNullability(ResTy) == MergedKind) 7145 return ResTy; 7146 7147 // Strip all nullability from ResTy. 7148 while (ResTy->getNullability(Ctx)) 7149 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7150 7151 // Create a new AttributedType with the new nullability kind. 7152 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7153 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7154 } 7155 7156 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7157 /// in the case of a the GNU conditional expr extension. 7158 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7159 SourceLocation ColonLoc, 7160 Expr *CondExpr, Expr *LHSExpr, 7161 Expr *RHSExpr) { 7162 if (!getLangOpts().CPlusPlus) { 7163 // C cannot handle TypoExpr nodes in the condition because it 7164 // doesn't handle dependent types properly, so make sure any TypoExprs have 7165 // been dealt with before checking the operands. 7166 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7167 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7168 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7169 7170 if (!CondResult.isUsable()) 7171 return ExprError(); 7172 7173 if (LHSExpr) { 7174 if (!LHSResult.isUsable()) 7175 return ExprError(); 7176 } 7177 7178 if (!RHSResult.isUsable()) 7179 return ExprError(); 7180 7181 CondExpr = CondResult.get(); 7182 LHSExpr = LHSResult.get(); 7183 RHSExpr = RHSResult.get(); 7184 } 7185 7186 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7187 // was the condition. 7188 OpaqueValueExpr *opaqueValue = nullptr; 7189 Expr *commonExpr = nullptr; 7190 if (!LHSExpr) { 7191 commonExpr = CondExpr; 7192 // Lower out placeholder types first. This is important so that we don't 7193 // try to capture a placeholder. This happens in few cases in C++; such 7194 // as Objective-C++'s dictionary subscripting syntax. 7195 if (commonExpr->hasPlaceholderType()) { 7196 ExprResult result = CheckPlaceholderExpr(commonExpr); 7197 if (!result.isUsable()) return ExprError(); 7198 commonExpr = result.get(); 7199 } 7200 // We usually want to apply unary conversions *before* saving, except 7201 // in the special case of a C++ l-value conditional. 7202 if (!(getLangOpts().CPlusPlus 7203 && !commonExpr->isTypeDependent() 7204 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7205 && commonExpr->isGLValue() 7206 && commonExpr->isOrdinaryOrBitFieldObject() 7207 && RHSExpr->isOrdinaryOrBitFieldObject() 7208 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7209 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7210 if (commonRes.isInvalid()) 7211 return ExprError(); 7212 commonExpr = commonRes.get(); 7213 } 7214 7215 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7216 commonExpr->getType(), 7217 commonExpr->getValueKind(), 7218 commonExpr->getObjectKind(), 7219 commonExpr); 7220 LHSExpr = CondExpr = opaqueValue; 7221 } 7222 7223 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7224 ExprValueKind VK = VK_RValue; 7225 ExprObjectKind OK = OK_Ordinary; 7226 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7227 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7228 VK, OK, QuestionLoc); 7229 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7230 RHS.isInvalid()) 7231 return ExprError(); 7232 7233 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7234 RHS.get()); 7235 7236 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7237 7238 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7239 Context); 7240 7241 if (!commonExpr) 7242 return new (Context) 7243 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7244 RHS.get(), result, VK, OK); 7245 7246 return new (Context) BinaryConditionalOperator( 7247 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7248 ColonLoc, result, VK, OK); 7249 } 7250 7251 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7252 // being closely modeled after the C99 spec:-). The odd characteristic of this 7253 // routine is it effectively iqnores the qualifiers on the top level pointee. 7254 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7255 // FIXME: add a couple examples in this comment. 7256 static Sema::AssignConvertType 7257 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7258 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7259 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7260 7261 // get the "pointed to" type (ignoring qualifiers at the top level) 7262 const Type *lhptee, *rhptee; 7263 Qualifiers lhq, rhq; 7264 std::tie(lhptee, lhq) = 7265 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7266 std::tie(rhptee, rhq) = 7267 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7268 7269 Sema::AssignConvertType ConvTy = Sema::Compatible; 7270 7271 // C99 6.5.16.1p1: This following citation is common to constraints 7272 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7273 // qualifiers of the type *pointed to* by the right; 7274 7275 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7276 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7277 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7278 // Ignore lifetime for further calculation. 7279 lhq.removeObjCLifetime(); 7280 rhq.removeObjCLifetime(); 7281 } 7282 7283 if (!lhq.compatiblyIncludes(rhq)) { 7284 // Treat address-space mismatches as fatal. TODO: address subspaces 7285 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7286 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7287 7288 // It's okay to add or remove GC or lifetime qualifiers when converting to 7289 // and from void*. 7290 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7291 .compatiblyIncludes( 7292 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7293 && (lhptee->isVoidType() || rhptee->isVoidType())) 7294 ; // keep old 7295 7296 // Treat lifetime mismatches as fatal. 7297 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7298 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7299 7300 // For GCC/MS compatibility, other qualifier mismatches are treated 7301 // as still compatible in C. 7302 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7303 } 7304 7305 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7306 // incomplete type and the other is a pointer to a qualified or unqualified 7307 // version of void... 7308 if (lhptee->isVoidType()) { 7309 if (rhptee->isIncompleteOrObjectType()) 7310 return ConvTy; 7311 7312 // As an extension, we allow cast to/from void* to function pointer. 7313 assert(rhptee->isFunctionType()); 7314 return Sema::FunctionVoidPointer; 7315 } 7316 7317 if (rhptee->isVoidType()) { 7318 if (lhptee->isIncompleteOrObjectType()) 7319 return ConvTy; 7320 7321 // As an extension, we allow cast to/from void* to function pointer. 7322 assert(lhptee->isFunctionType()); 7323 return Sema::FunctionVoidPointer; 7324 } 7325 7326 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7327 // unqualified versions of compatible types, ... 7328 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7329 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7330 // Check if the pointee types are compatible ignoring the sign. 7331 // We explicitly check for char so that we catch "char" vs 7332 // "unsigned char" on systems where "char" is unsigned. 7333 if (lhptee->isCharType()) 7334 ltrans = S.Context.UnsignedCharTy; 7335 else if (lhptee->hasSignedIntegerRepresentation()) 7336 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7337 7338 if (rhptee->isCharType()) 7339 rtrans = S.Context.UnsignedCharTy; 7340 else if (rhptee->hasSignedIntegerRepresentation()) 7341 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7342 7343 if (ltrans == rtrans) { 7344 // Types are compatible ignoring the sign. Qualifier incompatibility 7345 // takes priority over sign incompatibility because the sign 7346 // warning can be disabled. 7347 if (ConvTy != Sema::Compatible) 7348 return ConvTy; 7349 7350 return Sema::IncompatiblePointerSign; 7351 } 7352 7353 // If we are a multi-level pointer, it's possible that our issue is simply 7354 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7355 // the eventual target type is the same and the pointers have the same 7356 // level of indirection, this must be the issue. 7357 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7358 do { 7359 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7360 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7361 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7362 7363 if (lhptee == rhptee) 7364 return Sema::IncompatibleNestedPointerQualifiers; 7365 } 7366 7367 // General pointer incompatibility takes priority over qualifiers. 7368 return Sema::IncompatiblePointer; 7369 } 7370 if (!S.getLangOpts().CPlusPlus && 7371 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7372 return Sema::IncompatiblePointer; 7373 return ConvTy; 7374 } 7375 7376 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7377 /// block pointer types are compatible or whether a block and normal pointer 7378 /// are compatible. It is more restrict than comparing two function pointer 7379 // types. 7380 static Sema::AssignConvertType 7381 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7382 QualType RHSType) { 7383 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7384 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7385 7386 QualType lhptee, rhptee; 7387 7388 // get the "pointed to" type (ignoring qualifiers at the top level) 7389 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7390 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7391 7392 // In C++, the types have to match exactly. 7393 if (S.getLangOpts().CPlusPlus) 7394 return Sema::IncompatibleBlockPointer; 7395 7396 Sema::AssignConvertType ConvTy = Sema::Compatible; 7397 7398 // For blocks we enforce that qualifiers are identical. 7399 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7400 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7401 if (S.getLangOpts().OpenCL) { 7402 LQuals.removeAddressSpace(); 7403 RQuals.removeAddressSpace(); 7404 } 7405 if (LQuals != RQuals) 7406 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7407 7408 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7409 // assignment. 7410 // The current behavior is similar to C++ lambdas. A block might be 7411 // assigned to a variable iff its return type and parameters are compatible 7412 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7413 // an assignment. Presumably it should behave in way that a function pointer 7414 // assignment does in C, so for each parameter and return type: 7415 // * CVR and address space of LHS should be a superset of CVR and address 7416 // space of RHS. 7417 // * unqualified types should be compatible. 7418 if (S.getLangOpts().OpenCL) { 7419 if (!S.Context.typesAreBlockPointerCompatible( 7420 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7421 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7422 return Sema::IncompatibleBlockPointer; 7423 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7424 return Sema::IncompatibleBlockPointer; 7425 7426 return ConvTy; 7427 } 7428 7429 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7430 /// for assignment compatibility. 7431 static Sema::AssignConvertType 7432 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7433 QualType RHSType) { 7434 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7435 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7436 7437 if (LHSType->isObjCBuiltinType()) { 7438 // Class is not compatible with ObjC object pointers. 7439 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7440 !RHSType->isObjCQualifiedClassType()) 7441 return Sema::IncompatiblePointer; 7442 return Sema::Compatible; 7443 } 7444 if (RHSType->isObjCBuiltinType()) { 7445 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7446 !LHSType->isObjCQualifiedClassType()) 7447 return Sema::IncompatiblePointer; 7448 return Sema::Compatible; 7449 } 7450 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7451 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7452 7453 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7454 // make an exception for id<P> 7455 !LHSType->isObjCQualifiedIdType()) 7456 return Sema::CompatiblePointerDiscardsQualifiers; 7457 7458 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7459 return Sema::Compatible; 7460 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7461 return Sema::IncompatibleObjCQualifiedId; 7462 return Sema::IncompatiblePointer; 7463 } 7464 7465 Sema::AssignConvertType 7466 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7467 QualType LHSType, QualType RHSType) { 7468 // Fake up an opaque expression. We don't actually care about what 7469 // cast operations are required, so if CheckAssignmentConstraints 7470 // adds casts to this they'll be wasted, but fortunately that doesn't 7471 // usually happen on valid code. 7472 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7473 ExprResult RHSPtr = &RHSExpr; 7474 CastKind K = CK_Invalid; 7475 7476 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7477 } 7478 7479 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7480 /// has code to accommodate several GCC extensions when type checking 7481 /// pointers. Here are some objectionable examples that GCC considers warnings: 7482 /// 7483 /// int a, *pint; 7484 /// short *pshort; 7485 /// struct foo *pfoo; 7486 /// 7487 /// pint = pshort; // warning: assignment from incompatible pointer type 7488 /// a = pint; // warning: assignment makes integer from pointer without a cast 7489 /// pint = a; // warning: assignment makes pointer from integer without a cast 7490 /// pint = pfoo; // warning: assignment from incompatible pointer type 7491 /// 7492 /// As a result, the code for dealing with pointers is more complex than the 7493 /// C99 spec dictates. 7494 /// 7495 /// Sets 'Kind' for any result kind except Incompatible. 7496 Sema::AssignConvertType 7497 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7498 CastKind &Kind, bool ConvertRHS) { 7499 QualType RHSType = RHS.get()->getType(); 7500 QualType OrigLHSType = LHSType; 7501 7502 // Get canonical types. We're not formatting these types, just comparing 7503 // them. 7504 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7505 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7506 7507 // Common case: no conversion required. 7508 if (LHSType == RHSType) { 7509 Kind = CK_NoOp; 7510 return Compatible; 7511 } 7512 7513 // If we have an atomic type, try a non-atomic assignment, then just add an 7514 // atomic qualification step. 7515 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7516 Sema::AssignConvertType result = 7517 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7518 if (result != Compatible) 7519 return result; 7520 if (Kind != CK_NoOp && ConvertRHS) 7521 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7522 Kind = CK_NonAtomicToAtomic; 7523 return Compatible; 7524 } 7525 7526 // If the left-hand side is a reference type, then we are in a 7527 // (rare!) case where we've allowed the use of references in C, 7528 // e.g., as a parameter type in a built-in function. In this case, 7529 // just make sure that the type referenced is compatible with the 7530 // right-hand side type. The caller is responsible for adjusting 7531 // LHSType so that the resulting expression does not have reference 7532 // type. 7533 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7534 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7535 Kind = CK_LValueBitCast; 7536 return Compatible; 7537 } 7538 return Incompatible; 7539 } 7540 7541 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7542 // to the same ExtVector type. 7543 if (LHSType->isExtVectorType()) { 7544 if (RHSType->isExtVectorType()) 7545 return Incompatible; 7546 if (RHSType->isArithmeticType()) { 7547 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7548 if (ConvertRHS) 7549 RHS = prepareVectorSplat(LHSType, RHS.get()); 7550 Kind = CK_VectorSplat; 7551 return Compatible; 7552 } 7553 } 7554 7555 // Conversions to or from vector type. 7556 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7557 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7558 // Allow assignments of an AltiVec vector type to an equivalent GCC 7559 // vector type and vice versa 7560 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7561 Kind = CK_BitCast; 7562 return Compatible; 7563 } 7564 7565 // If we are allowing lax vector conversions, and LHS and RHS are both 7566 // vectors, the total size only needs to be the same. This is a bitcast; 7567 // no bits are changed but the result type is different. 7568 if (isLaxVectorConversion(RHSType, LHSType)) { 7569 Kind = CK_BitCast; 7570 return IncompatibleVectors; 7571 } 7572 } 7573 7574 // When the RHS comes from another lax conversion (e.g. binops between 7575 // scalars and vectors) the result is canonicalized as a vector. When the 7576 // LHS is also a vector, the lax is allowed by the condition above. Handle 7577 // the case where LHS is a scalar. 7578 if (LHSType->isScalarType()) { 7579 const VectorType *VecType = RHSType->getAs<VectorType>(); 7580 if (VecType && VecType->getNumElements() == 1 && 7581 isLaxVectorConversion(RHSType, LHSType)) { 7582 ExprResult *VecExpr = &RHS; 7583 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7584 Kind = CK_BitCast; 7585 return Compatible; 7586 } 7587 } 7588 7589 return Incompatible; 7590 } 7591 7592 // Diagnose attempts to convert between __float128 and long double where 7593 // such conversions currently can't be handled. 7594 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7595 return Incompatible; 7596 7597 // Arithmetic conversions. 7598 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7599 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7600 if (ConvertRHS) 7601 Kind = PrepareScalarCast(RHS, LHSType); 7602 return Compatible; 7603 } 7604 7605 // Conversions to normal pointers. 7606 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7607 // U* -> T* 7608 if (isa<PointerType>(RHSType)) { 7609 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7610 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7611 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7612 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7613 } 7614 7615 // int -> T* 7616 if (RHSType->isIntegerType()) { 7617 Kind = CK_IntegralToPointer; // FIXME: null? 7618 return IntToPointer; 7619 } 7620 7621 // C pointers are not compatible with ObjC object pointers, 7622 // with two exceptions: 7623 if (isa<ObjCObjectPointerType>(RHSType)) { 7624 // - conversions to void* 7625 if (LHSPointer->getPointeeType()->isVoidType()) { 7626 Kind = CK_BitCast; 7627 return Compatible; 7628 } 7629 7630 // - conversions from 'Class' to the redefinition type 7631 if (RHSType->isObjCClassType() && 7632 Context.hasSameType(LHSType, 7633 Context.getObjCClassRedefinitionType())) { 7634 Kind = CK_BitCast; 7635 return Compatible; 7636 } 7637 7638 Kind = CK_BitCast; 7639 return IncompatiblePointer; 7640 } 7641 7642 // U^ -> void* 7643 if (RHSType->getAs<BlockPointerType>()) { 7644 if (LHSPointer->getPointeeType()->isVoidType()) { 7645 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7646 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7647 ->getPointeeType() 7648 .getAddressSpace(); 7649 Kind = 7650 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7651 return Compatible; 7652 } 7653 } 7654 7655 return Incompatible; 7656 } 7657 7658 // Conversions to block pointers. 7659 if (isa<BlockPointerType>(LHSType)) { 7660 // U^ -> T^ 7661 if (RHSType->isBlockPointerType()) { 7662 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>() 7663 ->getPointeeType() 7664 .getAddressSpace(); 7665 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7666 ->getPointeeType() 7667 .getAddressSpace(); 7668 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7669 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7670 } 7671 7672 // int or null -> T^ 7673 if (RHSType->isIntegerType()) { 7674 Kind = CK_IntegralToPointer; // FIXME: null 7675 return IntToBlockPointer; 7676 } 7677 7678 // id -> T^ 7679 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7680 Kind = CK_AnyPointerToBlockPointerCast; 7681 return Compatible; 7682 } 7683 7684 // void* -> T^ 7685 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7686 if (RHSPT->getPointeeType()->isVoidType()) { 7687 Kind = CK_AnyPointerToBlockPointerCast; 7688 return Compatible; 7689 } 7690 7691 return Incompatible; 7692 } 7693 7694 // Conversions to Objective-C pointers. 7695 if (isa<ObjCObjectPointerType>(LHSType)) { 7696 // A* -> B* 7697 if (RHSType->isObjCObjectPointerType()) { 7698 Kind = CK_BitCast; 7699 Sema::AssignConvertType result = 7700 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7701 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7702 result == Compatible && 7703 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7704 result = IncompatibleObjCWeakRef; 7705 return result; 7706 } 7707 7708 // int or null -> A* 7709 if (RHSType->isIntegerType()) { 7710 Kind = CK_IntegralToPointer; // FIXME: null 7711 return IntToPointer; 7712 } 7713 7714 // In general, C pointers are not compatible with ObjC object pointers, 7715 // with two exceptions: 7716 if (isa<PointerType>(RHSType)) { 7717 Kind = CK_CPointerToObjCPointerCast; 7718 7719 // - conversions from 'void*' 7720 if (RHSType->isVoidPointerType()) { 7721 return Compatible; 7722 } 7723 7724 // - conversions to 'Class' from its redefinition type 7725 if (LHSType->isObjCClassType() && 7726 Context.hasSameType(RHSType, 7727 Context.getObjCClassRedefinitionType())) { 7728 return Compatible; 7729 } 7730 7731 return IncompatiblePointer; 7732 } 7733 7734 // Only under strict condition T^ is compatible with an Objective-C pointer. 7735 if (RHSType->isBlockPointerType() && 7736 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7737 if (ConvertRHS) 7738 maybeExtendBlockObject(RHS); 7739 Kind = CK_BlockPointerToObjCPointerCast; 7740 return Compatible; 7741 } 7742 7743 return Incompatible; 7744 } 7745 7746 // Conversions from pointers that are not covered by the above. 7747 if (isa<PointerType>(RHSType)) { 7748 // T* -> _Bool 7749 if (LHSType == Context.BoolTy) { 7750 Kind = CK_PointerToBoolean; 7751 return Compatible; 7752 } 7753 7754 // T* -> int 7755 if (LHSType->isIntegerType()) { 7756 Kind = CK_PointerToIntegral; 7757 return PointerToInt; 7758 } 7759 7760 return Incompatible; 7761 } 7762 7763 // Conversions from Objective-C pointers that are not covered by the above. 7764 if (isa<ObjCObjectPointerType>(RHSType)) { 7765 // T* -> _Bool 7766 if (LHSType == Context.BoolTy) { 7767 Kind = CK_PointerToBoolean; 7768 return Compatible; 7769 } 7770 7771 // T* -> int 7772 if (LHSType->isIntegerType()) { 7773 Kind = CK_PointerToIntegral; 7774 return PointerToInt; 7775 } 7776 7777 return Incompatible; 7778 } 7779 7780 // struct A -> struct B 7781 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7782 if (Context.typesAreCompatible(LHSType, RHSType)) { 7783 Kind = CK_NoOp; 7784 return Compatible; 7785 } 7786 } 7787 7788 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7789 Kind = CK_IntToOCLSampler; 7790 return Compatible; 7791 } 7792 7793 return Incompatible; 7794 } 7795 7796 /// \brief Constructs a transparent union from an expression that is 7797 /// used to initialize the transparent union. 7798 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7799 ExprResult &EResult, QualType UnionType, 7800 FieldDecl *Field) { 7801 // Build an initializer list that designates the appropriate member 7802 // of the transparent union. 7803 Expr *E = EResult.get(); 7804 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7805 E, SourceLocation()); 7806 Initializer->setType(UnionType); 7807 Initializer->setInitializedFieldInUnion(Field); 7808 7809 // Build a compound literal constructing a value of the transparent 7810 // union type from this initializer list. 7811 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7812 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7813 VK_RValue, Initializer, false); 7814 } 7815 7816 Sema::AssignConvertType 7817 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7818 ExprResult &RHS) { 7819 QualType RHSType = RHS.get()->getType(); 7820 7821 // If the ArgType is a Union type, we want to handle a potential 7822 // transparent_union GCC extension. 7823 const RecordType *UT = ArgType->getAsUnionType(); 7824 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7825 return Incompatible; 7826 7827 // The field to initialize within the transparent union. 7828 RecordDecl *UD = UT->getDecl(); 7829 FieldDecl *InitField = nullptr; 7830 // It's compatible if the expression matches any of the fields. 7831 for (auto *it : UD->fields()) { 7832 if (it->getType()->isPointerType()) { 7833 // If the transparent union contains a pointer type, we allow: 7834 // 1) void pointer 7835 // 2) null pointer constant 7836 if (RHSType->isPointerType()) 7837 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7838 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7839 InitField = it; 7840 break; 7841 } 7842 7843 if (RHS.get()->isNullPointerConstant(Context, 7844 Expr::NPC_ValueDependentIsNull)) { 7845 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7846 CK_NullToPointer); 7847 InitField = it; 7848 break; 7849 } 7850 } 7851 7852 CastKind Kind = CK_Invalid; 7853 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7854 == Compatible) { 7855 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7856 InitField = it; 7857 break; 7858 } 7859 } 7860 7861 if (!InitField) 7862 return Incompatible; 7863 7864 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7865 return Compatible; 7866 } 7867 7868 Sema::AssignConvertType 7869 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7870 bool Diagnose, 7871 bool DiagnoseCFAudited, 7872 bool ConvertRHS) { 7873 // We need to be able to tell the caller whether we diagnosed a problem, if 7874 // they ask us to issue diagnostics. 7875 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7876 7877 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7878 // we can't avoid *all* modifications at the moment, so we need some somewhere 7879 // to put the updated value. 7880 ExprResult LocalRHS = CallerRHS; 7881 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7882 7883 if (getLangOpts().CPlusPlus) { 7884 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7885 // C++ 5.17p3: If the left operand is not of class type, the 7886 // expression is implicitly converted (C++ 4) to the 7887 // cv-unqualified type of the left operand. 7888 QualType RHSType = RHS.get()->getType(); 7889 if (Diagnose) { 7890 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7891 AA_Assigning); 7892 } else { 7893 ImplicitConversionSequence ICS = 7894 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7895 /*SuppressUserConversions=*/false, 7896 /*AllowExplicit=*/false, 7897 /*InOverloadResolution=*/false, 7898 /*CStyle=*/false, 7899 /*AllowObjCWritebackConversion=*/false); 7900 if (ICS.isFailure()) 7901 return Incompatible; 7902 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7903 ICS, AA_Assigning); 7904 } 7905 if (RHS.isInvalid()) 7906 return Incompatible; 7907 Sema::AssignConvertType result = Compatible; 7908 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7909 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7910 result = IncompatibleObjCWeakRef; 7911 return result; 7912 } 7913 7914 // FIXME: Currently, we fall through and treat C++ classes like C 7915 // structures. 7916 // FIXME: We also fall through for atomics; not sure what should 7917 // happen there, though. 7918 } else if (RHS.get()->getType() == Context.OverloadTy) { 7919 // As a set of extensions to C, we support overloading on functions. These 7920 // functions need to be resolved here. 7921 DeclAccessPair DAP; 7922 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7923 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7924 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7925 else 7926 return Incompatible; 7927 } 7928 7929 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7930 // a null pointer constant. 7931 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7932 LHSType->isBlockPointerType()) && 7933 RHS.get()->isNullPointerConstant(Context, 7934 Expr::NPC_ValueDependentIsNull)) { 7935 if (Diagnose || ConvertRHS) { 7936 CastKind Kind; 7937 CXXCastPath Path; 7938 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7939 /*IgnoreBaseAccess=*/false, Diagnose); 7940 if (ConvertRHS) 7941 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7942 } 7943 return Compatible; 7944 } 7945 7946 // This check seems unnatural, however it is necessary to ensure the proper 7947 // conversion of functions/arrays. If the conversion were done for all 7948 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7949 // expressions that suppress this implicit conversion (&, sizeof). 7950 // 7951 // Suppress this for references: C++ 8.5.3p5. 7952 if (!LHSType->isReferenceType()) { 7953 // FIXME: We potentially allocate here even if ConvertRHS is false. 7954 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7955 if (RHS.isInvalid()) 7956 return Incompatible; 7957 } 7958 7959 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7960 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7961 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7962 if (PDecl && !PDecl->hasDefinition()) { 7963 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7964 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7965 } 7966 } 7967 7968 CastKind Kind = CK_Invalid; 7969 Sema::AssignConvertType result = 7970 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7971 7972 // C99 6.5.16.1p2: The value of the right operand is converted to the 7973 // type of the assignment expression. 7974 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7975 // so that we can use references in built-in functions even in C. 7976 // The getNonReferenceType() call makes sure that the resulting expression 7977 // does not have reference type. 7978 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7979 QualType Ty = LHSType.getNonLValueExprType(Context); 7980 Expr *E = RHS.get(); 7981 7982 // Check for various Objective-C errors. If we are not reporting 7983 // diagnostics and just checking for errors, e.g., during overload 7984 // resolution, return Incompatible to indicate the failure. 7985 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7986 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7987 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7988 if (!Diagnose) 7989 return Incompatible; 7990 } 7991 if (getLangOpts().ObjC1 && 7992 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7993 E->getType(), E, Diagnose) || 7994 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7995 if (!Diagnose) 7996 return Incompatible; 7997 // Replace the expression with a corrected version and continue so we 7998 // can find further errors. 7999 RHS = E; 8000 return Compatible; 8001 } 8002 8003 if (ConvertRHS) 8004 RHS = ImpCastExprToType(E, Ty, Kind); 8005 } 8006 return result; 8007 } 8008 8009 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8010 ExprResult &RHS) { 8011 Diag(Loc, diag::err_typecheck_invalid_operands) 8012 << LHS.get()->getType() << RHS.get()->getType() 8013 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8014 return QualType(); 8015 } 8016 8017 /// Try to convert a value of non-vector type to a vector type by converting 8018 /// the type to the element type of the vector and then performing a splat. 8019 /// If the language is OpenCL, we only use conversions that promote scalar 8020 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8021 /// for float->int. 8022 /// 8023 /// \param scalar - if non-null, actually perform the conversions 8024 /// \return true if the operation fails (but without diagnosing the failure) 8025 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8026 QualType scalarTy, 8027 QualType vectorEltTy, 8028 QualType vectorTy) { 8029 // The conversion to apply to the scalar before splatting it, 8030 // if necessary. 8031 CastKind scalarCast = CK_Invalid; 8032 8033 if (vectorEltTy->isIntegralType(S.Context)) { 8034 if (!scalarTy->isIntegralType(S.Context)) 8035 return true; 8036 if (S.getLangOpts().OpenCL && 8037 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 8038 return true; 8039 scalarCast = CK_IntegralCast; 8040 } else if (vectorEltTy->isRealFloatingType()) { 8041 if (scalarTy->isRealFloatingType()) { 8042 if (S.getLangOpts().OpenCL && 8043 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 8044 return true; 8045 scalarCast = CK_FloatingCast; 8046 } 8047 else if (scalarTy->isIntegralType(S.Context)) 8048 scalarCast = CK_IntegralToFloating; 8049 else 8050 return true; 8051 } else { 8052 return true; 8053 } 8054 8055 // Adjust scalar if desired. 8056 if (scalar) { 8057 if (scalarCast != CK_Invalid) 8058 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8059 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8060 } 8061 return false; 8062 } 8063 8064 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8065 SourceLocation Loc, bool IsCompAssign, 8066 bool AllowBothBool, 8067 bool AllowBoolConversions) { 8068 if (!IsCompAssign) { 8069 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8070 if (LHS.isInvalid()) 8071 return QualType(); 8072 } 8073 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8074 if (RHS.isInvalid()) 8075 return QualType(); 8076 8077 // For conversion purposes, we ignore any qualifiers. 8078 // For example, "const float" and "float" are equivalent. 8079 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8080 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8081 8082 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8083 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8084 assert(LHSVecType || RHSVecType); 8085 8086 // AltiVec-style "vector bool op vector bool" combinations are allowed 8087 // for some operators but not others. 8088 if (!AllowBothBool && 8089 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8090 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8091 return InvalidOperands(Loc, LHS, RHS); 8092 8093 // If the vector types are identical, return. 8094 if (Context.hasSameType(LHSType, RHSType)) 8095 return LHSType; 8096 8097 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8098 if (LHSVecType && RHSVecType && 8099 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8100 if (isa<ExtVectorType>(LHSVecType)) { 8101 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8102 return LHSType; 8103 } 8104 8105 if (!IsCompAssign) 8106 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8107 return RHSType; 8108 } 8109 8110 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8111 // can be mixed, with the result being the non-bool type. The non-bool 8112 // operand must have integer element type. 8113 if (AllowBoolConversions && LHSVecType && RHSVecType && 8114 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8115 (Context.getTypeSize(LHSVecType->getElementType()) == 8116 Context.getTypeSize(RHSVecType->getElementType()))) { 8117 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8118 LHSVecType->getElementType()->isIntegerType() && 8119 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8120 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8121 return LHSType; 8122 } 8123 if (!IsCompAssign && 8124 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8125 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8126 RHSVecType->getElementType()->isIntegerType()) { 8127 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8128 return RHSType; 8129 } 8130 } 8131 8132 // If there's an ext-vector type and a scalar, try to convert the scalar to 8133 // the vector element type and splat. 8134 // FIXME: this should also work for regular vector types as supported in GCC. 8135 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8136 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8137 LHSVecType->getElementType(), LHSType)) 8138 return LHSType; 8139 } 8140 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8141 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8142 LHSType, RHSVecType->getElementType(), 8143 RHSType)) 8144 return RHSType; 8145 } 8146 8147 // FIXME: The code below also handles conversion between vectors and 8148 // non-scalars, we should break this down into fine grained specific checks 8149 // and emit proper diagnostics. 8150 QualType VecType = LHSVecType ? LHSType : RHSType; 8151 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8152 QualType OtherType = LHSVecType ? RHSType : LHSType; 8153 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8154 if (isLaxVectorConversion(OtherType, VecType)) { 8155 // If we're allowing lax vector conversions, only the total (data) size 8156 // needs to be the same. For non compound assignment, if one of the types is 8157 // scalar, the result is always the vector type. 8158 if (!IsCompAssign) { 8159 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8160 return VecType; 8161 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8162 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8163 // type. Note that this is already done by non-compound assignments in 8164 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8165 // <1 x T> -> T. The result is also a vector type. 8166 } else if (OtherType->isExtVectorType() || 8167 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8168 ExprResult *RHSExpr = &RHS; 8169 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8170 return VecType; 8171 } 8172 } 8173 8174 // Okay, the expression is invalid. 8175 8176 // If there's a non-vector, non-real operand, diagnose that. 8177 if ((!RHSVecType && !RHSType->isRealType()) || 8178 (!LHSVecType && !LHSType->isRealType())) { 8179 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8180 << LHSType << RHSType 8181 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8182 return QualType(); 8183 } 8184 8185 // OpenCL V1.1 6.2.6.p1: 8186 // If the operands are of more than one vector type, then an error shall 8187 // occur. Implicit conversions between vector types are not permitted, per 8188 // section 6.2.1. 8189 if (getLangOpts().OpenCL && 8190 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8191 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8192 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8193 << RHSType; 8194 return QualType(); 8195 } 8196 8197 // Otherwise, use the generic diagnostic. 8198 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8199 << LHSType << RHSType 8200 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8201 return QualType(); 8202 } 8203 8204 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8205 // expression. These are mainly cases where the null pointer is used as an 8206 // integer instead of a pointer. 8207 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8208 SourceLocation Loc, bool IsCompare) { 8209 // The canonical way to check for a GNU null is with isNullPointerConstant, 8210 // but we use a bit of a hack here for speed; this is a relatively 8211 // hot path, and isNullPointerConstant is slow. 8212 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8213 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8214 8215 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8216 8217 // Avoid analyzing cases where the result will either be invalid (and 8218 // diagnosed as such) or entirely valid and not something to warn about. 8219 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8220 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8221 return; 8222 8223 // Comparison operations would not make sense with a null pointer no matter 8224 // what the other expression is. 8225 if (!IsCompare) { 8226 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8227 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8228 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8229 return; 8230 } 8231 8232 // The rest of the operations only make sense with a null pointer 8233 // if the other expression is a pointer. 8234 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8235 NonNullType->canDecayToPointerType()) 8236 return; 8237 8238 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8239 << LHSNull /* LHS is NULL */ << NonNullType 8240 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8241 } 8242 8243 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8244 ExprResult &RHS, 8245 SourceLocation Loc, bool IsDiv) { 8246 // Check for division/remainder by zero. 8247 llvm::APSInt RHSValue; 8248 if (!RHS.get()->isValueDependent() && 8249 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8250 S.DiagRuntimeBehavior(Loc, RHS.get(), 8251 S.PDiag(diag::warn_remainder_division_by_zero) 8252 << IsDiv << RHS.get()->getSourceRange()); 8253 } 8254 8255 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8256 SourceLocation Loc, 8257 bool IsCompAssign, bool IsDiv) { 8258 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8259 8260 if (LHS.get()->getType()->isVectorType() || 8261 RHS.get()->getType()->isVectorType()) 8262 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8263 /*AllowBothBool*/getLangOpts().AltiVec, 8264 /*AllowBoolConversions*/false); 8265 8266 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8267 if (LHS.isInvalid() || RHS.isInvalid()) 8268 return QualType(); 8269 8270 8271 if (compType.isNull() || !compType->isArithmeticType()) 8272 return InvalidOperands(Loc, LHS, RHS); 8273 if (IsDiv) 8274 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8275 return compType; 8276 } 8277 8278 QualType Sema::CheckRemainderOperands( 8279 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8280 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8281 8282 if (LHS.get()->getType()->isVectorType() || 8283 RHS.get()->getType()->isVectorType()) { 8284 if (LHS.get()->getType()->hasIntegerRepresentation() && 8285 RHS.get()->getType()->hasIntegerRepresentation()) 8286 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8287 /*AllowBothBool*/getLangOpts().AltiVec, 8288 /*AllowBoolConversions*/false); 8289 return InvalidOperands(Loc, LHS, RHS); 8290 } 8291 8292 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8293 if (LHS.isInvalid() || RHS.isInvalid()) 8294 return QualType(); 8295 8296 if (compType.isNull() || !compType->isIntegerType()) 8297 return InvalidOperands(Loc, LHS, RHS); 8298 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8299 return compType; 8300 } 8301 8302 /// \brief Diagnose invalid arithmetic on two void pointers. 8303 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8304 Expr *LHSExpr, Expr *RHSExpr) { 8305 S.Diag(Loc, S.getLangOpts().CPlusPlus 8306 ? diag::err_typecheck_pointer_arith_void_type 8307 : diag::ext_gnu_void_ptr) 8308 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8309 << RHSExpr->getSourceRange(); 8310 } 8311 8312 /// \brief Diagnose invalid arithmetic on a void pointer. 8313 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8314 Expr *Pointer) { 8315 S.Diag(Loc, S.getLangOpts().CPlusPlus 8316 ? diag::err_typecheck_pointer_arith_void_type 8317 : diag::ext_gnu_void_ptr) 8318 << 0 /* one pointer */ << Pointer->getSourceRange(); 8319 } 8320 8321 /// \brief Diagnose invalid arithmetic on two function pointers. 8322 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8323 Expr *LHS, Expr *RHS) { 8324 assert(LHS->getType()->isAnyPointerType()); 8325 assert(RHS->getType()->isAnyPointerType()); 8326 S.Diag(Loc, S.getLangOpts().CPlusPlus 8327 ? diag::err_typecheck_pointer_arith_function_type 8328 : diag::ext_gnu_ptr_func_arith) 8329 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8330 // We only show the second type if it differs from the first. 8331 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8332 RHS->getType()) 8333 << RHS->getType()->getPointeeType() 8334 << LHS->getSourceRange() << RHS->getSourceRange(); 8335 } 8336 8337 /// \brief Diagnose invalid arithmetic on a function pointer. 8338 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8339 Expr *Pointer) { 8340 assert(Pointer->getType()->isAnyPointerType()); 8341 S.Diag(Loc, S.getLangOpts().CPlusPlus 8342 ? diag::err_typecheck_pointer_arith_function_type 8343 : diag::ext_gnu_ptr_func_arith) 8344 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8345 << 0 /* one pointer, so only one type */ 8346 << Pointer->getSourceRange(); 8347 } 8348 8349 /// \brief Emit error if Operand is incomplete pointer type 8350 /// 8351 /// \returns True if pointer has incomplete type 8352 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8353 Expr *Operand) { 8354 QualType ResType = Operand->getType(); 8355 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8356 ResType = ResAtomicType->getValueType(); 8357 8358 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8359 QualType PointeeTy = ResType->getPointeeType(); 8360 return S.RequireCompleteType(Loc, PointeeTy, 8361 diag::err_typecheck_arithmetic_incomplete_type, 8362 PointeeTy, Operand->getSourceRange()); 8363 } 8364 8365 /// \brief Check the validity of an arithmetic pointer operand. 8366 /// 8367 /// If the operand has pointer type, this code will check for pointer types 8368 /// which are invalid in arithmetic operations. These will be diagnosed 8369 /// appropriately, including whether or not the use is supported as an 8370 /// extension. 8371 /// 8372 /// \returns True when the operand is valid to use (even if as an extension). 8373 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8374 Expr *Operand) { 8375 QualType ResType = Operand->getType(); 8376 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8377 ResType = ResAtomicType->getValueType(); 8378 8379 if (!ResType->isAnyPointerType()) return true; 8380 8381 QualType PointeeTy = ResType->getPointeeType(); 8382 if (PointeeTy->isVoidType()) { 8383 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8384 return !S.getLangOpts().CPlusPlus; 8385 } 8386 if (PointeeTy->isFunctionType()) { 8387 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8388 return !S.getLangOpts().CPlusPlus; 8389 } 8390 8391 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8392 8393 return true; 8394 } 8395 8396 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8397 /// operands. 8398 /// 8399 /// This routine will diagnose any invalid arithmetic on pointer operands much 8400 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8401 /// for emitting a single diagnostic even for operations where both LHS and RHS 8402 /// are (potentially problematic) pointers. 8403 /// 8404 /// \returns True when the operand is valid to use (even if as an extension). 8405 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8406 Expr *LHSExpr, Expr *RHSExpr) { 8407 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8408 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8409 if (!isLHSPointer && !isRHSPointer) return true; 8410 8411 QualType LHSPointeeTy, RHSPointeeTy; 8412 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8413 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8414 8415 // if both are pointers check if operation is valid wrt address spaces 8416 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8417 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8418 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8419 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8420 S.Diag(Loc, 8421 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8422 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8423 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8424 return false; 8425 } 8426 } 8427 8428 // Check for arithmetic on pointers to incomplete types. 8429 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8430 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8431 if (isLHSVoidPtr || isRHSVoidPtr) { 8432 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8433 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8434 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8435 8436 return !S.getLangOpts().CPlusPlus; 8437 } 8438 8439 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8440 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8441 if (isLHSFuncPtr || isRHSFuncPtr) { 8442 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8443 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8444 RHSExpr); 8445 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8446 8447 return !S.getLangOpts().CPlusPlus; 8448 } 8449 8450 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8451 return false; 8452 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8453 return false; 8454 8455 return true; 8456 } 8457 8458 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8459 /// literal. 8460 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8461 Expr *LHSExpr, Expr *RHSExpr) { 8462 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8463 Expr* IndexExpr = RHSExpr; 8464 if (!StrExpr) { 8465 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8466 IndexExpr = LHSExpr; 8467 } 8468 8469 bool IsStringPlusInt = StrExpr && 8470 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8471 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8472 return; 8473 8474 llvm::APSInt index; 8475 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8476 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8477 if (index.isNonNegative() && 8478 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8479 index.isUnsigned())) 8480 return; 8481 } 8482 8483 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8484 Self.Diag(OpLoc, diag::warn_string_plus_int) 8485 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8486 8487 // Only print a fixit for "str" + int, not for int + "str". 8488 if (IndexExpr == RHSExpr) { 8489 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8490 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8491 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8492 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8493 << FixItHint::CreateInsertion(EndLoc, "]"); 8494 } else 8495 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8496 } 8497 8498 /// \brief Emit a warning when adding a char literal to a string. 8499 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8500 Expr *LHSExpr, Expr *RHSExpr) { 8501 const Expr *StringRefExpr = LHSExpr; 8502 const CharacterLiteral *CharExpr = 8503 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8504 8505 if (!CharExpr) { 8506 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8507 StringRefExpr = RHSExpr; 8508 } 8509 8510 if (!CharExpr || !StringRefExpr) 8511 return; 8512 8513 const QualType StringType = StringRefExpr->getType(); 8514 8515 // Return if not a PointerType. 8516 if (!StringType->isAnyPointerType()) 8517 return; 8518 8519 // Return if not a CharacterType. 8520 if (!StringType->getPointeeType()->isAnyCharacterType()) 8521 return; 8522 8523 ASTContext &Ctx = Self.getASTContext(); 8524 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8525 8526 const QualType CharType = CharExpr->getType(); 8527 if (!CharType->isAnyCharacterType() && 8528 CharType->isIntegerType() && 8529 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8530 Self.Diag(OpLoc, diag::warn_string_plus_char) 8531 << DiagRange << Ctx.CharTy; 8532 } else { 8533 Self.Diag(OpLoc, diag::warn_string_plus_char) 8534 << DiagRange << CharExpr->getType(); 8535 } 8536 8537 // Only print a fixit for str + char, not for char + str. 8538 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8539 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8540 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8541 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8542 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8543 << FixItHint::CreateInsertion(EndLoc, "]"); 8544 } else { 8545 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8546 } 8547 } 8548 8549 /// \brief Emit error when two pointers are incompatible. 8550 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8551 Expr *LHSExpr, Expr *RHSExpr) { 8552 assert(LHSExpr->getType()->isAnyPointerType()); 8553 assert(RHSExpr->getType()->isAnyPointerType()); 8554 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8555 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8556 << RHSExpr->getSourceRange(); 8557 } 8558 8559 // C99 6.5.6 8560 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8561 SourceLocation Loc, BinaryOperatorKind Opc, 8562 QualType* CompLHSTy) { 8563 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8564 8565 if (LHS.get()->getType()->isVectorType() || 8566 RHS.get()->getType()->isVectorType()) { 8567 QualType compType = CheckVectorOperands( 8568 LHS, RHS, Loc, CompLHSTy, 8569 /*AllowBothBool*/getLangOpts().AltiVec, 8570 /*AllowBoolConversions*/getLangOpts().ZVector); 8571 if (CompLHSTy) *CompLHSTy = compType; 8572 return compType; 8573 } 8574 8575 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8576 if (LHS.isInvalid() || RHS.isInvalid()) 8577 return QualType(); 8578 8579 // Diagnose "string literal" '+' int and string '+' "char literal". 8580 if (Opc == BO_Add) { 8581 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8582 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8583 } 8584 8585 // handle the common case first (both operands are arithmetic). 8586 if (!compType.isNull() && compType->isArithmeticType()) { 8587 if (CompLHSTy) *CompLHSTy = compType; 8588 return compType; 8589 } 8590 8591 // Type-checking. Ultimately the pointer's going to be in PExp; 8592 // note that we bias towards the LHS being the pointer. 8593 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8594 8595 bool isObjCPointer; 8596 if (PExp->getType()->isPointerType()) { 8597 isObjCPointer = false; 8598 } else if (PExp->getType()->isObjCObjectPointerType()) { 8599 isObjCPointer = true; 8600 } else { 8601 std::swap(PExp, IExp); 8602 if (PExp->getType()->isPointerType()) { 8603 isObjCPointer = false; 8604 } else if (PExp->getType()->isObjCObjectPointerType()) { 8605 isObjCPointer = true; 8606 } else { 8607 return InvalidOperands(Loc, LHS, RHS); 8608 } 8609 } 8610 assert(PExp->getType()->isAnyPointerType()); 8611 8612 if (!IExp->getType()->isIntegerType()) 8613 return InvalidOperands(Loc, LHS, RHS); 8614 8615 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8616 return QualType(); 8617 8618 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8619 return QualType(); 8620 8621 // Check array bounds for pointer arithemtic 8622 CheckArrayAccess(PExp, IExp); 8623 8624 if (CompLHSTy) { 8625 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8626 if (LHSTy.isNull()) { 8627 LHSTy = LHS.get()->getType(); 8628 if (LHSTy->isPromotableIntegerType()) 8629 LHSTy = Context.getPromotedIntegerType(LHSTy); 8630 } 8631 *CompLHSTy = LHSTy; 8632 } 8633 8634 return PExp->getType(); 8635 } 8636 8637 // C99 6.5.6 8638 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8639 SourceLocation Loc, 8640 QualType* CompLHSTy) { 8641 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8642 8643 if (LHS.get()->getType()->isVectorType() || 8644 RHS.get()->getType()->isVectorType()) { 8645 QualType compType = CheckVectorOperands( 8646 LHS, RHS, Loc, CompLHSTy, 8647 /*AllowBothBool*/getLangOpts().AltiVec, 8648 /*AllowBoolConversions*/getLangOpts().ZVector); 8649 if (CompLHSTy) *CompLHSTy = compType; 8650 return compType; 8651 } 8652 8653 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8654 if (LHS.isInvalid() || RHS.isInvalid()) 8655 return QualType(); 8656 8657 // Enforce type constraints: C99 6.5.6p3. 8658 8659 // Handle the common case first (both operands are arithmetic). 8660 if (!compType.isNull() && compType->isArithmeticType()) { 8661 if (CompLHSTy) *CompLHSTy = compType; 8662 return compType; 8663 } 8664 8665 // Either ptr - int or ptr - ptr. 8666 if (LHS.get()->getType()->isAnyPointerType()) { 8667 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8668 8669 // Diagnose bad cases where we step over interface counts. 8670 if (LHS.get()->getType()->isObjCObjectPointerType() && 8671 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8672 return QualType(); 8673 8674 // The result type of a pointer-int computation is the pointer type. 8675 if (RHS.get()->getType()->isIntegerType()) { 8676 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8677 return QualType(); 8678 8679 // Check array bounds for pointer arithemtic 8680 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8681 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8682 8683 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8684 return LHS.get()->getType(); 8685 } 8686 8687 // Handle pointer-pointer subtractions. 8688 if (const PointerType *RHSPTy 8689 = RHS.get()->getType()->getAs<PointerType>()) { 8690 QualType rpointee = RHSPTy->getPointeeType(); 8691 8692 if (getLangOpts().CPlusPlus) { 8693 // Pointee types must be the same: C++ [expr.add] 8694 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8695 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8696 } 8697 } else { 8698 // Pointee types must be compatible C99 6.5.6p3 8699 if (!Context.typesAreCompatible( 8700 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8701 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8702 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8703 return QualType(); 8704 } 8705 } 8706 8707 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8708 LHS.get(), RHS.get())) 8709 return QualType(); 8710 8711 // The pointee type may have zero size. As an extension, a structure or 8712 // union may have zero size or an array may have zero length. In this 8713 // case subtraction does not make sense. 8714 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8715 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8716 if (ElementSize.isZero()) { 8717 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8718 << rpointee.getUnqualifiedType() 8719 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8720 } 8721 } 8722 8723 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8724 return Context.getPointerDiffType(); 8725 } 8726 } 8727 8728 return InvalidOperands(Loc, LHS, RHS); 8729 } 8730 8731 static bool isScopedEnumerationType(QualType T) { 8732 if (const EnumType *ET = T->getAs<EnumType>()) 8733 return ET->getDecl()->isScoped(); 8734 return false; 8735 } 8736 8737 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8738 SourceLocation Loc, BinaryOperatorKind Opc, 8739 QualType LHSType) { 8740 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8741 // so skip remaining warnings as we don't want to modify values within Sema. 8742 if (S.getLangOpts().OpenCL) 8743 return; 8744 8745 llvm::APSInt Right; 8746 // Check right/shifter operand 8747 if (RHS.get()->isValueDependent() || 8748 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8749 return; 8750 8751 if (Right.isNegative()) { 8752 S.DiagRuntimeBehavior(Loc, RHS.get(), 8753 S.PDiag(diag::warn_shift_negative) 8754 << RHS.get()->getSourceRange()); 8755 return; 8756 } 8757 llvm::APInt LeftBits(Right.getBitWidth(), 8758 S.Context.getTypeSize(LHS.get()->getType())); 8759 if (Right.uge(LeftBits)) { 8760 S.DiagRuntimeBehavior(Loc, RHS.get(), 8761 S.PDiag(diag::warn_shift_gt_typewidth) 8762 << RHS.get()->getSourceRange()); 8763 return; 8764 } 8765 if (Opc != BO_Shl) 8766 return; 8767 8768 // When left shifting an ICE which is signed, we can check for overflow which 8769 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8770 // integers have defined behavior modulo one more than the maximum value 8771 // representable in the result type, so never warn for those. 8772 llvm::APSInt Left; 8773 if (LHS.get()->isValueDependent() || 8774 LHSType->hasUnsignedIntegerRepresentation() || 8775 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8776 return; 8777 8778 // If LHS does not have a signed type and non-negative value 8779 // then, the behavior is undefined. Warn about it. 8780 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8781 S.DiagRuntimeBehavior(Loc, LHS.get(), 8782 S.PDiag(diag::warn_shift_lhs_negative) 8783 << LHS.get()->getSourceRange()); 8784 return; 8785 } 8786 8787 llvm::APInt ResultBits = 8788 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8789 if (LeftBits.uge(ResultBits)) 8790 return; 8791 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8792 Result = Result.shl(Right); 8793 8794 // Print the bit representation of the signed integer as an unsigned 8795 // hexadecimal number. 8796 SmallString<40> HexResult; 8797 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8798 8799 // If we are only missing a sign bit, this is less likely to result in actual 8800 // bugs -- if the result is cast back to an unsigned type, it will have the 8801 // expected value. Thus we place this behind a different warning that can be 8802 // turned off separately if needed. 8803 if (LeftBits == ResultBits - 1) { 8804 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8805 << HexResult << LHSType 8806 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8807 return; 8808 } 8809 8810 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8811 << HexResult.str() << Result.getMinSignedBits() << LHSType 8812 << Left.getBitWidth() << LHS.get()->getSourceRange() 8813 << RHS.get()->getSourceRange(); 8814 } 8815 8816 /// \brief Return the resulting type when a vector is shifted 8817 /// by a scalar or vector shift amount. 8818 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8819 SourceLocation Loc, bool IsCompAssign) { 8820 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8821 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8822 !LHS.get()->getType()->isVectorType()) { 8823 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8824 << RHS.get()->getType() << LHS.get()->getType() 8825 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8826 return QualType(); 8827 } 8828 8829 if (!IsCompAssign) { 8830 LHS = S.UsualUnaryConversions(LHS.get()); 8831 if (LHS.isInvalid()) return QualType(); 8832 } 8833 8834 RHS = S.UsualUnaryConversions(RHS.get()); 8835 if (RHS.isInvalid()) return QualType(); 8836 8837 QualType LHSType = LHS.get()->getType(); 8838 // Note that LHS might be a scalar because the routine calls not only in 8839 // OpenCL case. 8840 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8841 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8842 8843 // Note that RHS might not be a vector. 8844 QualType RHSType = RHS.get()->getType(); 8845 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8846 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8847 8848 // The operands need to be integers. 8849 if (!LHSEleType->isIntegerType()) { 8850 S.Diag(Loc, diag::err_typecheck_expect_int) 8851 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8852 return QualType(); 8853 } 8854 8855 if (!RHSEleType->isIntegerType()) { 8856 S.Diag(Loc, diag::err_typecheck_expect_int) 8857 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8858 return QualType(); 8859 } 8860 8861 if (!LHSVecTy) { 8862 assert(RHSVecTy); 8863 if (IsCompAssign) 8864 return RHSType; 8865 if (LHSEleType != RHSEleType) { 8866 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8867 LHSEleType = RHSEleType; 8868 } 8869 QualType VecTy = 8870 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8871 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8872 LHSType = VecTy; 8873 } else if (RHSVecTy) { 8874 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8875 // are applied component-wise. So if RHS is a vector, then ensure 8876 // that the number of elements is the same as LHS... 8877 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8878 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8879 << LHS.get()->getType() << RHS.get()->getType() 8880 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8881 return QualType(); 8882 } 8883 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 8884 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 8885 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 8886 if (LHSBT != RHSBT && 8887 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 8888 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 8889 << LHS.get()->getType() << RHS.get()->getType() 8890 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8891 } 8892 } 8893 } else { 8894 // ...else expand RHS to match the number of elements in LHS. 8895 QualType VecTy = 8896 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8897 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8898 } 8899 8900 return LHSType; 8901 } 8902 8903 // C99 6.5.7 8904 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8905 SourceLocation Loc, BinaryOperatorKind Opc, 8906 bool IsCompAssign) { 8907 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8908 8909 // Vector shifts promote their scalar inputs to vector type. 8910 if (LHS.get()->getType()->isVectorType() || 8911 RHS.get()->getType()->isVectorType()) { 8912 if (LangOpts.ZVector) { 8913 // The shift operators for the z vector extensions work basically 8914 // like general shifts, except that neither the LHS nor the RHS is 8915 // allowed to be a "vector bool". 8916 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8917 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8918 return InvalidOperands(Loc, LHS, RHS); 8919 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8920 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8921 return InvalidOperands(Loc, LHS, RHS); 8922 } 8923 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8924 } 8925 8926 // Shifts don't perform usual arithmetic conversions, they just do integer 8927 // promotions on each operand. C99 6.5.7p3 8928 8929 // For the LHS, do usual unary conversions, but then reset them away 8930 // if this is a compound assignment. 8931 ExprResult OldLHS = LHS; 8932 LHS = UsualUnaryConversions(LHS.get()); 8933 if (LHS.isInvalid()) 8934 return QualType(); 8935 QualType LHSType = LHS.get()->getType(); 8936 if (IsCompAssign) LHS = OldLHS; 8937 8938 // The RHS is simpler. 8939 RHS = UsualUnaryConversions(RHS.get()); 8940 if (RHS.isInvalid()) 8941 return QualType(); 8942 QualType RHSType = RHS.get()->getType(); 8943 8944 // C99 6.5.7p2: Each of the operands shall have integer type. 8945 if (!LHSType->hasIntegerRepresentation() || 8946 !RHSType->hasIntegerRepresentation()) 8947 return InvalidOperands(Loc, LHS, RHS); 8948 8949 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8950 // hasIntegerRepresentation() above instead of this. 8951 if (isScopedEnumerationType(LHSType) || 8952 isScopedEnumerationType(RHSType)) { 8953 return InvalidOperands(Loc, LHS, RHS); 8954 } 8955 // Sanity-check shift operands 8956 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8957 8958 // "The type of the result is that of the promoted left operand." 8959 return LHSType; 8960 } 8961 8962 static bool IsWithinTemplateSpecialization(Decl *D) { 8963 if (DeclContext *DC = D->getDeclContext()) { 8964 if (isa<ClassTemplateSpecializationDecl>(DC)) 8965 return true; 8966 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8967 return FD->isFunctionTemplateSpecialization(); 8968 } 8969 return false; 8970 } 8971 8972 /// If two different enums are compared, raise a warning. 8973 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8974 Expr *RHS) { 8975 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8976 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8977 8978 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8979 if (!LHSEnumType) 8980 return; 8981 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8982 if (!RHSEnumType) 8983 return; 8984 8985 // Ignore anonymous enums. 8986 if (!LHSEnumType->getDecl()->getIdentifier()) 8987 return; 8988 if (!RHSEnumType->getDecl()->getIdentifier()) 8989 return; 8990 8991 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8992 return; 8993 8994 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8995 << LHSStrippedType << RHSStrippedType 8996 << LHS->getSourceRange() << RHS->getSourceRange(); 8997 } 8998 8999 /// \brief Diagnose bad pointer comparisons. 9000 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9001 ExprResult &LHS, ExprResult &RHS, 9002 bool IsError) { 9003 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9004 : diag::ext_typecheck_comparison_of_distinct_pointers) 9005 << LHS.get()->getType() << RHS.get()->getType() 9006 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9007 } 9008 9009 /// \brief Returns false if the pointers are converted to a composite type, 9010 /// true otherwise. 9011 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9012 ExprResult &LHS, ExprResult &RHS) { 9013 // C++ [expr.rel]p2: 9014 // [...] Pointer conversions (4.10) and qualification 9015 // conversions (4.4) are performed on pointer operands (or on 9016 // a pointer operand and a null pointer constant) to bring 9017 // them to their composite pointer type. [...] 9018 // 9019 // C++ [expr.eq]p1 uses the same notion for (in)equality 9020 // comparisons of pointers. 9021 9022 QualType LHSType = LHS.get()->getType(); 9023 QualType RHSType = RHS.get()->getType(); 9024 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9025 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9026 9027 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9028 if (T.isNull()) { 9029 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9030 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9031 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9032 else 9033 S.InvalidOperands(Loc, LHS, RHS); 9034 return true; 9035 } 9036 9037 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9038 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9039 return false; 9040 } 9041 9042 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9043 ExprResult &LHS, 9044 ExprResult &RHS, 9045 bool IsError) { 9046 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9047 : diag::ext_typecheck_comparison_of_fptr_to_void) 9048 << LHS.get()->getType() << RHS.get()->getType() 9049 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9050 } 9051 9052 static bool isObjCObjectLiteral(ExprResult &E) { 9053 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9054 case Stmt::ObjCArrayLiteralClass: 9055 case Stmt::ObjCDictionaryLiteralClass: 9056 case Stmt::ObjCStringLiteralClass: 9057 case Stmt::ObjCBoxedExprClass: 9058 return true; 9059 default: 9060 // Note that ObjCBoolLiteral is NOT an object literal! 9061 return false; 9062 } 9063 } 9064 9065 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9066 const ObjCObjectPointerType *Type = 9067 LHS->getType()->getAs<ObjCObjectPointerType>(); 9068 9069 // If this is not actually an Objective-C object, bail out. 9070 if (!Type) 9071 return false; 9072 9073 // Get the LHS object's interface type. 9074 QualType InterfaceType = Type->getPointeeType(); 9075 9076 // If the RHS isn't an Objective-C object, bail out. 9077 if (!RHS->getType()->isObjCObjectPointerType()) 9078 return false; 9079 9080 // Try to find the -isEqual: method. 9081 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9082 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9083 InterfaceType, 9084 /*instance=*/true); 9085 if (!Method) { 9086 if (Type->isObjCIdType()) { 9087 // For 'id', just check the global pool. 9088 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9089 /*receiverId=*/true); 9090 } else { 9091 // Check protocols. 9092 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9093 /*instance=*/true); 9094 } 9095 } 9096 9097 if (!Method) 9098 return false; 9099 9100 QualType T = Method->parameters()[0]->getType(); 9101 if (!T->isObjCObjectPointerType()) 9102 return false; 9103 9104 QualType R = Method->getReturnType(); 9105 if (!R->isScalarType()) 9106 return false; 9107 9108 return true; 9109 } 9110 9111 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9112 FromE = FromE->IgnoreParenImpCasts(); 9113 switch (FromE->getStmtClass()) { 9114 default: 9115 break; 9116 case Stmt::ObjCStringLiteralClass: 9117 // "string literal" 9118 return LK_String; 9119 case Stmt::ObjCArrayLiteralClass: 9120 // "array literal" 9121 return LK_Array; 9122 case Stmt::ObjCDictionaryLiteralClass: 9123 // "dictionary literal" 9124 return LK_Dictionary; 9125 case Stmt::BlockExprClass: 9126 return LK_Block; 9127 case Stmt::ObjCBoxedExprClass: { 9128 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9129 switch (Inner->getStmtClass()) { 9130 case Stmt::IntegerLiteralClass: 9131 case Stmt::FloatingLiteralClass: 9132 case Stmt::CharacterLiteralClass: 9133 case Stmt::ObjCBoolLiteralExprClass: 9134 case Stmt::CXXBoolLiteralExprClass: 9135 // "numeric literal" 9136 return LK_Numeric; 9137 case Stmt::ImplicitCastExprClass: { 9138 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9139 // Boolean literals can be represented by implicit casts. 9140 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9141 return LK_Numeric; 9142 break; 9143 } 9144 default: 9145 break; 9146 } 9147 return LK_Boxed; 9148 } 9149 } 9150 return LK_None; 9151 } 9152 9153 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9154 ExprResult &LHS, ExprResult &RHS, 9155 BinaryOperator::Opcode Opc){ 9156 Expr *Literal; 9157 Expr *Other; 9158 if (isObjCObjectLiteral(LHS)) { 9159 Literal = LHS.get(); 9160 Other = RHS.get(); 9161 } else { 9162 Literal = RHS.get(); 9163 Other = LHS.get(); 9164 } 9165 9166 // Don't warn on comparisons against nil. 9167 Other = Other->IgnoreParenCasts(); 9168 if (Other->isNullPointerConstant(S.getASTContext(), 9169 Expr::NPC_ValueDependentIsNotNull)) 9170 return; 9171 9172 // This should be kept in sync with warn_objc_literal_comparison. 9173 // LK_String should always be after the other literals, since it has its own 9174 // warning flag. 9175 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9176 assert(LiteralKind != Sema::LK_Block); 9177 if (LiteralKind == Sema::LK_None) { 9178 llvm_unreachable("Unknown Objective-C object literal kind"); 9179 } 9180 9181 if (LiteralKind == Sema::LK_String) 9182 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9183 << Literal->getSourceRange(); 9184 else 9185 S.Diag(Loc, diag::warn_objc_literal_comparison) 9186 << LiteralKind << Literal->getSourceRange(); 9187 9188 if (BinaryOperator::isEqualityOp(Opc) && 9189 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9190 SourceLocation Start = LHS.get()->getLocStart(); 9191 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9192 CharSourceRange OpRange = 9193 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9194 9195 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9196 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9197 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9198 << FixItHint::CreateInsertion(End, "]"); 9199 } 9200 } 9201 9202 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9203 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9204 ExprResult &RHS, SourceLocation Loc, 9205 BinaryOperatorKind Opc) { 9206 // Check that left hand side is !something. 9207 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9208 if (!UO || UO->getOpcode() != UO_LNot) return; 9209 9210 // Only check if the right hand side is non-bool arithmetic type. 9211 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9212 9213 // Make sure that the something in !something is not bool. 9214 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9215 if (SubExpr->isKnownToHaveBooleanValue()) return; 9216 9217 // Emit warning. 9218 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9219 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9220 << Loc << IsBitwiseOp; 9221 9222 // First note suggest !(x < y) 9223 SourceLocation FirstOpen = SubExpr->getLocStart(); 9224 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9225 FirstClose = S.getLocForEndOfToken(FirstClose); 9226 if (FirstClose.isInvalid()) 9227 FirstOpen = SourceLocation(); 9228 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9229 << IsBitwiseOp 9230 << FixItHint::CreateInsertion(FirstOpen, "(") 9231 << FixItHint::CreateInsertion(FirstClose, ")"); 9232 9233 // Second note suggests (!x) < y 9234 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9235 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9236 SecondClose = S.getLocForEndOfToken(SecondClose); 9237 if (SecondClose.isInvalid()) 9238 SecondOpen = SourceLocation(); 9239 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9240 << FixItHint::CreateInsertion(SecondOpen, "(") 9241 << FixItHint::CreateInsertion(SecondClose, ")"); 9242 } 9243 9244 // Get the decl for a simple expression: a reference to a variable, 9245 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9246 static ValueDecl *getCompareDecl(Expr *E) { 9247 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9248 return DR->getDecl(); 9249 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9250 if (Ivar->isFreeIvar()) 9251 return Ivar->getDecl(); 9252 } 9253 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9254 if (Mem->isImplicitAccess()) 9255 return Mem->getMemberDecl(); 9256 } 9257 return nullptr; 9258 } 9259 9260 // C99 6.5.8, C++ [expr.rel] 9261 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9262 SourceLocation Loc, BinaryOperatorKind Opc, 9263 bool IsRelational) { 9264 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9265 9266 // Handle vector comparisons separately. 9267 if (LHS.get()->getType()->isVectorType() || 9268 RHS.get()->getType()->isVectorType()) 9269 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9270 9271 QualType LHSType = LHS.get()->getType(); 9272 QualType RHSType = RHS.get()->getType(); 9273 9274 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9275 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9276 9277 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9278 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9279 9280 if (!LHSType->hasFloatingRepresentation() && 9281 !(LHSType->isBlockPointerType() && IsRelational) && 9282 !LHS.get()->getLocStart().isMacroID() && 9283 !RHS.get()->getLocStart().isMacroID() && 9284 !inTemplateInstantiation()) { 9285 // For non-floating point types, check for self-comparisons of the form 9286 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9287 // often indicate logic errors in the program. 9288 // 9289 // NOTE: Don't warn about comparison expressions resulting from macro 9290 // expansion. Also don't warn about comparisons which are only self 9291 // comparisons within a template specialization. The warnings should catch 9292 // obvious cases in the definition of the template anyways. The idea is to 9293 // warn when the typed comparison operator will always evaluate to the same 9294 // result. 9295 ValueDecl *DL = getCompareDecl(LHSStripped); 9296 ValueDecl *DR = getCompareDecl(RHSStripped); 9297 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9298 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9299 << 0 // self- 9300 << (Opc == BO_EQ 9301 || Opc == BO_LE 9302 || Opc == BO_GE)); 9303 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9304 !DL->getType()->isReferenceType() && 9305 !DR->getType()->isReferenceType()) { 9306 // what is it always going to eval to? 9307 char always_evals_to; 9308 switch(Opc) { 9309 case BO_EQ: // e.g. array1 == array2 9310 always_evals_to = 0; // false 9311 break; 9312 case BO_NE: // e.g. array1 != array2 9313 always_evals_to = 1; // true 9314 break; 9315 default: 9316 // best we can say is 'a constant' 9317 always_evals_to = 2; // e.g. array1 <= array2 9318 break; 9319 } 9320 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9321 << 1 // array 9322 << always_evals_to); 9323 } 9324 9325 if (isa<CastExpr>(LHSStripped)) 9326 LHSStripped = LHSStripped->IgnoreParenCasts(); 9327 if (isa<CastExpr>(RHSStripped)) 9328 RHSStripped = RHSStripped->IgnoreParenCasts(); 9329 9330 // Warn about comparisons against a string constant (unless the other 9331 // operand is null), the user probably wants strcmp. 9332 Expr *literalString = nullptr; 9333 Expr *literalStringStripped = nullptr; 9334 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9335 !RHSStripped->isNullPointerConstant(Context, 9336 Expr::NPC_ValueDependentIsNull)) { 9337 literalString = LHS.get(); 9338 literalStringStripped = LHSStripped; 9339 } else if ((isa<StringLiteral>(RHSStripped) || 9340 isa<ObjCEncodeExpr>(RHSStripped)) && 9341 !LHSStripped->isNullPointerConstant(Context, 9342 Expr::NPC_ValueDependentIsNull)) { 9343 literalString = RHS.get(); 9344 literalStringStripped = RHSStripped; 9345 } 9346 9347 if (literalString) { 9348 DiagRuntimeBehavior(Loc, nullptr, 9349 PDiag(diag::warn_stringcompare) 9350 << isa<ObjCEncodeExpr>(literalStringStripped) 9351 << literalString->getSourceRange()); 9352 } 9353 } 9354 9355 // C99 6.5.8p3 / C99 6.5.9p4 9356 UsualArithmeticConversions(LHS, RHS); 9357 if (LHS.isInvalid() || RHS.isInvalid()) 9358 return QualType(); 9359 9360 LHSType = LHS.get()->getType(); 9361 RHSType = RHS.get()->getType(); 9362 9363 // The result of comparisons is 'bool' in C++, 'int' in C. 9364 QualType ResultTy = Context.getLogicalOperationType(); 9365 9366 if (IsRelational) { 9367 if (LHSType->isRealType() && RHSType->isRealType()) 9368 return ResultTy; 9369 } else { 9370 // Check for comparisons of floating point operands using != and ==. 9371 if (LHSType->hasFloatingRepresentation()) 9372 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9373 9374 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9375 return ResultTy; 9376 } 9377 9378 const Expr::NullPointerConstantKind LHSNullKind = 9379 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9380 const Expr::NullPointerConstantKind RHSNullKind = 9381 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9382 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9383 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9384 9385 if (!IsRelational && LHSIsNull != RHSIsNull) { 9386 bool IsEquality = Opc == BO_EQ; 9387 if (RHSIsNull) 9388 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9389 RHS.get()->getSourceRange()); 9390 else 9391 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9392 LHS.get()->getSourceRange()); 9393 } 9394 9395 if ((LHSType->isIntegerType() && !LHSIsNull) || 9396 (RHSType->isIntegerType() && !RHSIsNull)) { 9397 // Skip normal pointer conversion checks in this case; we have better 9398 // diagnostics for this below. 9399 } else if (getLangOpts().CPlusPlus) { 9400 // Equality comparison of a function pointer to a void pointer is invalid, 9401 // but we allow it as an extension. 9402 // FIXME: If we really want to allow this, should it be part of composite 9403 // pointer type computation so it works in conditionals too? 9404 if (!IsRelational && 9405 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9406 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9407 // This is a gcc extension compatibility comparison. 9408 // In a SFINAE context, we treat this as a hard error to maintain 9409 // conformance with the C++ standard. 9410 diagnoseFunctionPointerToVoidComparison( 9411 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9412 9413 if (isSFINAEContext()) 9414 return QualType(); 9415 9416 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9417 return ResultTy; 9418 } 9419 9420 // C++ [expr.eq]p2: 9421 // If at least one operand is a pointer [...] bring them to their 9422 // composite pointer type. 9423 // C++ [expr.rel]p2: 9424 // If both operands are pointers, [...] bring them to their composite 9425 // pointer type. 9426 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9427 (IsRelational ? 2 : 1) && 9428 (!LangOpts.ObjCAutoRefCount || 9429 !(LHSType->isObjCObjectPointerType() || 9430 RHSType->isObjCObjectPointerType()))) { 9431 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9432 return QualType(); 9433 else 9434 return ResultTy; 9435 } 9436 } else if (LHSType->isPointerType() && 9437 RHSType->isPointerType()) { // C99 6.5.8p2 9438 // All of the following pointer-related warnings are GCC extensions, except 9439 // when handling null pointer constants. 9440 QualType LCanPointeeTy = 9441 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9442 QualType RCanPointeeTy = 9443 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9444 9445 // C99 6.5.9p2 and C99 6.5.8p2 9446 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9447 RCanPointeeTy.getUnqualifiedType())) { 9448 // Valid unless a relational comparison of function pointers 9449 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9450 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9451 << LHSType << RHSType << LHS.get()->getSourceRange() 9452 << RHS.get()->getSourceRange(); 9453 } 9454 } else if (!IsRelational && 9455 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9456 // Valid unless comparison between non-null pointer and function pointer 9457 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9458 && !LHSIsNull && !RHSIsNull) 9459 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9460 /*isError*/false); 9461 } else { 9462 // Invalid 9463 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9464 } 9465 if (LCanPointeeTy != RCanPointeeTy) { 9466 // Treat NULL constant as a special case in OpenCL. 9467 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9468 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9469 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9470 Diag(Loc, 9471 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9472 << LHSType << RHSType << 0 /* comparison */ 9473 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9474 } 9475 } 9476 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9477 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9478 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9479 : CK_BitCast; 9480 if (LHSIsNull && !RHSIsNull) 9481 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9482 else 9483 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9484 } 9485 return ResultTy; 9486 } 9487 9488 if (getLangOpts().CPlusPlus) { 9489 // C++ [expr.eq]p4: 9490 // Two operands of type std::nullptr_t or one operand of type 9491 // std::nullptr_t and the other a null pointer constant compare equal. 9492 if (!IsRelational && LHSIsNull && RHSIsNull) { 9493 if (LHSType->isNullPtrType()) { 9494 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9495 return ResultTy; 9496 } 9497 if (RHSType->isNullPtrType()) { 9498 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9499 return ResultTy; 9500 } 9501 } 9502 9503 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9504 // These aren't covered by the composite pointer type rules. 9505 if (!IsRelational && RHSType->isNullPtrType() && 9506 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9507 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9508 return ResultTy; 9509 } 9510 if (!IsRelational && LHSType->isNullPtrType() && 9511 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9512 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9513 return ResultTy; 9514 } 9515 9516 if (IsRelational && 9517 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9518 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9519 // HACK: Relational comparison of nullptr_t against a pointer type is 9520 // invalid per DR583, but we allow it within std::less<> and friends, 9521 // since otherwise common uses of it break. 9522 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9523 // friends to have std::nullptr_t overload candidates. 9524 DeclContext *DC = CurContext; 9525 if (isa<FunctionDecl>(DC)) 9526 DC = DC->getParent(); 9527 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9528 if (CTSD->isInStdNamespace() && 9529 llvm::StringSwitch<bool>(CTSD->getName()) 9530 .Cases("less", "less_equal", "greater", "greater_equal", true) 9531 .Default(false)) { 9532 if (RHSType->isNullPtrType()) 9533 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9534 else 9535 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9536 return ResultTy; 9537 } 9538 } 9539 } 9540 9541 // C++ [expr.eq]p2: 9542 // If at least one operand is a pointer to member, [...] bring them to 9543 // their composite pointer type. 9544 if (!IsRelational && 9545 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9546 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9547 return QualType(); 9548 else 9549 return ResultTy; 9550 } 9551 9552 // Handle scoped enumeration types specifically, since they don't promote 9553 // to integers. 9554 if (LHS.get()->getType()->isEnumeralType() && 9555 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9556 RHS.get()->getType())) 9557 return ResultTy; 9558 } 9559 9560 // Handle block pointer types. 9561 if (!IsRelational && LHSType->isBlockPointerType() && 9562 RHSType->isBlockPointerType()) { 9563 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9564 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9565 9566 if (!LHSIsNull && !RHSIsNull && 9567 !Context.typesAreCompatible(lpointee, rpointee)) { 9568 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9569 << LHSType << RHSType << LHS.get()->getSourceRange() 9570 << RHS.get()->getSourceRange(); 9571 } 9572 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9573 return ResultTy; 9574 } 9575 9576 // Allow block pointers to be compared with null pointer constants. 9577 if (!IsRelational 9578 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9579 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9580 if (!LHSIsNull && !RHSIsNull) { 9581 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9582 ->getPointeeType()->isVoidType()) 9583 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9584 ->getPointeeType()->isVoidType()))) 9585 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9586 << LHSType << RHSType << LHS.get()->getSourceRange() 9587 << RHS.get()->getSourceRange(); 9588 } 9589 if (LHSIsNull && !RHSIsNull) 9590 LHS = ImpCastExprToType(LHS.get(), RHSType, 9591 RHSType->isPointerType() ? CK_BitCast 9592 : CK_AnyPointerToBlockPointerCast); 9593 else 9594 RHS = ImpCastExprToType(RHS.get(), LHSType, 9595 LHSType->isPointerType() ? CK_BitCast 9596 : CK_AnyPointerToBlockPointerCast); 9597 return ResultTy; 9598 } 9599 9600 if (LHSType->isObjCObjectPointerType() || 9601 RHSType->isObjCObjectPointerType()) { 9602 const PointerType *LPT = LHSType->getAs<PointerType>(); 9603 const PointerType *RPT = RHSType->getAs<PointerType>(); 9604 if (LPT || RPT) { 9605 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9606 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9607 9608 if (!LPtrToVoid && !RPtrToVoid && 9609 !Context.typesAreCompatible(LHSType, RHSType)) { 9610 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9611 /*isError*/false); 9612 } 9613 if (LHSIsNull && !RHSIsNull) { 9614 Expr *E = LHS.get(); 9615 if (getLangOpts().ObjCAutoRefCount) 9616 CheckObjCConversion(SourceRange(), RHSType, E, 9617 CCK_ImplicitConversion); 9618 LHS = ImpCastExprToType(E, RHSType, 9619 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9620 } 9621 else { 9622 Expr *E = RHS.get(); 9623 if (getLangOpts().ObjCAutoRefCount) 9624 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9625 /*Diagnose=*/true, 9626 /*DiagnoseCFAudited=*/false, Opc); 9627 RHS = ImpCastExprToType(E, LHSType, 9628 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9629 } 9630 return ResultTy; 9631 } 9632 if (LHSType->isObjCObjectPointerType() && 9633 RHSType->isObjCObjectPointerType()) { 9634 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9635 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9636 /*isError*/false); 9637 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9638 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9639 9640 if (LHSIsNull && !RHSIsNull) 9641 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9642 else 9643 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9644 return ResultTy; 9645 } 9646 } 9647 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9648 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9649 unsigned DiagID = 0; 9650 bool isError = false; 9651 if (LangOpts.DebuggerSupport) { 9652 // Under a debugger, allow the comparison of pointers to integers, 9653 // since users tend to want to compare addresses. 9654 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9655 (RHSIsNull && RHSType->isIntegerType())) { 9656 if (IsRelational) { 9657 isError = getLangOpts().CPlusPlus; 9658 DiagID = 9659 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9660 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9661 } 9662 } else if (getLangOpts().CPlusPlus) { 9663 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9664 isError = true; 9665 } else if (IsRelational) 9666 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9667 else 9668 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9669 9670 if (DiagID) { 9671 Diag(Loc, DiagID) 9672 << LHSType << RHSType << LHS.get()->getSourceRange() 9673 << RHS.get()->getSourceRange(); 9674 if (isError) 9675 return QualType(); 9676 } 9677 9678 if (LHSType->isIntegerType()) 9679 LHS = ImpCastExprToType(LHS.get(), RHSType, 9680 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9681 else 9682 RHS = ImpCastExprToType(RHS.get(), LHSType, 9683 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9684 return ResultTy; 9685 } 9686 9687 // Handle block pointers. 9688 if (!IsRelational && RHSIsNull 9689 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9690 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9691 return ResultTy; 9692 } 9693 if (!IsRelational && LHSIsNull 9694 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9695 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9696 return ResultTy; 9697 } 9698 9699 if (getLangOpts().OpenCLVersion >= 200) { 9700 if (LHSIsNull && RHSType->isQueueT()) { 9701 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9702 return ResultTy; 9703 } 9704 9705 if (LHSType->isQueueT() && RHSIsNull) { 9706 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9707 return ResultTy; 9708 } 9709 } 9710 9711 return InvalidOperands(Loc, LHS, RHS); 9712 } 9713 9714 // Return a signed ext_vector_type that is of identical size and number of 9715 // elements. For floating point vectors, return an integer type of identical 9716 // size and number of elements. In the non ext_vector_type case, search from 9717 // the largest type to the smallest type to avoid cases where long long == long, 9718 // where long gets picked over long long. 9719 QualType Sema::GetSignedVectorType(QualType V) { 9720 const VectorType *VTy = V->getAs<VectorType>(); 9721 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9722 9723 if (isa<ExtVectorType>(VTy)) { 9724 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9725 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9726 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9727 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9728 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9729 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9730 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9731 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9732 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9733 "Unhandled vector element size in vector compare"); 9734 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9735 } 9736 9737 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 9738 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 9739 VectorType::GenericVector); 9740 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9741 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 9742 VectorType::GenericVector); 9743 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9744 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 9745 VectorType::GenericVector); 9746 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9747 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 9748 VectorType::GenericVector); 9749 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 9750 "Unhandled vector element size in vector compare"); 9751 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 9752 VectorType::GenericVector); 9753 } 9754 9755 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9756 /// operates on extended vector types. Instead of producing an IntTy result, 9757 /// like a scalar comparison, a vector comparison produces a vector of integer 9758 /// types. 9759 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9760 SourceLocation Loc, 9761 bool IsRelational) { 9762 // Check to make sure we're operating on vectors of the same type and width, 9763 // Allowing one side to be a scalar of element type. 9764 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9765 /*AllowBothBool*/true, 9766 /*AllowBoolConversions*/getLangOpts().ZVector); 9767 if (vType.isNull()) 9768 return vType; 9769 9770 QualType LHSType = LHS.get()->getType(); 9771 9772 // If AltiVec, the comparison results in a numeric type, i.e. 9773 // bool for C++, int for C 9774 if (getLangOpts().AltiVec && 9775 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9776 return Context.getLogicalOperationType(); 9777 9778 // For non-floating point types, check for self-comparisons of the form 9779 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9780 // often indicate logic errors in the program. 9781 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 9782 if (DeclRefExpr* DRL 9783 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9784 if (DeclRefExpr* DRR 9785 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9786 if (DRL->getDecl() == DRR->getDecl()) 9787 DiagRuntimeBehavior(Loc, nullptr, 9788 PDiag(diag::warn_comparison_always) 9789 << 0 // self- 9790 << 2 // "a constant" 9791 ); 9792 } 9793 9794 // Check for comparisons of floating point operands using != and ==. 9795 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9796 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9797 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9798 } 9799 9800 // Return a signed type for the vector. 9801 return GetSignedVectorType(vType); 9802 } 9803 9804 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9805 SourceLocation Loc) { 9806 // Ensure that either both operands are of the same vector type, or 9807 // one operand is of a vector type and the other is of its element type. 9808 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9809 /*AllowBothBool*/true, 9810 /*AllowBoolConversions*/false); 9811 if (vType.isNull()) 9812 return InvalidOperands(Loc, LHS, RHS); 9813 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9814 vType->hasFloatingRepresentation()) 9815 return InvalidOperands(Loc, LHS, RHS); 9816 9817 return GetSignedVectorType(LHS.get()->getType()); 9818 } 9819 9820 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 9821 SourceLocation Loc, 9822 BinaryOperatorKind Opc) { 9823 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9824 9825 bool IsCompAssign = 9826 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 9827 9828 if (LHS.get()->getType()->isVectorType() || 9829 RHS.get()->getType()->isVectorType()) { 9830 if (LHS.get()->getType()->hasIntegerRepresentation() && 9831 RHS.get()->getType()->hasIntegerRepresentation()) 9832 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9833 /*AllowBothBool*/true, 9834 /*AllowBoolConversions*/getLangOpts().ZVector); 9835 return InvalidOperands(Loc, LHS, RHS); 9836 } 9837 9838 if (Opc == BO_And) 9839 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9840 9841 ExprResult LHSResult = LHS, RHSResult = RHS; 9842 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9843 IsCompAssign); 9844 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9845 return QualType(); 9846 LHS = LHSResult.get(); 9847 RHS = RHSResult.get(); 9848 9849 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9850 return compType; 9851 return InvalidOperands(Loc, LHS, RHS); 9852 } 9853 9854 // C99 6.5.[13,14] 9855 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9856 SourceLocation Loc, 9857 BinaryOperatorKind Opc) { 9858 // Check vector operands differently. 9859 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9860 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9861 9862 // Diagnose cases where the user write a logical and/or but probably meant a 9863 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9864 // is a constant. 9865 if (LHS.get()->getType()->isIntegerType() && 9866 !LHS.get()->getType()->isBooleanType() && 9867 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9868 // Don't warn in macros or template instantiations. 9869 !Loc.isMacroID() && !inTemplateInstantiation()) { 9870 // If the RHS can be constant folded, and if it constant folds to something 9871 // that isn't 0 or 1 (which indicate a potential logical operation that 9872 // happened to fold to true/false) then warn. 9873 // Parens on the RHS are ignored. 9874 llvm::APSInt Result; 9875 if (RHS.get()->EvaluateAsInt(Result, Context)) 9876 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9877 !RHS.get()->getExprLoc().isMacroID()) || 9878 (Result != 0 && Result != 1)) { 9879 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9880 << RHS.get()->getSourceRange() 9881 << (Opc == BO_LAnd ? "&&" : "||"); 9882 // Suggest replacing the logical operator with the bitwise version 9883 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9884 << (Opc == BO_LAnd ? "&" : "|") 9885 << FixItHint::CreateReplacement(SourceRange( 9886 Loc, getLocForEndOfToken(Loc)), 9887 Opc == BO_LAnd ? "&" : "|"); 9888 if (Opc == BO_LAnd) 9889 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9890 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9891 << FixItHint::CreateRemoval( 9892 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9893 RHS.get()->getLocEnd())); 9894 } 9895 } 9896 9897 if (!Context.getLangOpts().CPlusPlus) { 9898 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9899 // not operate on the built-in scalar and vector float types. 9900 if (Context.getLangOpts().OpenCL && 9901 Context.getLangOpts().OpenCLVersion < 120) { 9902 if (LHS.get()->getType()->isFloatingType() || 9903 RHS.get()->getType()->isFloatingType()) 9904 return InvalidOperands(Loc, LHS, RHS); 9905 } 9906 9907 LHS = UsualUnaryConversions(LHS.get()); 9908 if (LHS.isInvalid()) 9909 return QualType(); 9910 9911 RHS = UsualUnaryConversions(RHS.get()); 9912 if (RHS.isInvalid()) 9913 return QualType(); 9914 9915 if (!LHS.get()->getType()->isScalarType() || 9916 !RHS.get()->getType()->isScalarType()) 9917 return InvalidOperands(Loc, LHS, RHS); 9918 9919 return Context.IntTy; 9920 } 9921 9922 // The following is safe because we only use this method for 9923 // non-overloadable operands. 9924 9925 // C++ [expr.log.and]p1 9926 // C++ [expr.log.or]p1 9927 // The operands are both contextually converted to type bool. 9928 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9929 if (LHSRes.isInvalid()) 9930 return InvalidOperands(Loc, LHS, RHS); 9931 LHS = LHSRes; 9932 9933 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9934 if (RHSRes.isInvalid()) 9935 return InvalidOperands(Loc, LHS, RHS); 9936 RHS = RHSRes; 9937 9938 // C++ [expr.log.and]p2 9939 // C++ [expr.log.or]p2 9940 // The result is a bool. 9941 return Context.BoolTy; 9942 } 9943 9944 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9945 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9946 if (!ME) return false; 9947 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9948 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 9949 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 9950 if (!Base) return false; 9951 return Base->getMethodDecl() != nullptr; 9952 } 9953 9954 /// Is the given expression (which must be 'const') a reference to a 9955 /// variable which was originally non-const, but which has become 9956 /// 'const' due to being captured within a block? 9957 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9958 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9959 assert(E->isLValue() && E->getType().isConstQualified()); 9960 E = E->IgnoreParens(); 9961 9962 // Must be a reference to a declaration from an enclosing scope. 9963 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9964 if (!DRE) return NCCK_None; 9965 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9966 9967 // The declaration must be a variable which is not declared 'const'. 9968 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9969 if (!var) return NCCK_None; 9970 if (var->getType().isConstQualified()) return NCCK_None; 9971 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9972 9973 // Decide whether the first capture was for a block or a lambda. 9974 DeclContext *DC = S.CurContext, *Prev = nullptr; 9975 // Decide whether the first capture was for a block or a lambda. 9976 while (DC) { 9977 // For init-capture, it is possible that the variable belongs to the 9978 // template pattern of the current context. 9979 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9980 if (var->isInitCapture() && 9981 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9982 break; 9983 if (DC == var->getDeclContext()) 9984 break; 9985 Prev = DC; 9986 DC = DC->getParent(); 9987 } 9988 // Unless we have an init-capture, we've gone one step too far. 9989 if (!var->isInitCapture()) 9990 DC = Prev; 9991 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9992 } 9993 9994 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9995 Ty = Ty.getNonReferenceType(); 9996 if (IsDereference && Ty->isPointerType()) 9997 Ty = Ty->getPointeeType(); 9998 return !Ty.isConstQualified(); 9999 } 10000 10001 /// Emit the "read-only variable not assignable" error and print notes to give 10002 /// more information about why the variable is not assignable, such as pointing 10003 /// to the declaration of a const variable, showing that a method is const, or 10004 /// that the function is returning a const reference. 10005 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10006 SourceLocation Loc) { 10007 // Update err_typecheck_assign_const and note_typecheck_assign_const 10008 // when this enum is changed. 10009 enum { 10010 ConstFunction, 10011 ConstVariable, 10012 ConstMember, 10013 ConstMethod, 10014 ConstUnknown, // Keep as last element 10015 }; 10016 10017 SourceRange ExprRange = E->getSourceRange(); 10018 10019 // Only emit one error on the first const found. All other consts will emit 10020 // a note to the error. 10021 bool DiagnosticEmitted = false; 10022 10023 // Track if the current expression is the result of a dereference, and if the 10024 // next checked expression is the result of a dereference. 10025 bool IsDereference = false; 10026 bool NextIsDereference = false; 10027 10028 // Loop to process MemberExpr chains. 10029 while (true) { 10030 IsDereference = NextIsDereference; 10031 10032 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10033 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10034 NextIsDereference = ME->isArrow(); 10035 const ValueDecl *VD = ME->getMemberDecl(); 10036 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10037 // Mutable fields can be modified even if the class is const. 10038 if (Field->isMutable()) { 10039 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10040 break; 10041 } 10042 10043 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10044 if (!DiagnosticEmitted) { 10045 S.Diag(Loc, diag::err_typecheck_assign_const) 10046 << ExprRange << ConstMember << false /*static*/ << Field 10047 << Field->getType(); 10048 DiagnosticEmitted = true; 10049 } 10050 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10051 << ConstMember << false /*static*/ << Field << Field->getType() 10052 << Field->getSourceRange(); 10053 } 10054 E = ME->getBase(); 10055 continue; 10056 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10057 if (VDecl->getType().isConstQualified()) { 10058 if (!DiagnosticEmitted) { 10059 S.Diag(Loc, diag::err_typecheck_assign_const) 10060 << ExprRange << ConstMember << true /*static*/ << VDecl 10061 << VDecl->getType(); 10062 DiagnosticEmitted = true; 10063 } 10064 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10065 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10066 << VDecl->getSourceRange(); 10067 } 10068 // Static fields do not inherit constness from parents. 10069 break; 10070 } 10071 break; 10072 } // End MemberExpr 10073 break; 10074 } 10075 10076 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10077 // Function calls 10078 const FunctionDecl *FD = CE->getDirectCallee(); 10079 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10080 if (!DiagnosticEmitted) { 10081 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10082 << ConstFunction << FD; 10083 DiagnosticEmitted = true; 10084 } 10085 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10086 diag::note_typecheck_assign_const) 10087 << ConstFunction << FD << FD->getReturnType() 10088 << FD->getReturnTypeSourceRange(); 10089 } 10090 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10091 // Point to variable declaration. 10092 if (const ValueDecl *VD = DRE->getDecl()) { 10093 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10094 if (!DiagnosticEmitted) { 10095 S.Diag(Loc, diag::err_typecheck_assign_const) 10096 << ExprRange << ConstVariable << VD << VD->getType(); 10097 DiagnosticEmitted = true; 10098 } 10099 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10100 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10101 } 10102 } 10103 } else if (isa<CXXThisExpr>(E)) { 10104 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10105 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10106 if (MD->isConst()) { 10107 if (!DiagnosticEmitted) { 10108 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10109 << ConstMethod << MD; 10110 DiagnosticEmitted = true; 10111 } 10112 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10113 << ConstMethod << MD << MD->getSourceRange(); 10114 } 10115 } 10116 } 10117 } 10118 10119 if (DiagnosticEmitted) 10120 return; 10121 10122 // Can't determine a more specific message, so display the generic error. 10123 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10124 } 10125 10126 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10127 /// emit an error and return true. If so, return false. 10128 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10129 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10130 10131 S.CheckShadowingDeclModification(E, Loc); 10132 10133 SourceLocation OrigLoc = Loc; 10134 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10135 &Loc); 10136 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10137 IsLV = Expr::MLV_InvalidMessageExpression; 10138 if (IsLV == Expr::MLV_Valid) 10139 return false; 10140 10141 unsigned DiagID = 0; 10142 bool NeedType = false; 10143 switch (IsLV) { // C99 6.5.16p2 10144 case Expr::MLV_ConstQualified: 10145 // Use a specialized diagnostic when we're assigning to an object 10146 // from an enclosing function or block. 10147 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10148 if (NCCK == NCCK_Block) 10149 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10150 else 10151 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10152 break; 10153 } 10154 10155 // In ARC, use some specialized diagnostics for occasions where we 10156 // infer 'const'. These are always pseudo-strong variables. 10157 if (S.getLangOpts().ObjCAutoRefCount) { 10158 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10159 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10160 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10161 10162 // Use the normal diagnostic if it's pseudo-__strong but the 10163 // user actually wrote 'const'. 10164 if (var->isARCPseudoStrong() && 10165 (!var->getTypeSourceInfo() || 10166 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10167 // There are two pseudo-strong cases: 10168 // - self 10169 ObjCMethodDecl *method = S.getCurMethodDecl(); 10170 if (method && var == method->getSelfDecl()) 10171 DiagID = method->isClassMethod() 10172 ? diag::err_typecheck_arc_assign_self_class_method 10173 : diag::err_typecheck_arc_assign_self; 10174 10175 // - fast enumeration variables 10176 else 10177 DiagID = diag::err_typecheck_arr_assign_enumeration; 10178 10179 SourceRange Assign; 10180 if (Loc != OrigLoc) 10181 Assign = SourceRange(OrigLoc, OrigLoc); 10182 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10183 // We need to preserve the AST regardless, so migration tool 10184 // can do its job. 10185 return false; 10186 } 10187 } 10188 } 10189 10190 // If none of the special cases above are triggered, then this is a 10191 // simple const assignment. 10192 if (DiagID == 0) { 10193 DiagnoseConstAssignment(S, E, Loc); 10194 return true; 10195 } 10196 10197 break; 10198 case Expr::MLV_ConstAddrSpace: 10199 DiagnoseConstAssignment(S, E, Loc); 10200 return true; 10201 case Expr::MLV_ArrayType: 10202 case Expr::MLV_ArrayTemporary: 10203 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10204 NeedType = true; 10205 break; 10206 case Expr::MLV_NotObjectType: 10207 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10208 NeedType = true; 10209 break; 10210 case Expr::MLV_LValueCast: 10211 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10212 break; 10213 case Expr::MLV_Valid: 10214 llvm_unreachable("did not take early return for MLV_Valid"); 10215 case Expr::MLV_InvalidExpression: 10216 case Expr::MLV_MemberFunction: 10217 case Expr::MLV_ClassTemporary: 10218 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10219 break; 10220 case Expr::MLV_IncompleteType: 10221 case Expr::MLV_IncompleteVoidType: 10222 return S.RequireCompleteType(Loc, E->getType(), 10223 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10224 case Expr::MLV_DuplicateVectorComponents: 10225 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10226 break; 10227 case Expr::MLV_NoSetterProperty: 10228 llvm_unreachable("readonly properties should be processed differently"); 10229 case Expr::MLV_InvalidMessageExpression: 10230 DiagID = diag::err_readonly_message_assignment; 10231 break; 10232 case Expr::MLV_SubObjCPropertySetting: 10233 DiagID = diag::err_no_subobject_property_setting; 10234 break; 10235 } 10236 10237 SourceRange Assign; 10238 if (Loc != OrigLoc) 10239 Assign = SourceRange(OrigLoc, OrigLoc); 10240 if (NeedType) 10241 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10242 else 10243 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10244 return true; 10245 } 10246 10247 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10248 SourceLocation Loc, 10249 Sema &Sema) { 10250 // C / C++ fields 10251 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10252 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10253 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10254 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10255 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10256 } 10257 10258 // Objective-C instance variables 10259 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10260 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10261 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10262 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10263 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10264 if (RL && RR && RL->getDecl() == RR->getDecl()) 10265 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10266 } 10267 } 10268 10269 // C99 6.5.16.1 10270 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10271 SourceLocation Loc, 10272 QualType CompoundType) { 10273 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10274 10275 // Verify that LHS is a modifiable lvalue, and emit error if not. 10276 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10277 return QualType(); 10278 10279 QualType LHSType = LHSExpr->getType(); 10280 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10281 CompoundType; 10282 // OpenCL v1.2 s6.1.1.1 p2: 10283 // The half data type can only be used to declare a pointer to a buffer that 10284 // contains half values 10285 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10286 LHSType->isHalfType()) { 10287 Diag(Loc, diag::err_opencl_half_load_store) << 1 10288 << LHSType.getUnqualifiedType(); 10289 return QualType(); 10290 } 10291 10292 AssignConvertType ConvTy; 10293 if (CompoundType.isNull()) { 10294 Expr *RHSCheck = RHS.get(); 10295 10296 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10297 10298 QualType LHSTy(LHSType); 10299 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10300 if (RHS.isInvalid()) 10301 return QualType(); 10302 // Special case of NSObject attributes on c-style pointer types. 10303 if (ConvTy == IncompatiblePointer && 10304 ((Context.isObjCNSObjectType(LHSType) && 10305 RHSType->isObjCObjectPointerType()) || 10306 (Context.isObjCNSObjectType(RHSType) && 10307 LHSType->isObjCObjectPointerType()))) 10308 ConvTy = Compatible; 10309 10310 if (ConvTy == Compatible && 10311 LHSType->isObjCObjectType()) 10312 Diag(Loc, diag::err_objc_object_assignment) 10313 << LHSType; 10314 10315 // If the RHS is a unary plus or minus, check to see if they = and + are 10316 // right next to each other. If so, the user may have typo'd "x =+ 4" 10317 // instead of "x += 4". 10318 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10319 RHSCheck = ICE->getSubExpr(); 10320 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10321 if ((UO->getOpcode() == UO_Plus || 10322 UO->getOpcode() == UO_Minus) && 10323 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10324 // Only if the two operators are exactly adjacent. 10325 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10326 // And there is a space or other character before the subexpr of the 10327 // unary +/-. We don't want to warn on "x=-1". 10328 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10329 UO->getSubExpr()->getLocStart().isFileID()) { 10330 Diag(Loc, diag::warn_not_compound_assign) 10331 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10332 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10333 } 10334 } 10335 10336 if (ConvTy == Compatible) { 10337 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10338 // Warn about retain cycles where a block captures the LHS, but 10339 // not if the LHS is a simple variable into which the block is 10340 // being stored...unless that variable can be captured by reference! 10341 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10342 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10343 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10344 checkRetainCycles(LHSExpr, RHS.get()); 10345 } 10346 10347 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10348 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10349 // It is safe to assign a weak reference into a strong variable. 10350 // Although this code can still have problems: 10351 // id x = self.weakProp; 10352 // id y = self.weakProp; 10353 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10354 // paths through the function. This should be revisited if 10355 // -Wrepeated-use-of-weak is made flow-sensitive. 10356 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10357 // variable, which will be valid for the current autorelease scope. 10358 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10359 RHS.get()->getLocStart())) 10360 getCurFunction()->markSafeWeakUse(RHS.get()); 10361 10362 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10363 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10364 } 10365 } 10366 } else { 10367 // Compound assignment "x += y" 10368 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10369 } 10370 10371 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10372 RHS.get(), AA_Assigning)) 10373 return QualType(); 10374 10375 CheckForNullPointerDereference(*this, LHSExpr); 10376 10377 // C99 6.5.16p3: The type of an assignment expression is the type of the 10378 // left operand unless the left operand has qualified type, in which case 10379 // it is the unqualified version of the type of the left operand. 10380 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10381 // is converted to the type of the assignment expression (above). 10382 // C++ 5.17p1: the type of the assignment expression is that of its left 10383 // operand. 10384 return (getLangOpts().CPlusPlus 10385 ? LHSType : LHSType.getUnqualifiedType()); 10386 } 10387 10388 // Only ignore explicit casts to void. 10389 static bool IgnoreCommaOperand(const Expr *E) { 10390 E = E->IgnoreParens(); 10391 10392 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10393 if (CE->getCastKind() == CK_ToVoid) { 10394 return true; 10395 } 10396 } 10397 10398 return false; 10399 } 10400 10401 // Look for instances where it is likely the comma operator is confused with 10402 // another operator. There is a whitelist of acceptable expressions for the 10403 // left hand side of the comma operator, otherwise emit a warning. 10404 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10405 // No warnings in macros 10406 if (Loc.isMacroID()) 10407 return; 10408 10409 // Don't warn in template instantiations. 10410 if (inTemplateInstantiation()) 10411 return; 10412 10413 // Scope isn't fine-grained enough to whitelist the specific cases, so 10414 // instead, skip more than needed, then call back into here with the 10415 // CommaVisitor in SemaStmt.cpp. 10416 // The whitelisted locations are the initialization and increment portions 10417 // of a for loop. The additional checks are on the condition of 10418 // if statements, do/while loops, and for loops. 10419 const unsigned ForIncrementFlags = 10420 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10421 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10422 const unsigned ScopeFlags = getCurScope()->getFlags(); 10423 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10424 (ScopeFlags & ForInitFlags) == ForInitFlags) 10425 return; 10426 10427 // If there are multiple comma operators used together, get the RHS of the 10428 // of the comma operator as the LHS. 10429 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10430 if (BO->getOpcode() != BO_Comma) 10431 break; 10432 LHS = BO->getRHS(); 10433 } 10434 10435 // Only allow some expressions on LHS to not warn. 10436 if (IgnoreCommaOperand(LHS)) 10437 return; 10438 10439 Diag(Loc, diag::warn_comma_operator); 10440 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10441 << LHS->getSourceRange() 10442 << FixItHint::CreateInsertion(LHS->getLocStart(), 10443 LangOpts.CPlusPlus ? "static_cast<void>(" 10444 : "(void)(") 10445 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10446 ")"); 10447 } 10448 10449 // C99 6.5.17 10450 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10451 SourceLocation Loc) { 10452 LHS = S.CheckPlaceholderExpr(LHS.get()); 10453 RHS = S.CheckPlaceholderExpr(RHS.get()); 10454 if (LHS.isInvalid() || RHS.isInvalid()) 10455 return QualType(); 10456 10457 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10458 // operands, but not unary promotions. 10459 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10460 10461 // So we treat the LHS as a ignored value, and in C++ we allow the 10462 // containing site to determine what should be done with the RHS. 10463 LHS = S.IgnoredValueConversions(LHS.get()); 10464 if (LHS.isInvalid()) 10465 return QualType(); 10466 10467 S.DiagnoseUnusedExprResult(LHS.get()); 10468 10469 if (!S.getLangOpts().CPlusPlus) { 10470 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10471 if (RHS.isInvalid()) 10472 return QualType(); 10473 if (!RHS.get()->getType()->isVoidType()) 10474 S.RequireCompleteType(Loc, RHS.get()->getType(), 10475 diag::err_incomplete_type); 10476 } 10477 10478 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10479 S.DiagnoseCommaOperator(LHS.get(), Loc); 10480 10481 return RHS.get()->getType(); 10482 } 10483 10484 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10485 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10486 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10487 ExprValueKind &VK, 10488 ExprObjectKind &OK, 10489 SourceLocation OpLoc, 10490 bool IsInc, bool IsPrefix) { 10491 if (Op->isTypeDependent()) 10492 return S.Context.DependentTy; 10493 10494 QualType ResType = Op->getType(); 10495 // Atomic types can be used for increment / decrement where the non-atomic 10496 // versions can, so ignore the _Atomic() specifier for the purpose of 10497 // checking. 10498 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10499 ResType = ResAtomicType->getValueType(); 10500 10501 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10502 10503 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10504 // Decrement of bool is not allowed. 10505 if (!IsInc) { 10506 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10507 return QualType(); 10508 } 10509 // Increment of bool sets it to true, but is deprecated. 10510 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10511 : diag::warn_increment_bool) 10512 << Op->getSourceRange(); 10513 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10514 // Error on enum increments and decrements in C++ mode 10515 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10516 return QualType(); 10517 } else if (ResType->isRealType()) { 10518 // OK! 10519 } else if (ResType->isPointerType()) { 10520 // C99 6.5.2.4p2, 6.5.6p2 10521 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10522 return QualType(); 10523 } else if (ResType->isObjCObjectPointerType()) { 10524 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10525 // Otherwise, we just need a complete type. 10526 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10527 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10528 return QualType(); 10529 } else if (ResType->isAnyComplexType()) { 10530 // C99 does not support ++/-- on complex types, we allow as an extension. 10531 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10532 << ResType << Op->getSourceRange(); 10533 } else if (ResType->isPlaceholderType()) { 10534 ExprResult PR = S.CheckPlaceholderExpr(Op); 10535 if (PR.isInvalid()) return QualType(); 10536 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10537 IsInc, IsPrefix); 10538 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10539 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10540 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10541 (ResType->getAs<VectorType>()->getVectorKind() != 10542 VectorType::AltiVecBool)) { 10543 // The z vector extensions allow ++ and -- for non-bool vectors. 10544 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10545 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10546 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10547 } else { 10548 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10549 << ResType << int(IsInc) << Op->getSourceRange(); 10550 return QualType(); 10551 } 10552 // At this point, we know we have a real, complex or pointer type. 10553 // Now make sure the operand is a modifiable lvalue. 10554 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10555 return QualType(); 10556 // In C++, a prefix increment is the same type as the operand. Otherwise 10557 // (in C or with postfix), the increment is the unqualified type of the 10558 // operand. 10559 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10560 VK = VK_LValue; 10561 OK = Op->getObjectKind(); 10562 return ResType; 10563 } else { 10564 VK = VK_RValue; 10565 return ResType.getUnqualifiedType(); 10566 } 10567 } 10568 10569 10570 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10571 /// This routine allows us to typecheck complex/recursive expressions 10572 /// where the declaration is needed for type checking. We only need to 10573 /// handle cases when the expression references a function designator 10574 /// or is an lvalue. Here are some examples: 10575 /// - &(x) => x 10576 /// - &*****f => f for f a function designator. 10577 /// - &s.xx => s 10578 /// - &s.zz[1].yy -> s, if zz is an array 10579 /// - *(x + 1) -> x, if x is an array 10580 /// - &"123"[2] -> 0 10581 /// - & __real__ x -> x 10582 static ValueDecl *getPrimaryDecl(Expr *E) { 10583 switch (E->getStmtClass()) { 10584 case Stmt::DeclRefExprClass: 10585 return cast<DeclRefExpr>(E)->getDecl(); 10586 case Stmt::MemberExprClass: 10587 // If this is an arrow operator, the address is an offset from 10588 // the base's value, so the object the base refers to is 10589 // irrelevant. 10590 if (cast<MemberExpr>(E)->isArrow()) 10591 return nullptr; 10592 // Otherwise, the expression refers to a part of the base 10593 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10594 case Stmt::ArraySubscriptExprClass: { 10595 // FIXME: This code shouldn't be necessary! We should catch the implicit 10596 // promotion of register arrays earlier. 10597 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10598 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10599 if (ICE->getSubExpr()->getType()->isArrayType()) 10600 return getPrimaryDecl(ICE->getSubExpr()); 10601 } 10602 return nullptr; 10603 } 10604 case Stmt::UnaryOperatorClass: { 10605 UnaryOperator *UO = cast<UnaryOperator>(E); 10606 10607 switch(UO->getOpcode()) { 10608 case UO_Real: 10609 case UO_Imag: 10610 case UO_Extension: 10611 return getPrimaryDecl(UO->getSubExpr()); 10612 default: 10613 return nullptr; 10614 } 10615 } 10616 case Stmt::ParenExprClass: 10617 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10618 case Stmt::ImplicitCastExprClass: 10619 // If the result of an implicit cast is an l-value, we care about 10620 // the sub-expression; otherwise, the result here doesn't matter. 10621 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10622 default: 10623 return nullptr; 10624 } 10625 } 10626 10627 namespace { 10628 enum { 10629 AO_Bit_Field = 0, 10630 AO_Vector_Element = 1, 10631 AO_Property_Expansion = 2, 10632 AO_Register_Variable = 3, 10633 AO_No_Error = 4 10634 }; 10635 } 10636 /// \brief Diagnose invalid operand for address of operations. 10637 /// 10638 /// \param Type The type of operand which cannot have its address taken. 10639 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10640 Expr *E, unsigned Type) { 10641 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10642 } 10643 10644 /// CheckAddressOfOperand - The operand of & must be either a function 10645 /// designator or an lvalue designating an object. If it is an lvalue, the 10646 /// object cannot be declared with storage class register or be a bit field. 10647 /// Note: The usual conversions are *not* applied to the operand of the & 10648 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10649 /// In C++, the operand might be an overloaded function name, in which case 10650 /// we allow the '&' but retain the overloaded-function type. 10651 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10652 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10653 if (PTy->getKind() == BuiltinType::Overload) { 10654 Expr *E = OrigOp.get()->IgnoreParens(); 10655 if (!isa<OverloadExpr>(E)) { 10656 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10657 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10658 << OrigOp.get()->getSourceRange(); 10659 return QualType(); 10660 } 10661 10662 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10663 if (isa<UnresolvedMemberExpr>(Ovl)) 10664 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10665 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10666 << OrigOp.get()->getSourceRange(); 10667 return QualType(); 10668 } 10669 10670 return Context.OverloadTy; 10671 } 10672 10673 if (PTy->getKind() == BuiltinType::UnknownAny) 10674 return Context.UnknownAnyTy; 10675 10676 if (PTy->getKind() == BuiltinType::BoundMember) { 10677 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10678 << OrigOp.get()->getSourceRange(); 10679 return QualType(); 10680 } 10681 10682 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10683 if (OrigOp.isInvalid()) return QualType(); 10684 } 10685 10686 if (OrigOp.get()->isTypeDependent()) 10687 return Context.DependentTy; 10688 10689 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10690 10691 // Make sure to ignore parentheses in subsequent checks 10692 Expr *op = OrigOp.get()->IgnoreParens(); 10693 10694 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10695 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10696 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10697 return QualType(); 10698 } 10699 10700 if (getLangOpts().C99) { 10701 // Implement C99-only parts of addressof rules. 10702 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10703 if (uOp->getOpcode() == UO_Deref) 10704 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10705 // (assuming the deref expression is valid). 10706 return uOp->getSubExpr()->getType(); 10707 } 10708 // Technically, there should be a check for array subscript 10709 // expressions here, but the result of one is always an lvalue anyway. 10710 } 10711 ValueDecl *dcl = getPrimaryDecl(op); 10712 10713 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10714 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10715 op->getLocStart())) 10716 return QualType(); 10717 10718 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10719 unsigned AddressOfError = AO_No_Error; 10720 10721 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10722 bool sfinae = (bool)isSFINAEContext(); 10723 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10724 : diag::ext_typecheck_addrof_temporary) 10725 << op->getType() << op->getSourceRange(); 10726 if (sfinae) 10727 return QualType(); 10728 // Materialize the temporary as an lvalue so that we can take its address. 10729 OrigOp = op = 10730 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10731 } else if (isa<ObjCSelectorExpr>(op)) { 10732 return Context.getPointerType(op->getType()); 10733 } else if (lval == Expr::LV_MemberFunction) { 10734 // If it's an instance method, make a member pointer. 10735 // The expression must have exactly the form &A::foo. 10736 10737 // If the underlying expression isn't a decl ref, give up. 10738 if (!isa<DeclRefExpr>(op)) { 10739 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10740 << OrigOp.get()->getSourceRange(); 10741 return QualType(); 10742 } 10743 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10744 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10745 10746 // The id-expression was parenthesized. 10747 if (OrigOp.get() != DRE) { 10748 Diag(OpLoc, diag::err_parens_pointer_member_function) 10749 << OrigOp.get()->getSourceRange(); 10750 10751 // The method was named without a qualifier. 10752 } else if (!DRE->getQualifier()) { 10753 if (MD->getParent()->getName().empty()) 10754 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10755 << op->getSourceRange(); 10756 else { 10757 SmallString<32> Str; 10758 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10759 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10760 << op->getSourceRange() 10761 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10762 } 10763 } 10764 10765 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10766 if (isa<CXXDestructorDecl>(MD)) 10767 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10768 10769 QualType MPTy = Context.getMemberPointerType( 10770 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10771 // Under the MS ABI, lock down the inheritance model now. 10772 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10773 (void)isCompleteType(OpLoc, MPTy); 10774 return MPTy; 10775 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10776 // C99 6.5.3.2p1 10777 // The operand must be either an l-value or a function designator 10778 if (!op->getType()->isFunctionType()) { 10779 // Use a special diagnostic for loads from property references. 10780 if (isa<PseudoObjectExpr>(op)) { 10781 AddressOfError = AO_Property_Expansion; 10782 } else { 10783 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10784 << op->getType() << op->getSourceRange(); 10785 return QualType(); 10786 } 10787 } 10788 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10789 // The operand cannot be a bit-field 10790 AddressOfError = AO_Bit_Field; 10791 } else if (op->getObjectKind() == OK_VectorComponent) { 10792 // The operand cannot be an element of a vector 10793 AddressOfError = AO_Vector_Element; 10794 } else if (dcl) { // C99 6.5.3.2p1 10795 // We have an lvalue with a decl. Make sure the decl is not declared 10796 // with the register storage-class specifier. 10797 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10798 // in C++ it is not error to take address of a register 10799 // variable (c++03 7.1.1P3) 10800 if (vd->getStorageClass() == SC_Register && 10801 !getLangOpts().CPlusPlus) { 10802 AddressOfError = AO_Register_Variable; 10803 } 10804 } else if (isa<MSPropertyDecl>(dcl)) { 10805 AddressOfError = AO_Property_Expansion; 10806 } else if (isa<FunctionTemplateDecl>(dcl)) { 10807 return Context.OverloadTy; 10808 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10809 // Okay: we can take the address of a field. 10810 // Could be a pointer to member, though, if there is an explicit 10811 // scope qualifier for the class. 10812 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10813 DeclContext *Ctx = dcl->getDeclContext(); 10814 if (Ctx && Ctx->isRecord()) { 10815 if (dcl->getType()->isReferenceType()) { 10816 Diag(OpLoc, 10817 diag::err_cannot_form_pointer_to_member_of_reference_type) 10818 << dcl->getDeclName() << dcl->getType(); 10819 return QualType(); 10820 } 10821 10822 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10823 Ctx = Ctx->getParent(); 10824 10825 QualType MPTy = Context.getMemberPointerType( 10826 op->getType(), 10827 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10828 // Under the MS ABI, lock down the inheritance model now. 10829 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10830 (void)isCompleteType(OpLoc, MPTy); 10831 return MPTy; 10832 } 10833 } 10834 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10835 !isa<BindingDecl>(dcl)) 10836 llvm_unreachable("Unknown/unexpected decl type"); 10837 } 10838 10839 if (AddressOfError != AO_No_Error) { 10840 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10841 return QualType(); 10842 } 10843 10844 if (lval == Expr::LV_IncompleteVoidType) { 10845 // Taking the address of a void variable is technically illegal, but we 10846 // allow it in cases which are otherwise valid. 10847 // Example: "extern void x; void* y = &x;". 10848 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10849 } 10850 10851 // If the operand has type "type", the result has type "pointer to type". 10852 if (op->getType()->isObjCObjectType()) 10853 return Context.getObjCObjectPointerType(op->getType()); 10854 10855 CheckAddressOfPackedMember(op); 10856 10857 return Context.getPointerType(op->getType()); 10858 } 10859 10860 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10861 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10862 if (!DRE) 10863 return; 10864 const Decl *D = DRE->getDecl(); 10865 if (!D) 10866 return; 10867 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10868 if (!Param) 10869 return; 10870 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10871 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10872 return; 10873 if (FunctionScopeInfo *FD = S.getCurFunction()) 10874 if (!FD->ModifiedNonNullParams.count(Param)) 10875 FD->ModifiedNonNullParams.insert(Param); 10876 } 10877 10878 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10879 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10880 SourceLocation OpLoc) { 10881 if (Op->isTypeDependent()) 10882 return S.Context.DependentTy; 10883 10884 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10885 if (ConvResult.isInvalid()) 10886 return QualType(); 10887 Op = ConvResult.get(); 10888 QualType OpTy = Op->getType(); 10889 QualType Result; 10890 10891 if (isa<CXXReinterpretCastExpr>(Op)) { 10892 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10893 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10894 Op->getSourceRange()); 10895 } 10896 10897 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10898 { 10899 Result = PT->getPointeeType(); 10900 } 10901 else if (const ObjCObjectPointerType *OPT = 10902 OpTy->getAs<ObjCObjectPointerType>()) 10903 Result = OPT->getPointeeType(); 10904 else { 10905 ExprResult PR = S.CheckPlaceholderExpr(Op); 10906 if (PR.isInvalid()) return QualType(); 10907 if (PR.get() != Op) 10908 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10909 } 10910 10911 if (Result.isNull()) { 10912 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10913 << OpTy << Op->getSourceRange(); 10914 return QualType(); 10915 } 10916 10917 // Note that per both C89 and C99, indirection is always legal, even if Result 10918 // is an incomplete type or void. It would be possible to warn about 10919 // dereferencing a void pointer, but it's completely well-defined, and such a 10920 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10921 // for pointers to 'void' but is fine for any other pointer type: 10922 // 10923 // C++ [expr.unary.op]p1: 10924 // [...] the expression to which [the unary * operator] is applied shall 10925 // be a pointer to an object type, or a pointer to a function type 10926 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10927 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10928 << OpTy << Op->getSourceRange(); 10929 10930 // Dereferences are usually l-values... 10931 VK = VK_LValue; 10932 10933 // ...except that certain expressions are never l-values in C. 10934 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10935 VK = VK_RValue; 10936 10937 return Result; 10938 } 10939 10940 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10941 BinaryOperatorKind Opc; 10942 switch (Kind) { 10943 default: llvm_unreachable("Unknown binop!"); 10944 case tok::periodstar: Opc = BO_PtrMemD; break; 10945 case tok::arrowstar: Opc = BO_PtrMemI; break; 10946 case tok::star: Opc = BO_Mul; break; 10947 case tok::slash: Opc = BO_Div; break; 10948 case tok::percent: Opc = BO_Rem; break; 10949 case tok::plus: Opc = BO_Add; break; 10950 case tok::minus: Opc = BO_Sub; break; 10951 case tok::lessless: Opc = BO_Shl; break; 10952 case tok::greatergreater: Opc = BO_Shr; break; 10953 case tok::lessequal: Opc = BO_LE; break; 10954 case tok::less: Opc = BO_LT; break; 10955 case tok::greaterequal: Opc = BO_GE; break; 10956 case tok::greater: Opc = BO_GT; break; 10957 case tok::exclaimequal: Opc = BO_NE; break; 10958 case tok::equalequal: Opc = BO_EQ; break; 10959 case tok::amp: Opc = BO_And; break; 10960 case tok::caret: Opc = BO_Xor; break; 10961 case tok::pipe: Opc = BO_Or; break; 10962 case tok::ampamp: Opc = BO_LAnd; break; 10963 case tok::pipepipe: Opc = BO_LOr; break; 10964 case tok::equal: Opc = BO_Assign; break; 10965 case tok::starequal: Opc = BO_MulAssign; break; 10966 case tok::slashequal: Opc = BO_DivAssign; break; 10967 case tok::percentequal: Opc = BO_RemAssign; break; 10968 case tok::plusequal: Opc = BO_AddAssign; break; 10969 case tok::minusequal: Opc = BO_SubAssign; break; 10970 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10971 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10972 case tok::ampequal: Opc = BO_AndAssign; break; 10973 case tok::caretequal: Opc = BO_XorAssign; break; 10974 case tok::pipeequal: Opc = BO_OrAssign; break; 10975 case tok::comma: Opc = BO_Comma; break; 10976 } 10977 return Opc; 10978 } 10979 10980 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10981 tok::TokenKind Kind) { 10982 UnaryOperatorKind Opc; 10983 switch (Kind) { 10984 default: llvm_unreachable("Unknown unary op!"); 10985 case tok::plusplus: Opc = UO_PreInc; break; 10986 case tok::minusminus: Opc = UO_PreDec; break; 10987 case tok::amp: Opc = UO_AddrOf; break; 10988 case tok::star: Opc = UO_Deref; break; 10989 case tok::plus: Opc = UO_Plus; break; 10990 case tok::minus: Opc = UO_Minus; break; 10991 case tok::tilde: Opc = UO_Not; break; 10992 case tok::exclaim: Opc = UO_LNot; break; 10993 case tok::kw___real: Opc = UO_Real; break; 10994 case tok::kw___imag: Opc = UO_Imag; break; 10995 case tok::kw___extension__: Opc = UO_Extension; break; 10996 } 10997 return Opc; 10998 } 10999 11000 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11001 /// This warning is only emitted for builtin assignment operations. It is also 11002 /// suppressed in the event of macro expansions. 11003 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11004 SourceLocation OpLoc) { 11005 if (S.inTemplateInstantiation()) 11006 return; 11007 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11008 return; 11009 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11010 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11011 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11012 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11013 if (!LHSDeclRef || !RHSDeclRef || 11014 LHSDeclRef->getLocation().isMacroID() || 11015 RHSDeclRef->getLocation().isMacroID()) 11016 return; 11017 const ValueDecl *LHSDecl = 11018 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11019 const ValueDecl *RHSDecl = 11020 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11021 if (LHSDecl != RHSDecl) 11022 return; 11023 if (LHSDecl->getType().isVolatileQualified()) 11024 return; 11025 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11026 if (RefTy->getPointeeType().isVolatileQualified()) 11027 return; 11028 11029 S.Diag(OpLoc, diag::warn_self_assignment) 11030 << LHSDeclRef->getType() 11031 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11032 } 11033 11034 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11035 /// is usually indicative of introspection within the Objective-C pointer. 11036 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11037 SourceLocation OpLoc) { 11038 if (!S.getLangOpts().ObjC1) 11039 return; 11040 11041 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11042 const Expr *LHS = L.get(); 11043 const Expr *RHS = R.get(); 11044 11045 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11046 ObjCPointerExpr = LHS; 11047 OtherExpr = RHS; 11048 } 11049 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11050 ObjCPointerExpr = RHS; 11051 OtherExpr = LHS; 11052 } 11053 11054 // This warning is deliberately made very specific to reduce false 11055 // positives with logic that uses '&' for hashing. This logic mainly 11056 // looks for code trying to introspect into tagged pointers, which 11057 // code should generally never do. 11058 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11059 unsigned Diag = diag::warn_objc_pointer_masking; 11060 // Determine if we are introspecting the result of performSelectorXXX. 11061 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11062 // Special case messages to -performSelector and friends, which 11063 // can return non-pointer values boxed in a pointer value. 11064 // Some clients may wish to silence warnings in this subcase. 11065 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11066 Selector S = ME->getSelector(); 11067 StringRef SelArg0 = S.getNameForSlot(0); 11068 if (SelArg0.startswith("performSelector")) 11069 Diag = diag::warn_objc_pointer_masking_performSelector; 11070 } 11071 11072 S.Diag(OpLoc, Diag) 11073 << ObjCPointerExpr->getSourceRange(); 11074 } 11075 } 11076 11077 static NamedDecl *getDeclFromExpr(Expr *E) { 11078 if (!E) 11079 return nullptr; 11080 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11081 return DRE->getDecl(); 11082 if (auto *ME = dyn_cast<MemberExpr>(E)) 11083 return ME->getMemberDecl(); 11084 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11085 return IRE->getDecl(); 11086 return nullptr; 11087 } 11088 11089 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11090 /// operator @p Opc at location @c TokLoc. This routine only supports 11091 /// built-in operations; ActOnBinOp handles overloaded operators. 11092 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11093 BinaryOperatorKind Opc, 11094 Expr *LHSExpr, Expr *RHSExpr) { 11095 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11096 // The syntax only allows initializer lists on the RHS of assignment, 11097 // so we don't need to worry about accepting invalid code for 11098 // non-assignment operators. 11099 // C++11 5.17p9: 11100 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11101 // of x = {} is x = T(). 11102 InitializationKind Kind = 11103 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11104 InitializedEntity Entity = 11105 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11106 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11107 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11108 if (Init.isInvalid()) 11109 return Init; 11110 RHSExpr = Init.get(); 11111 } 11112 11113 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11114 QualType ResultTy; // Result type of the binary operator. 11115 // The following two variables are used for compound assignment operators 11116 QualType CompLHSTy; // Type of LHS after promotions for computation 11117 QualType CompResultTy; // Type of computation result 11118 ExprValueKind VK = VK_RValue; 11119 ExprObjectKind OK = OK_Ordinary; 11120 11121 if (!getLangOpts().CPlusPlus) { 11122 // C cannot handle TypoExpr nodes on either side of a binop because it 11123 // doesn't handle dependent types properly, so make sure any TypoExprs have 11124 // been dealt with before checking the operands. 11125 LHS = CorrectDelayedTyposInExpr(LHSExpr); 11126 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 11127 if (Opc != BO_Assign) 11128 return ExprResult(E); 11129 // Avoid correcting the RHS to the same Expr as the LHS. 11130 Decl *D = getDeclFromExpr(E); 11131 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11132 }); 11133 if (!LHS.isUsable() || !RHS.isUsable()) 11134 return ExprError(); 11135 } 11136 11137 if (getLangOpts().OpenCL) { 11138 QualType LHSTy = LHSExpr->getType(); 11139 QualType RHSTy = RHSExpr->getType(); 11140 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11141 // the ATOMIC_VAR_INIT macro. 11142 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11143 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11144 if (BO_Assign == Opc) 11145 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11146 else 11147 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11148 return ExprError(); 11149 } 11150 11151 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11152 // only with a builtin functions and therefore should be disallowed here. 11153 if (LHSTy->isImageType() || RHSTy->isImageType() || 11154 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11155 LHSTy->isPipeType() || RHSTy->isPipeType() || 11156 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11157 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11158 return ExprError(); 11159 } 11160 } 11161 11162 switch (Opc) { 11163 case BO_Assign: 11164 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11165 if (getLangOpts().CPlusPlus && 11166 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11167 VK = LHS.get()->getValueKind(); 11168 OK = LHS.get()->getObjectKind(); 11169 } 11170 if (!ResultTy.isNull()) { 11171 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11172 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11173 } 11174 RecordModifiableNonNullParam(*this, LHS.get()); 11175 break; 11176 case BO_PtrMemD: 11177 case BO_PtrMemI: 11178 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11179 Opc == BO_PtrMemI); 11180 break; 11181 case BO_Mul: 11182 case BO_Div: 11183 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11184 Opc == BO_Div); 11185 break; 11186 case BO_Rem: 11187 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11188 break; 11189 case BO_Add: 11190 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11191 break; 11192 case BO_Sub: 11193 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11194 break; 11195 case BO_Shl: 11196 case BO_Shr: 11197 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11198 break; 11199 case BO_LE: 11200 case BO_LT: 11201 case BO_GE: 11202 case BO_GT: 11203 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11204 break; 11205 case BO_EQ: 11206 case BO_NE: 11207 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11208 break; 11209 case BO_And: 11210 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11211 case BO_Xor: 11212 case BO_Or: 11213 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11214 break; 11215 case BO_LAnd: 11216 case BO_LOr: 11217 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11218 break; 11219 case BO_MulAssign: 11220 case BO_DivAssign: 11221 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11222 Opc == BO_DivAssign); 11223 CompLHSTy = CompResultTy; 11224 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11225 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11226 break; 11227 case BO_RemAssign: 11228 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11229 CompLHSTy = CompResultTy; 11230 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11231 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11232 break; 11233 case BO_AddAssign: 11234 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11235 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11236 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11237 break; 11238 case BO_SubAssign: 11239 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11240 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11241 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11242 break; 11243 case BO_ShlAssign: 11244 case BO_ShrAssign: 11245 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11246 CompLHSTy = CompResultTy; 11247 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11248 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11249 break; 11250 case BO_AndAssign: 11251 case BO_OrAssign: // fallthrough 11252 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11253 case BO_XorAssign: 11254 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11255 CompLHSTy = CompResultTy; 11256 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11257 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11258 break; 11259 case BO_Comma: 11260 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11261 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11262 VK = RHS.get()->getValueKind(); 11263 OK = RHS.get()->getObjectKind(); 11264 } 11265 break; 11266 } 11267 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11268 return ExprError(); 11269 11270 // Check for array bounds violations for both sides of the BinaryOperator 11271 CheckArrayAccess(LHS.get()); 11272 CheckArrayAccess(RHS.get()); 11273 11274 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11275 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11276 &Context.Idents.get("object_setClass"), 11277 SourceLocation(), LookupOrdinaryName); 11278 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11279 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11280 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11281 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11282 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11283 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11284 } 11285 else 11286 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11287 } 11288 else if (const ObjCIvarRefExpr *OIRE = 11289 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11290 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11291 11292 if (CompResultTy.isNull()) 11293 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11294 OK, OpLoc, FPFeatures); 11295 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11296 OK_ObjCProperty) { 11297 VK = VK_LValue; 11298 OK = LHS.get()->getObjectKind(); 11299 } 11300 return new (Context) CompoundAssignOperator( 11301 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11302 OpLoc, FPFeatures); 11303 } 11304 11305 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11306 /// operators are mixed in a way that suggests that the programmer forgot that 11307 /// comparison operators have higher precedence. The most typical example of 11308 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11309 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11310 SourceLocation OpLoc, Expr *LHSExpr, 11311 Expr *RHSExpr) { 11312 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11313 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11314 11315 // Check that one of the sides is a comparison operator and the other isn't. 11316 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11317 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11318 if (isLeftComp == isRightComp) 11319 return; 11320 11321 // Bitwise operations are sometimes used as eager logical ops. 11322 // Don't diagnose this. 11323 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11324 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11325 if (isLeftBitwise || isRightBitwise) 11326 return; 11327 11328 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11329 OpLoc) 11330 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11331 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11332 SourceRange ParensRange = isLeftComp ? 11333 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11334 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11335 11336 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11337 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11338 SuggestParentheses(Self, OpLoc, 11339 Self.PDiag(diag::note_precedence_silence) << OpStr, 11340 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11341 SuggestParentheses(Self, OpLoc, 11342 Self.PDiag(diag::note_precedence_bitwise_first) 11343 << BinaryOperator::getOpcodeStr(Opc), 11344 ParensRange); 11345 } 11346 11347 /// \brief It accepts a '&&' expr that is inside a '||' one. 11348 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11349 /// in parentheses. 11350 static void 11351 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11352 BinaryOperator *Bop) { 11353 assert(Bop->getOpcode() == BO_LAnd); 11354 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11355 << Bop->getSourceRange() << OpLoc; 11356 SuggestParentheses(Self, Bop->getOperatorLoc(), 11357 Self.PDiag(diag::note_precedence_silence) 11358 << Bop->getOpcodeStr(), 11359 Bop->getSourceRange()); 11360 } 11361 11362 /// \brief Returns true if the given expression can be evaluated as a constant 11363 /// 'true'. 11364 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11365 bool Res; 11366 return !E->isValueDependent() && 11367 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11368 } 11369 11370 /// \brief Returns true if the given expression can be evaluated as a constant 11371 /// 'false'. 11372 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11373 bool Res; 11374 return !E->isValueDependent() && 11375 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11376 } 11377 11378 /// \brief Look for '&&' in the left hand of a '||' expr. 11379 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11380 Expr *LHSExpr, Expr *RHSExpr) { 11381 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11382 if (Bop->getOpcode() == BO_LAnd) { 11383 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11384 if (EvaluatesAsFalse(S, RHSExpr)) 11385 return; 11386 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11387 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11388 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11389 } else if (Bop->getOpcode() == BO_LOr) { 11390 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11391 // If it's "a || b && 1 || c" we didn't warn earlier for 11392 // "a || b && 1", but warn now. 11393 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11394 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11395 } 11396 } 11397 } 11398 } 11399 11400 /// \brief Look for '&&' in the right hand of a '||' expr. 11401 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11402 Expr *LHSExpr, Expr *RHSExpr) { 11403 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11404 if (Bop->getOpcode() == BO_LAnd) { 11405 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11406 if (EvaluatesAsFalse(S, LHSExpr)) 11407 return; 11408 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11409 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11410 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11411 } 11412 } 11413 } 11414 11415 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11416 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11417 /// the '&' expression in parentheses. 11418 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11419 SourceLocation OpLoc, Expr *SubExpr) { 11420 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11421 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11422 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11423 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11424 << Bop->getSourceRange() << OpLoc; 11425 SuggestParentheses(S, Bop->getOperatorLoc(), 11426 S.PDiag(diag::note_precedence_silence) 11427 << Bop->getOpcodeStr(), 11428 Bop->getSourceRange()); 11429 } 11430 } 11431 } 11432 11433 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11434 Expr *SubExpr, StringRef Shift) { 11435 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11436 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11437 StringRef Op = Bop->getOpcodeStr(); 11438 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11439 << Bop->getSourceRange() << OpLoc << Shift << Op; 11440 SuggestParentheses(S, Bop->getOperatorLoc(), 11441 S.PDiag(diag::note_precedence_silence) << Op, 11442 Bop->getSourceRange()); 11443 } 11444 } 11445 } 11446 11447 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11448 Expr *LHSExpr, Expr *RHSExpr) { 11449 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11450 if (!OCE) 11451 return; 11452 11453 FunctionDecl *FD = OCE->getDirectCallee(); 11454 if (!FD || !FD->isOverloadedOperator()) 11455 return; 11456 11457 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11458 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11459 return; 11460 11461 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11462 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11463 << (Kind == OO_LessLess); 11464 SuggestParentheses(S, OCE->getOperatorLoc(), 11465 S.PDiag(diag::note_precedence_silence) 11466 << (Kind == OO_LessLess ? "<<" : ">>"), 11467 OCE->getSourceRange()); 11468 SuggestParentheses(S, OpLoc, 11469 S.PDiag(diag::note_evaluate_comparison_first), 11470 SourceRange(OCE->getArg(1)->getLocStart(), 11471 RHSExpr->getLocEnd())); 11472 } 11473 11474 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11475 /// precedence. 11476 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11477 SourceLocation OpLoc, Expr *LHSExpr, 11478 Expr *RHSExpr){ 11479 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11480 if (BinaryOperator::isBitwiseOp(Opc)) 11481 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11482 11483 // Diagnose "arg1 & arg2 | arg3" 11484 if ((Opc == BO_Or || Opc == BO_Xor) && 11485 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11486 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11487 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11488 } 11489 11490 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11491 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11492 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11493 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11494 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11495 } 11496 11497 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11498 || Opc == BO_Shr) { 11499 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11500 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11501 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11502 } 11503 11504 // Warn on overloaded shift operators and comparisons, such as: 11505 // cout << 5 == 4; 11506 if (BinaryOperator::isComparisonOp(Opc)) 11507 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11508 } 11509 11510 // Binary Operators. 'Tok' is the token for the operator. 11511 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11512 tok::TokenKind Kind, 11513 Expr *LHSExpr, Expr *RHSExpr) { 11514 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11515 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11516 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11517 11518 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11519 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11520 11521 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11522 } 11523 11524 /// Build an overloaded binary operator expression in the given scope. 11525 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11526 BinaryOperatorKind Opc, 11527 Expr *LHS, Expr *RHS) { 11528 // Find all of the overloaded operators visible from this 11529 // point. We perform both an operator-name lookup from the local 11530 // scope and an argument-dependent lookup based on the types of 11531 // the arguments. 11532 UnresolvedSet<16> Functions; 11533 OverloadedOperatorKind OverOp 11534 = BinaryOperator::getOverloadedOperator(Opc); 11535 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11536 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11537 RHS->getType(), Functions); 11538 11539 // Build the (potentially-overloaded, potentially-dependent) 11540 // binary operation. 11541 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11542 } 11543 11544 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11545 BinaryOperatorKind Opc, 11546 Expr *LHSExpr, Expr *RHSExpr) { 11547 // We want to end up calling one of checkPseudoObjectAssignment 11548 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11549 // both expressions are overloadable or either is type-dependent), 11550 // or CreateBuiltinBinOp (in any other case). We also want to get 11551 // any placeholder types out of the way. 11552 11553 // Handle pseudo-objects in the LHS. 11554 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11555 // Assignments with a pseudo-object l-value need special analysis. 11556 if (pty->getKind() == BuiltinType::PseudoObject && 11557 BinaryOperator::isAssignmentOp(Opc)) 11558 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11559 11560 // Don't resolve overloads if the other type is overloadable. 11561 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 11562 // We can't actually test that if we still have a placeholder, 11563 // though. Fortunately, none of the exceptions we see in that 11564 // code below are valid when the LHS is an overload set. Note 11565 // that an overload set can be dependently-typed, but it never 11566 // instantiates to having an overloadable type. 11567 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11568 if (resolvedRHS.isInvalid()) return ExprError(); 11569 RHSExpr = resolvedRHS.get(); 11570 11571 if (RHSExpr->isTypeDependent() || 11572 RHSExpr->getType()->isOverloadableType()) 11573 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11574 } 11575 11576 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11577 if (LHS.isInvalid()) return ExprError(); 11578 LHSExpr = LHS.get(); 11579 } 11580 11581 // Handle pseudo-objects in the RHS. 11582 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11583 // An overload in the RHS can potentially be resolved by the type 11584 // being assigned to. 11585 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11586 if (getLangOpts().CPlusPlus && 11587 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 11588 LHSExpr->getType()->isOverloadableType())) 11589 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11590 11591 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11592 } 11593 11594 // Don't resolve overloads if the other type is overloadable. 11595 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 11596 LHSExpr->getType()->isOverloadableType()) 11597 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11598 11599 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11600 if (!resolvedRHS.isUsable()) return ExprError(); 11601 RHSExpr = resolvedRHS.get(); 11602 } 11603 11604 if (getLangOpts().CPlusPlus) { 11605 // If either expression is type-dependent, always build an 11606 // overloaded op. 11607 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11608 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11609 11610 // Otherwise, build an overloaded op if either expression has an 11611 // overloadable type. 11612 if (LHSExpr->getType()->isOverloadableType() || 11613 RHSExpr->getType()->isOverloadableType()) 11614 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11615 } 11616 11617 // Build a built-in binary operation. 11618 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11619 } 11620 11621 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11622 UnaryOperatorKind Opc, 11623 Expr *InputExpr) { 11624 ExprResult Input = InputExpr; 11625 ExprValueKind VK = VK_RValue; 11626 ExprObjectKind OK = OK_Ordinary; 11627 QualType resultType; 11628 if (getLangOpts().OpenCL) { 11629 QualType Ty = InputExpr->getType(); 11630 // The only legal unary operation for atomics is '&'. 11631 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11632 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11633 // only with a builtin functions and therefore should be disallowed here. 11634 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11635 || Ty->isBlockPointerType())) { 11636 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11637 << InputExpr->getType() 11638 << Input.get()->getSourceRange()); 11639 } 11640 } 11641 switch (Opc) { 11642 case UO_PreInc: 11643 case UO_PreDec: 11644 case UO_PostInc: 11645 case UO_PostDec: 11646 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11647 OpLoc, 11648 Opc == UO_PreInc || 11649 Opc == UO_PostInc, 11650 Opc == UO_PreInc || 11651 Opc == UO_PreDec); 11652 break; 11653 case UO_AddrOf: 11654 resultType = CheckAddressOfOperand(Input, OpLoc); 11655 RecordModifiableNonNullParam(*this, InputExpr); 11656 break; 11657 case UO_Deref: { 11658 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11659 if (Input.isInvalid()) return ExprError(); 11660 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11661 break; 11662 } 11663 case UO_Plus: 11664 case UO_Minus: 11665 Input = UsualUnaryConversions(Input.get()); 11666 if (Input.isInvalid()) return ExprError(); 11667 resultType = Input.get()->getType(); 11668 if (resultType->isDependentType()) 11669 break; 11670 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11671 break; 11672 else if (resultType->isVectorType() && 11673 // The z vector extensions don't allow + or - with bool vectors. 11674 (!Context.getLangOpts().ZVector || 11675 resultType->getAs<VectorType>()->getVectorKind() != 11676 VectorType::AltiVecBool)) 11677 break; 11678 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11679 Opc == UO_Plus && 11680 resultType->isPointerType()) 11681 break; 11682 11683 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11684 << resultType << Input.get()->getSourceRange()); 11685 11686 case UO_Not: // bitwise complement 11687 Input = UsualUnaryConversions(Input.get()); 11688 if (Input.isInvalid()) 11689 return ExprError(); 11690 resultType = Input.get()->getType(); 11691 if (resultType->isDependentType()) 11692 break; 11693 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11694 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11695 // C99 does not support '~' for complex conjugation. 11696 Diag(OpLoc, diag::ext_integer_complement_complex) 11697 << resultType << Input.get()->getSourceRange(); 11698 else if (resultType->hasIntegerRepresentation()) 11699 break; 11700 else if (resultType->isExtVectorType()) { 11701 if (Context.getLangOpts().OpenCL) { 11702 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11703 // on vector float types. 11704 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11705 if (!T->isIntegerType()) 11706 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11707 << resultType << Input.get()->getSourceRange()); 11708 } 11709 break; 11710 } else { 11711 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11712 << resultType << Input.get()->getSourceRange()); 11713 } 11714 break; 11715 11716 case UO_LNot: // logical negation 11717 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11718 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11719 if (Input.isInvalid()) return ExprError(); 11720 resultType = Input.get()->getType(); 11721 11722 // Though we still have to promote half FP to float... 11723 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11724 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11725 resultType = Context.FloatTy; 11726 } 11727 11728 if (resultType->isDependentType()) 11729 break; 11730 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11731 // C99 6.5.3.3p1: ok, fallthrough; 11732 if (Context.getLangOpts().CPlusPlus) { 11733 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11734 // operand contextually converted to bool. 11735 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11736 ScalarTypeToBooleanCastKind(resultType)); 11737 } else if (Context.getLangOpts().OpenCL && 11738 Context.getLangOpts().OpenCLVersion < 120) { 11739 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11740 // operate on scalar float types. 11741 if (!resultType->isIntegerType() && !resultType->isPointerType()) 11742 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11743 << resultType << Input.get()->getSourceRange()); 11744 } 11745 } else if (resultType->isExtVectorType()) { 11746 if (Context.getLangOpts().OpenCL && 11747 Context.getLangOpts().OpenCLVersion < 120) { 11748 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11749 // operate on vector float types. 11750 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11751 if (!T->isIntegerType()) 11752 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11753 << resultType << Input.get()->getSourceRange()); 11754 } 11755 // Vector logical not returns the signed variant of the operand type. 11756 resultType = GetSignedVectorType(resultType); 11757 break; 11758 } else { 11759 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11760 << resultType << Input.get()->getSourceRange()); 11761 } 11762 11763 // LNot always has type int. C99 6.5.3.3p5. 11764 // In C++, it's bool. C++ 5.3.1p8 11765 resultType = Context.getLogicalOperationType(); 11766 break; 11767 case UO_Real: 11768 case UO_Imag: 11769 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11770 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11771 // complex l-values to ordinary l-values and all other values to r-values. 11772 if (Input.isInvalid()) return ExprError(); 11773 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11774 if (Input.get()->getValueKind() != VK_RValue && 11775 Input.get()->getObjectKind() == OK_Ordinary) 11776 VK = Input.get()->getValueKind(); 11777 } else if (!getLangOpts().CPlusPlus) { 11778 // In C, a volatile scalar is read by __imag. In C++, it is not. 11779 Input = DefaultLvalueConversion(Input.get()); 11780 } 11781 break; 11782 case UO_Extension: 11783 case UO_Coawait: 11784 resultType = Input.get()->getType(); 11785 VK = Input.get()->getValueKind(); 11786 OK = Input.get()->getObjectKind(); 11787 break; 11788 } 11789 if (resultType.isNull() || Input.isInvalid()) 11790 return ExprError(); 11791 11792 // Check for array bounds violations in the operand of the UnaryOperator, 11793 // except for the '*' and '&' operators that have to be handled specially 11794 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11795 // that are explicitly defined as valid by the standard). 11796 if (Opc != UO_AddrOf && Opc != UO_Deref) 11797 CheckArrayAccess(Input.get()); 11798 11799 return new (Context) 11800 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11801 } 11802 11803 /// \brief Determine whether the given expression is a qualified member 11804 /// access expression, of a form that could be turned into a pointer to member 11805 /// with the address-of operator. 11806 static bool isQualifiedMemberAccess(Expr *E) { 11807 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11808 if (!DRE->getQualifier()) 11809 return false; 11810 11811 ValueDecl *VD = DRE->getDecl(); 11812 if (!VD->isCXXClassMember()) 11813 return false; 11814 11815 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11816 return true; 11817 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11818 return Method->isInstance(); 11819 11820 return false; 11821 } 11822 11823 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11824 if (!ULE->getQualifier()) 11825 return false; 11826 11827 for (NamedDecl *D : ULE->decls()) { 11828 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11829 if (Method->isInstance()) 11830 return true; 11831 } else { 11832 // Overload set does not contain methods. 11833 break; 11834 } 11835 } 11836 11837 return false; 11838 } 11839 11840 return false; 11841 } 11842 11843 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11844 UnaryOperatorKind Opc, Expr *Input) { 11845 // First things first: handle placeholders so that the 11846 // overloaded-operator check considers the right type. 11847 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11848 // Increment and decrement of pseudo-object references. 11849 if (pty->getKind() == BuiltinType::PseudoObject && 11850 UnaryOperator::isIncrementDecrementOp(Opc)) 11851 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11852 11853 // extension is always a builtin operator. 11854 if (Opc == UO_Extension) 11855 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11856 11857 // & gets special logic for several kinds of placeholder. 11858 // The builtin code knows what to do. 11859 if (Opc == UO_AddrOf && 11860 (pty->getKind() == BuiltinType::Overload || 11861 pty->getKind() == BuiltinType::UnknownAny || 11862 pty->getKind() == BuiltinType::BoundMember)) 11863 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11864 11865 // Anything else needs to be handled now. 11866 ExprResult Result = CheckPlaceholderExpr(Input); 11867 if (Result.isInvalid()) return ExprError(); 11868 Input = Result.get(); 11869 } 11870 11871 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11872 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11873 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11874 // Find all of the overloaded operators visible from this 11875 // point. We perform both an operator-name lookup from the local 11876 // scope and an argument-dependent lookup based on the types of 11877 // the arguments. 11878 UnresolvedSet<16> Functions; 11879 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11880 if (S && OverOp != OO_None) 11881 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11882 Functions); 11883 11884 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11885 } 11886 11887 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11888 } 11889 11890 // Unary Operators. 'Tok' is the token for the operator. 11891 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11892 tok::TokenKind Op, Expr *Input) { 11893 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11894 } 11895 11896 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11897 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11898 LabelDecl *TheDecl) { 11899 TheDecl->markUsed(Context); 11900 // Create the AST node. The address of a label always has type 'void*'. 11901 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11902 Context.getPointerType(Context.VoidTy)); 11903 } 11904 11905 /// Given the last statement in a statement-expression, check whether 11906 /// the result is a producing expression (like a call to an 11907 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11908 /// release out of the full-expression. Otherwise, return null. 11909 /// Cannot fail. 11910 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11911 // Should always be wrapped with one of these. 11912 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11913 if (!cleanups) return nullptr; 11914 11915 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11916 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11917 return nullptr; 11918 11919 // Splice out the cast. This shouldn't modify any interesting 11920 // features of the statement. 11921 Expr *producer = cast->getSubExpr(); 11922 assert(producer->getType() == cast->getType()); 11923 assert(producer->getValueKind() == cast->getValueKind()); 11924 cleanups->setSubExpr(producer); 11925 return cleanups; 11926 } 11927 11928 void Sema::ActOnStartStmtExpr() { 11929 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11930 } 11931 11932 void Sema::ActOnStmtExprError() { 11933 // Note that function is also called by TreeTransform when leaving a 11934 // StmtExpr scope without rebuilding anything. 11935 11936 DiscardCleanupsInEvaluationContext(); 11937 PopExpressionEvaluationContext(); 11938 } 11939 11940 ExprResult 11941 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11942 SourceLocation RPLoc) { // "({..})" 11943 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11944 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11945 11946 if (hasAnyUnrecoverableErrorsInThisFunction()) 11947 DiscardCleanupsInEvaluationContext(); 11948 assert(!Cleanup.exprNeedsCleanups() && 11949 "cleanups within StmtExpr not correctly bound!"); 11950 PopExpressionEvaluationContext(); 11951 11952 // FIXME: there are a variety of strange constraints to enforce here, for 11953 // example, it is not possible to goto into a stmt expression apparently. 11954 // More semantic analysis is needed. 11955 11956 // If there are sub-stmts in the compound stmt, take the type of the last one 11957 // as the type of the stmtexpr. 11958 QualType Ty = Context.VoidTy; 11959 bool StmtExprMayBindToTemp = false; 11960 if (!Compound->body_empty()) { 11961 Stmt *LastStmt = Compound->body_back(); 11962 LabelStmt *LastLabelStmt = nullptr; 11963 // If LastStmt is a label, skip down through into the body. 11964 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11965 LastLabelStmt = Label; 11966 LastStmt = Label->getSubStmt(); 11967 } 11968 11969 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11970 // Do function/array conversion on the last expression, but not 11971 // lvalue-to-rvalue. However, initialize an unqualified type. 11972 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11973 if (LastExpr.isInvalid()) 11974 return ExprError(); 11975 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11976 11977 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11978 // In ARC, if the final expression ends in a consume, splice 11979 // the consume out and bind it later. In the alternate case 11980 // (when dealing with a retainable type), the result 11981 // initialization will create a produce. In both cases the 11982 // result will be +1, and we'll need to balance that out with 11983 // a bind. 11984 if (Expr *rebuiltLastStmt 11985 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11986 LastExpr = rebuiltLastStmt; 11987 } else { 11988 LastExpr = PerformCopyInitialization( 11989 InitializedEntity::InitializeResult(LPLoc, 11990 Ty, 11991 false), 11992 SourceLocation(), 11993 LastExpr); 11994 } 11995 11996 if (LastExpr.isInvalid()) 11997 return ExprError(); 11998 if (LastExpr.get() != nullptr) { 11999 if (!LastLabelStmt) 12000 Compound->setLastStmt(LastExpr.get()); 12001 else 12002 LastLabelStmt->setSubStmt(LastExpr.get()); 12003 StmtExprMayBindToTemp = true; 12004 } 12005 } 12006 } 12007 } 12008 12009 // FIXME: Check that expression type is complete/non-abstract; statement 12010 // expressions are not lvalues. 12011 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12012 if (StmtExprMayBindToTemp) 12013 return MaybeBindToTemporary(ResStmtExpr); 12014 return ResStmtExpr; 12015 } 12016 12017 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12018 TypeSourceInfo *TInfo, 12019 ArrayRef<OffsetOfComponent> Components, 12020 SourceLocation RParenLoc) { 12021 QualType ArgTy = TInfo->getType(); 12022 bool Dependent = ArgTy->isDependentType(); 12023 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12024 12025 // We must have at least one component that refers to the type, and the first 12026 // one is known to be a field designator. Verify that the ArgTy represents 12027 // a struct/union/class. 12028 if (!Dependent && !ArgTy->isRecordType()) 12029 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12030 << ArgTy << TypeRange); 12031 12032 // Type must be complete per C99 7.17p3 because a declaring a variable 12033 // with an incomplete type would be ill-formed. 12034 if (!Dependent 12035 && RequireCompleteType(BuiltinLoc, ArgTy, 12036 diag::err_offsetof_incomplete_type, TypeRange)) 12037 return ExprError(); 12038 12039 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 12040 // GCC extension, diagnose them. 12041 // FIXME: This diagnostic isn't actually visible because the location is in 12042 // a system header! 12043 if (Components.size() != 1) 12044 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 12045 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 12046 12047 bool DidWarnAboutNonPOD = false; 12048 QualType CurrentType = ArgTy; 12049 SmallVector<OffsetOfNode, 4> Comps; 12050 SmallVector<Expr*, 4> Exprs; 12051 for (const OffsetOfComponent &OC : Components) { 12052 if (OC.isBrackets) { 12053 // Offset of an array sub-field. TODO: Should we allow vector elements? 12054 if (!CurrentType->isDependentType()) { 12055 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12056 if(!AT) 12057 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12058 << CurrentType); 12059 CurrentType = AT->getElementType(); 12060 } else 12061 CurrentType = Context.DependentTy; 12062 12063 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12064 if (IdxRval.isInvalid()) 12065 return ExprError(); 12066 Expr *Idx = IdxRval.get(); 12067 12068 // The expression must be an integral expression. 12069 // FIXME: An integral constant expression? 12070 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12071 !Idx->getType()->isIntegerType()) 12072 return ExprError(Diag(Idx->getLocStart(), 12073 diag::err_typecheck_subscript_not_integer) 12074 << Idx->getSourceRange()); 12075 12076 // Record this array index. 12077 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12078 Exprs.push_back(Idx); 12079 continue; 12080 } 12081 12082 // Offset of a field. 12083 if (CurrentType->isDependentType()) { 12084 // We have the offset of a field, but we can't look into the dependent 12085 // type. Just record the identifier of the field. 12086 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12087 CurrentType = Context.DependentTy; 12088 continue; 12089 } 12090 12091 // We need to have a complete type to look into. 12092 if (RequireCompleteType(OC.LocStart, CurrentType, 12093 diag::err_offsetof_incomplete_type)) 12094 return ExprError(); 12095 12096 // Look for the designated field. 12097 const RecordType *RC = CurrentType->getAs<RecordType>(); 12098 if (!RC) 12099 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12100 << CurrentType); 12101 RecordDecl *RD = RC->getDecl(); 12102 12103 // C++ [lib.support.types]p5: 12104 // The macro offsetof accepts a restricted set of type arguments in this 12105 // International Standard. type shall be a POD structure or a POD union 12106 // (clause 9). 12107 // C++11 [support.types]p4: 12108 // If type is not a standard-layout class (Clause 9), the results are 12109 // undefined. 12110 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12111 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12112 unsigned DiagID = 12113 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12114 : diag::ext_offsetof_non_pod_type; 12115 12116 if (!IsSafe && !DidWarnAboutNonPOD && 12117 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12118 PDiag(DiagID) 12119 << SourceRange(Components[0].LocStart, OC.LocEnd) 12120 << CurrentType)) 12121 DidWarnAboutNonPOD = true; 12122 } 12123 12124 // Look for the field. 12125 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12126 LookupQualifiedName(R, RD); 12127 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12128 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12129 if (!MemberDecl) { 12130 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12131 MemberDecl = IndirectMemberDecl->getAnonField(); 12132 } 12133 12134 if (!MemberDecl) 12135 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12136 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12137 OC.LocEnd)); 12138 12139 // C99 7.17p3: 12140 // (If the specified member is a bit-field, the behavior is undefined.) 12141 // 12142 // We diagnose this as an error. 12143 if (MemberDecl->isBitField()) { 12144 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12145 << MemberDecl->getDeclName() 12146 << SourceRange(BuiltinLoc, RParenLoc); 12147 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12148 return ExprError(); 12149 } 12150 12151 RecordDecl *Parent = MemberDecl->getParent(); 12152 if (IndirectMemberDecl) 12153 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12154 12155 // If the member was found in a base class, introduce OffsetOfNodes for 12156 // the base class indirections. 12157 CXXBasePaths Paths; 12158 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12159 Paths)) { 12160 if (Paths.getDetectedVirtual()) { 12161 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12162 << MemberDecl->getDeclName() 12163 << SourceRange(BuiltinLoc, RParenLoc); 12164 return ExprError(); 12165 } 12166 12167 CXXBasePath &Path = Paths.front(); 12168 for (const CXXBasePathElement &B : Path) 12169 Comps.push_back(OffsetOfNode(B.Base)); 12170 } 12171 12172 if (IndirectMemberDecl) { 12173 for (auto *FI : IndirectMemberDecl->chain()) { 12174 assert(isa<FieldDecl>(FI)); 12175 Comps.push_back(OffsetOfNode(OC.LocStart, 12176 cast<FieldDecl>(FI), OC.LocEnd)); 12177 } 12178 } else 12179 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12180 12181 CurrentType = MemberDecl->getType().getNonReferenceType(); 12182 } 12183 12184 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12185 Comps, Exprs, RParenLoc); 12186 } 12187 12188 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12189 SourceLocation BuiltinLoc, 12190 SourceLocation TypeLoc, 12191 ParsedType ParsedArgTy, 12192 ArrayRef<OffsetOfComponent> Components, 12193 SourceLocation RParenLoc) { 12194 12195 TypeSourceInfo *ArgTInfo; 12196 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12197 if (ArgTy.isNull()) 12198 return ExprError(); 12199 12200 if (!ArgTInfo) 12201 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12202 12203 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12204 } 12205 12206 12207 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12208 Expr *CondExpr, 12209 Expr *LHSExpr, Expr *RHSExpr, 12210 SourceLocation RPLoc) { 12211 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12212 12213 ExprValueKind VK = VK_RValue; 12214 ExprObjectKind OK = OK_Ordinary; 12215 QualType resType; 12216 bool ValueDependent = false; 12217 bool CondIsTrue = false; 12218 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12219 resType = Context.DependentTy; 12220 ValueDependent = true; 12221 } else { 12222 // The conditional expression is required to be a constant expression. 12223 llvm::APSInt condEval(32); 12224 ExprResult CondICE 12225 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12226 diag::err_typecheck_choose_expr_requires_constant, false); 12227 if (CondICE.isInvalid()) 12228 return ExprError(); 12229 CondExpr = CondICE.get(); 12230 CondIsTrue = condEval.getZExtValue(); 12231 12232 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12233 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12234 12235 resType = ActiveExpr->getType(); 12236 ValueDependent = ActiveExpr->isValueDependent(); 12237 VK = ActiveExpr->getValueKind(); 12238 OK = ActiveExpr->getObjectKind(); 12239 } 12240 12241 return new (Context) 12242 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12243 CondIsTrue, resType->isDependentType(), ValueDependent); 12244 } 12245 12246 //===----------------------------------------------------------------------===// 12247 // Clang Extensions. 12248 //===----------------------------------------------------------------------===// 12249 12250 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12251 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12252 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12253 12254 if (LangOpts.CPlusPlus) { 12255 Decl *ManglingContextDecl; 12256 if (MangleNumberingContext *MCtx = 12257 getCurrentMangleNumberContext(Block->getDeclContext(), 12258 ManglingContextDecl)) { 12259 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12260 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12261 } 12262 } 12263 12264 PushBlockScope(CurScope, Block); 12265 CurContext->addDecl(Block); 12266 if (CurScope) 12267 PushDeclContext(CurScope, Block); 12268 else 12269 CurContext = Block; 12270 12271 getCurBlock()->HasImplicitReturnType = true; 12272 12273 // Enter a new evaluation context to insulate the block from any 12274 // cleanups from the enclosing full-expression. 12275 PushExpressionEvaluationContext( 12276 ExpressionEvaluationContext::PotentiallyEvaluated); 12277 } 12278 12279 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12280 Scope *CurScope) { 12281 assert(ParamInfo.getIdentifier() == nullptr && 12282 "block-id should have no identifier!"); 12283 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12284 BlockScopeInfo *CurBlock = getCurBlock(); 12285 12286 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12287 QualType T = Sig->getType(); 12288 12289 // FIXME: We should allow unexpanded parameter packs here, but that would, 12290 // in turn, make the block expression contain unexpanded parameter packs. 12291 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12292 // Drop the parameters. 12293 FunctionProtoType::ExtProtoInfo EPI; 12294 EPI.HasTrailingReturn = false; 12295 EPI.TypeQuals |= DeclSpec::TQ_const; 12296 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12297 Sig = Context.getTrivialTypeSourceInfo(T); 12298 } 12299 12300 // GetTypeForDeclarator always produces a function type for a block 12301 // literal signature. Furthermore, it is always a FunctionProtoType 12302 // unless the function was written with a typedef. 12303 assert(T->isFunctionType() && 12304 "GetTypeForDeclarator made a non-function block signature"); 12305 12306 // Look for an explicit signature in that function type. 12307 FunctionProtoTypeLoc ExplicitSignature; 12308 12309 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12310 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12311 12312 // Check whether that explicit signature was synthesized by 12313 // GetTypeForDeclarator. If so, don't save that as part of the 12314 // written signature. 12315 if (ExplicitSignature.getLocalRangeBegin() == 12316 ExplicitSignature.getLocalRangeEnd()) { 12317 // This would be much cheaper if we stored TypeLocs instead of 12318 // TypeSourceInfos. 12319 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12320 unsigned Size = Result.getFullDataSize(); 12321 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12322 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12323 12324 ExplicitSignature = FunctionProtoTypeLoc(); 12325 } 12326 } 12327 12328 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12329 CurBlock->FunctionType = T; 12330 12331 const FunctionType *Fn = T->getAs<FunctionType>(); 12332 QualType RetTy = Fn->getReturnType(); 12333 bool isVariadic = 12334 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12335 12336 CurBlock->TheDecl->setIsVariadic(isVariadic); 12337 12338 // Context.DependentTy is used as a placeholder for a missing block 12339 // return type. TODO: what should we do with declarators like: 12340 // ^ * { ... } 12341 // If the answer is "apply template argument deduction".... 12342 if (RetTy != Context.DependentTy) { 12343 CurBlock->ReturnType = RetTy; 12344 CurBlock->TheDecl->setBlockMissingReturnType(false); 12345 CurBlock->HasImplicitReturnType = false; 12346 } 12347 12348 // Push block parameters from the declarator if we had them. 12349 SmallVector<ParmVarDecl*, 8> Params; 12350 if (ExplicitSignature) { 12351 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12352 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12353 if (Param->getIdentifier() == nullptr && 12354 !Param->isImplicit() && 12355 !Param->isInvalidDecl() && 12356 !getLangOpts().CPlusPlus) 12357 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12358 Params.push_back(Param); 12359 } 12360 12361 // Fake up parameter variables if we have a typedef, like 12362 // ^ fntype { ... } 12363 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12364 for (const auto &I : Fn->param_types()) { 12365 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12366 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12367 Params.push_back(Param); 12368 } 12369 } 12370 12371 // Set the parameters on the block decl. 12372 if (!Params.empty()) { 12373 CurBlock->TheDecl->setParams(Params); 12374 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12375 /*CheckParameterNames=*/false); 12376 } 12377 12378 // Finally we can process decl attributes. 12379 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12380 12381 // Put the parameter variables in scope. 12382 for (auto AI : CurBlock->TheDecl->parameters()) { 12383 AI->setOwningFunction(CurBlock->TheDecl); 12384 12385 // If this has an identifier, add it to the scope stack. 12386 if (AI->getIdentifier()) { 12387 CheckShadow(CurBlock->TheScope, AI); 12388 12389 PushOnScopeChains(AI, CurBlock->TheScope); 12390 } 12391 } 12392 } 12393 12394 /// ActOnBlockError - If there is an error parsing a block, this callback 12395 /// is invoked to pop the information about the block from the action impl. 12396 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12397 // Leave the expression-evaluation context. 12398 DiscardCleanupsInEvaluationContext(); 12399 PopExpressionEvaluationContext(); 12400 12401 // Pop off CurBlock, handle nested blocks. 12402 PopDeclContext(); 12403 PopFunctionScopeInfo(); 12404 } 12405 12406 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12407 /// literal was successfully completed. ^(int x){...} 12408 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12409 Stmt *Body, Scope *CurScope) { 12410 // If blocks are disabled, emit an error. 12411 if (!LangOpts.Blocks) 12412 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12413 12414 // Leave the expression-evaluation context. 12415 if (hasAnyUnrecoverableErrorsInThisFunction()) 12416 DiscardCleanupsInEvaluationContext(); 12417 assert(!Cleanup.exprNeedsCleanups() && 12418 "cleanups within block not correctly bound!"); 12419 PopExpressionEvaluationContext(); 12420 12421 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12422 12423 if (BSI->HasImplicitReturnType) 12424 deduceClosureReturnType(*BSI); 12425 12426 PopDeclContext(); 12427 12428 QualType RetTy = Context.VoidTy; 12429 if (!BSI->ReturnType.isNull()) 12430 RetTy = BSI->ReturnType; 12431 12432 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12433 QualType BlockTy; 12434 12435 // Set the captured variables on the block. 12436 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12437 SmallVector<BlockDecl::Capture, 4> Captures; 12438 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12439 if (Cap.isThisCapture()) 12440 continue; 12441 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12442 Cap.isNested(), Cap.getInitExpr()); 12443 Captures.push_back(NewCap); 12444 } 12445 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12446 12447 // If the user wrote a function type in some form, try to use that. 12448 if (!BSI->FunctionType.isNull()) { 12449 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12450 12451 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12452 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12453 12454 // Turn protoless block types into nullary block types. 12455 if (isa<FunctionNoProtoType>(FTy)) { 12456 FunctionProtoType::ExtProtoInfo EPI; 12457 EPI.ExtInfo = Ext; 12458 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12459 12460 // Otherwise, if we don't need to change anything about the function type, 12461 // preserve its sugar structure. 12462 } else if (FTy->getReturnType() == RetTy && 12463 (!NoReturn || FTy->getNoReturnAttr())) { 12464 BlockTy = BSI->FunctionType; 12465 12466 // Otherwise, make the minimal modifications to the function type. 12467 } else { 12468 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12469 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12470 EPI.TypeQuals = 0; // FIXME: silently? 12471 EPI.ExtInfo = Ext; 12472 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12473 } 12474 12475 // If we don't have a function type, just build one from nothing. 12476 } else { 12477 FunctionProtoType::ExtProtoInfo EPI; 12478 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12479 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12480 } 12481 12482 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12483 BlockTy = Context.getBlockPointerType(BlockTy); 12484 12485 // If needed, diagnose invalid gotos and switches in the block. 12486 if (getCurFunction()->NeedsScopeChecking() && 12487 !PP.isCodeCompletionEnabled()) 12488 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12489 12490 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12491 12492 // Try to apply the named return value optimization. We have to check again 12493 // if we can do this, though, because blocks keep return statements around 12494 // to deduce an implicit return type. 12495 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12496 !BSI->TheDecl->isDependentContext()) 12497 computeNRVO(Body, BSI); 12498 12499 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12500 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12501 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12502 12503 // If the block isn't obviously global, i.e. it captures anything at 12504 // all, then we need to do a few things in the surrounding context: 12505 if (Result->getBlockDecl()->hasCaptures()) { 12506 // First, this expression has a new cleanup object. 12507 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12508 Cleanup.setExprNeedsCleanups(true); 12509 12510 // It also gets a branch-protected scope if any of the captured 12511 // variables needs destruction. 12512 for (const auto &CI : Result->getBlockDecl()->captures()) { 12513 const VarDecl *var = CI.getVariable(); 12514 if (var->getType().isDestructedType() != QualType::DK_none) { 12515 getCurFunction()->setHasBranchProtectedScope(); 12516 break; 12517 } 12518 } 12519 } 12520 12521 return Result; 12522 } 12523 12524 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12525 SourceLocation RPLoc) { 12526 TypeSourceInfo *TInfo; 12527 GetTypeFromParser(Ty, &TInfo); 12528 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12529 } 12530 12531 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12532 Expr *E, TypeSourceInfo *TInfo, 12533 SourceLocation RPLoc) { 12534 Expr *OrigExpr = E; 12535 bool IsMS = false; 12536 12537 // CUDA device code does not support varargs. 12538 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12539 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12540 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12541 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12542 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12543 } 12544 } 12545 12546 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12547 // as Microsoft ABI on an actual Microsoft platform, where 12548 // __builtin_ms_va_list and __builtin_va_list are the same.) 12549 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12550 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12551 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12552 if (Context.hasSameType(MSVaListType, E->getType())) { 12553 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12554 return ExprError(); 12555 IsMS = true; 12556 } 12557 } 12558 12559 // Get the va_list type 12560 QualType VaListType = Context.getBuiltinVaListType(); 12561 if (!IsMS) { 12562 if (VaListType->isArrayType()) { 12563 // Deal with implicit array decay; for example, on x86-64, 12564 // va_list is an array, but it's supposed to decay to 12565 // a pointer for va_arg. 12566 VaListType = Context.getArrayDecayedType(VaListType); 12567 // Make sure the input expression also decays appropriately. 12568 ExprResult Result = UsualUnaryConversions(E); 12569 if (Result.isInvalid()) 12570 return ExprError(); 12571 E = Result.get(); 12572 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12573 // If va_list is a record type and we are compiling in C++ mode, 12574 // check the argument using reference binding. 12575 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12576 Context, Context.getLValueReferenceType(VaListType), false); 12577 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12578 if (Init.isInvalid()) 12579 return ExprError(); 12580 E = Init.getAs<Expr>(); 12581 } else { 12582 // Otherwise, the va_list argument must be an l-value because 12583 // it is modified by va_arg. 12584 if (!E->isTypeDependent() && 12585 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12586 return ExprError(); 12587 } 12588 } 12589 12590 if (!IsMS && !E->isTypeDependent() && 12591 !Context.hasSameType(VaListType, E->getType())) 12592 return ExprError(Diag(E->getLocStart(), 12593 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12594 << OrigExpr->getType() << E->getSourceRange()); 12595 12596 if (!TInfo->getType()->isDependentType()) { 12597 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12598 diag::err_second_parameter_to_va_arg_incomplete, 12599 TInfo->getTypeLoc())) 12600 return ExprError(); 12601 12602 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12603 TInfo->getType(), 12604 diag::err_second_parameter_to_va_arg_abstract, 12605 TInfo->getTypeLoc())) 12606 return ExprError(); 12607 12608 if (!TInfo->getType().isPODType(Context)) { 12609 Diag(TInfo->getTypeLoc().getBeginLoc(), 12610 TInfo->getType()->isObjCLifetimeType() 12611 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12612 : diag::warn_second_parameter_to_va_arg_not_pod) 12613 << TInfo->getType() 12614 << TInfo->getTypeLoc().getSourceRange(); 12615 } 12616 12617 // Check for va_arg where arguments of the given type will be promoted 12618 // (i.e. this va_arg is guaranteed to have undefined behavior). 12619 QualType PromoteType; 12620 if (TInfo->getType()->isPromotableIntegerType()) { 12621 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12622 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12623 PromoteType = QualType(); 12624 } 12625 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12626 PromoteType = Context.DoubleTy; 12627 if (!PromoteType.isNull()) 12628 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12629 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12630 << TInfo->getType() 12631 << PromoteType 12632 << TInfo->getTypeLoc().getSourceRange()); 12633 } 12634 12635 QualType T = TInfo->getType().getNonLValueExprType(Context); 12636 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12637 } 12638 12639 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12640 // The type of __null will be int or long, depending on the size of 12641 // pointers on the target. 12642 QualType Ty; 12643 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12644 if (pw == Context.getTargetInfo().getIntWidth()) 12645 Ty = Context.IntTy; 12646 else if (pw == Context.getTargetInfo().getLongWidth()) 12647 Ty = Context.LongTy; 12648 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12649 Ty = Context.LongLongTy; 12650 else { 12651 llvm_unreachable("I don't know size of pointer!"); 12652 } 12653 12654 return new (Context) GNUNullExpr(Ty, TokenLoc); 12655 } 12656 12657 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12658 bool Diagnose) { 12659 if (!getLangOpts().ObjC1) 12660 return false; 12661 12662 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12663 if (!PT) 12664 return false; 12665 12666 if (!PT->isObjCIdType()) { 12667 // Check if the destination is the 'NSString' interface. 12668 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12669 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12670 return false; 12671 } 12672 12673 // Ignore any parens, implicit casts (should only be 12674 // array-to-pointer decays), and not-so-opaque values. The last is 12675 // important for making this trigger for property assignments. 12676 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12677 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12678 if (OV->getSourceExpr()) 12679 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12680 12681 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12682 if (!SL || !SL->isAscii()) 12683 return false; 12684 if (Diagnose) { 12685 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12686 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12687 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12688 } 12689 return true; 12690 } 12691 12692 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12693 const Expr *SrcExpr) { 12694 if (!DstType->isFunctionPointerType() || 12695 !SrcExpr->getType()->isFunctionType()) 12696 return false; 12697 12698 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12699 if (!DRE) 12700 return false; 12701 12702 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12703 if (!FD) 12704 return false; 12705 12706 return !S.checkAddressOfFunctionIsAvailable(FD, 12707 /*Complain=*/true, 12708 SrcExpr->getLocStart()); 12709 } 12710 12711 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12712 SourceLocation Loc, 12713 QualType DstType, QualType SrcType, 12714 Expr *SrcExpr, AssignmentAction Action, 12715 bool *Complained) { 12716 if (Complained) 12717 *Complained = false; 12718 12719 // Decode the result (notice that AST's are still created for extensions). 12720 bool CheckInferredResultType = false; 12721 bool isInvalid = false; 12722 unsigned DiagKind = 0; 12723 FixItHint Hint; 12724 ConversionFixItGenerator ConvHints; 12725 bool MayHaveConvFixit = false; 12726 bool MayHaveFunctionDiff = false; 12727 const ObjCInterfaceDecl *IFace = nullptr; 12728 const ObjCProtocolDecl *PDecl = nullptr; 12729 12730 switch (ConvTy) { 12731 case Compatible: 12732 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12733 return false; 12734 12735 case PointerToInt: 12736 DiagKind = diag::ext_typecheck_convert_pointer_int; 12737 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12738 MayHaveConvFixit = true; 12739 break; 12740 case IntToPointer: 12741 DiagKind = diag::ext_typecheck_convert_int_pointer; 12742 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12743 MayHaveConvFixit = true; 12744 break; 12745 case IncompatiblePointer: 12746 if (Action == AA_Passing_CFAudited) 12747 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12748 else if (SrcType->isFunctionPointerType() && 12749 DstType->isFunctionPointerType()) 12750 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12751 else 12752 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12753 12754 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12755 SrcType->isObjCObjectPointerType(); 12756 if (Hint.isNull() && !CheckInferredResultType) { 12757 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12758 } 12759 else if (CheckInferredResultType) { 12760 SrcType = SrcType.getUnqualifiedType(); 12761 DstType = DstType.getUnqualifiedType(); 12762 } 12763 MayHaveConvFixit = true; 12764 break; 12765 case IncompatiblePointerSign: 12766 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12767 break; 12768 case FunctionVoidPointer: 12769 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12770 break; 12771 case IncompatiblePointerDiscardsQualifiers: { 12772 // Perform array-to-pointer decay if necessary. 12773 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12774 12775 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12776 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12777 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12778 DiagKind = diag::err_typecheck_incompatible_address_space; 12779 break; 12780 12781 12782 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12783 DiagKind = diag::err_typecheck_incompatible_ownership; 12784 break; 12785 } 12786 12787 llvm_unreachable("unknown error case for discarding qualifiers!"); 12788 // fallthrough 12789 } 12790 case CompatiblePointerDiscardsQualifiers: 12791 // If the qualifiers lost were because we were applying the 12792 // (deprecated) C++ conversion from a string literal to a char* 12793 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12794 // Ideally, this check would be performed in 12795 // checkPointerTypesForAssignment. However, that would require a 12796 // bit of refactoring (so that the second argument is an 12797 // expression, rather than a type), which should be done as part 12798 // of a larger effort to fix checkPointerTypesForAssignment for 12799 // C++ semantics. 12800 if (getLangOpts().CPlusPlus && 12801 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12802 return false; 12803 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12804 break; 12805 case IncompatibleNestedPointerQualifiers: 12806 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12807 break; 12808 case IntToBlockPointer: 12809 DiagKind = diag::err_int_to_block_pointer; 12810 break; 12811 case IncompatibleBlockPointer: 12812 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12813 break; 12814 case IncompatibleObjCQualifiedId: { 12815 if (SrcType->isObjCQualifiedIdType()) { 12816 const ObjCObjectPointerType *srcOPT = 12817 SrcType->getAs<ObjCObjectPointerType>(); 12818 for (auto *srcProto : srcOPT->quals()) { 12819 PDecl = srcProto; 12820 break; 12821 } 12822 if (const ObjCInterfaceType *IFaceT = 12823 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12824 IFace = IFaceT->getDecl(); 12825 } 12826 else if (DstType->isObjCQualifiedIdType()) { 12827 const ObjCObjectPointerType *dstOPT = 12828 DstType->getAs<ObjCObjectPointerType>(); 12829 for (auto *dstProto : dstOPT->quals()) { 12830 PDecl = dstProto; 12831 break; 12832 } 12833 if (const ObjCInterfaceType *IFaceT = 12834 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12835 IFace = IFaceT->getDecl(); 12836 } 12837 DiagKind = diag::warn_incompatible_qualified_id; 12838 break; 12839 } 12840 case IncompatibleVectors: 12841 DiagKind = diag::warn_incompatible_vectors; 12842 break; 12843 case IncompatibleObjCWeakRef: 12844 DiagKind = diag::err_arc_weak_unavailable_assign; 12845 break; 12846 case Incompatible: 12847 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12848 if (Complained) 12849 *Complained = true; 12850 return true; 12851 } 12852 12853 DiagKind = diag::err_typecheck_convert_incompatible; 12854 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12855 MayHaveConvFixit = true; 12856 isInvalid = true; 12857 MayHaveFunctionDiff = true; 12858 break; 12859 } 12860 12861 QualType FirstType, SecondType; 12862 switch (Action) { 12863 case AA_Assigning: 12864 case AA_Initializing: 12865 // The destination type comes first. 12866 FirstType = DstType; 12867 SecondType = SrcType; 12868 break; 12869 12870 case AA_Returning: 12871 case AA_Passing: 12872 case AA_Passing_CFAudited: 12873 case AA_Converting: 12874 case AA_Sending: 12875 case AA_Casting: 12876 // The source type comes first. 12877 FirstType = SrcType; 12878 SecondType = DstType; 12879 break; 12880 } 12881 12882 PartialDiagnostic FDiag = PDiag(DiagKind); 12883 if (Action == AA_Passing_CFAudited) 12884 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12885 else 12886 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12887 12888 // If we can fix the conversion, suggest the FixIts. 12889 assert(ConvHints.isNull() || Hint.isNull()); 12890 if (!ConvHints.isNull()) { 12891 for (FixItHint &H : ConvHints.Hints) 12892 FDiag << H; 12893 } else { 12894 FDiag << Hint; 12895 } 12896 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12897 12898 if (MayHaveFunctionDiff) 12899 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12900 12901 Diag(Loc, FDiag); 12902 if (DiagKind == diag::warn_incompatible_qualified_id && 12903 PDecl && IFace && !IFace->hasDefinition()) 12904 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 12905 << IFace->getName() << PDecl->getName(); 12906 12907 if (SecondType == Context.OverloadTy) 12908 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12909 FirstType, /*TakingAddress=*/true); 12910 12911 if (CheckInferredResultType) 12912 EmitRelatedResultTypeNote(SrcExpr); 12913 12914 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12915 EmitRelatedResultTypeNoteForReturn(DstType); 12916 12917 if (Complained) 12918 *Complained = true; 12919 return isInvalid; 12920 } 12921 12922 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12923 llvm::APSInt *Result) { 12924 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12925 public: 12926 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12927 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12928 } 12929 } Diagnoser; 12930 12931 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12932 } 12933 12934 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12935 llvm::APSInt *Result, 12936 unsigned DiagID, 12937 bool AllowFold) { 12938 class IDDiagnoser : public VerifyICEDiagnoser { 12939 unsigned DiagID; 12940 12941 public: 12942 IDDiagnoser(unsigned DiagID) 12943 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12944 12945 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12946 S.Diag(Loc, DiagID) << SR; 12947 } 12948 } Diagnoser(DiagID); 12949 12950 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12951 } 12952 12953 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12954 SourceRange SR) { 12955 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12956 } 12957 12958 ExprResult 12959 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12960 VerifyICEDiagnoser &Diagnoser, 12961 bool AllowFold) { 12962 SourceLocation DiagLoc = E->getLocStart(); 12963 12964 if (getLangOpts().CPlusPlus11) { 12965 // C++11 [expr.const]p5: 12966 // If an expression of literal class type is used in a context where an 12967 // integral constant expression is required, then that class type shall 12968 // have a single non-explicit conversion function to an integral or 12969 // unscoped enumeration type 12970 ExprResult Converted; 12971 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12972 public: 12973 CXX11ConvertDiagnoser(bool Silent) 12974 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12975 Silent, true) {} 12976 12977 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12978 QualType T) override { 12979 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12980 } 12981 12982 SemaDiagnosticBuilder diagnoseIncomplete( 12983 Sema &S, SourceLocation Loc, QualType T) override { 12984 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12985 } 12986 12987 SemaDiagnosticBuilder diagnoseExplicitConv( 12988 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12989 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12990 } 12991 12992 SemaDiagnosticBuilder noteExplicitConv( 12993 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12994 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12995 << ConvTy->isEnumeralType() << ConvTy; 12996 } 12997 12998 SemaDiagnosticBuilder diagnoseAmbiguous( 12999 Sema &S, SourceLocation Loc, QualType T) override { 13000 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13001 } 13002 13003 SemaDiagnosticBuilder noteAmbiguous( 13004 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13005 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13006 << ConvTy->isEnumeralType() << ConvTy; 13007 } 13008 13009 SemaDiagnosticBuilder diagnoseConversion( 13010 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13011 llvm_unreachable("conversion functions are permitted"); 13012 } 13013 } ConvertDiagnoser(Diagnoser.Suppress); 13014 13015 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13016 ConvertDiagnoser); 13017 if (Converted.isInvalid()) 13018 return Converted; 13019 E = Converted.get(); 13020 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13021 return ExprError(); 13022 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13023 // An ICE must be of integral or unscoped enumeration type. 13024 if (!Diagnoser.Suppress) 13025 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13026 return ExprError(); 13027 } 13028 13029 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13030 // in the non-ICE case. 13031 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13032 if (Result) 13033 *Result = E->EvaluateKnownConstInt(Context); 13034 return E; 13035 } 13036 13037 Expr::EvalResult EvalResult; 13038 SmallVector<PartialDiagnosticAt, 8> Notes; 13039 EvalResult.Diag = &Notes; 13040 13041 // Try to evaluate the expression, and produce diagnostics explaining why it's 13042 // not a constant expression as a side-effect. 13043 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13044 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13045 13046 // In C++11, we can rely on diagnostics being produced for any expression 13047 // which is not a constant expression. If no diagnostics were produced, then 13048 // this is a constant expression. 13049 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13050 if (Result) 13051 *Result = EvalResult.Val.getInt(); 13052 return E; 13053 } 13054 13055 // If our only note is the usual "invalid subexpression" note, just point 13056 // the caret at its location rather than producing an essentially 13057 // redundant note. 13058 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13059 diag::note_invalid_subexpr_in_const_expr) { 13060 DiagLoc = Notes[0].first; 13061 Notes.clear(); 13062 } 13063 13064 if (!Folded || !AllowFold) { 13065 if (!Diagnoser.Suppress) { 13066 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13067 for (const PartialDiagnosticAt &Note : Notes) 13068 Diag(Note.first, Note.second); 13069 } 13070 13071 return ExprError(); 13072 } 13073 13074 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13075 for (const PartialDiagnosticAt &Note : Notes) 13076 Diag(Note.first, Note.second); 13077 13078 if (Result) 13079 *Result = EvalResult.Val.getInt(); 13080 return E; 13081 } 13082 13083 namespace { 13084 // Handle the case where we conclude a expression which we speculatively 13085 // considered to be unevaluated is actually evaluated. 13086 class TransformToPE : public TreeTransform<TransformToPE> { 13087 typedef TreeTransform<TransformToPE> BaseTransform; 13088 13089 public: 13090 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13091 13092 // Make sure we redo semantic analysis 13093 bool AlwaysRebuild() { return true; } 13094 13095 // Make sure we handle LabelStmts correctly. 13096 // FIXME: This does the right thing, but maybe we need a more general 13097 // fix to TreeTransform? 13098 StmtResult TransformLabelStmt(LabelStmt *S) { 13099 S->getDecl()->setStmt(nullptr); 13100 return BaseTransform::TransformLabelStmt(S); 13101 } 13102 13103 // We need to special-case DeclRefExprs referring to FieldDecls which 13104 // are not part of a member pointer formation; normal TreeTransforming 13105 // doesn't catch this case because of the way we represent them in the AST. 13106 // FIXME: This is a bit ugly; is it really the best way to handle this 13107 // case? 13108 // 13109 // Error on DeclRefExprs referring to FieldDecls. 13110 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13111 if (isa<FieldDecl>(E->getDecl()) && 13112 !SemaRef.isUnevaluatedContext()) 13113 return SemaRef.Diag(E->getLocation(), 13114 diag::err_invalid_non_static_member_use) 13115 << E->getDecl() << E->getSourceRange(); 13116 13117 return BaseTransform::TransformDeclRefExpr(E); 13118 } 13119 13120 // Exception: filter out member pointer formation 13121 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13122 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13123 return E; 13124 13125 return BaseTransform::TransformUnaryOperator(E); 13126 } 13127 13128 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13129 // Lambdas never need to be transformed. 13130 return E; 13131 } 13132 }; 13133 } 13134 13135 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13136 assert(isUnevaluatedContext() && 13137 "Should only transform unevaluated expressions"); 13138 ExprEvalContexts.back().Context = 13139 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13140 if (isUnevaluatedContext()) 13141 return E; 13142 return TransformToPE(*this).TransformExpr(E); 13143 } 13144 13145 void 13146 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13147 Decl *LambdaContextDecl, 13148 bool IsDecltype) { 13149 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13150 LambdaContextDecl, IsDecltype); 13151 Cleanup.reset(); 13152 if (!MaybeODRUseExprs.empty()) 13153 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13154 } 13155 13156 void 13157 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13158 ReuseLambdaContextDecl_t, 13159 bool IsDecltype) { 13160 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13161 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13162 } 13163 13164 void Sema::PopExpressionEvaluationContext() { 13165 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13166 unsigned NumTypos = Rec.NumTypos; 13167 13168 if (!Rec.Lambdas.empty()) { 13169 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13170 unsigned D; 13171 if (Rec.isUnevaluated()) { 13172 // C++11 [expr.prim.lambda]p2: 13173 // A lambda-expression shall not appear in an unevaluated operand 13174 // (Clause 5). 13175 D = diag::err_lambda_unevaluated_operand; 13176 } else { 13177 // C++1y [expr.const]p2: 13178 // A conditional-expression e is a core constant expression unless the 13179 // evaluation of e, following the rules of the abstract machine, would 13180 // evaluate [...] a lambda-expression. 13181 D = diag::err_lambda_in_constant_expression; 13182 } 13183 13184 // C++1z allows lambda expressions as core constant expressions. 13185 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13186 // 1607) from appearing within template-arguments and array-bounds that 13187 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13188 // unevaluated contexts) might lift some of these restrictions in a 13189 // future version. 13190 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z) 13191 for (const auto *L : Rec.Lambdas) 13192 Diag(L->getLocStart(), D); 13193 } else { 13194 // Mark the capture expressions odr-used. This was deferred 13195 // during lambda expression creation. 13196 for (auto *Lambda : Rec.Lambdas) { 13197 for (auto *C : Lambda->capture_inits()) 13198 MarkDeclarationsReferencedInExpr(C); 13199 } 13200 } 13201 } 13202 13203 // When are coming out of an unevaluated context, clear out any 13204 // temporaries that we may have created as part of the evaluation of 13205 // the expression in that context: they aren't relevant because they 13206 // will never be constructed. 13207 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13208 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13209 ExprCleanupObjects.end()); 13210 Cleanup = Rec.ParentCleanup; 13211 CleanupVarDeclMarking(); 13212 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13213 // Otherwise, merge the contexts together. 13214 } else { 13215 Cleanup.mergeFrom(Rec.ParentCleanup); 13216 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13217 Rec.SavedMaybeODRUseExprs.end()); 13218 } 13219 13220 // Pop the current expression evaluation context off the stack. 13221 ExprEvalContexts.pop_back(); 13222 13223 if (!ExprEvalContexts.empty()) 13224 ExprEvalContexts.back().NumTypos += NumTypos; 13225 else 13226 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13227 "last ExpressionEvaluationContextRecord"); 13228 } 13229 13230 void Sema::DiscardCleanupsInEvaluationContext() { 13231 ExprCleanupObjects.erase( 13232 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13233 ExprCleanupObjects.end()); 13234 Cleanup.reset(); 13235 MaybeODRUseExprs.clear(); 13236 } 13237 13238 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13239 if (!E->getType()->isVariablyModifiedType()) 13240 return E; 13241 return TransformToPotentiallyEvaluated(E); 13242 } 13243 13244 /// Are we within a context in which some evaluation could be performed (be it 13245 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13246 /// captured by C++'s idea of an "unevaluated context". 13247 static bool isEvaluatableContext(Sema &SemaRef) { 13248 switch (SemaRef.ExprEvalContexts.back().Context) { 13249 case Sema::ExpressionEvaluationContext::Unevaluated: 13250 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13251 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13252 // Expressions in this context are never evaluated. 13253 return false; 13254 13255 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13256 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13257 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13258 // Expressions in this context could be evaluated. 13259 return true; 13260 13261 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13262 // Referenced declarations will only be used if the construct in the 13263 // containing expression is used, at which point we'll be given another 13264 // turn to mark them. 13265 return false; 13266 } 13267 llvm_unreachable("Invalid context"); 13268 } 13269 13270 /// Are we within a context in which references to resolved functions or to 13271 /// variables result in odr-use? 13272 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13273 // An expression in a template is not really an expression until it's been 13274 // instantiated, so it doesn't trigger odr-use. 13275 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13276 return false; 13277 13278 switch (SemaRef.ExprEvalContexts.back().Context) { 13279 case Sema::ExpressionEvaluationContext::Unevaluated: 13280 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13281 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13282 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13283 return false; 13284 13285 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13286 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13287 return true; 13288 13289 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13290 return false; 13291 } 13292 llvm_unreachable("Invalid context"); 13293 } 13294 13295 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13296 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13297 return Func->isConstexpr() && 13298 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13299 } 13300 13301 /// \brief Mark a function referenced, and check whether it is odr-used 13302 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13303 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13304 bool MightBeOdrUse) { 13305 assert(Func && "No function?"); 13306 13307 Func->setReferenced(); 13308 13309 // C++11 [basic.def.odr]p3: 13310 // A function whose name appears as a potentially-evaluated expression is 13311 // odr-used if it is the unique lookup result or the selected member of a 13312 // set of overloaded functions [...]. 13313 // 13314 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13315 // can just check that here. 13316 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13317 13318 // Determine whether we require a function definition to exist, per 13319 // C++11 [temp.inst]p3: 13320 // Unless a function template specialization has been explicitly 13321 // instantiated or explicitly specialized, the function template 13322 // specialization is implicitly instantiated when the specialization is 13323 // referenced in a context that requires a function definition to exist. 13324 // 13325 // That is either when this is an odr-use, or when a usage of a constexpr 13326 // function occurs within an evaluatable context. 13327 bool NeedDefinition = 13328 OdrUse || (isEvaluatableContext(*this) && 13329 isImplicitlyDefinableConstexprFunction(Func)); 13330 13331 // C++14 [temp.expl.spec]p6: 13332 // If a template [...] is explicitly specialized then that specialization 13333 // shall be declared before the first use of that specialization that would 13334 // cause an implicit instantiation to take place, in every translation unit 13335 // in which such a use occurs 13336 if (NeedDefinition && 13337 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13338 Func->getMemberSpecializationInfo())) 13339 checkSpecializationVisibility(Loc, Func); 13340 13341 // C++14 [except.spec]p17: 13342 // An exception-specification is considered to be needed when: 13343 // - the function is odr-used or, if it appears in an unevaluated operand, 13344 // would be odr-used if the expression were potentially-evaluated; 13345 // 13346 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13347 // function is a pure virtual function we're calling, and in that case the 13348 // function was selected by overload resolution and we need to resolve its 13349 // exception specification for a different reason. 13350 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13351 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13352 ResolveExceptionSpec(Loc, FPT); 13353 13354 // If we don't need to mark the function as used, and we don't need to 13355 // try to provide a definition, there's nothing more to do. 13356 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13357 (!NeedDefinition || Func->getBody())) 13358 return; 13359 13360 // Note that this declaration has been used. 13361 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13362 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13363 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13364 if (Constructor->isDefaultConstructor()) { 13365 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13366 return; 13367 DefineImplicitDefaultConstructor(Loc, Constructor); 13368 } else if (Constructor->isCopyConstructor()) { 13369 DefineImplicitCopyConstructor(Loc, Constructor); 13370 } else if (Constructor->isMoveConstructor()) { 13371 DefineImplicitMoveConstructor(Loc, Constructor); 13372 } 13373 } else if (Constructor->getInheritedConstructor()) { 13374 DefineInheritingConstructor(Loc, Constructor); 13375 } 13376 } else if (CXXDestructorDecl *Destructor = 13377 dyn_cast<CXXDestructorDecl>(Func)) { 13378 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13379 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13380 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13381 return; 13382 DefineImplicitDestructor(Loc, Destructor); 13383 } 13384 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13385 MarkVTableUsed(Loc, Destructor->getParent()); 13386 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13387 if (MethodDecl->isOverloadedOperator() && 13388 MethodDecl->getOverloadedOperator() == OO_Equal) { 13389 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13390 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13391 if (MethodDecl->isCopyAssignmentOperator()) 13392 DefineImplicitCopyAssignment(Loc, MethodDecl); 13393 else if (MethodDecl->isMoveAssignmentOperator()) 13394 DefineImplicitMoveAssignment(Loc, MethodDecl); 13395 } 13396 } else if (isa<CXXConversionDecl>(MethodDecl) && 13397 MethodDecl->getParent()->isLambda()) { 13398 CXXConversionDecl *Conversion = 13399 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13400 if (Conversion->isLambdaToBlockPointerConversion()) 13401 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13402 else 13403 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13404 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13405 MarkVTableUsed(Loc, MethodDecl->getParent()); 13406 } 13407 13408 // Recursive functions should be marked when used from another function. 13409 // FIXME: Is this really right? 13410 if (CurContext == Func) return; 13411 13412 // Implicit instantiation of function templates and member functions of 13413 // class templates. 13414 if (Func->isImplicitlyInstantiable()) { 13415 bool AlreadyInstantiated = false; 13416 SourceLocation PointOfInstantiation = Loc; 13417 if (FunctionTemplateSpecializationInfo *SpecInfo 13418 = Func->getTemplateSpecializationInfo()) { 13419 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13420 SpecInfo->setPointOfInstantiation(Loc); 13421 else if (SpecInfo->getTemplateSpecializationKind() 13422 == TSK_ImplicitInstantiation) { 13423 AlreadyInstantiated = true; 13424 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13425 } 13426 } else if (MemberSpecializationInfo *MSInfo 13427 = Func->getMemberSpecializationInfo()) { 13428 if (MSInfo->getPointOfInstantiation().isInvalid()) 13429 MSInfo->setPointOfInstantiation(Loc); 13430 else if (MSInfo->getTemplateSpecializationKind() 13431 == TSK_ImplicitInstantiation) { 13432 AlreadyInstantiated = true; 13433 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13434 } 13435 } 13436 13437 if (!AlreadyInstantiated || Func->isConstexpr()) { 13438 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13439 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13440 CodeSynthesisContexts.size()) 13441 PendingLocalImplicitInstantiations.push_back( 13442 std::make_pair(Func, PointOfInstantiation)); 13443 else if (Func->isConstexpr()) 13444 // Do not defer instantiations of constexpr functions, to avoid the 13445 // expression evaluator needing to call back into Sema if it sees a 13446 // call to such a function. 13447 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13448 else { 13449 PendingInstantiations.push_back(std::make_pair(Func, 13450 PointOfInstantiation)); 13451 // Notify the consumer that a function was implicitly instantiated. 13452 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13453 } 13454 } 13455 } else { 13456 // Walk redefinitions, as some of them may be instantiable. 13457 for (auto i : Func->redecls()) { 13458 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13459 MarkFunctionReferenced(Loc, i, OdrUse); 13460 } 13461 } 13462 13463 if (!OdrUse) return; 13464 13465 // Keep track of used but undefined functions. 13466 if (!Func->isDefined()) { 13467 if (mightHaveNonExternalLinkage(Func)) 13468 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13469 else if (Func->getMostRecentDecl()->isInlined() && 13470 !LangOpts.GNUInline && 13471 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13472 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13473 } 13474 13475 Func->markUsed(Context); 13476 } 13477 13478 static void 13479 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13480 ValueDecl *var, DeclContext *DC) { 13481 DeclContext *VarDC = var->getDeclContext(); 13482 13483 // If the parameter still belongs to the translation unit, then 13484 // we're actually just using one parameter in the declaration of 13485 // the next. 13486 if (isa<ParmVarDecl>(var) && 13487 isa<TranslationUnitDecl>(VarDC)) 13488 return; 13489 13490 // For C code, don't diagnose about capture if we're not actually in code 13491 // right now; it's impossible to write a non-constant expression outside of 13492 // function context, so we'll get other (more useful) diagnostics later. 13493 // 13494 // For C++, things get a bit more nasty... it would be nice to suppress this 13495 // diagnostic for certain cases like using a local variable in an array bound 13496 // for a member of a local class, but the correct predicate is not obvious. 13497 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13498 return; 13499 13500 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13501 unsigned ContextKind = 3; // unknown 13502 if (isa<CXXMethodDecl>(VarDC) && 13503 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13504 ContextKind = 2; 13505 } else if (isa<FunctionDecl>(VarDC)) { 13506 ContextKind = 0; 13507 } else if (isa<BlockDecl>(VarDC)) { 13508 ContextKind = 1; 13509 } 13510 13511 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13512 << var << ValueKind << ContextKind << VarDC; 13513 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13514 << var; 13515 13516 // FIXME: Add additional diagnostic info about class etc. which prevents 13517 // capture. 13518 } 13519 13520 13521 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13522 bool &SubCapturesAreNested, 13523 QualType &CaptureType, 13524 QualType &DeclRefType) { 13525 // Check whether we've already captured it. 13526 if (CSI->CaptureMap.count(Var)) { 13527 // If we found a capture, any subcaptures are nested. 13528 SubCapturesAreNested = true; 13529 13530 // Retrieve the capture type for this variable. 13531 CaptureType = CSI->getCapture(Var).getCaptureType(); 13532 13533 // Compute the type of an expression that refers to this variable. 13534 DeclRefType = CaptureType.getNonReferenceType(); 13535 13536 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13537 // are mutable in the sense that user can change their value - they are 13538 // private instances of the captured declarations. 13539 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13540 if (Cap.isCopyCapture() && 13541 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13542 !(isa<CapturedRegionScopeInfo>(CSI) && 13543 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13544 DeclRefType.addConst(); 13545 return true; 13546 } 13547 return false; 13548 } 13549 13550 // Only block literals, captured statements, and lambda expressions can 13551 // capture; other scopes don't work. 13552 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13553 SourceLocation Loc, 13554 const bool Diagnose, Sema &S) { 13555 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13556 return getLambdaAwareParentOfDeclContext(DC); 13557 else if (Var->hasLocalStorage()) { 13558 if (Diagnose) 13559 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13560 } 13561 return nullptr; 13562 } 13563 13564 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13565 // certain types of variables (unnamed, variably modified types etc.) 13566 // so check for eligibility. 13567 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13568 SourceLocation Loc, 13569 const bool Diagnose, Sema &S) { 13570 13571 bool IsBlock = isa<BlockScopeInfo>(CSI); 13572 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13573 13574 // Lambdas are not allowed to capture unnamed variables 13575 // (e.g. anonymous unions). 13576 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13577 // assuming that's the intent. 13578 if (IsLambda && !Var->getDeclName()) { 13579 if (Diagnose) { 13580 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13581 S.Diag(Var->getLocation(), diag::note_declared_at); 13582 } 13583 return false; 13584 } 13585 13586 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13587 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13588 if (Diagnose) { 13589 S.Diag(Loc, diag::err_ref_vm_type); 13590 S.Diag(Var->getLocation(), diag::note_previous_decl) 13591 << Var->getDeclName(); 13592 } 13593 return false; 13594 } 13595 // Prohibit structs with flexible array members too. 13596 // We cannot capture what is in the tail end of the struct. 13597 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13598 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13599 if (Diagnose) { 13600 if (IsBlock) 13601 S.Diag(Loc, diag::err_ref_flexarray_type); 13602 else 13603 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13604 << Var->getDeclName(); 13605 S.Diag(Var->getLocation(), diag::note_previous_decl) 13606 << Var->getDeclName(); 13607 } 13608 return false; 13609 } 13610 } 13611 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13612 // Lambdas and captured statements are not allowed to capture __block 13613 // variables; they don't support the expected semantics. 13614 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13615 if (Diagnose) { 13616 S.Diag(Loc, diag::err_capture_block_variable) 13617 << Var->getDeclName() << !IsLambda; 13618 S.Diag(Var->getLocation(), diag::note_previous_decl) 13619 << Var->getDeclName(); 13620 } 13621 return false; 13622 } 13623 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 13624 if (S.getLangOpts().OpenCL && IsBlock && 13625 Var->getType()->isBlockPointerType()) { 13626 if (Diagnose) 13627 S.Diag(Loc, diag::err_opencl_block_ref_block); 13628 return false; 13629 } 13630 13631 return true; 13632 } 13633 13634 // Returns true if the capture by block was successful. 13635 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13636 SourceLocation Loc, 13637 const bool BuildAndDiagnose, 13638 QualType &CaptureType, 13639 QualType &DeclRefType, 13640 const bool Nested, 13641 Sema &S) { 13642 Expr *CopyExpr = nullptr; 13643 bool ByRef = false; 13644 13645 // Blocks are not allowed to capture arrays. 13646 if (CaptureType->isArrayType()) { 13647 if (BuildAndDiagnose) { 13648 S.Diag(Loc, diag::err_ref_array_type); 13649 S.Diag(Var->getLocation(), diag::note_previous_decl) 13650 << Var->getDeclName(); 13651 } 13652 return false; 13653 } 13654 13655 // Forbid the block-capture of autoreleasing variables. 13656 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13657 if (BuildAndDiagnose) { 13658 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13659 << /*block*/ 0; 13660 S.Diag(Var->getLocation(), diag::note_previous_decl) 13661 << Var->getDeclName(); 13662 } 13663 return false; 13664 } 13665 13666 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13667 if (const auto *PT = CaptureType->getAs<PointerType>()) { 13668 // This function finds out whether there is an AttributedType of kind 13669 // attr_objc_ownership in Ty. The existence of AttributedType of kind 13670 // attr_objc_ownership implies __autoreleasing was explicitly specified 13671 // rather than being added implicitly by the compiler. 13672 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 13673 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 13674 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 13675 return true; 13676 13677 // Peel off AttributedTypes that are not of kind objc_ownership. 13678 Ty = AttrTy->getModifiedType(); 13679 } 13680 13681 return false; 13682 }; 13683 13684 QualType PointeeTy = PT->getPointeeType(); 13685 13686 if (PointeeTy->getAs<ObjCObjectPointerType>() && 13687 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13688 !IsObjCOwnershipAttributedType(PointeeTy)) { 13689 if (BuildAndDiagnose) { 13690 SourceLocation VarLoc = Var->getLocation(); 13691 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13692 { 13693 auto AddAutoreleaseNote = 13694 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 13695 // Provide a fix-it for the '__autoreleasing' keyword at the 13696 // appropriate location in the variable's type. 13697 if (const auto *TSI = Var->getTypeSourceInfo()) { 13698 PointerTypeLoc PTL = 13699 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 13700 if (PTL) { 13701 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 13702 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 13703 S.getLangOpts()); 13704 if (Loc.isValid()) { 13705 StringRef CharAtLoc = Lexer::getSourceText( 13706 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 13707 S.getSourceManager(), S.getLangOpts()); 13708 AddAutoreleaseNote << FixItHint::CreateInsertion( 13709 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 13710 ? " __autoreleasing " 13711 : " __autoreleasing"); 13712 } 13713 } 13714 } 13715 } 13716 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13717 } 13718 } 13719 } 13720 13721 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13722 if (HasBlocksAttr || CaptureType->isReferenceType() || 13723 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13724 // Block capture by reference does not change the capture or 13725 // declaration reference types. 13726 ByRef = true; 13727 } else { 13728 // Block capture by copy introduces 'const'. 13729 CaptureType = CaptureType.getNonReferenceType().withConst(); 13730 DeclRefType = CaptureType; 13731 13732 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13733 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13734 // The capture logic needs the destructor, so make sure we mark it. 13735 // Usually this is unnecessary because most local variables have 13736 // their destructors marked at declaration time, but parameters are 13737 // an exception because it's technically only the call site that 13738 // actually requires the destructor. 13739 if (isa<ParmVarDecl>(Var)) 13740 S.FinalizeVarWithDestructor(Var, Record); 13741 13742 // Enter a new evaluation context to insulate the copy 13743 // full-expression. 13744 EnterExpressionEvaluationContext scope( 13745 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 13746 13747 // According to the blocks spec, the capture of a variable from 13748 // the stack requires a const copy constructor. This is not true 13749 // of the copy/move done to move a __block variable to the heap. 13750 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13751 DeclRefType.withConst(), 13752 VK_LValue, Loc); 13753 13754 ExprResult Result 13755 = S.PerformCopyInitialization( 13756 InitializedEntity::InitializeBlock(Var->getLocation(), 13757 CaptureType, false), 13758 Loc, DeclRef); 13759 13760 // Build a full-expression copy expression if initialization 13761 // succeeded and used a non-trivial constructor. Recover from 13762 // errors by pretending that the copy isn't necessary. 13763 if (!Result.isInvalid() && 13764 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13765 ->isTrivial()) { 13766 Result = S.MaybeCreateExprWithCleanups(Result); 13767 CopyExpr = Result.get(); 13768 } 13769 } 13770 } 13771 } 13772 13773 // Actually capture the variable. 13774 if (BuildAndDiagnose) 13775 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13776 SourceLocation(), CaptureType, CopyExpr); 13777 13778 return true; 13779 13780 } 13781 13782 13783 /// \brief Capture the given variable in the captured region. 13784 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13785 VarDecl *Var, 13786 SourceLocation Loc, 13787 const bool BuildAndDiagnose, 13788 QualType &CaptureType, 13789 QualType &DeclRefType, 13790 const bool RefersToCapturedVariable, 13791 Sema &S) { 13792 // By default, capture variables by reference. 13793 bool ByRef = true; 13794 // Using an LValue reference type is consistent with Lambdas (see below). 13795 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13796 if (S.IsOpenMPCapturedDecl(Var)) 13797 DeclRefType = DeclRefType.getUnqualifiedType(); 13798 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13799 } 13800 13801 if (ByRef) 13802 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13803 else 13804 CaptureType = DeclRefType; 13805 13806 Expr *CopyExpr = nullptr; 13807 if (BuildAndDiagnose) { 13808 // The current implementation assumes that all variables are captured 13809 // by references. Since there is no capture by copy, no expression 13810 // evaluation will be needed. 13811 RecordDecl *RD = RSI->TheRecordDecl; 13812 13813 FieldDecl *Field 13814 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13815 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13816 nullptr, false, ICIS_NoInit); 13817 Field->setImplicit(true); 13818 Field->setAccess(AS_private); 13819 RD->addDecl(Field); 13820 13821 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13822 DeclRefType, VK_LValue, Loc); 13823 Var->setReferenced(true); 13824 Var->markUsed(S.Context); 13825 } 13826 13827 // Actually capture the variable. 13828 if (BuildAndDiagnose) 13829 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13830 SourceLocation(), CaptureType, CopyExpr); 13831 13832 13833 return true; 13834 } 13835 13836 /// \brief Create a field within the lambda class for the variable 13837 /// being captured. 13838 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13839 QualType FieldType, QualType DeclRefType, 13840 SourceLocation Loc, 13841 bool RefersToCapturedVariable) { 13842 CXXRecordDecl *Lambda = LSI->Lambda; 13843 13844 // Build the non-static data member. 13845 FieldDecl *Field 13846 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13847 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13848 nullptr, false, ICIS_NoInit); 13849 Field->setImplicit(true); 13850 Field->setAccess(AS_private); 13851 Lambda->addDecl(Field); 13852 } 13853 13854 /// \brief Capture the given variable in the lambda. 13855 static bool captureInLambda(LambdaScopeInfo *LSI, 13856 VarDecl *Var, 13857 SourceLocation Loc, 13858 const bool BuildAndDiagnose, 13859 QualType &CaptureType, 13860 QualType &DeclRefType, 13861 const bool RefersToCapturedVariable, 13862 const Sema::TryCaptureKind Kind, 13863 SourceLocation EllipsisLoc, 13864 const bool IsTopScope, 13865 Sema &S) { 13866 13867 // Determine whether we are capturing by reference or by value. 13868 bool ByRef = false; 13869 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13870 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13871 } else { 13872 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13873 } 13874 13875 // Compute the type of the field that will capture this variable. 13876 if (ByRef) { 13877 // C++11 [expr.prim.lambda]p15: 13878 // An entity is captured by reference if it is implicitly or 13879 // explicitly captured but not captured by copy. It is 13880 // unspecified whether additional unnamed non-static data 13881 // members are declared in the closure type for entities 13882 // captured by reference. 13883 // 13884 // FIXME: It is not clear whether we want to build an lvalue reference 13885 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13886 // to do the former, while EDG does the latter. Core issue 1249 will 13887 // clarify, but for now we follow GCC because it's a more permissive and 13888 // easily defensible position. 13889 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13890 } else { 13891 // C++11 [expr.prim.lambda]p14: 13892 // For each entity captured by copy, an unnamed non-static 13893 // data member is declared in the closure type. The 13894 // declaration order of these members is unspecified. The type 13895 // of such a data member is the type of the corresponding 13896 // captured entity if the entity is not a reference to an 13897 // object, or the referenced type otherwise. [Note: If the 13898 // captured entity is a reference to a function, the 13899 // corresponding data member is also a reference to a 13900 // function. - end note ] 13901 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13902 if (!RefType->getPointeeType()->isFunctionType()) 13903 CaptureType = RefType->getPointeeType(); 13904 } 13905 13906 // Forbid the lambda copy-capture of autoreleasing variables. 13907 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13908 if (BuildAndDiagnose) { 13909 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13910 S.Diag(Var->getLocation(), diag::note_previous_decl) 13911 << Var->getDeclName(); 13912 } 13913 return false; 13914 } 13915 13916 // Make sure that by-copy captures are of a complete and non-abstract type. 13917 if (BuildAndDiagnose) { 13918 if (!CaptureType->isDependentType() && 13919 S.RequireCompleteType(Loc, CaptureType, 13920 diag::err_capture_of_incomplete_type, 13921 Var->getDeclName())) 13922 return false; 13923 13924 if (S.RequireNonAbstractType(Loc, CaptureType, 13925 diag::err_capture_of_abstract_type)) 13926 return false; 13927 } 13928 } 13929 13930 // Capture this variable in the lambda. 13931 if (BuildAndDiagnose) 13932 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13933 RefersToCapturedVariable); 13934 13935 // Compute the type of a reference to this captured variable. 13936 if (ByRef) 13937 DeclRefType = CaptureType.getNonReferenceType(); 13938 else { 13939 // C++ [expr.prim.lambda]p5: 13940 // The closure type for a lambda-expression has a public inline 13941 // function call operator [...]. This function call operator is 13942 // declared const (9.3.1) if and only if the lambda-expression's 13943 // parameter-declaration-clause is not followed by mutable. 13944 DeclRefType = CaptureType.getNonReferenceType(); 13945 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13946 DeclRefType.addConst(); 13947 } 13948 13949 // Add the capture. 13950 if (BuildAndDiagnose) 13951 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13952 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13953 13954 return true; 13955 } 13956 13957 bool Sema::tryCaptureVariable( 13958 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13959 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13960 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13961 // An init-capture is notionally from the context surrounding its 13962 // declaration, but its parent DC is the lambda class. 13963 DeclContext *VarDC = Var->getDeclContext(); 13964 if (Var->isInitCapture()) 13965 VarDC = VarDC->getParent(); 13966 13967 DeclContext *DC = CurContext; 13968 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13969 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13970 // We need to sync up the Declaration Context with the 13971 // FunctionScopeIndexToStopAt 13972 if (FunctionScopeIndexToStopAt) { 13973 unsigned FSIndex = FunctionScopes.size() - 1; 13974 while (FSIndex != MaxFunctionScopesIndex) { 13975 DC = getLambdaAwareParentOfDeclContext(DC); 13976 --FSIndex; 13977 } 13978 } 13979 13980 13981 // If the variable is declared in the current context, there is no need to 13982 // capture it. 13983 if (VarDC == DC) return true; 13984 13985 // Capture global variables if it is required to use private copy of this 13986 // variable. 13987 bool IsGlobal = !Var->hasLocalStorage(); 13988 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13989 return true; 13990 13991 // Walk up the stack to determine whether we can capture the variable, 13992 // performing the "simple" checks that don't depend on type. We stop when 13993 // we've either hit the declared scope of the variable or find an existing 13994 // capture of that variable. We start from the innermost capturing-entity 13995 // (the DC) and ensure that all intervening capturing-entities 13996 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13997 // declcontext can either capture the variable or have already captured 13998 // the variable. 13999 CaptureType = Var->getType(); 14000 DeclRefType = CaptureType.getNonReferenceType(); 14001 bool Nested = false; 14002 bool Explicit = (Kind != TryCapture_Implicit); 14003 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14004 do { 14005 // Only block literals, captured statements, and lambda expressions can 14006 // capture; other scopes don't work. 14007 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14008 ExprLoc, 14009 BuildAndDiagnose, 14010 *this); 14011 // We need to check for the parent *first* because, if we *have* 14012 // private-captured a global variable, we need to recursively capture it in 14013 // intermediate blocks, lambdas, etc. 14014 if (!ParentDC) { 14015 if (IsGlobal) { 14016 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14017 break; 14018 } 14019 return true; 14020 } 14021 14022 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14023 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14024 14025 14026 // Check whether we've already captured it. 14027 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14028 DeclRefType)) { 14029 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14030 break; 14031 } 14032 // If we are instantiating a generic lambda call operator body, 14033 // we do not want to capture new variables. What was captured 14034 // during either a lambdas transformation or initial parsing 14035 // should be used. 14036 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14037 if (BuildAndDiagnose) { 14038 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14039 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14040 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14041 Diag(Var->getLocation(), diag::note_previous_decl) 14042 << Var->getDeclName(); 14043 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14044 } else 14045 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14046 } 14047 return true; 14048 } 14049 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14050 // certain types of variables (unnamed, variably modified types etc.) 14051 // so check for eligibility. 14052 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14053 return true; 14054 14055 // Try to capture variable-length arrays types. 14056 if (Var->getType()->isVariablyModifiedType()) { 14057 // We're going to walk down into the type and look for VLA 14058 // expressions. 14059 QualType QTy = Var->getType(); 14060 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14061 QTy = PVD->getOriginalType(); 14062 captureVariablyModifiedType(Context, QTy, CSI); 14063 } 14064 14065 if (getLangOpts().OpenMP) { 14066 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14067 // OpenMP private variables should not be captured in outer scope, so 14068 // just break here. Similarly, global variables that are captured in a 14069 // target region should not be captured outside the scope of the region. 14070 if (RSI->CapRegionKind == CR_OpenMP) { 14071 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14072 // When we detect target captures we are looking from inside the 14073 // target region, therefore we need to propagate the capture from the 14074 // enclosing region. Therefore, the capture is not initially nested. 14075 if (IsTargetCap) 14076 FunctionScopesIndex--; 14077 14078 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 14079 Nested = !IsTargetCap; 14080 DeclRefType = DeclRefType.getUnqualifiedType(); 14081 CaptureType = Context.getLValueReferenceType(DeclRefType); 14082 break; 14083 } 14084 } 14085 } 14086 } 14087 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14088 // No capture-default, and this is not an explicit capture 14089 // so cannot capture this variable. 14090 if (BuildAndDiagnose) { 14091 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14092 Diag(Var->getLocation(), diag::note_previous_decl) 14093 << Var->getDeclName(); 14094 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14095 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14096 diag::note_lambda_decl); 14097 // FIXME: If we error out because an outer lambda can not implicitly 14098 // capture a variable that an inner lambda explicitly captures, we 14099 // should have the inner lambda do the explicit capture - because 14100 // it makes for cleaner diagnostics later. This would purely be done 14101 // so that the diagnostic does not misleadingly claim that a variable 14102 // can not be captured by a lambda implicitly even though it is captured 14103 // explicitly. Suggestion: 14104 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14105 // at the function head 14106 // - cache the StartingDeclContext - this must be a lambda 14107 // - captureInLambda in the innermost lambda the variable. 14108 } 14109 return true; 14110 } 14111 14112 FunctionScopesIndex--; 14113 DC = ParentDC; 14114 Explicit = false; 14115 } while (!VarDC->Equals(DC)); 14116 14117 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14118 // computing the type of the capture at each step, checking type-specific 14119 // requirements, and adding captures if requested. 14120 // If the variable had already been captured previously, we start capturing 14121 // at the lambda nested within that one. 14122 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14123 ++I) { 14124 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14125 14126 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14127 if (!captureInBlock(BSI, Var, ExprLoc, 14128 BuildAndDiagnose, CaptureType, 14129 DeclRefType, Nested, *this)) 14130 return true; 14131 Nested = true; 14132 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14133 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14134 BuildAndDiagnose, CaptureType, 14135 DeclRefType, Nested, *this)) 14136 return true; 14137 Nested = true; 14138 } else { 14139 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14140 if (!captureInLambda(LSI, Var, ExprLoc, 14141 BuildAndDiagnose, CaptureType, 14142 DeclRefType, Nested, Kind, EllipsisLoc, 14143 /*IsTopScope*/I == N - 1, *this)) 14144 return true; 14145 Nested = true; 14146 } 14147 } 14148 return false; 14149 } 14150 14151 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14152 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14153 QualType CaptureType; 14154 QualType DeclRefType; 14155 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14156 /*BuildAndDiagnose=*/true, CaptureType, 14157 DeclRefType, nullptr); 14158 } 14159 14160 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14161 QualType CaptureType; 14162 QualType DeclRefType; 14163 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14164 /*BuildAndDiagnose=*/false, CaptureType, 14165 DeclRefType, nullptr); 14166 } 14167 14168 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14169 QualType CaptureType; 14170 QualType DeclRefType; 14171 14172 // Determine whether we can capture this variable. 14173 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14174 /*BuildAndDiagnose=*/false, CaptureType, 14175 DeclRefType, nullptr)) 14176 return QualType(); 14177 14178 return DeclRefType; 14179 } 14180 14181 14182 14183 // If either the type of the variable or the initializer is dependent, 14184 // return false. Otherwise, determine whether the variable is a constant 14185 // expression. Use this if you need to know if a variable that might or 14186 // might not be dependent is truly a constant expression. 14187 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14188 ASTContext &Context) { 14189 14190 if (Var->getType()->isDependentType()) 14191 return false; 14192 const VarDecl *DefVD = nullptr; 14193 Var->getAnyInitializer(DefVD); 14194 if (!DefVD) 14195 return false; 14196 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14197 Expr *Init = cast<Expr>(Eval->Value); 14198 if (Init->isValueDependent()) 14199 return false; 14200 return IsVariableAConstantExpression(Var, Context); 14201 } 14202 14203 14204 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14205 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14206 // an object that satisfies the requirements for appearing in a 14207 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14208 // is immediately applied." This function handles the lvalue-to-rvalue 14209 // conversion part. 14210 MaybeODRUseExprs.erase(E->IgnoreParens()); 14211 14212 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14213 // to a variable that is a constant expression, and if so, identify it as 14214 // a reference to a variable that does not involve an odr-use of that 14215 // variable. 14216 if (LambdaScopeInfo *LSI = getCurLambda()) { 14217 Expr *SansParensExpr = E->IgnoreParens(); 14218 VarDecl *Var = nullptr; 14219 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14220 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14221 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14222 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14223 14224 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14225 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14226 } 14227 } 14228 14229 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14230 Res = CorrectDelayedTyposInExpr(Res); 14231 14232 if (!Res.isUsable()) 14233 return Res; 14234 14235 // If a constant-expression is a reference to a variable where we delay 14236 // deciding whether it is an odr-use, just assume we will apply the 14237 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14238 // (a non-type template argument), we have special handling anyway. 14239 UpdateMarkingForLValueToRValue(Res.get()); 14240 return Res; 14241 } 14242 14243 void Sema::CleanupVarDeclMarking() { 14244 for (Expr *E : MaybeODRUseExprs) { 14245 VarDecl *Var; 14246 SourceLocation Loc; 14247 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14248 Var = cast<VarDecl>(DRE->getDecl()); 14249 Loc = DRE->getLocation(); 14250 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14251 Var = cast<VarDecl>(ME->getMemberDecl()); 14252 Loc = ME->getMemberLoc(); 14253 } else { 14254 llvm_unreachable("Unexpected expression"); 14255 } 14256 14257 MarkVarDeclODRUsed(Var, Loc, *this, 14258 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14259 } 14260 14261 MaybeODRUseExprs.clear(); 14262 } 14263 14264 14265 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14266 VarDecl *Var, Expr *E) { 14267 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14268 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14269 Var->setReferenced(); 14270 14271 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14272 14273 bool OdrUseContext = isOdrUseContext(SemaRef); 14274 bool NeedDefinition = 14275 OdrUseContext || (isEvaluatableContext(SemaRef) && 14276 Var->isUsableInConstantExpressions(SemaRef.Context)); 14277 14278 VarTemplateSpecializationDecl *VarSpec = 14279 dyn_cast<VarTemplateSpecializationDecl>(Var); 14280 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14281 "Can't instantiate a partial template specialization."); 14282 14283 // If this might be a member specialization of a static data member, check 14284 // the specialization is visible. We already did the checks for variable 14285 // template specializations when we created them. 14286 if (NeedDefinition && TSK != TSK_Undeclared && 14287 !isa<VarTemplateSpecializationDecl>(Var)) 14288 SemaRef.checkSpecializationVisibility(Loc, Var); 14289 14290 // Perform implicit instantiation of static data members, static data member 14291 // templates of class templates, and variable template specializations. Delay 14292 // instantiations of variable templates, except for those that could be used 14293 // in a constant expression. 14294 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14295 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14296 14297 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14298 if (Var->getPointOfInstantiation().isInvalid()) { 14299 // This is a modification of an existing AST node. Notify listeners. 14300 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14301 L->StaticDataMemberInstantiated(Var); 14302 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14303 // Don't bother trying to instantiate it again, unless we might need 14304 // its initializer before we get to the end of the TU. 14305 TryInstantiating = false; 14306 } 14307 14308 if (Var->getPointOfInstantiation().isInvalid()) 14309 Var->setTemplateSpecializationKind(TSK, Loc); 14310 14311 if (TryInstantiating) { 14312 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14313 bool InstantiationDependent = false; 14314 bool IsNonDependent = 14315 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14316 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14317 : true; 14318 14319 // Do not instantiate specializations that are still type-dependent. 14320 if (IsNonDependent) { 14321 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14322 // Do not defer instantiations of variables which could be used in a 14323 // constant expression. 14324 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14325 } else { 14326 SemaRef.PendingInstantiations 14327 .push_back(std::make_pair(Var, PointOfInstantiation)); 14328 } 14329 } 14330 } 14331 } 14332 14333 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14334 // the requirements for appearing in a constant expression (5.19) and, if 14335 // it is an object, the lvalue-to-rvalue conversion (4.1) 14336 // is immediately applied." We check the first part here, and 14337 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14338 // Note that we use the C++11 definition everywhere because nothing in 14339 // C++03 depends on whether we get the C++03 version correct. The second 14340 // part does not apply to references, since they are not objects. 14341 if (OdrUseContext && E && 14342 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14343 // A reference initialized by a constant expression can never be 14344 // odr-used, so simply ignore it. 14345 if (!Var->getType()->isReferenceType()) 14346 SemaRef.MaybeODRUseExprs.insert(E); 14347 } else if (OdrUseContext) { 14348 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14349 /*MaxFunctionScopeIndex ptr*/ nullptr); 14350 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14351 // If this is a dependent context, we don't need to mark variables as 14352 // odr-used, but we may still need to track them for lambda capture. 14353 // FIXME: Do we also need to do this inside dependent typeid expressions 14354 // (which are modeled as unevaluated at this point)? 14355 const bool RefersToEnclosingScope = 14356 (SemaRef.CurContext != Var->getDeclContext() && 14357 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14358 if (RefersToEnclosingScope) { 14359 LambdaScopeInfo *const LSI = 14360 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14361 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14362 // If a variable could potentially be odr-used, defer marking it so 14363 // until we finish analyzing the full expression for any 14364 // lvalue-to-rvalue 14365 // or discarded value conversions that would obviate odr-use. 14366 // Add it to the list of potential captures that will be analyzed 14367 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14368 // unless the variable is a reference that was initialized by a constant 14369 // expression (this will never need to be captured or odr-used). 14370 assert(E && "Capture variable should be used in an expression."); 14371 if (!Var->getType()->isReferenceType() || 14372 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14373 LSI->addPotentialCapture(E->IgnoreParens()); 14374 } 14375 } 14376 } 14377 } 14378 14379 /// \brief Mark a variable referenced, and check whether it is odr-used 14380 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14381 /// used directly for normal expressions referring to VarDecl. 14382 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14383 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14384 } 14385 14386 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14387 Decl *D, Expr *E, bool MightBeOdrUse) { 14388 if (SemaRef.isInOpenMPDeclareTargetContext()) 14389 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14390 14391 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14392 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14393 return; 14394 } 14395 14396 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14397 14398 // If this is a call to a method via a cast, also mark the method in the 14399 // derived class used in case codegen can devirtualize the call. 14400 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14401 if (!ME) 14402 return; 14403 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14404 if (!MD) 14405 return; 14406 // Only attempt to devirtualize if this is truly a virtual call. 14407 bool IsVirtualCall = MD->isVirtual() && 14408 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14409 if (!IsVirtualCall) 14410 return; 14411 const Expr *Base = ME->getBase(); 14412 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14413 if (!MostDerivedClassDecl) 14414 return; 14415 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14416 if (!DM || DM->isPure()) 14417 return; 14418 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14419 } 14420 14421 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14422 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14423 // TODO: update this with DR# once a defect report is filed. 14424 // C++11 defect. The address of a pure member should not be an ODR use, even 14425 // if it's a qualified reference. 14426 bool OdrUse = true; 14427 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14428 if (Method->isVirtual()) 14429 OdrUse = false; 14430 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14431 } 14432 14433 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14434 void Sema::MarkMemberReferenced(MemberExpr *E) { 14435 // C++11 [basic.def.odr]p2: 14436 // A non-overloaded function whose name appears as a potentially-evaluated 14437 // expression or a member of a set of candidate functions, if selected by 14438 // overload resolution when referred to from a potentially-evaluated 14439 // expression, is odr-used, unless it is a pure virtual function and its 14440 // name is not explicitly qualified. 14441 bool MightBeOdrUse = true; 14442 if (E->performsVirtualDispatch(getLangOpts())) { 14443 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14444 if (Method->isPure()) 14445 MightBeOdrUse = false; 14446 } 14447 SourceLocation Loc = E->getMemberLoc().isValid() ? 14448 E->getMemberLoc() : E->getLocStart(); 14449 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14450 } 14451 14452 /// \brief Perform marking for a reference to an arbitrary declaration. It 14453 /// marks the declaration referenced, and performs odr-use checking for 14454 /// functions and variables. This method should not be used when building a 14455 /// normal expression which refers to a variable. 14456 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14457 bool MightBeOdrUse) { 14458 if (MightBeOdrUse) { 14459 if (auto *VD = dyn_cast<VarDecl>(D)) { 14460 MarkVariableReferenced(Loc, VD); 14461 return; 14462 } 14463 } 14464 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14465 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14466 return; 14467 } 14468 D->setReferenced(); 14469 } 14470 14471 namespace { 14472 // Mark all of the declarations used by a type as referenced. 14473 // FIXME: Not fully implemented yet! We need to have a better understanding 14474 // of when we're entering a context we should not recurse into. 14475 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 14476 // TreeTransforms rebuilding the type in a new context. Rather than 14477 // duplicating the TreeTransform logic, we should consider reusing it here. 14478 // Currently that causes problems when rebuilding LambdaExprs. 14479 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14480 Sema &S; 14481 SourceLocation Loc; 14482 14483 public: 14484 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14485 14486 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14487 14488 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14489 }; 14490 } 14491 14492 bool MarkReferencedDecls::TraverseTemplateArgument( 14493 const TemplateArgument &Arg) { 14494 { 14495 // A non-type template argument is a constant-evaluated context. 14496 EnterExpressionEvaluationContext Evaluated( 14497 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 14498 if (Arg.getKind() == TemplateArgument::Declaration) { 14499 if (Decl *D = Arg.getAsDecl()) 14500 S.MarkAnyDeclReferenced(Loc, D, true); 14501 } else if (Arg.getKind() == TemplateArgument::Expression) { 14502 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 14503 } 14504 } 14505 14506 return Inherited::TraverseTemplateArgument(Arg); 14507 } 14508 14509 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14510 MarkReferencedDecls Marker(*this, Loc); 14511 Marker.TraverseType(T); 14512 } 14513 14514 namespace { 14515 /// \brief Helper class that marks all of the declarations referenced by 14516 /// potentially-evaluated subexpressions as "referenced". 14517 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14518 Sema &S; 14519 bool SkipLocalVariables; 14520 14521 public: 14522 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14523 14524 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14525 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14526 14527 void VisitDeclRefExpr(DeclRefExpr *E) { 14528 // If we were asked not to visit local variables, don't. 14529 if (SkipLocalVariables) { 14530 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14531 if (VD->hasLocalStorage()) 14532 return; 14533 } 14534 14535 S.MarkDeclRefReferenced(E); 14536 } 14537 14538 void VisitMemberExpr(MemberExpr *E) { 14539 S.MarkMemberReferenced(E); 14540 Inherited::VisitMemberExpr(E); 14541 } 14542 14543 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14544 S.MarkFunctionReferenced(E->getLocStart(), 14545 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14546 Visit(E->getSubExpr()); 14547 } 14548 14549 void VisitCXXNewExpr(CXXNewExpr *E) { 14550 if (E->getOperatorNew()) 14551 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14552 if (E->getOperatorDelete()) 14553 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14554 Inherited::VisitCXXNewExpr(E); 14555 } 14556 14557 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14558 if (E->getOperatorDelete()) 14559 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14560 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14561 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14562 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14563 S.MarkFunctionReferenced(E->getLocStart(), 14564 S.LookupDestructor(Record)); 14565 } 14566 14567 Inherited::VisitCXXDeleteExpr(E); 14568 } 14569 14570 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14571 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14572 Inherited::VisitCXXConstructExpr(E); 14573 } 14574 14575 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14576 Visit(E->getExpr()); 14577 } 14578 14579 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14580 Inherited::VisitImplicitCastExpr(E); 14581 14582 if (E->getCastKind() == CK_LValueToRValue) 14583 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14584 } 14585 }; 14586 } 14587 14588 /// \brief Mark any declarations that appear within this expression or any 14589 /// potentially-evaluated subexpressions as "referenced". 14590 /// 14591 /// \param SkipLocalVariables If true, don't mark local variables as 14592 /// 'referenced'. 14593 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14594 bool SkipLocalVariables) { 14595 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14596 } 14597 14598 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14599 /// of the program being compiled. 14600 /// 14601 /// This routine emits the given diagnostic when the code currently being 14602 /// type-checked is "potentially evaluated", meaning that there is a 14603 /// possibility that the code will actually be executable. Code in sizeof() 14604 /// expressions, code used only during overload resolution, etc., are not 14605 /// potentially evaluated. This routine will suppress such diagnostics or, 14606 /// in the absolutely nutty case of potentially potentially evaluated 14607 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14608 /// later. 14609 /// 14610 /// This routine should be used for all diagnostics that describe the run-time 14611 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14612 /// Failure to do so will likely result in spurious diagnostics or failures 14613 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14614 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14615 const PartialDiagnostic &PD) { 14616 switch (ExprEvalContexts.back().Context) { 14617 case ExpressionEvaluationContext::Unevaluated: 14618 case ExpressionEvaluationContext::UnevaluatedList: 14619 case ExpressionEvaluationContext::UnevaluatedAbstract: 14620 case ExpressionEvaluationContext::DiscardedStatement: 14621 // The argument will never be evaluated, so don't complain. 14622 break; 14623 14624 case ExpressionEvaluationContext::ConstantEvaluated: 14625 // Relevant diagnostics should be produced by constant evaluation. 14626 break; 14627 14628 case ExpressionEvaluationContext::PotentiallyEvaluated: 14629 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14630 if (Statement && getCurFunctionOrMethodDecl()) { 14631 FunctionScopes.back()->PossiblyUnreachableDiags. 14632 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14633 } 14634 else 14635 Diag(Loc, PD); 14636 14637 return true; 14638 } 14639 14640 return false; 14641 } 14642 14643 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14644 CallExpr *CE, FunctionDecl *FD) { 14645 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14646 return false; 14647 14648 // If we're inside a decltype's expression, don't check for a valid return 14649 // type or construct temporaries until we know whether this is the last call. 14650 if (ExprEvalContexts.back().IsDecltype) { 14651 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14652 return false; 14653 } 14654 14655 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14656 FunctionDecl *FD; 14657 CallExpr *CE; 14658 14659 public: 14660 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14661 : FD(FD), CE(CE) { } 14662 14663 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14664 if (!FD) { 14665 S.Diag(Loc, diag::err_call_incomplete_return) 14666 << T << CE->getSourceRange(); 14667 return; 14668 } 14669 14670 S.Diag(Loc, diag::err_call_function_incomplete_return) 14671 << CE->getSourceRange() << FD->getDeclName() << T; 14672 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14673 << FD->getDeclName(); 14674 } 14675 } Diagnoser(FD, CE); 14676 14677 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14678 return true; 14679 14680 return false; 14681 } 14682 14683 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14684 // will prevent this condition from triggering, which is what we want. 14685 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14686 SourceLocation Loc; 14687 14688 unsigned diagnostic = diag::warn_condition_is_assignment; 14689 bool IsOrAssign = false; 14690 14691 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14692 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14693 return; 14694 14695 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14696 14697 // Greylist some idioms by putting them into a warning subcategory. 14698 if (ObjCMessageExpr *ME 14699 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14700 Selector Sel = ME->getSelector(); 14701 14702 // self = [<foo> init...] 14703 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14704 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14705 14706 // <foo> = [<bar> nextObject] 14707 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14708 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14709 } 14710 14711 Loc = Op->getOperatorLoc(); 14712 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14713 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14714 return; 14715 14716 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14717 Loc = Op->getOperatorLoc(); 14718 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14719 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14720 else { 14721 // Not an assignment. 14722 return; 14723 } 14724 14725 Diag(Loc, diagnostic) << E->getSourceRange(); 14726 14727 SourceLocation Open = E->getLocStart(); 14728 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14729 Diag(Loc, diag::note_condition_assign_silence) 14730 << FixItHint::CreateInsertion(Open, "(") 14731 << FixItHint::CreateInsertion(Close, ")"); 14732 14733 if (IsOrAssign) 14734 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14735 << FixItHint::CreateReplacement(Loc, "!="); 14736 else 14737 Diag(Loc, diag::note_condition_assign_to_comparison) 14738 << FixItHint::CreateReplacement(Loc, "=="); 14739 } 14740 14741 /// \brief Redundant parentheses over an equality comparison can indicate 14742 /// that the user intended an assignment used as condition. 14743 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14744 // Don't warn if the parens came from a macro. 14745 SourceLocation parenLoc = ParenE->getLocStart(); 14746 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14747 return; 14748 // Don't warn for dependent expressions. 14749 if (ParenE->isTypeDependent()) 14750 return; 14751 14752 Expr *E = ParenE->IgnoreParens(); 14753 14754 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14755 if (opE->getOpcode() == BO_EQ && 14756 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14757 == Expr::MLV_Valid) { 14758 SourceLocation Loc = opE->getOperatorLoc(); 14759 14760 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14761 SourceRange ParenERange = ParenE->getSourceRange(); 14762 Diag(Loc, diag::note_equality_comparison_silence) 14763 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14764 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14765 Diag(Loc, diag::note_equality_comparison_to_assign) 14766 << FixItHint::CreateReplacement(Loc, "="); 14767 } 14768 } 14769 14770 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14771 bool IsConstexpr) { 14772 DiagnoseAssignmentAsCondition(E); 14773 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14774 DiagnoseEqualityWithExtraParens(parenE); 14775 14776 ExprResult result = CheckPlaceholderExpr(E); 14777 if (result.isInvalid()) return ExprError(); 14778 E = result.get(); 14779 14780 if (!E->isTypeDependent()) { 14781 if (getLangOpts().CPlusPlus) 14782 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14783 14784 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14785 if (ERes.isInvalid()) 14786 return ExprError(); 14787 E = ERes.get(); 14788 14789 QualType T = E->getType(); 14790 if (!T->isScalarType()) { // C99 6.8.4.1p1 14791 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14792 << T << E->getSourceRange(); 14793 return ExprError(); 14794 } 14795 CheckBoolLikeConversion(E, Loc); 14796 } 14797 14798 return E; 14799 } 14800 14801 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14802 Expr *SubExpr, ConditionKind CK) { 14803 // Empty conditions are valid in for-statements. 14804 if (!SubExpr) 14805 return ConditionResult(); 14806 14807 ExprResult Cond; 14808 switch (CK) { 14809 case ConditionKind::Boolean: 14810 Cond = CheckBooleanCondition(Loc, SubExpr); 14811 break; 14812 14813 case ConditionKind::ConstexprIf: 14814 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14815 break; 14816 14817 case ConditionKind::Switch: 14818 Cond = CheckSwitchCondition(Loc, SubExpr); 14819 break; 14820 } 14821 if (Cond.isInvalid()) 14822 return ConditionError(); 14823 14824 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14825 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14826 if (!FullExpr.get()) 14827 return ConditionError(); 14828 14829 return ConditionResult(*this, nullptr, FullExpr, 14830 CK == ConditionKind::ConstexprIf); 14831 } 14832 14833 namespace { 14834 /// A visitor for rebuilding a call to an __unknown_any expression 14835 /// to have an appropriate type. 14836 struct RebuildUnknownAnyFunction 14837 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14838 14839 Sema &S; 14840 14841 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14842 14843 ExprResult VisitStmt(Stmt *S) { 14844 llvm_unreachable("unexpected statement!"); 14845 } 14846 14847 ExprResult VisitExpr(Expr *E) { 14848 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14849 << E->getSourceRange(); 14850 return ExprError(); 14851 } 14852 14853 /// Rebuild an expression which simply semantically wraps another 14854 /// expression which it shares the type and value kind of. 14855 template <class T> ExprResult rebuildSugarExpr(T *E) { 14856 ExprResult SubResult = Visit(E->getSubExpr()); 14857 if (SubResult.isInvalid()) return ExprError(); 14858 14859 Expr *SubExpr = SubResult.get(); 14860 E->setSubExpr(SubExpr); 14861 E->setType(SubExpr->getType()); 14862 E->setValueKind(SubExpr->getValueKind()); 14863 assert(E->getObjectKind() == OK_Ordinary); 14864 return E; 14865 } 14866 14867 ExprResult VisitParenExpr(ParenExpr *E) { 14868 return rebuildSugarExpr(E); 14869 } 14870 14871 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14872 return rebuildSugarExpr(E); 14873 } 14874 14875 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14876 ExprResult SubResult = Visit(E->getSubExpr()); 14877 if (SubResult.isInvalid()) return ExprError(); 14878 14879 Expr *SubExpr = SubResult.get(); 14880 E->setSubExpr(SubExpr); 14881 E->setType(S.Context.getPointerType(SubExpr->getType())); 14882 assert(E->getValueKind() == VK_RValue); 14883 assert(E->getObjectKind() == OK_Ordinary); 14884 return E; 14885 } 14886 14887 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14888 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14889 14890 E->setType(VD->getType()); 14891 14892 assert(E->getValueKind() == VK_RValue); 14893 if (S.getLangOpts().CPlusPlus && 14894 !(isa<CXXMethodDecl>(VD) && 14895 cast<CXXMethodDecl>(VD)->isInstance())) 14896 E->setValueKind(VK_LValue); 14897 14898 return E; 14899 } 14900 14901 ExprResult VisitMemberExpr(MemberExpr *E) { 14902 return resolveDecl(E, E->getMemberDecl()); 14903 } 14904 14905 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14906 return resolveDecl(E, E->getDecl()); 14907 } 14908 }; 14909 } 14910 14911 /// Given a function expression of unknown-any type, try to rebuild it 14912 /// to have a function type. 14913 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14914 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14915 if (Result.isInvalid()) return ExprError(); 14916 return S.DefaultFunctionArrayConversion(Result.get()); 14917 } 14918 14919 namespace { 14920 /// A visitor for rebuilding an expression of type __unknown_anytype 14921 /// into one which resolves the type directly on the referring 14922 /// expression. Strict preservation of the original source 14923 /// structure is not a goal. 14924 struct RebuildUnknownAnyExpr 14925 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14926 14927 Sema &S; 14928 14929 /// The current destination type. 14930 QualType DestType; 14931 14932 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14933 : S(S), DestType(CastType) {} 14934 14935 ExprResult VisitStmt(Stmt *S) { 14936 llvm_unreachable("unexpected statement!"); 14937 } 14938 14939 ExprResult VisitExpr(Expr *E) { 14940 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14941 << E->getSourceRange(); 14942 return ExprError(); 14943 } 14944 14945 ExprResult VisitCallExpr(CallExpr *E); 14946 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14947 14948 /// Rebuild an expression which simply semantically wraps another 14949 /// expression which it shares the type and value kind of. 14950 template <class T> ExprResult rebuildSugarExpr(T *E) { 14951 ExprResult SubResult = Visit(E->getSubExpr()); 14952 if (SubResult.isInvalid()) return ExprError(); 14953 Expr *SubExpr = SubResult.get(); 14954 E->setSubExpr(SubExpr); 14955 E->setType(SubExpr->getType()); 14956 E->setValueKind(SubExpr->getValueKind()); 14957 assert(E->getObjectKind() == OK_Ordinary); 14958 return E; 14959 } 14960 14961 ExprResult VisitParenExpr(ParenExpr *E) { 14962 return rebuildSugarExpr(E); 14963 } 14964 14965 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14966 return rebuildSugarExpr(E); 14967 } 14968 14969 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14970 const PointerType *Ptr = DestType->getAs<PointerType>(); 14971 if (!Ptr) { 14972 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14973 << E->getSourceRange(); 14974 return ExprError(); 14975 } 14976 14977 if (isa<CallExpr>(E->getSubExpr())) { 14978 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 14979 << E->getSourceRange(); 14980 return ExprError(); 14981 } 14982 14983 assert(E->getValueKind() == VK_RValue); 14984 assert(E->getObjectKind() == OK_Ordinary); 14985 E->setType(DestType); 14986 14987 // Build the sub-expression as if it were an object of the pointee type. 14988 DestType = Ptr->getPointeeType(); 14989 ExprResult SubResult = Visit(E->getSubExpr()); 14990 if (SubResult.isInvalid()) return ExprError(); 14991 E->setSubExpr(SubResult.get()); 14992 return E; 14993 } 14994 14995 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14996 14997 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14998 14999 ExprResult VisitMemberExpr(MemberExpr *E) { 15000 return resolveDecl(E, E->getMemberDecl()); 15001 } 15002 15003 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15004 return resolveDecl(E, E->getDecl()); 15005 } 15006 }; 15007 } 15008 15009 /// Rebuilds a call expression which yielded __unknown_anytype. 15010 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15011 Expr *CalleeExpr = E->getCallee(); 15012 15013 enum FnKind { 15014 FK_MemberFunction, 15015 FK_FunctionPointer, 15016 FK_BlockPointer 15017 }; 15018 15019 FnKind Kind; 15020 QualType CalleeType = CalleeExpr->getType(); 15021 if (CalleeType == S.Context.BoundMemberTy) { 15022 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15023 Kind = FK_MemberFunction; 15024 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15025 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15026 CalleeType = Ptr->getPointeeType(); 15027 Kind = FK_FunctionPointer; 15028 } else { 15029 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15030 Kind = FK_BlockPointer; 15031 } 15032 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15033 15034 // Verify that this is a legal result type of a function. 15035 if (DestType->isArrayType() || DestType->isFunctionType()) { 15036 unsigned diagID = diag::err_func_returning_array_function; 15037 if (Kind == FK_BlockPointer) 15038 diagID = diag::err_block_returning_array_function; 15039 15040 S.Diag(E->getExprLoc(), diagID) 15041 << DestType->isFunctionType() << DestType; 15042 return ExprError(); 15043 } 15044 15045 // Otherwise, go ahead and set DestType as the call's result. 15046 E->setType(DestType.getNonLValueExprType(S.Context)); 15047 E->setValueKind(Expr::getValueKindForType(DestType)); 15048 assert(E->getObjectKind() == OK_Ordinary); 15049 15050 // Rebuild the function type, replacing the result type with DestType. 15051 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15052 if (Proto) { 15053 // __unknown_anytype(...) is a special case used by the debugger when 15054 // it has no idea what a function's signature is. 15055 // 15056 // We want to build this call essentially under the K&R 15057 // unprototyped rules, but making a FunctionNoProtoType in C++ 15058 // would foul up all sorts of assumptions. However, we cannot 15059 // simply pass all arguments as variadic arguments, nor can we 15060 // portably just call the function under a non-variadic type; see 15061 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15062 // However, it turns out that in practice it is generally safe to 15063 // call a function declared as "A foo(B,C,D);" under the prototype 15064 // "A foo(B,C,D,...);". The only known exception is with the 15065 // Windows ABI, where any variadic function is implicitly cdecl 15066 // regardless of its normal CC. Therefore we change the parameter 15067 // types to match the types of the arguments. 15068 // 15069 // This is a hack, but it is far superior to moving the 15070 // corresponding target-specific code from IR-gen to Sema/AST. 15071 15072 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15073 SmallVector<QualType, 8> ArgTypes; 15074 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15075 ArgTypes.reserve(E->getNumArgs()); 15076 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15077 Expr *Arg = E->getArg(i); 15078 QualType ArgType = Arg->getType(); 15079 if (E->isLValue()) { 15080 ArgType = S.Context.getLValueReferenceType(ArgType); 15081 } else if (E->isXValue()) { 15082 ArgType = S.Context.getRValueReferenceType(ArgType); 15083 } 15084 ArgTypes.push_back(ArgType); 15085 } 15086 ParamTypes = ArgTypes; 15087 } 15088 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15089 Proto->getExtProtoInfo()); 15090 } else { 15091 DestType = S.Context.getFunctionNoProtoType(DestType, 15092 FnType->getExtInfo()); 15093 } 15094 15095 // Rebuild the appropriate pointer-to-function type. 15096 switch (Kind) { 15097 case FK_MemberFunction: 15098 // Nothing to do. 15099 break; 15100 15101 case FK_FunctionPointer: 15102 DestType = S.Context.getPointerType(DestType); 15103 break; 15104 15105 case FK_BlockPointer: 15106 DestType = S.Context.getBlockPointerType(DestType); 15107 break; 15108 } 15109 15110 // Finally, we can recurse. 15111 ExprResult CalleeResult = Visit(CalleeExpr); 15112 if (!CalleeResult.isUsable()) return ExprError(); 15113 E->setCallee(CalleeResult.get()); 15114 15115 // Bind a temporary if necessary. 15116 return S.MaybeBindToTemporary(E); 15117 } 15118 15119 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15120 // Verify that this is a legal result type of a call. 15121 if (DestType->isArrayType() || DestType->isFunctionType()) { 15122 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15123 << DestType->isFunctionType() << DestType; 15124 return ExprError(); 15125 } 15126 15127 // Rewrite the method result type if available. 15128 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15129 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15130 Method->setReturnType(DestType); 15131 } 15132 15133 // Change the type of the message. 15134 E->setType(DestType.getNonReferenceType()); 15135 E->setValueKind(Expr::getValueKindForType(DestType)); 15136 15137 return S.MaybeBindToTemporary(E); 15138 } 15139 15140 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15141 // The only case we should ever see here is a function-to-pointer decay. 15142 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15143 assert(E->getValueKind() == VK_RValue); 15144 assert(E->getObjectKind() == OK_Ordinary); 15145 15146 E->setType(DestType); 15147 15148 // Rebuild the sub-expression as the pointee (function) type. 15149 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15150 15151 ExprResult Result = Visit(E->getSubExpr()); 15152 if (!Result.isUsable()) return ExprError(); 15153 15154 E->setSubExpr(Result.get()); 15155 return E; 15156 } else if (E->getCastKind() == CK_LValueToRValue) { 15157 assert(E->getValueKind() == VK_RValue); 15158 assert(E->getObjectKind() == OK_Ordinary); 15159 15160 assert(isa<BlockPointerType>(E->getType())); 15161 15162 E->setType(DestType); 15163 15164 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15165 DestType = S.Context.getLValueReferenceType(DestType); 15166 15167 ExprResult Result = Visit(E->getSubExpr()); 15168 if (!Result.isUsable()) return ExprError(); 15169 15170 E->setSubExpr(Result.get()); 15171 return E; 15172 } else { 15173 llvm_unreachable("Unhandled cast type!"); 15174 } 15175 } 15176 15177 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15178 ExprValueKind ValueKind = VK_LValue; 15179 QualType Type = DestType; 15180 15181 // We know how to make this work for certain kinds of decls: 15182 15183 // - functions 15184 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15185 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15186 DestType = Ptr->getPointeeType(); 15187 ExprResult Result = resolveDecl(E, VD); 15188 if (Result.isInvalid()) return ExprError(); 15189 return S.ImpCastExprToType(Result.get(), Type, 15190 CK_FunctionToPointerDecay, VK_RValue); 15191 } 15192 15193 if (!Type->isFunctionType()) { 15194 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15195 << VD << E->getSourceRange(); 15196 return ExprError(); 15197 } 15198 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15199 // We must match the FunctionDecl's type to the hack introduced in 15200 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15201 // type. See the lengthy commentary in that routine. 15202 QualType FDT = FD->getType(); 15203 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15204 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15205 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15206 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15207 SourceLocation Loc = FD->getLocation(); 15208 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15209 FD->getDeclContext(), 15210 Loc, Loc, FD->getNameInfo().getName(), 15211 DestType, FD->getTypeSourceInfo(), 15212 SC_None, false/*isInlineSpecified*/, 15213 FD->hasPrototype(), 15214 false/*isConstexprSpecified*/); 15215 15216 if (FD->getQualifier()) 15217 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15218 15219 SmallVector<ParmVarDecl*, 16> Params; 15220 for (const auto &AI : FT->param_types()) { 15221 ParmVarDecl *Param = 15222 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15223 Param->setScopeInfo(0, Params.size()); 15224 Params.push_back(Param); 15225 } 15226 NewFD->setParams(Params); 15227 DRE->setDecl(NewFD); 15228 VD = DRE->getDecl(); 15229 } 15230 } 15231 15232 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15233 if (MD->isInstance()) { 15234 ValueKind = VK_RValue; 15235 Type = S.Context.BoundMemberTy; 15236 } 15237 15238 // Function references aren't l-values in C. 15239 if (!S.getLangOpts().CPlusPlus) 15240 ValueKind = VK_RValue; 15241 15242 // - variables 15243 } else if (isa<VarDecl>(VD)) { 15244 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15245 Type = RefTy->getPointeeType(); 15246 } else if (Type->isFunctionType()) { 15247 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15248 << VD << E->getSourceRange(); 15249 return ExprError(); 15250 } 15251 15252 // - nothing else 15253 } else { 15254 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15255 << VD << E->getSourceRange(); 15256 return ExprError(); 15257 } 15258 15259 // Modifying the declaration like this is friendly to IR-gen but 15260 // also really dangerous. 15261 VD->setType(DestType); 15262 E->setType(Type); 15263 E->setValueKind(ValueKind); 15264 return E; 15265 } 15266 15267 /// Check a cast of an unknown-any type. We intentionally only 15268 /// trigger this for C-style casts. 15269 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15270 Expr *CastExpr, CastKind &CastKind, 15271 ExprValueKind &VK, CXXCastPath &Path) { 15272 // The type we're casting to must be either void or complete. 15273 if (!CastType->isVoidType() && 15274 RequireCompleteType(TypeRange.getBegin(), CastType, 15275 diag::err_typecheck_cast_to_incomplete)) 15276 return ExprError(); 15277 15278 // Rewrite the casted expression from scratch. 15279 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15280 if (!result.isUsable()) return ExprError(); 15281 15282 CastExpr = result.get(); 15283 VK = CastExpr->getValueKind(); 15284 CastKind = CK_NoOp; 15285 15286 return CastExpr; 15287 } 15288 15289 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15290 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15291 } 15292 15293 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15294 Expr *arg, QualType ¶mType) { 15295 // If the syntactic form of the argument is not an explicit cast of 15296 // any sort, just do default argument promotion. 15297 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15298 if (!castArg) { 15299 ExprResult result = DefaultArgumentPromotion(arg); 15300 if (result.isInvalid()) return ExprError(); 15301 paramType = result.get()->getType(); 15302 return result; 15303 } 15304 15305 // Otherwise, use the type that was written in the explicit cast. 15306 assert(!arg->hasPlaceholderType()); 15307 paramType = castArg->getTypeAsWritten(); 15308 15309 // Copy-initialize a parameter of that type. 15310 InitializedEntity entity = 15311 InitializedEntity::InitializeParameter(Context, paramType, 15312 /*consumed*/ false); 15313 return PerformCopyInitialization(entity, callLoc, arg); 15314 } 15315 15316 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15317 Expr *orig = E; 15318 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15319 while (true) { 15320 E = E->IgnoreParenImpCasts(); 15321 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15322 E = call->getCallee(); 15323 diagID = diag::err_uncasted_call_of_unknown_any; 15324 } else { 15325 break; 15326 } 15327 } 15328 15329 SourceLocation loc; 15330 NamedDecl *d; 15331 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15332 loc = ref->getLocation(); 15333 d = ref->getDecl(); 15334 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15335 loc = mem->getMemberLoc(); 15336 d = mem->getMemberDecl(); 15337 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15338 diagID = diag::err_uncasted_call_of_unknown_any; 15339 loc = msg->getSelectorStartLoc(); 15340 d = msg->getMethodDecl(); 15341 if (!d) { 15342 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15343 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15344 << orig->getSourceRange(); 15345 return ExprError(); 15346 } 15347 } else { 15348 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15349 << E->getSourceRange(); 15350 return ExprError(); 15351 } 15352 15353 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15354 15355 // Never recoverable. 15356 return ExprError(); 15357 } 15358 15359 /// Check for operands with placeholder types and complain if found. 15360 /// Returns true if there was an error and no recovery was possible. 15361 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15362 if (!getLangOpts().CPlusPlus) { 15363 // C cannot handle TypoExpr nodes on either side of a binop because it 15364 // doesn't handle dependent types properly, so make sure any TypoExprs have 15365 // been dealt with before checking the operands. 15366 ExprResult Result = CorrectDelayedTyposInExpr(E); 15367 if (!Result.isUsable()) return ExprError(); 15368 E = Result.get(); 15369 } 15370 15371 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15372 if (!placeholderType) return E; 15373 15374 switch (placeholderType->getKind()) { 15375 15376 // Overloaded expressions. 15377 case BuiltinType::Overload: { 15378 // Try to resolve a single function template specialization. 15379 // This is obligatory. 15380 ExprResult Result = E; 15381 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15382 return Result; 15383 15384 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15385 // leaves Result unchanged on failure. 15386 Result = E; 15387 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15388 return Result; 15389 15390 // If that failed, try to recover with a call. 15391 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15392 /*complain*/ true); 15393 return Result; 15394 } 15395 15396 // Bound member functions. 15397 case BuiltinType::BoundMember: { 15398 ExprResult result = E; 15399 const Expr *BME = E->IgnoreParens(); 15400 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15401 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15402 if (isa<CXXPseudoDestructorExpr>(BME)) { 15403 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15404 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15405 if (ME->getMemberNameInfo().getName().getNameKind() == 15406 DeclarationName::CXXDestructorName) 15407 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15408 } 15409 tryToRecoverWithCall(result, PD, 15410 /*complain*/ true); 15411 return result; 15412 } 15413 15414 // ARC unbridged casts. 15415 case BuiltinType::ARCUnbridgedCast: { 15416 Expr *realCast = stripARCUnbridgedCast(E); 15417 diagnoseARCUnbridgedCast(realCast); 15418 return realCast; 15419 } 15420 15421 // Expressions of unknown type. 15422 case BuiltinType::UnknownAny: 15423 return diagnoseUnknownAnyExpr(*this, E); 15424 15425 // Pseudo-objects. 15426 case BuiltinType::PseudoObject: 15427 return checkPseudoObjectRValue(E); 15428 15429 case BuiltinType::BuiltinFn: { 15430 // Accept __noop without parens by implicitly converting it to a call expr. 15431 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15432 if (DRE) { 15433 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15434 if (FD->getBuiltinID() == Builtin::BI__noop) { 15435 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15436 CK_BuiltinFnToFnPtr).get(); 15437 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15438 VK_RValue, SourceLocation()); 15439 } 15440 } 15441 15442 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15443 return ExprError(); 15444 } 15445 15446 // Expressions of unknown type. 15447 case BuiltinType::OMPArraySection: 15448 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15449 return ExprError(); 15450 15451 // Everything else should be impossible. 15452 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15453 case BuiltinType::Id: 15454 #include "clang/Basic/OpenCLImageTypes.def" 15455 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15456 #define PLACEHOLDER_TYPE(Id, SingletonId) 15457 #include "clang/AST/BuiltinTypes.def" 15458 break; 15459 } 15460 15461 llvm_unreachable("invalid placeholder type!"); 15462 } 15463 15464 bool Sema::CheckCaseExpression(Expr *E) { 15465 if (E->isTypeDependent()) 15466 return true; 15467 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15468 return E->getType()->isIntegralOrEnumerationType(); 15469 return false; 15470 } 15471 15472 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15473 ExprResult 15474 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15475 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15476 "Unknown Objective-C Boolean value!"); 15477 QualType BoolT = Context.ObjCBuiltinBoolTy; 15478 if (!Context.getBOOLDecl()) { 15479 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15480 Sema::LookupOrdinaryName); 15481 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15482 NamedDecl *ND = Result.getFoundDecl(); 15483 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15484 Context.setBOOLDecl(TD); 15485 } 15486 } 15487 if (Context.getBOOLDecl()) 15488 BoolT = Context.getBOOLType(); 15489 return new (Context) 15490 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15491 } 15492 15493 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15494 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15495 SourceLocation RParen) { 15496 15497 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15498 15499 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15500 [&](const AvailabilitySpec &Spec) { 15501 return Spec.getPlatform() == Platform; 15502 }); 15503 15504 VersionTuple Version; 15505 if (Spec != AvailSpecs.end()) 15506 Version = Spec->getVersion(); 15507 15508 return new (Context) 15509 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15510 } 15511