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 (getLangOpts().ObjCAutoRefCount && 708 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 709 Cleanup.setExprNeedsCleanups(true); 710 711 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 712 nullptr, VK_RValue); 713 714 // C11 6.3.2.1p2: 715 // ... if the lvalue has atomic type, the value has the non-atomic version 716 // of the type of the lvalue ... 717 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 718 T = Atomic->getValueType().getUnqualifiedType(); 719 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 720 nullptr, VK_RValue); 721 } 722 723 return Res; 724 } 725 726 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 727 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 728 if (Res.isInvalid()) 729 return ExprError(); 730 Res = DefaultLvalueConversion(Res.get()); 731 if (Res.isInvalid()) 732 return ExprError(); 733 return Res; 734 } 735 736 /// CallExprUnaryConversions - a special case of an unary conversion 737 /// performed on a function designator of a call expression. 738 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 739 QualType Ty = E->getType(); 740 ExprResult Res = E; 741 // Only do implicit cast for a function type, but not for a pointer 742 // to function type. 743 if (Ty->isFunctionType()) { 744 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 745 CK_FunctionToPointerDecay).get(); 746 if (Res.isInvalid()) 747 return ExprError(); 748 } 749 Res = DefaultLvalueConversion(Res.get()); 750 if (Res.isInvalid()) 751 return ExprError(); 752 return Res.get(); 753 } 754 755 /// UsualUnaryConversions - Performs various conversions that are common to most 756 /// operators (C99 6.3). The conversions of array and function types are 757 /// sometimes suppressed. For example, the array->pointer conversion doesn't 758 /// apply if the array is an argument to the sizeof or address (&) operators. 759 /// In these instances, this routine should *not* be called. 760 ExprResult Sema::UsualUnaryConversions(Expr *E) { 761 // First, convert to an r-value. 762 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 763 if (Res.isInvalid()) 764 return ExprError(); 765 E = Res.get(); 766 767 QualType Ty = E->getType(); 768 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 769 770 // Half FP have to be promoted to float unless it is natively supported 771 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 772 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 773 774 // Try to perform integral promotions if the object has a theoretically 775 // promotable type. 776 if (Ty->isIntegralOrUnscopedEnumerationType()) { 777 // C99 6.3.1.1p2: 778 // 779 // The following may be used in an expression wherever an int or 780 // unsigned int may be used: 781 // - an object or expression with an integer type whose integer 782 // conversion rank is less than or equal to the rank of int 783 // and unsigned int. 784 // - A bit-field of type _Bool, int, signed int, or unsigned int. 785 // 786 // If an int can represent all values of the original type, the 787 // value is converted to an int; otherwise, it is converted to an 788 // unsigned int. These are called the integer promotions. All 789 // other types are unchanged by the integer promotions. 790 791 QualType PTy = Context.isPromotableBitField(E); 792 if (!PTy.isNull()) { 793 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 794 return E; 795 } 796 if (Ty->isPromotableIntegerType()) { 797 QualType PT = Context.getPromotedIntegerType(Ty); 798 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 799 return E; 800 } 801 } 802 return E; 803 } 804 805 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 806 /// do not have a prototype. Arguments that have type float or __fp16 807 /// are promoted to double. All other argument types are converted by 808 /// UsualUnaryConversions(). 809 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 810 QualType Ty = E->getType(); 811 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 812 813 ExprResult Res = UsualUnaryConversions(E); 814 if (Res.isInvalid()) 815 return ExprError(); 816 E = Res.get(); 817 818 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 819 // double. 820 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 821 if (BTy && (BTy->getKind() == BuiltinType::Half || 822 BTy->getKind() == BuiltinType::Float)) { 823 if (getLangOpts().OpenCL && 824 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 825 if (BTy->getKind() == BuiltinType::Half) { 826 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 827 } 828 } else { 829 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 830 } 831 } 832 833 // C++ performs lvalue-to-rvalue conversion as a default argument 834 // promotion, even on class types, but note: 835 // C++11 [conv.lval]p2: 836 // When an lvalue-to-rvalue conversion occurs in an unevaluated 837 // operand or a subexpression thereof the value contained in the 838 // referenced object is not accessed. Otherwise, if the glvalue 839 // has a class type, the conversion copy-initializes a temporary 840 // of type T from the glvalue and the result of the conversion 841 // is a prvalue for the temporary. 842 // FIXME: add some way to gate this entire thing for correctness in 843 // potentially potentially evaluated contexts. 844 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 845 ExprResult Temp = PerformCopyInitialization( 846 InitializedEntity::InitializeTemporary(E->getType()), 847 E->getExprLoc(), E); 848 if (Temp.isInvalid()) 849 return ExprError(); 850 E = Temp.get(); 851 } 852 853 return E; 854 } 855 856 /// Determine the degree of POD-ness for an expression. 857 /// Incomplete types are considered POD, since this check can be performed 858 /// when we're in an unevaluated context. 859 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 860 if (Ty->isIncompleteType()) { 861 // C++11 [expr.call]p7: 862 // After these conversions, if the argument does not have arithmetic, 863 // enumeration, pointer, pointer to member, or class type, the program 864 // is ill-formed. 865 // 866 // Since we've already performed array-to-pointer and function-to-pointer 867 // decay, the only such type in C++ is cv void. This also handles 868 // initializer lists as variadic arguments. 869 if (Ty->isVoidType()) 870 return VAK_Invalid; 871 872 if (Ty->isObjCObjectType()) 873 return VAK_Invalid; 874 return VAK_Valid; 875 } 876 877 if (Ty.isCXX98PODType(Context)) 878 return VAK_Valid; 879 880 // C++11 [expr.call]p7: 881 // Passing a potentially-evaluated argument of class type (Clause 9) 882 // having a non-trivial copy constructor, a non-trivial move constructor, 883 // or a non-trivial destructor, with no corresponding parameter, 884 // is conditionally-supported with implementation-defined semantics. 885 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 886 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 887 if (!Record->hasNonTrivialCopyConstructor() && 888 !Record->hasNonTrivialMoveConstructor() && 889 !Record->hasNonTrivialDestructor()) 890 return VAK_ValidInCXX11; 891 892 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 893 return VAK_Valid; 894 895 if (Ty->isObjCObjectType()) 896 return VAK_Invalid; 897 898 if (getLangOpts().MSVCCompat) 899 return VAK_MSVCUndefined; 900 901 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 902 // permitted to reject them. We should consider doing so. 903 return VAK_Undefined; 904 } 905 906 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 907 // Don't allow one to pass an Objective-C interface to a vararg. 908 const QualType &Ty = E->getType(); 909 VarArgKind VAK = isValidVarArgType(Ty); 910 911 // Complain about passing non-POD types through varargs. 912 switch (VAK) { 913 case VAK_ValidInCXX11: 914 DiagRuntimeBehavior( 915 E->getLocStart(), nullptr, 916 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 917 << Ty << CT); 918 // Fall through. 919 case VAK_Valid: 920 if (Ty->isRecordType()) { 921 // This is unlikely to be what the user intended. If the class has a 922 // 'c_str' member function, the user probably meant to call that. 923 DiagRuntimeBehavior(E->getLocStart(), nullptr, 924 PDiag(diag::warn_pass_class_arg_to_vararg) 925 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 926 } 927 break; 928 929 case VAK_Undefined: 930 case VAK_MSVCUndefined: 931 DiagRuntimeBehavior( 932 E->getLocStart(), nullptr, 933 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 934 << getLangOpts().CPlusPlus11 << Ty << CT); 935 break; 936 937 case VAK_Invalid: 938 if (Ty->isObjCObjectType()) 939 DiagRuntimeBehavior( 940 E->getLocStart(), nullptr, 941 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 942 << Ty << CT); 943 else 944 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 945 << isa<InitListExpr>(E) << Ty << CT; 946 break; 947 } 948 } 949 950 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 951 /// will create a trap if the resulting type is not a POD type. 952 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 953 FunctionDecl *FDecl) { 954 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 955 // Strip the unbridged-cast placeholder expression off, if applicable. 956 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 957 (CT == VariadicMethod || 958 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 959 E = stripARCUnbridgedCast(E); 960 961 // Otherwise, do normal placeholder checking. 962 } else { 963 ExprResult ExprRes = CheckPlaceholderExpr(E); 964 if (ExprRes.isInvalid()) 965 return ExprError(); 966 E = ExprRes.get(); 967 } 968 } 969 970 ExprResult ExprRes = DefaultArgumentPromotion(E); 971 if (ExprRes.isInvalid()) 972 return ExprError(); 973 E = ExprRes.get(); 974 975 // Diagnostics regarding non-POD argument types are 976 // emitted along with format string checking in Sema::CheckFunctionCall(). 977 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 978 // Turn this into a trap. 979 CXXScopeSpec SS; 980 SourceLocation TemplateKWLoc; 981 UnqualifiedId Name; 982 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 983 E->getLocStart()); 984 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 985 Name, true, false); 986 if (TrapFn.isInvalid()) 987 return ExprError(); 988 989 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 990 E->getLocStart(), None, 991 E->getLocEnd()); 992 if (Call.isInvalid()) 993 return ExprError(); 994 995 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 996 Call.get(), E); 997 if (Comma.isInvalid()) 998 return ExprError(); 999 return Comma.get(); 1000 } 1001 1002 if (!getLangOpts().CPlusPlus && 1003 RequireCompleteType(E->getExprLoc(), E->getType(), 1004 diag::err_call_incomplete_argument)) 1005 return ExprError(); 1006 1007 return E; 1008 } 1009 1010 /// \brief Converts an integer to complex float type. Helper function of 1011 /// UsualArithmeticConversions() 1012 /// 1013 /// \return false if the integer expression is an integer type and is 1014 /// successfully converted to the complex type. 1015 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1016 ExprResult &ComplexExpr, 1017 QualType IntTy, 1018 QualType ComplexTy, 1019 bool SkipCast) { 1020 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1021 if (SkipCast) return false; 1022 if (IntTy->isIntegerType()) { 1023 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1025 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1026 CK_FloatingRealToComplex); 1027 } else { 1028 assert(IntTy->isComplexIntegerType()); 1029 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1030 CK_IntegralComplexToFloatingComplex); 1031 } 1032 return false; 1033 } 1034 1035 /// \brief Handle arithmetic conversion with complex types. Helper function of 1036 /// UsualArithmeticConversions() 1037 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1038 ExprResult &RHS, QualType LHSType, 1039 QualType RHSType, 1040 bool IsCompAssign) { 1041 // if we have an integer operand, the result is the complex type. 1042 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1043 /*skipCast*/false)) 1044 return LHSType; 1045 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1046 /*skipCast*/IsCompAssign)) 1047 return RHSType; 1048 1049 // This handles complex/complex, complex/float, or float/complex. 1050 // When both operands are complex, the shorter operand is converted to the 1051 // type of the longer, and that is the type of the result. This corresponds 1052 // to what is done when combining two real floating-point operands. 1053 // The fun begins when size promotion occur across type domains. 1054 // From H&S 6.3.4: When one operand is complex and the other is a real 1055 // floating-point type, the less precise type is converted, within it's 1056 // real or complex domain, to the precision of the other type. For example, 1057 // when combining a "long double" with a "double _Complex", the 1058 // "double _Complex" is promoted to "long double _Complex". 1059 1060 // Compute the rank of the two types, regardless of whether they are complex. 1061 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1062 1063 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1064 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1065 QualType LHSElementType = 1066 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1067 QualType RHSElementType = 1068 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1069 1070 QualType ResultType = S.Context.getComplexType(LHSElementType); 1071 if (Order < 0) { 1072 // Promote the precision of the LHS if not an assignment. 1073 ResultType = S.Context.getComplexType(RHSElementType); 1074 if (!IsCompAssign) { 1075 if (LHSComplexType) 1076 LHS = 1077 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1078 else 1079 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1080 } 1081 } else if (Order > 0) { 1082 // Promote the precision of the RHS. 1083 if (RHSComplexType) 1084 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1085 else 1086 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1087 } 1088 return ResultType; 1089 } 1090 1091 /// \brief Hande arithmetic conversion from integer to float. Helper function 1092 /// of UsualArithmeticConversions() 1093 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1094 ExprResult &IntExpr, 1095 QualType FloatTy, QualType IntTy, 1096 bool ConvertFloat, bool ConvertInt) { 1097 if (IntTy->isIntegerType()) { 1098 if (ConvertInt) 1099 // Convert intExpr to the lhs floating point type. 1100 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1101 CK_IntegralToFloating); 1102 return FloatTy; 1103 } 1104 1105 // Convert both sides to the appropriate complex float. 1106 assert(IntTy->isComplexIntegerType()); 1107 QualType result = S.Context.getComplexType(FloatTy); 1108 1109 // _Complex int -> _Complex float 1110 if (ConvertInt) 1111 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1112 CK_IntegralComplexToFloatingComplex); 1113 1114 // float -> _Complex float 1115 if (ConvertFloat) 1116 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1117 CK_FloatingRealToComplex); 1118 1119 return result; 1120 } 1121 1122 /// \brief Handle arithmethic conversion with floating point types. Helper 1123 /// function of UsualArithmeticConversions() 1124 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1125 ExprResult &RHS, QualType LHSType, 1126 QualType RHSType, bool IsCompAssign) { 1127 bool LHSFloat = LHSType->isRealFloatingType(); 1128 bool RHSFloat = RHSType->isRealFloatingType(); 1129 1130 // If we have two real floating types, convert the smaller operand 1131 // to the bigger result. 1132 if (LHSFloat && RHSFloat) { 1133 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1134 if (order > 0) { 1135 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1136 return LHSType; 1137 } 1138 1139 assert(order < 0 && "illegal float comparison"); 1140 if (!IsCompAssign) 1141 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1142 return RHSType; 1143 } 1144 1145 if (LHSFloat) { 1146 // Half FP has to be promoted to float unless it is natively supported 1147 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1148 LHSType = S.Context.FloatTy; 1149 1150 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1151 /*convertFloat=*/!IsCompAssign, 1152 /*convertInt=*/ true); 1153 } 1154 assert(RHSFloat); 1155 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1156 /*convertInt=*/ true, 1157 /*convertFloat=*/!IsCompAssign); 1158 } 1159 1160 /// \brief Diagnose attempts to convert between __float128 and long double if 1161 /// there is no support for such conversion. Helper function of 1162 /// UsualArithmeticConversions(). 1163 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1164 QualType RHSType) { 1165 /* No issue converting if at least one of the types is not a floating point 1166 type or the two types have the same rank. 1167 */ 1168 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1169 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1170 return false; 1171 1172 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1173 "The remaining types must be floating point types."); 1174 1175 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1176 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1177 1178 QualType LHSElemType = LHSComplex ? 1179 LHSComplex->getElementType() : LHSType; 1180 QualType RHSElemType = RHSComplex ? 1181 RHSComplex->getElementType() : RHSType; 1182 1183 // No issue if the two types have the same representation 1184 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1185 &S.Context.getFloatTypeSemantics(RHSElemType)) 1186 return false; 1187 1188 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1189 RHSElemType == S.Context.LongDoubleTy); 1190 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1191 RHSElemType == S.Context.Float128Ty); 1192 1193 /* We've handled the situation where __float128 and long double have the same 1194 representation. The only other allowable conversion is if long double is 1195 really just double. 1196 */ 1197 return Float128AndLongDouble && 1198 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1199 &llvm::APFloat::IEEEdouble()); 1200 } 1201 1202 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1203 1204 namespace { 1205 /// These helper callbacks are placed in an anonymous namespace to 1206 /// permit their use as function template parameters. 1207 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1208 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1209 } 1210 1211 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1212 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1213 CK_IntegralComplexCast); 1214 } 1215 } 1216 1217 /// \brief Handle integer arithmetic conversions. Helper function of 1218 /// UsualArithmeticConversions() 1219 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1220 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1221 ExprResult &RHS, QualType LHSType, 1222 QualType RHSType, bool IsCompAssign) { 1223 // The rules for this case are in C99 6.3.1.8 1224 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1225 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1226 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1227 if (LHSSigned == RHSSigned) { 1228 // Same signedness; use the higher-ranked type 1229 if (order >= 0) { 1230 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1231 return LHSType; 1232 } else if (!IsCompAssign) 1233 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1234 return RHSType; 1235 } else if (order != (LHSSigned ? 1 : -1)) { 1236 // The unsigned type has greater than or equal rank to the 1237 // signed type, so use the unsigned type 1238 if (RHSSigned) { 1239 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1240 return LHSType; 1241 } else if (!IsCompAssign) 1242 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1243 return RHSType; 1244 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1245 // The two types are different widths; if we are here, that 1246 // means the signed type is larger than the unsigned type, so 1247 // use the signed type. 1248 if (LHSSigned) { 1249 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1250 return LHSType; 1251 } else if (!IsCompAssign) 1252 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1253 return RHSType; 1254 } else { 1255 // The signed type is higher-ranked than the unsigned type, 1256 // but isn't actually any bigger (like unsigned int and long 1257 // on most 32-bit systems). Use the unsigned type corresponding 1258 // to the signed type. 1259 QualType result = 1260 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1261 RHS = (*doRHSCast)(S, RHS.get(), result); 1262 if (!IsCompAssign) 1263 LHS = (*doLHSCast)(S, LHS.get(), result); 1264 return result; 1265 } 1266 } 1267 1268 /// \brief Handle conversions with GCC complex int extension. Helper function 1269 /// of UsualArithmeticConversions() 1270 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1271 ExprResult &RHS, QualType LHSType, 1272 QualType RHSType, 1273 bool IsCompAssign) { 1274 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1275 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1276 1277 if (LHSComplexInt && RHSComplexInt) { 1278 QualType LHSEltType = LHSComplexInt->getElementType(); 1279 QualType RHSEltType = RHSComplexInt->getElementType(); 1280 QualType ScalarType = 1281 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1282 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1283 1284 return S.Context.getComplexType(ScalarType); 1285 } 1286 1287 if (LHSComplexInt) { 1288 QualType LHSEltType = LHSComplexInt->getElementType(); 1289 QualType ScalarType = 1290 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1291 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1292 QualType ComplexType = S.Context.getComplexType(ScalarType); 1293 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1294 CK_IntegralRealToComplex); 1295 1296 return ComplexType; 1297 } 1298 1299 assert(RHSComplexInt); 1300 1301 QualType RHSEltType = RHSComplexInt->getElementType(); 1302 QualType ScalarType = 1303 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1304 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1305 QualType ComplexType = S.Context.getComplexType(ScalarType); 1306 1307 if (!IsCompAssign) 1308 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1309 CK_IntegralRealToComplex); 1310 return ComplexType; 1311 } 1312 1313 /// UsualArithmeticConversions - Performs various conversions that are common to 1314 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1315 /// routine returns the first non-arithmetic type found. The client is 1316 /// responsible for emitting appropriate error diagnostics. 1317 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1318 bool IsCompAssign) { 1319 if (!IsCompAssign) { 1320 LHS = UsualUnaryConversions(LHS.get()); 1321 if (LHS.isInvalid()) 1322 return QualType(); 1323 } 1324 1325 RHS = UsualUnaryConversions(RHS.get()); 1326 if (RHS.isInvalid()) 1327 return QualType(); 1328 1329 // For conversion purposes, we ignore any qualifiers. 1330 // For example, "const float" and "float" are equivalent. 1331 QualType LHSType = 1332 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1333 QualType RHSType = 1334 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1335 1336 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1337 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1338 LHSType = AtomicLHS->getValueType(); 1339 1340 // If both types are identical, no conversion is needed. 1341 if (LHSType == RHSType) 1342 return LHSType; 1343 1344 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1345 // The caller can deal with this (e.g. pointer + int). 1346 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1347 return QualType(); 1348 1349 // Apply unary and bitfield promotions to the LHS's type. 1350 QualType LHSUnpromotedType = LHSType; 1351 if (LHSType->isPromotableIntegerType()) 1352 LHSType = Context.getPromotedIntegerType(LHSType); 1353 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1354 if (!LHSBitfieldPromoteTy.isNull()) 1355 LHSType = LHSBitfieldPromoteTy; 1356 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1357 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1358 1359 // If both types are identical, no conversion is needed. 1360 if (LHSType == RHSType) 1361 return LHSType; 1362 1363 // At this point, we have two different arithmetic types. 1364 1365 // Diagnose attempts to convert between __float128 and long double where 1366 // such conversions currently can't be handled. 1367 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1368 return QualType(); 1369 1370 // Handle complex types first (C99 6.3.1.8p1). 1371 if (LHSType->isComplexType() || RHSType->isComplexType()) 1372 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1373 IsCompAssign); 1374 1375 // Now handle "real" floating types (i.e. float, double, long double). 1376 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1377 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1378 IsCompAssign); 1379 1380 // Handle GCC complex int extension. 1381 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1382 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1383 IsCompAssign); 1384 1385 // Finally, we have two differing integer types. 1386 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1387 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1388 } 1389 1390 1391 //===----------------------------------------------------------------------===// 1392 // Semantic Analysis for various Expression Types 1393 //===----------------------------------------------------------------------===// 1394 1395 1396 ExprResult 1397 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1398 SourceLocation DefaultLoc, 1399 SourceLocation RParenLoc, 1400 Expr *ControllingExpr, 1401 ArrayRef<ParsedType> ArgTypes, 1402 ArrayRef<Expr *> ArgExprs) { 1403 unsigned NumAssocs = ArgTypes.size(); 1404 assert(NumAssocs == ArgExprs.size()); 1405 1406 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1407 for (unsigned i = 0; i < NumAssocs; ++i) { 1408 if (ArgTypes[i]) 1409 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1410 else 1411 Types[i] = nullptr; 1412 } 1413 1414 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1415 ControllingExpr, 1416 llvm::makeArrayRef(Types, NumAssocs), 1417 ArgExprs); 1418 delete [] Types; 1419 return ER; 1420 } 1421 1422 ExprResult 1423 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1424 SourceLocation DefaultLoc, 1425 SourceLocation RParenLoc, 1426 Expr *ControllingExpr, 1427 ArrayRef<TypeSourceInfo *> Types, 1428 ArrayRef<Expr *> Exprs) { 1429 unsigned NumAssocs = Types.size(); 1430 assert(NumAssocs == Exprs.size()); 1431 1432 // Decay and strip qualifiers for the controlling expression type, and handle 1433 // placeholder type replacement. See committee discussion from WG14 DR423. 1434 { 1435 EnterExpressionEvaluationContext Unevaluated(*this, Sema::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 (ActiveTemplateInstantiations.empty() && 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 = !ActiveTemplateInstantiations.empty() && 1892 ActiveTemplateInstantiations.back().Kind == 1893 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1894 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1895 bool isInstance = CurMethod && 1896 CurMethod->isInstance() && 1897 DC == CurMethod->getParent() && !isDefaultArgument; 1898 1899 // Give a code modification hint to insert 'this->'. 1900 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1901 // Actually quite difficult! 1902 if (getLangOpts().MSVCCompat) 1903 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1904 if (isInstance) { 1905 Diag(R.getNameLoc(), diagnostic) << Name 1906 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1907 CheckCXXThisCapture(R.getNameLoc()); 1908 } else { 1909 Diag(R.getNameLoc(), diagnostic) << Name; 1910 } 1911 1912 // Do we really want to note all of these? 1913 for (NamedDecl *D : R) 1914 Diag(D->getLocation(), diag::note_dependent_var_use); 1915 1916 // Return true if we are inside a default argument instantiation 1917 // and the found name refers to an instance member function, otherwise 1918 // the function calling DiagnoseEmptyLookup will try to create an 1919 // implicit member call and this is wrong for default argument. 1920 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1921 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1922 return true; 1923 } 1924 1925 // Tell the callee to try to recover. 1926 return false; 1927 } 1928 1929 R.clear(); 1930 } 1931 1932 // In Microsoft mode, if we are performing lookup from within a friend 1933 // function definition declared at class scope then we must set 1934 // DC to the lexical parent to be able to search into the parent 1935 // class. 1936 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1937 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1938 DC->getLexicalParent()->isRecord()) 1939 DC = DC->getLexicalParent(); 1940 else 1941 DC = DC->getParent(); 1942 } 1943 1944 // We didn't find anything, so try to correct for a typo. 1945 TypoCorrection Corrected; 1946 if (S && Out) { 1947 SourceLocation TypoLoc = R.getNameLoc(); 1948 assert(!ExplicitTemplateArgs && 1949 "Diagnosing an empty lookup with explicit template args!"); 1950 *Out = CorrectTypoDelayed( 1951 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1952 [=](const TypoCorrection &TC) { 1953 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1954 diagnostic, diagnostic_suggest); 1955 }, 1956 nullptr, CTK_ErrorRecovery); 1957 if (*Out) 1958 return true; 1959 } else if (S && (Corrected = 1960 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1961 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1962 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1963 bool DroppedSpecifier = 1964 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1965 R.setLookupName(Corrected.getCorrection()); 1966 1967 bool AcceptableWithRecovery = false; 1968 bool AcceptableWithoutRecovery = false; 1969 NamedDecl *ND = Corrected.getFoundDecl(); 1970 if (ND) { 1971 if (Corrected.isOverloaded()) { 1972 OverloadCandidateSet OCS(R.getNameLoc(), 1973 OverloadCandidateSet::CSK_Normal); 1974 OverloadCandidateSet::iterator Best; 1975 for (NamedDecl *CD : Corrected) { 1976 if (FunctionTemplateDecl *FTD = 1977 dyn_cast<FunctionTemplateDecl>(CD)) 1978 AddTemplateOverloadCandidate( 1979 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1980 Args, OCS); 1981 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1982 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1983 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1984 Args, OCS); 1985 } 1986 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1987 case OR_Success: 1988 ND = Best->FoundDecl; 1989 Corrected.setCorrectionDecl(ND); 1990 break; 1991 default: 1992 // FIXME: Arbitrarily pick the first declaration for the note. 1993 Corrected.setCorrectionDecl(ND); 1994 break; 1995 } 1996 } 1997 R.addDecl(ND); 1998 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1999 CXXRecordDecl *Record = nullptr; 2000 if (Corrected.getCorrectionSpecifier()) { 2001 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2002 Record = Ty->getAsCXXRecordDecl(); 2003 } 2004 if (!Record) 2005 Record = cast<CXXRecordDecl>( 2006 ND->getDeclContext()->getRedeclContext()); 2007 R.setNamingClass(Record); 2008 } 2009 2010 auto *UnderlyingND = ND->getUnderlyingDecl(); 2011 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2012 isa<FunctionTemplateDecl>(UnderlyingND); 2013 // FIXME: If we ended up with a typo for a type name or 2014 // Objective-C class name, we're in trouble because the parser 2015 // is in the wrong place to recover. Suggest the typo 2016 // correction, but don't make it a fix-it since we're not going 2017 // to recover well anyway. 2018 AcceptableWithoutRecovery = 2019 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2020 } else { 2021 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2022 // because we aren't able to recover. 2023 AcceptableWithoutRecovery = true; 2024 } 2025 2026 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2027 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2028 ? diag::note_implicit_param_decl 2029 : diag::note_previous_decl; 2030 if (SS.isEmpty()) 2031 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2032 PDiag(NoteID), AcceptableWithRecovery); 2033 else 2034 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2035 << Name << computeDeclContext(SS, false) 2036 << DroppedSpecifier << SS.getRange(), 2037 PDiag(NoteID), AcceptableWithRecovery); 2038 2039 // Tell the callee whether to try to recover. 2040 return !AcceptableWithRecovery; 2041 } 2042 } 2043 R.clear(); 2044 2045 // Emit a special diagnostic for failed member lookups. 2046 // FIXME: computing the declaration context might fail here (?) 2047 if (!SS.isEmpty()) { 2048 Diag(R.getNameLoc(), diag::err_no_member) 2049 << Name << computeDeclContext(SS, false) 2050 << SS.getRange(); 2051 return true; 2052 } 2053 2054 // Give up, we can't recover. 2055 Diag(R.getNameLoc(), diagnostic) << Name; 2056 return true; 2057 } 2058 2059 /// In Microsoft mode, if we are inside a template class whose parent class has 2060 /// dependent base classes, and we can't resolve an unqualified identifier, then 2061 /// assume the identifier is a member of a dependent base class. We can only 2062 /// recover successfully in static methods, instance methods, and other contexts 2063 /// where 'this' is available. This doesn't precisely match MSVC's 2064 /// instantiation model, but it's close enough. 2065 static Expr * 2066 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2067 DeclarationNameInfo &NameInfo, 2068 SourceLocation TemplateKWLoc, 2069 const TemplateArgumentListInfo *TemplateArgs) { 2070 // Only try to recover from lookup into dependent bases in static methods or 2071 // contexts where 'this' is available. 2072 QualType ThisType = S.getCurrentThisType(); 2073 const CXXRecordDecl *RD = nullptr; 2074 if (!ThisType.isNull()) 2075 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2076 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2077 RD = MD->getParent(); 2078 if (!RD || !RD->hasAnyDependentBases()) 2079 return nullptr; 2080 2081 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2082 // is available, suggest inserting 'this->' as a fixit. 2083 SourceLocation Loc = NameInfo.getLoc(); 2084 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2085 DB << NameInfo.getName() << RD; 2086 2087 if (!ThisType.isNull()) { 2088 DB << FixItHint::CreateInsertion(Loc, "this->"); 2089 return CXXDependentScopeMemberExpr::Create( 2090 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2091 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2092 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2093 } 2094 2095 // Synthesize a fake NNS that points to the derived class. This will 2096 // perform name lookup during template instantiation. 2097 CXXScopeSpec SS; 2098 auto *NNS = 2099 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2100 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2101 return DependentScopeDeclRefExpr::Create( 2102 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2103 TemplateArgs); 2104 } 2105 2106 ExprResult 2107 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2108 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2109 bool HasTrailingLParen, bool IsAddressOfOperand, 2110 std::unique_ptr<CorrectionCandidateCallback> CCC, 2111 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2112 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2113 "cannot be direct & operand and have a trailing lparen"); 2114 if (SS.isInvalid()) 2115 return ExprError(); 2116 2117 TemplateArgumentListInfo TemplateArgsBuffer; 2118 2119 // Decompose the UnqualifiedId into the following data. 2120 DeclarationNameInfo NameInfo; 2121 const TemplateArgumentListInfo *TemplateArgs; 2122 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2123 2124 DeclarationName Name = NameInfo.getName(); 2125 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2126 SourceLocation NameLoc = NameInfo.getLoc(); 2127 2128 // C++ [temp.dep.expr]p3: 2129 // An id-expression is type-dependent if it contains: 2130 // -- an identifier that was declared with a dependent type, 2131 // (note: handled after lookup) 2132 // -- a template-id that is dependent, 2133 // (note: handled in BuildTemplateIdExpr) 2134 // -- a conversion-function-id that specifies a dependent type, 2135 // -- a nested-name-specifier that contains a class-name that 2136 // names a dependent type. 2137 // Determine whether this is a member of an unknown specialization; 2138 // we need to handle these differently. 2139 bool DependentID = false; 2140 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2141 Name.getCXXNameType()->isDependentType()) { 2142 DependentID = true; 2143 } else if (SS.isSet()) { 2144 if (DeclContext *DC = computeDeclContext(SS, false)) { 2145 if (RequireCompleteDeclContext(SS, DC)) 2146 return ExprError(); 2147 } else { 2148 DependentID = true; 2149 } 2150 } 2151 2152 if (DependentID) 2153 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2154 IsAddressOfOperand, TemplateArgs); 2155 2156 // Perform the required lookup. 2157 LookupResult R(*this, NameInfo, 2158 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2159 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2160 if (TemplateArgs) { 2161 // Lookup the template name again to correctly establish the context in 2162 // which it was found. This is really unfortunate as we already did the 2163 // lookup to determine that it was a template name in the first place. If 2164 // this becomes a performance hit, we can work harder to preserve those 2165 // results until we get here but it's likely not worth it. 2166 bool MemberOfUnknownSpecialization; 2167 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2168 MemberOfUnknownSpecialization); 2169 2170 if (MemberOfUnknownSpecialization || 2171 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2172 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2173 IsAddressOfOperand, TemplateArgs); 2174 } else { 2175 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2176 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2177 2178 // If the result might be in a dependent base class, this is a dependent 2179 // id-expression. 2180 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2181 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2182 IsAddressOfOperand, TemplateArgs); 2183 2184 // If this reference is in an Objective-C method, then we need to do 2185 // some special Objective-C lookup, too. 2186 if (IvarLookupFollowUp) { 2187 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2188 if (E.isInvalid()) 2189 return ExprError(); 2190 2191 if (Expr *Ex = E.getAs<Expr>()) 2192 return Ex; 2193 } 2194 } 2195 2196 if (R.isAmbiguous()) 2197 return ExprError(); 2198 2199 // This could be an implicitly declared function reference (legal in C90, 2200 // extension in C99, forbidden in C++). 2201 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2202 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2203 if (D) R.addDecl(D); 2204 } 2205 2206 // Determine whether this name might be a candidate for 2207 // argument-dependent lookup. 2208 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2209 2210 if (R.empty() && !ADL) { 2211 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2212 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2213 TemplateKWLoc, TemplateArgs)) 2214 return E; 2215 } 2216 2217 // Don't diagnose an empty lookup for inline assembly. 2218 if (IsInlineAsmIdentifier) 2219 return ExprError(); 2220 2221 // If this name wasn't predeclared and if this is not a function 2222 // call, diagnose the problem. 2223 TypoExpr *TE = nullptr; 2224 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2225 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2226 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2227 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2228 "Typo correction callback misconfigured"); 2229 if (CCC) { 2230 // Make sure the callback knows what the typo being diagnosed is. 2231 CCC->setTypoName(II); 2232 if (SS.isValid()) 2233 CCC->setTypoNNS(SS.getScopeRep()); 2234 } 2235 if (DiagnoseEmptyLookup(S, SS, R, 2236 CCC ? std::move(CCC) : std::move(DefaultValidator), 2237 nullptr, None, &TE)) { 2238 if (TE && KeywordReplacement) { 2239 auto &State = getTypoExprState(TE); 2240 auto BestTC = State.Consumer->getNextCorrection(); 2241 if (BestTC.isKeyword()) { 2242 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2243 if (State.DiagHandler) 2244 State.DiagHandler(BestTC); 2245 KeywordReplacement->startToken(); 2246 KeywordReplacement->setKind(II->getTokenID()); 2247 KeywordReplacement->setIdentifierInfo(II); 2248 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2249 // Clean up the state associated with the TypoExpr, since it has 2250 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2251 clearDelayedTypo(TE); 2252 // Signal that a correction to a keyword was performed by returning a 2253 // valid-but-null ExprResult. 2254 return (Expr*)nullptr; 2255 } 2256 State.Consumer->resetCorrectionStream(); 2257 } 2258 return TE ? TE : ExprError(); 2259 } 2260 2261 assert(!R.empty() && 2262 "DiagnoseEmptyLookup returned false but added no results"); 2263 2264 // If we found an Objective-C instance variable, let 2265 // LookupInObjCMethod build the appropriate expression to 2266 // reference the ivar. 2267 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2268 R.clear(); 2269 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2270 // In a hopelessly buggy code, Objective-C instance variable 2271 // lookup fails and no expression will be built to reference it. 2272 if (!E.isInvalid() && !E.get()) 2273 return ExprError(); 2274 return E; 2275 } 2276 } 2277 2278 // This is guaranteed from this point on. 2279 assert(!R.empty() || ADL); 2280 2281 // Check whether this might be a C++ implicit instance member access. 2282 // C++ [class.mfct.non-static]p3: 2283 // When an id-expression that is not part of a class member access 2284 // syntax and not used to form a pointer to member is used in the 2285 // body of a non-static member function of class X, if name lookup 2286 // resolves the name in the id-expression to a non-static non-type 2287 // member of some class C, the id-expression is transformed into a 2288 // class member access expression using (*this) as the 2289 // postfix-expression to the left of the . operator. 2290 // 2291 // But we don't actually need to do this for '&' operands if R 2292 // resolved to a function or overloaded function set, because the 2293 // expression is ill-formed if it actually works out to be a 2294 // non-static member function: 2295 // 2296 // C++ [expr.ref]p4: 2297 // Otherwise, if E1.E2 refers to a non-static member function. . . 2298 // [t]he expression can be used only as the left-hand operand of a 2299 // member function call. 2300 // 2301 // There are other safeguards against such uses, but it's important 2302 // to get this right here so that we don't end up making a 2303 // spuriously dependent expression if we're inside a dependent 2304 // instance method. 2305 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2306 bool MightBeImplicitMember; 2307 if (!IsAddressOfOperand) 2308 MightBeImplicitMember = true; 2309 else if (!SS.isEmpty()) 2310 MightBeImplicitMember = false; 2311 else if (R.isOverloadedResult()) 2312 MightBeImplicitMember = false; 2313 else if (R.isUnresolvableResult()) 2314 MightBeImplicitMember = true; 2315 else 2316 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2317 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2318 isa<MSPropertyDecl>(R.getFoundDecl()); 2319 2320 if (MightBeImplicitMember) 2321 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2322 R, TemplateArgs, S); 2323 } 2324 2325 if (TemplateArgs || TemplateKWLoc.isValid()) { 2326 2327 // In C++1y, if this is a variable template id, then check it 2328 // in BuildTemplateIdExpr(). 2329 // The single lookup result must be a variable template declaration. 2330 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2331 Id.TemplateId->Kind == TNK_Var_template) { 2332 assert(R.getAsSingle<VarTemplateDecl>() && 2333 "There should only be one declaration found."); 2334 } 2335 2336 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2337 } 2338 2339 return BuildDeclarationNameExpr(SS, R, ADL); 2340 } 2341 2342 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2343 /// declaration name, generally during template instantiation. 2344 /// There's a large number of things which don't need to be done along 2345 /// this path. 2346 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2347 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2348 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2349 DeclContext *DC = computeDeclContext(SS, false); 2350 if (!DC) 2351 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2352 NameInfo, /*TemplateArgs=*/nullptr); 2353 2354 if (RequireCompleteDeclContext(SS, DC)) 2355 return ExprError(); 2356 2357 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2358 LookupQualifiedName(R, DC); 2359 2360 if (R.isAmbiguous()) 2361 return ExprError(); 2362 2363 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2364 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2365 NameInfo, /*TemplateArgs=*/nullptr); 2366 2367 if (R.empty()) { 2368 Diag(NameInfo.getLoc(), diag::err_no_member) 2369 << NameInfo.getName() << DC << SS.getRange(); 2370 return ExprError(); 2371 } 2372 2373 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2374 // Diagnose a missing typename if this resolved unambiguously to a type in 2375 // a dependent context. If we can recover with a type, downgrade this to 2376 // a warning in Microsoft compatibility mode. 2377 unsigned DiagID = diag::err_typename_missing; 2378 if (RecoveryTSI && getLangOpts().MSVCCompat) 2379 DiagID = diag::ext_typename_missing; 2380 SourceLocation Loc = SS.getBeginLoc(); 2381 auto D = Diag(Loc, DiagID); 2382 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2383 << SourceRange(Loc, NameInfo.getEndLoc()); 2384 2385 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2386 // context. 2387 if (!RecoveryTSI) 2388 return ExprError(); 2389 2390 // Only issue the fixit if we're prepared to recover. 2391 D << FixItHint::CreateInsertion(Loc, "typename "); 2392 2393 // Recover by pretending this was an elaborated type. 2394 QualType Ty = Context.getTypeDeclType(TD); 2395 TypeLocBuilder TLB; 2396 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2397 2398 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2399 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2400 QTL.setElaboratedKeywordLoc(SourceLocation()); 2401 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2402 2403 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2404 2405 return ExprEmpty(); 2406 } 2407 2408 // Defend against this resolving to an implicit member access. We usually 2409 // won't get here if this might be a legitimate a class member (we end up in 2410 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2411 // a pointer-to-member or in an unevaluated context in C++11. 2412 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2413 return BuildPossibleImplicitMemberExpr(SS, 2414 /*TemplateKWLoc=*/SourceLocation(), 2415 R, /*TemplateArgs=*/nullptr, S); 2416 2417 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2418 } 2419 2420 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2421 /// detected that we're currently inside an ObjC method. Perform some 2422 /// additional lookup. 2423 /// 2424 /// Ideally, most of this would be done by lookup, but there's 2425 /// actually quite a lot of extra work involved. 2426 /// 2427 /// Returns a null sentinel to indicate trivial success. 2428 ExprResult 2429 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2430 IdentifierInfo *II, bool AllowBuiltinCreation) { 2431 SourceLocation Loc = Lookup.getNameLoc(); 2432 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2433 2434 // Check for error condition which is already reported. 2435 if (!CurMethod) 2436 return ExprError(); 2437 2438 // There are two cases to handle here. 1) scoped lookup could have failed, 2439 // in which case we should look for an ivar. 2) scoped lookup could have 2440 // found a decl, but that decl is outside the current instance method (i.e. 2441 // a global variable). In these two cases, we do a lookup for an ivar with 2442 // this name, if the lookup sucedes, we replace it our current decl. 2443 2444 // If we're in a class method, we don't normally want to look for 2445 // ivars. But if we don't find anything else, and there's an 2446 // ivar, that's an error. 2447 bool IsClassMethod = CurMethod->isClassMethod(); 2448 2449 bool LookForIvars; 2450 if (Lookup.empty()) 2451 LookForIvars = true; 2452 else if (IsClassMethod) 2453 LookForIvars = false; 2454 else 2455 LookForIvars = (Lookup.isSingleResult() && 2456 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2457 ObjCInterfaceDecl *IFace = nullptr; 2458 if (LookForIvars) { 2459 IFace = CurMethod->getClassInterface(); 2460 ObjCInterfaceDecl *ClassDeclared; 2461 ObjCIvarDecl *IV = nullptr; 2462 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2463 // Diagnose using an ivar in a class method. 2464 if (IsClassMethod) 2465 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2466 << IV->getDeclName()); 2467 2468 // If we're referencing an invalid decl, just return this as a silent 2469 // error node. The error diagnostic was already emitted on the decl. 2470 if (IV->isInvalidDecl()) 2471 return ExprError(); 2472 2473 // Check if referencing a field with __attribute__((deprecated)). 2474 if (DiagnoseUseOfDecl(IV, Loc)) 2475 return ExprError(); 2476 2477 // Diagnose the use of an ivar outside of the declaring class. 2478 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2479 !declaresSameEntity(ClassDeclared, IFace) && 2480 !getLangOpts().DebuggerSupport) 2481 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2482 2483 // FIXME: This should use a new expr for a direct reference, don't 2484 // turn this into Self->ivar, just return a BareIVarExpr or something. 2485 IdentifierInfo &II = Context.Idents.get("self"); 2486 UnqualifiedId SelfName; 2487 SelfName.setIdentifier(&II, SourceLocation()); 2488 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2489 CXXScopeSpec SelfScopeSpec; 2490 SourceLocation TemplateKWLoc; 2491 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2492 SelfName, false, false); 2493 if (SelfExpr.isInvalid()) 2494 return ExprError(); 2495 2496 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2497 if (SelfExpr.isInvalid()) 2498 return ExprError(); 2499 2500 MarkAnyDeclReferenced(Loc, IV, true); 2501 2502 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2503 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2504 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2505 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2506 2507 ObjCIvarRefExpr *Result = new (Context) 2508 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2509 IV->getLocation(), SelfExpr.get(), true, true); 2510 2511 if (getLangOpts().ObjCAutoRefCount) { 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 (CurContext->isClosure()) 2517 Diag(Loc, diag::warn_implicitly_retains_self) 2518 << FixItHint::CreateInsertion(Loc, "self->"); 2519 } 2520 2521 return Result; 2522 } 2523 } else if (CurMethod->isInstanceMethod()) { 2524 // We should warn if a local variable hides an ivar. 2525 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2526 ObjCInterfaceDecl *ClassDeclared; 2527 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2528 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2529 declaresSameEntity(IFace, ClassDeclared)) 2530 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2531 } 2532 } 2533 } else if (Lookup.isSingleResult() && 2534 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2535 // If accessing a stand-alone ivar in a class method, this is an error. 2536 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2537 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2538 << IV->getDeclName()); 2539 } 2540 2541 if (Lookup.empty() && II && AllowBuiltinCreation) { 2542 // FIXME. Consolidate this with similar code in LookupName. 2543 if (unsigned BuiltinID = II->getBuiltinID()) { 2544 if (!(getLangOpts().CPlusPlus && 2545 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2546 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2547 S, Lookup.isForRedeclaration(), 2548 Lookup.getNameLoc()); 2549 if (D) Lookup.addDecl(D); 2550 } 2551 } 2552 } 2553 // Sentinel value saying that we didn't do anything special. 2554 return ExprResult((Expr *)nullptr); 2555 } 2556 2557 /// \brief Cast a base object to a member's actual type. 2558 /// 2559 /// Logically this happens in three phases: 2560 /// 2561 /// * First we cast from the base type to the naming class. 2562 /// The naming class is the class into which we were looking 2563 /// when we found the member; it's the qualifier type if a 2564 /// qualifier was provided, and otherwise it's the base type. 2565 /// 2566 /// * Next we cast from the naming class to the declaring class. 2567 /// If the member we found was brought into a class's scope by 2568 /// a using declaration, this is that class; otherwise it's 2569 /// the class declaring the member. 2570 /// 2571 /// * Finally we cast from the declaring class to the "true" 2572 /// declaring class of the member. This conversion does not 2573 /// obey access control. 2574 ExprResult 2575 Sema::PerformObjectMemberConversion(Expr *From, 2576 NestedNameSpecifier *Qualifier, 2577 NamedDecl *FoundDecl, 2578 NamedDecl *Member) { 2579 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2580 if (!RD) 2581 return From; 2582 2583 QualType DestRecordType; 2584 QualType DestType; 2585 QualType FromRecordType; 2586 QualType FromType = From->getType(); 2587 bool PointerConversions = false; 2588 if (isa<FieldDecl>(Member)) { 2589 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2590 2591 if (FromType->getAs<PointerType>()) { 2592 DestType = Context.getPointerType(DestRecordType); 2593 FromRecordType = FromType->getPointeeType(); 2594 PointerConversions = true; 2595 } else { 2596 DestType = DestRecordType; 2597 FromRecordType = FromType; 2598 } 2599 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2600 if (Method->isStatic()) 2601 return From; 2602 2603 DestType = Method->getThisType(Context); 2604 DestRecordType = DestType->getPointeeType(); 2605 2606 if (FromType->getAs<PointerType>()) { 2607 FromRecordType = FromType->getPointeeType(); 2608 PointerConversions = true; 2609 } else { 2610 FromRecordType = FromType; 2611 DestType = DestRecordType; 2612 } 2613 } else { 2614 // No conversion necessary. 2615 return From; 2616 } 2617 2618 if (DestType->isDependentType() || FromType->isDependentType()) 2619 return From; 2620 2621 // If the unqualified types are the same, no conversion is necessary. 2622 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2623 return From; 2624 2625 SourceRange FromRange = From->getSourceRange(); 2626 SourceLocation FromLoc = FromRange.getBegin(); 2627 2628 ExprValueKind VK = From->getValueKind(); 2629 2630 // C++ [class.member.lookup]p8: 2631 // [...] Ambiguities can often be resolved by qualifying a name with its 2632 // class name. 2633 // 2634 // If the member was a qualified name and the qualified referred to a 2635 // specific base subobject type, we'll cast to that intermediate type 2636 // first and then to the object in which the member is declared. That allows 2637 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2638 // 2639 // class Base { public: int x; }; 2640 // class Derived1 : public Base { }; 2641 // class Derived2 : public Base { }; 2642 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2643 // 2644 // void VeryDerived::f() { 2645 // x = 17; // error: ambiguous base subobjects 2646 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2647 // } 2648 if (Qualifier && Qualifier->getAsType()) { 2649 QualType QType = QualType(Qualifier->getAsType(), 0); 2650 assert(QType->isRecordType() && "lookup done with non-record type"); 2651 2652 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2653 2654 // In C++98, the qualifier type doesn't actually have to be a base 2655 // type of the object type, in which case we just ignore it. 2656 // Otherwise build the appropriate casts. 2657 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2658 CXXCastPath BasePath; 2659 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2660 FromLoc, FromRange, &BasePath)) 2661 return ExprError(); 2662 2663 if (PointerConversions) 2664 QType = Context.getPointerType(QType); 2665 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2666 VK, &BasePath).get(); 2667 2668 FromType = QType; 2669 FromRecordType = QRecordType; 2670 2671 // If the qualifier type was the same as the destination type, 2672 // we're done. 2673 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2674 return From; 2675 } 2676 } 2677 2678 bool IgnoreAccess = false; 2679 2680 // If we actually found the member through a using declaration, cast 2681 // down to the using declaration's type. 2682 // 2683 // Pointer equality is fine here because only one declaration of a 2684 // class ever has member declarations. 2685 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2686 assert(isa<UsingShadowDecl>(FoundDecl)); 2687 QualType URecordType = Context.getTypeDeclType( 2688 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2689 2690 // We only need to do this if the naming-class to declaring-class 2691 // conversion is non-trivial. 2692 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2693 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2694 CXXCastPath BasePath; 2695 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2696 FromLoc, FromRange, &BasePath)) 2697 return ExprError(); 2698 2699 QualType UType = URecordType; 2700 if (PointerConversions) 2701 UType = Context.getPointerType(UType); 2702 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2703 VK, &BasePath).get(); 2704 FromType = UType; 2705 FromRecordType = URecordType; 2706 } 2707 2708 // We don't do access control for the conversion from the 2709 // declaring class to the true declaring class. 2710 IgnoreAccess = true; 2711 } 2712 2713 CXXCastPath BasePath; 2714 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2715 FromLoc, FromRange, &BasePath, 2716 IgnoreAccess)) 2717 return ExprError(); 2718 2719 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2720 VK, &BasePath); 2721 } 2722 2723 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2724 const LookupResult &R, 2725 bool HasTrailingLParen) { 2726 // Only when used directly as the postfix-expression of a call. 2727 if (!HasTrailingLParen) 2728 return false; 2729 2730 // Never if a scope specifier was provided. 2731 if (SS.isSet()) 2732 return false; 2733 2734 // Only in C++ or ObjC++. 2735 if (!getLangOpts().CPlusPlus) 2736 return false; 2737 2738 // Turn off ADL when we find certain kinds of declarations during 2739 // normal lookup: 2740 for (NamedDecl *D : R) { 2741 // C++0x [basic.lookup.argdep]p3: 2742 // -- a declaration of a class member 2743 // Since using decls preserve this property, we check this on the 2744 // original decl. 2745 if (D->isCXXClassMember()) 2746 return false; 2747 2748 // C++0x [basic.lookup.argdep]p3: 2749 // -- a block-scope function declaration that is not a 2750 // using-declaration 2751 // NOTE: we also trigger this for function templates (in fact, we 2752 // don't check the decl type at all, since all other decl types 2753 // turn off ADL anyway). 2754 if (isa<UsingShadowDecl>(D)) 2755 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2756 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2757 return false; 2758 2759 // C++0x [basic.lookup.argdep]p3: 2760 // -- a declaration that is neither a function or a function 2761 // template 2762 // And also for builtin functions. 2763 if (isa<FunctionDecl>(D)) { 2764 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2765 2766 // But also builtin functions. 2767 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2768 return false; 2769 } else if (!isa<FunctionTemplateDecl>(D)) 2770 return false; 2771 } 2772 2773 return true; 2774 } 2775 2776 2777 /// Diagnoses obvious problems with the use of the given declaration 2778 /// as an expression. This is only actually called for lookups that 2779 /// were not overloaded, and it doesn't promise that the declaration 2780 /// will in fact be used. 2781 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2782 if (D->isInvalidDecl()) 2783 return true; 2784 2785 if (isa<TypedefNameDecl>(D)) { 2786 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2787 return true; 2788 } 2789 2790 if (isa<ObjCInterfaceDecl>(D)) { 2791 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2792 return true; 2793 } 2794 2795 if (isa<NamespaceDecl>(D)) { 2796 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2797 return true; 2798 } 2799 2800 return false; 2801 } 2802 2803 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2804 LookupResult &R, bool NeedsADL, 2805 bool AcceptInvalidDecl) { 2806 // If this is a single, fully-resolved result and we don't need ADL, 2807 // just build an ordinary singleton decl ref. 2808 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2809 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2810 R.getRepresentativeDecl(), nullptr, 2811 AcceptInvalidDecl); 2812 2813 // We only need to check the declaration if there's exactly one 2814 // result, because in the overloaded case the results can only be 2815 // functions and function templates. 2816 if (R.isSingleResult() && 2817 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2818 return ExprError(); 2819 2820 // Otherwise, just build an unresolved lookup expression. Suppress 2821 // any lookup-related diagnostics; we'll hash these out later, when 2822 // we've picked a target. 2823 R.suppressDiagnostics(); 2824 2825 UnresolvedLookupExpr *ULE 2826 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2827 SS.getWithLocInContext(Context), 2828 R.getLookupNameInfo(), 2829 NeedsADL, R.isOverloadedResult(), 2830 R.begin(), R.end()); 2831 2832 return ULE; 2833 } 2834 2835 static void 2836 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2837 ValueDecl *var, DeclContext *DC); 2838 2839 /// \brief Complete semantic analysis for a reference to the given declaration. 2840 ExprResult Sema::BuildDeclarationNameExpr( 2841 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2842 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2843 bool AcceptInvalidDecl) { 2844 assert(D && "Cannot refer to a NULL declaration"); 2845 assert(!isa<FunctionTemplateDecl>(D) && 2846 "Cannot refer unambiguously to a function template"); 2847 2848 SourceLocation Loc = NameInfo.getLoc(); 2849 if (CheckDeclInExpr(*this, Loc, D)) 2850 return ExprError(); 2851 2852 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2853 // Specifically diagnose references to class templates that are missing 2854 // a template argument list. 2855 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2856 << Template << SS.getRange(); 2857 Diag(Template->getLocation(), diag::note_template_decl_here); 2858 return ExprError(); 2859 } 2860 2861 // Make sure that we're referring to a value. 2862 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2863 if (!VD) { 2864 Diag(Loc, diag::err_ref_non_value) 2865 << D << SS.getRange(); 2866 Diag(D->getLocation(), diag::note_declared_at); 2867 return ExprError(); 2868 } 2869 2870 // Check whether this declaration can be used. Note that we suppress 2871 // this check when we're going to perform argument-dependent lookup 2872 // on this function name, because this might not be the function 2873 // that overload resolution actually selects. 2874 if (DiagnoseUseOfDecl(VD, Loc)) 2875 return ExprError(); 2876 2877 // Only create DeclRefExpr's for valid Decl's. 2878 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2879 return ExprError(); 2880 2881 // Handle members of anonymous structs and unions. If we got here, 2882 // and the reference is to a class member indirect field, then this 2883 // must be the subject of a pointer-to-member expression. 2884 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2885 if (!indirectField->isCXXClassMember()) 2886 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2887 indirectField); 2888 2889 { 2890 QualType type = VD->getType(); 2891 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2892 // C++ [except.spec]p17: 2893 // An exception-specification is considered to be needed when: 2894 // - in an expression, the function is the unique lookup result or 2895 // the selected member of a set of overloaded functions. 2896 ResolveExceptionSpec(Loc, FPT); 2897 type = VD->getType(); 2898 } 2899 ExprValueKind valueKind = VK_RValue; 2900 2901 switch (D->getKind()) { 2902 // Ignore all the non-ValueDecl kinds. 2903 #define ABSTRACT_DECL(kind) 2904 #define VALUE(type, base) 2905 #define DECL(type, base) \ 2906 case Decl::type: 2907 #include "clang/AST/DeclNodes.inc" 2908 llvm_unreachable("invalid value decl kind"); 2909 2910 // These shouldn't make it here. 2911 case Decl::ObjCAtDefsField: 2912 case Decl::ObjCIvar: 2913 llvm_unreachable("forming non-member reference to ivar?"); 2914 2915 // Enum constants are always r-values and never references. 2916 // Unresolved using declarations are dependent. 2917 case Decl::EnumConstant: 2918 case Decl::UnresolvedUsingValue: 2919 case Decl::OMPDeclareReduction: 2920 valueKind = VK_RValue; 2921 break; 2922 2923 // Fields and indirect fields that got here must be for 2924 // pointer-to-member expressions; we just call them l-values for 2925 // internal consistency, because this subexpression doesn't really 2926 // exist in the high-level semantics. 2927 case Decl::Field: 2928 case Decl::IndirectField: 2929 assert(getLangOpts().CPlusPlus && 2930 "building reference to field in C?"); 2931 2932 // These can't have reference type in well-formed programs, but 2933 // for internal consistency we do this anyway. 2934 type = type.getNonReferenceType(); 2935 valueKind = VK_LValue; 2936 break; 2937 2938 // Non-type template parameters are either l-values or r-values 2939 // depending on the type. 2940 case Decl::NonTypeTemplateParm: { 2941 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2942 type = reftype->getPointeeType(); 2943 valueKind = VK_LValue; // even if the parameter is an r-value reference 2944 break; 2945 } 2946 2947 // For non-references, we need to strip qualifiers just in case 2948 // the template parameter was declared as 'const int' or whatever. 2949 valueKind = VK_RValue; 2950 type = type.getUnqualifiedType(); 2951 break; 2952 } 2953 2954 case Decl::Var: 2955 case Decl::VarTemplateSpecialization: 2956 case Decl::VarTemplatePartialSpecialization: 2957 case Decl::Decomposition: 2958 case Decl::OMPCapturedExpr: 2959 // In C, "extern void blah;" is valid and is an r-value. 2960 if (!getLangOpts().CPlusPlus && 2961 !type.hasQualifiers() && 2962 type->isVoidType()) { 2963 valueKind = VK_RValue; 2964 break; 2965 } 2966 // fallthrough 2967 2968 case Decl::ImplicitParam: 2969 case Decl::ParmVar: { 2970 // These are always l-values. 2971 valueKind = VK_LValue; 2972 type = type.getNonReferenceType(); 2973 2974 // FIXME: Does the addition of const really only apply in 2975 // potentially-evaluated contexts? Since the variable isn't actually 2976 // captured in an unevaluated context, it seems that the answer is no. 2977 if (!isUnevaluatedContext()) { 2978 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2979 if (!CapturedType.isNull()) 2980 type = CapturedType; 2981 } 2982 2983 break; 2984 } 2985 2986 case Decl::Binding: { 2987 // These are always lvalues. 2988 valueKind = VK_LValue; 2989 type = type.getNonReferenceType(); 2990 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2991 // decides how that's supposed to work. 2992 auto *BD = cast<BindingDecl>(VD); 2993 if (BD->getDeclContext()->isFunctionOrMethod() && 2994 BD->getDeclContext() != CurContext) 2995 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2996 break; 2997 } 2998 2999 case Decl::Function: { 3000 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3001 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3002 type = Context.BuiltinFnTy; 3003 valueKind = VK_RValue; 3004 break; 3005 } 3006 } 3007 3008 const FunctionType *fty = type->castAs<FunctionType>(); 3009 3010 // If we're referring to a function with an __unknown_anytype 3011 // result type, make the entire expression __unknown_anytype. 3012 if (fty->getReturnType() == Context.UnknownAnyTy) { 3013 type = Context.UnknownAnyTy; 3014 valueKind = VK_RValue; 3015 break; 3016 } 3017 3018 // Functions are l-values in C++. 3019 if (getLangOpts().CPlusPlus) { 3020 valueKind = VK_LValue; 3021 break; 3022 } 3023 3024 // C99 DR 316 says that, if a function type comes from a 3025 // function definition (without a prototype), that type is only 3026 // used for checking compatibility. Therefore, when referencing 3027 // the function, we pretend that we don't have the full function 3028 // type. 3029 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3030 isa<FunctionProtoType>(fty)) 3031 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3032 fty->getExtInfo()); 3033 3034 // Functions are r-values in C. 3035 valueKind = VK_RValue; 3036 break; 3037 } 3038 3039 case Decl::MSProperty: 3040 valueKind = VK_LValue; 3041 break; 3042 3043 case Decl::CXXMethod: 3044 // If we're referring to a method with an __unknown_anytype 3045 // result type, make the entire expression __unknown_anytype. 3046 // This should only be possible with a type written directly. 3047 if (const FunctionProtoType *proto 3048 = dyn_cast<FunctionProtoType>(VD->getType())) 3049 if (proto->getReturnType() == Context.UnknownAnyTy) { 3050 type = Context.UnknownAnyTy; 3051 valueKind = VK_RValue; 3052 break; 3053 } 3054 3055 // C++ methods are l-values if static, r-values if non-static. 3056 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3057 valueKind = VK_LValue; 3058 break; 3059 } 3060 // fallthrough 3061 3062 case Decl::CXXConversion: 3063 case Decl::CXXDestructor: 3064 case Decl::CXXConstructor: 3065 valueKind = VK_RValue; 3066 break; 3067 } 3068 3069 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3070 TemplateArgs); 3071 } 3072 } 3073 3074 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3075 SmallString<32> &Target) { 3076 Target.resize(CharByteWidth * (Source.size() + 1)); 3077 char *ResultPtr = &Target[0]; 3078 const llvm::UTF8 *ErrorPtr; 3079 bool success = 3080 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3081 (void)success; 3082 assert(success); 3083 Target.resize(ResultPtr - &Target[0]); 3084 } 3085 3086 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3087 PredefinedExpr::IdentType IT) { 3088 // Pick the current block, lambda, captured statement or function. 3089 Decl *currentDecl = nullptr; 3090 if (const BlockScopeInfo *BSI = getCurBlock()) 3091 currentDecl = BSI->TheDecl; 3092 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3093 currentDecl = LSI->CallOperator; 3094 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3095 currentDecl = CSI->TheCapturedDecl; 3096 else 3097 currentDecl = getCurFunctionOrMethodDecl(); 3098 3099 if (!currentDecl) { 3100 Diag(Loc, diag::ext_predef_outside_function); 3101 currentDecl = Context.getTranslationUnitDecl(); 3102 } 3103 3104 QualType ResTy; 3105 StringLiteral *SL = nullptr; 3106 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3107 ResTy = Context.DependentTy; 3108 else { 3109 // Pre-defined identifiers are of type char[x], where x is the length of 3110 // the string. 3111 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3112 unsigned Length = Str.length(); 3113 3114 llvm::APInt LengthI(32, Length + 1); 3115 if (IT == PredefinedExpr::LFunction) { 3116 ResTy = Context.WideCharTy.withConst(); 3117 SmallString<32> RawChars; 3118 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3119 Str, RawChars); 3120 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3121 /*IndexTypeQuals*/ 0); 3122 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3123 /*Pascal*/ false, ResTy, Loc); 3124 } else { 3125 ResTy = Context.CharTy.withConst(); 3126 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3127 /*IndexTypeQuals*/ 0); 3128 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3129 /*Pascal*/ false, ResTy, Loc); 3130 } 3131 } 3132 3133 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3134 } 3135 3136 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3137 PredefinedExpr::IdentType IT; 3138 3139 switch (Kind) { 3140 default: llvm_unreachable("Unknown simple primary expr!"); 3141 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3142 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3143 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3144 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3145 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3146 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3147 } 3148 3149 return BuildPredefinedExpr(Loc, IT); 3150 } 3151 3152 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3153 SmallString<16> CharBuffer; 3154 bool Invalid = false; 3155 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3156 if (Invalid) 3157 return ExprError(); 3158 3159 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3160 PP, Tok.getKind()); 3161 if (Literal.hadError()) 3162 return ExprError(); 3163 3164 QualType Ty; 3165 if (Literal.isWide()) 3166 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3167 else if (Literal.isUTF16()) 3168 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3169 else if (Literal.isUTF32()) 3170 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3171 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3172 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3173 else 3174 Ty = Context.CharTy; // 'x' -> char in C++ 3175 3176 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3177 if (Literal.isWide()) 3178 Kind = CharacterLiteral::Wide; 3179 else if (Literal.isUTF16()) 3180 Kind = CharacterLiteral::UTF16; 3181 else if (Literal.isUTF32()) 3182 Kind = CharacterLiteral::UTF32; 3183 else if (Literal.isUTF8()) 3184 Kind = CharacterLiteral::UTF8; 3185 3186 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3187 Tok.getLocation()); 3188 3189 if (Literal.getUDSuffix().empty()) 3190 return Lit; 3191 3192 // We're building a user-defined literal. 3193 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3194 SourceLocation UDSuffixLoc = 3195 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3196 3197 // Make sure we're allowed user-defined literals here. 3198 if (!UDLScope) 3199 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3200 3201 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3202 // operator "" X (ch) 3203 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3204 Lit, Tok.getLocation()); 3205 } 3206 3207 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3208 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3209 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3210 Context.IntTy, Loc); 3211 } 3212 3213 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3214 QualType Ty, SourceLocation Loc) { 3215 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3216 3217 using llvm::APFloat; 3218 APFloat Val(Format); 3219 3220 APFloat::opStatus result = Literal.GetFloatValue(Val); 3221 3222 // Overflow is always an error, but underflow is only an error if 3223 // we underflowed to zero (APFloat reports denormals as underflow). 3224 if ((result & APFloat::opOverflow) || 3225 ((result & APFloat::opUnderflow) && Val.isZero())) { 3226 unsigned diagnostic; 3227 SmallString<20> buffer; 3228 if (result & APFloat::opOverflow) { 3229 diagnostic = diag::warn_float_overflow; 3230 APFloat::getLargest(Format).toString(buffer); 3231 } else { 3232 diagnostic = diag::warn_float_underflow; 3233 APFloat::getSmallest(Format).toString(buffer); 3234 } 3235 3236 S.Diag(Loc, diagnostic) 3237 << Ty 3238 << StringRef(buffer.data(), buffer.size()); 3239 } 3240 3241 bool isExact = (result == APFloat::opOK); 3242 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3243 } 3244 3245 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3246 assert(E && "Invalid expression"); 3247 3248 if (E->isValueDependent()) 3249 return false; 3250 3251 QualType QT = E->getType(); 3252 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3253 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3254 return true; 3255 } 3256 3257 llvm::APSInt ValueAPS; 3258 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3259 3260 if (R.isInvalid()) 3261 return true; 3262 3263 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3264 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3265 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3266 << ValueAPS.toString(10) << ValueIsPositive; 3267 return true; 3268 } 3269 3270 return false; 3271 } 3272 3273 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3274 // Fast path for a single digit (which is quite common). A single digit 3275 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3276 if (Tok.getLength() == 1) { 3277 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3278 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3279 } 3280 3281 SmallString<128> SpellingBuffer; 3282 // NumericLiteralParser wants to overread by one character. Add padding to 3283 // the buffer in case the token is copied to the buffer. If getSpelling() 3284 // returns a StringRef to the memory buffer, it should have a null char at 3285 // the EOF, so it is also safe. 3286 SpellingBuffer.resize(Tok.getLength() + 1); 3287 3288 // Get the spelling of the token, which eliminates trigraphs, etc. 3289 bool Invalid = false; 3290 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3291 if (Invalid) 3292 return ExprError(); 3293 3294 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3295 if (Literal.hadError) 3296 return ExprError(); 3297 3298 if (Literal.hasUDSuffix()) { 3299 // We're building a user-defined literal. 3300 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3301 SourceLocation UDSuffixLoc = 3302 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3303 3304 // Make sure we're allowed user-defined literals here. 3305 if (!UDLScope) 3306 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3307 3308 QualType CookedTy; 3309 if (Literal.isFloatingLiteral()) { 3310 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3311 // long double, the literal is treated as a call of the form 3312 // operator "" X (f L) 3313 CookedTy = Context.LongDoubleTy; 3314 } else { 3315 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3316 // unsigned long long, the literal is treated as a call of the form 3317 // operator "" X (n ULL) 3318 CookedTy = Context.UnsignedLongLongTy; 3319 } 3320 3321 DeclarationName OpName = 3322 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3323 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3324 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3325 3326 SourceLocation TokLoc = Tok.getLocation(); 3327 3328 // Perform literal operator lookup to determine if we're building a raw 3329 // literal or a cooked one. 3330 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3331 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3332 /*AllowRaw*/true, /*AllowTemplate*/true, 3333 /*AllowStringTemplate*/false)) { 3334 case LOLR_Error: 3335 return ExprError(); 3336 3337 case LOLR_Cooked: { 3338 Expr *Lit; 3339 if (Literal.isFloatingLiteral()) { 3340 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3341 } else { 3342 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3343 if (Literal.GetIntegerValue(ResultVal)) 3344 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3345 << /* Unsigned */ 1; 3346 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3347 Tok.getLocation()); 3348 } 3349 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3350 } 3351 3352 case LOLR_Raw: { 3353 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3354 // literal is treated as a call of the form 3355 // operator "" X ("n") 3356 unsigned Length = Literal.getUDSuffixOffset(); 3357 QualType StrTy = Context.getConstantArrayType( 3358 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3359 ArrayType::Normal, 0); 3360 Expr *Lit = StringLiteral::Create( 3361 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3362 /*Pascal*/false, StrTy, &TokLoc, 1); 3363 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3364 } 3365 3366 case LOLR_Template: { 3367 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3368 // template), L is treated as a call fo the form 3369 // operator "" X <'c1', 'c2', ... 'ck'>() 3370 // where n is the source character sequence c1 c2 ... ck. 3371 TemplateArgumentListInfo ExplicitArgs; 3372 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3373 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3374 llvm::APSInt Value(CharBits, CharIsUnsigned); 3375 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3376 Value = TokSpelling[I]; 3377 TemplateArgument Arg(Context, Value, Context.CharTy); 3378 TemplateArgumentLocInfo ArgInfo; 3379 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3380 } 3381 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3382 &ExplicitArgs); 3383 } 3384 case LOLR_StringTemplate: 3385 llvm_unreachable("unexpected literal operator lookup result"); 3386 } 3387 } 3388 3389 Expr *Res; 3390 3391 if (Literal.isFloatingLiteral()) { 3392 QualType Ty; 3393 if (Literal.isHalf){ 3394 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3395 Ty = Context.HalfTy; 3396 else { 3397 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3398 return ExprError(); 3399 } 3400 } else if (Literal.isFloat) 3401 Ty = Context.FloatTy; 3402 else if (Literal.isLong) 3403 Ty = Context.LongDoubleTy; 3404 else if (Literal.isFloat128) 3405 Ty = Context.Float128Ty; 3406 else 3407 Ty = Context.DoubleTy; 3408 3409 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3410 3411 if (Ty == Context.DoubleTy) { 3412 if (getLangOpts().SinglePrecisionConstants) { 3413 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3414 if (BTy->getKind() != BuiltinType::Float) { 3415 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3416 } 3417 } else if (getLangOpts().OpenCL && 3418 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3419 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3420 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3421 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3422 } 3423 } 3424 } else if (!Literal.isIntegerLiteral()) { 3425 return ExprError(); 3426 } else { 3427 QualType Ty; 3428 3429 // 'long long' is a C99 or C++11 feature. 3430 if (!getLangOpts().C99 && Literal.isLongLong) { 3431 if (getLangOpts().CPlusPlus) 3432 Diag(Tok.getLocation(), 3433 getLangOpts().CPlusPlus11 ? 3434 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3435 else 3436 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3437 } 3438 3439 // Get the value in the widest-possible width. 3440 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3441 llvm::APInt ResultVal(MaxWidth, 0); 3442 3443 if (Literal.GetIntegerValue(ResultVal)) { 3444 // If this value didn't fit into uintmax_t, error and force to ull. 3445 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3446 << /* Unsigned */ 1; 3447 Ty = Context.UnsignedLongLongTy; 3448 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3449 "long long is not intmax_t?"); 3450 } else { 3451 // If this value fits into a ULL, try to figure out what else it fits into 3452 // according to the rules of C99 6.4.4.1p5. 3453 3454 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3455 // be an unsigned int. 3456 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3457 3458 // Check from smallest to largest, picking the smallest type we can. 3459 unsigned Width = 0; 3460 3461 // Microsoft specific integer suffixes are explicitly sized. 3462 if (Literal.MicrosoftInteger) { 3463 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3464 Width = 8; 3465 Ty = Context.CharTy; 3466 } else { 3467 Width = Literal.MicrosoftInteger; 3468 Ty = Context.getIntTypeForBitwidth(Width, 3469 /*Signed=*/!Literal.isUnsigned); 3470 } 3471 } 3472 3473 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3474 // Are int/unsigned possibilities? 3475 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3476 3477 // Does it fit in a unsigned int? 3478 if (ResultVal.isIntN(IntSize)) { 3479 // Does it fit in a signed int? 3480 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3481 Ty = Context.IntTy; 3482 else if (AllowUnsigned) 3483 Ty = Context.UnsignedIntTy; 3484 Width = IntSize; 3485 } 3486 } 3487 3488 // Are long/unsigned long possibilities? 3489 if (Ty.isNull() && !Literal.isLongLong) { 3490 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3491 3492 // Does it fit in a unsigned long? 3493 if (ResultVal.isIntN(LongSize)) { 3494 // Does it fit in a signed long? 3495 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3496 Ty = Context.LongTy; 3497 else if (AllowUnsigned) 3498 Ty = Context.UnsignedLongTy; 3499 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3500 // is compatible. 3501 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3502 const unsigned LongLongSize = 3503 Context.getTargetInfo().getLongLongWidth(); 3504 Diag(Tok.getLocation(), 3505 getLangOpts().CPlusPlus 3506 ? Literal.isLong 3507 ? diag::warn_old_implicitly_unsigned_long_cxx 3508 : /*C++98 UB*/ diag:: 3509 ext_old_implicitly_unsigned_long_cxx 3510 : diag::warn_old_implicitly_unsigned_long) 3511 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3512 : /*will be ill-formed*/ 1); 3513 Ty = Context.UnsignedLongTy; 3514 } 3515 Width = LongSize; 3516 } 3517 } 3518 3519 // Check long long if needed. 3520 if (Ty.isNull()) { 3521 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3522 3523 // Does it fit in a unsigned long long? 3524 if (ResultVal.isIntN(LongLongSize)) { 3525 // Does it fit in a signed long long? 3526 // To be compatible with MSVC, hex integer literals ending with the 3527 // LL or i64 suffix are always signed in Microsoft mode. 3528 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3529 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3530 Ty = Context.LongLongTy; 3531 else if (AllowUnsigned) 3532 Ty = Context.UnsignedLongLongTy; 3533 Width = LongLongSize; 3534 } 3535 } 3536 3537 // If we still couldn't decide a type, we probably have something that 3538 // does not fit in a signed long long, but has no U suffix. 3539 if (Ty.isNull()) { 3540 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3541 Ty = Context.UnsignedLongLongTy; 3542 Width = Context.getTargetInfo().getLongLongWidth(); 3543 } 3544 3545 if (ResultVal.getBitWidth() != Width) 3546 ResultVal = ResultVal.trunc(Width); 3547 } 3548 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3549 } 3550 3551 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3552 if (Literal.isImaginary) 3553 Res = new (Context) ImaginaryLiteral(Res, 3554 Context.getComplexType(Res->getType())); 3555 3556 return Res; 3557 } 3558 3559 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3560 assert(E && "ActOnParenExpr() missing expr"); 3561 return new (Context) ParenExpr(L, R, E); 3562 } 3563 3564 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3565 SourceLocation Loc, 3566 SourceRange ArgRange) { 3567 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3568 // scalar or vector data type argument..." 3569 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3570 // type (C99 6.2.5p18) or void. 3571 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3572 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3573 << T << ArgRange; 3574 return true; 3575 } 3576 3577 assert((T->isVoidType() || !T->isIncompleteType()) && 3578 "Scalar types should always be complete"); 3579 return false; 3580 } 3581 3582 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3583 SourceLocation Loc, 3584 SourceRange ArgRange, 3585 UnaryExprOrTypeTrait TraitKind) { 3586 // Invalid types must be hard errors for SFINAE in C++. 3587 if (S.LangOpts.CPlusPlus) 3588 return true; 3589 3590 // C99 6.5.3.4p1: 3591 if (T->isFunctionType() && 3592 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3593 // sizeof(function)/alignof(function) is allowed as an extension. 3594 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3595 << TraitKind << ArgRange; 3596 return false; 3597 } 3598 3599 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3600 // this is an error (OpenCL v1.1 s6.3.k) 3601 if (T->isVoidType()) { 3602 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3603 : diag::ext_sizeof_alignof_void_type; 3604 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3605 return false; 3606 } 3607 3608 return true; 3609 } 3610 3611 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3612 SourceLocation Loc, 3613 SourceRange ArgRange, 3614 UnaryExprOrTypeTrait TraitKind) { 3615 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3616 // runtime doesn't allow it. 3617 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3618 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3619 << T << (TraitKind == UETT_SizeOf) 3620 << ArgRange; 3621 return true; 3622 } 3623 3624 return false; 3625 } 3626 3627 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3628 /// pointer type is equal to T) and emit a warning if it is. 3629 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3630 Expr *E) { 3631 // Don't warn if the operation changed the type. 3632 if (T != E->getType()) 3633 return; 3634 3635 // Now look for array decays. 3636 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3637 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3638 return; 3639 3640 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3641 << ICE->getType() 3642 << ICE->getSubExpr()->getType(); 3643 } 3644 3645 /// \brief Check the constraints on expression operands to unary type expression 3646 /// and type traits. 3647 /// 3648 /// Completes any types necessary and validates the constraints on the operand 3649 /// expression. The logic mostly mirrors the type-based overload, but may modify 3650 /// the expression as it completes the type for that expression through template 3651 /// instantiation, etc. 3652 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3653 UnaryExprOrTypeTrait ExprKind) { 3654 QualType ExprTy = E->getType(); 3655 assert(!ExprTy->isReferenceType()); 3656 3657 if (ExprKind == UETT_VecStep) 3658 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3659 E->getSourceRange()); 3660 3661 // Whitelist some types as extensions 3662 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3663 E->getSourceRange(), ExprKind)) 3664 return false; 3665 3666 // 'alignof' applied to an expression only requires the base element type of 3667 // the expression to be complete. 'sizeof' requires the expression's type to 3668 // be complete (and will attempt to complete it if it's an array of unknown 3669 // bound). 3670 if (ExprKind == UETT_AlignOf) { 3671 if (RequireCompleteType(E->getExprLoc(), 3672 Context.getBaseElementType(E->getType()), 3673 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3674 E->getSourceRange())) 3675 return true; 3676 } else { 3677 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3678 ExprKind, E->getSourceRange())) 3679 return true; 3680 } 3681 3682 // Completing the expression's type may have changed it. 3683 ExprTy = E->getType(); 3684 assert(!ExprTy->isReferenceType()); 3685 3686 if (ExprTy->isFunctionType()) { 3687 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3688 << ExprKind << E->getSourceRange(); 3689 return true; 3690 } 3691 3692 // The operand for sizeof and alignof is in an unevaluated expression context, 3693 // so side effects could result in unintended consequences. 3694 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3695 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3696 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3697 3698 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3699 E->getSourceRange(), ExprKind)) 3700 return true; 3701 3702 if (ExprKind == UETT_SizeOf) { 3703 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3704 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3705 QualType OType = PVD->getOriginalType(); 3706 QualType Type = PVD->getType(); 3707 if (Type->isPointerType() && OType->isArrayType()) { 3708 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3709 << Type << OType; 3710 Diag(PVD->getLocation(), diag::note_declared_at); 3711 } 3712 } 3713 } 3714 3715 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3716 // decays into a pointer and returns an unintended result. This is most 3717 // likely a typo for "sizeof(array) op x". 3718 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3719 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3720 BO->getLHS()); 3721 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3722 BO->getRHS()); 3723 } 3724 } 3725 3726 return false; 3727 } 3728 3729 /// \brief Check the constraints on operands to unary expression and type 3730 /// traits. 3731 /// 3732 /// This will complete any types necessary, and validate the various constraints 3733 /// on those operands. 3734 /// 3735 /// The UsualUnaryConversions() function is *not* called by this routine. 3736 /// C99 6.3.2.1p[2-4] all state: 3737 /// Except when it is the operand of the sizeof operator ... 3738 /// 3739 /// C++ [expr.sizeof]p4 3740 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3741 /// standard conversions are not applied to the operand of sizeof. 3742 /// 3743 /// This policy is followed for all of the unary trait expressions. 3744 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3745 SourceLocation OpLoc, 3746 SourceRange ExprRange, 3747 UnaryExprOrTypeTrait ExprKind) { 3748 if (ExprType->isDependentType()) 3749 return false; 3750 3751 // C++ [expr.sizeof]p2: 3752 // When applied to a reference or a reference type, the result 3753 // is the size of the referenced type. 3754 // C++11 [expr.alignof]p3: 3755 // When alignof is applied to a reference type, the result 3756 // shall be the alignment of the referenced type. 3757 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3758 ExprType = Ref->getPointeeType(); 3759 3760 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3761 // When alignof or _Alignof is applied to an array type, the result 3762 // is the alignment of the element type. 3763 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3764 ExprType = Context.getBaseElementType(ExprType); 3765 3766 if (ExprKind == UETT_VecStep) 3767 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3768 3769 // Whitelist some types as extensions 3770 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3771 ExprKind)) 3772 return false; 3773 3774 if (RequireCompleteType(OpLoc, ExprType, 3775 diag::err_sizeof_alignof_incomplete_type, 3776 ExprKind, ExprRange)) 3777 return true; 3778 3779 if (ExprType->isFunctionType()) { 3780 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3781 << ExprKind << ExprRange; 3782 return true; 3783 } 3784 3785 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3786 ExprKind)) 3787 return true; 3788 3789 return false; 3790 } 3791 3792 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3793 E = E->IgnoreParens(); 3794 3795 // Cannot know anything else if the expression is dependent. 3796 if (E->isTypeDependent()) 3797 return false; 3798 3799 if (E->getObjectKind() == OK_BitField) { 3800 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3801 << 1 << E->getSourceRange(); 3802 return true; 3803 } 3804 3805 ValueDecl *D = nullptr; 3806 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3807 D = DRE->getDecl(); 3808 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3809 D = ME->getMemberDecl(); 3810 } 3811 3812 // If it's a field, require the containing struct to have a 3813 // complete definition so that we can compute the layout. 3814 // 3815 // This can happen in C++11 onwards, either by naming the member 3816 // in a way that is not transformed into a member access expression 3817 // (in an unevaluated operand, for instance), or by naming the member 3818 // in a trailing-return-type. 3819 // 3820 // For the record, since __alignof__ on expressions is a GCC 3821 // extension, GCC seems to permit this but always gives the 3822 // nonsensical answer 0. 3823 // 3824 // We don't really need the layout here --- we could instead just 3825 // directly check for all the appropriate alignment-lowing 3826 // attributes --- but that would require duplicating a lot of 3827 // logic that just isn't worth duplicating for such a marginal 3828 // use-case. 3829 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3830 // Fast path this check, since we at least know the record has a 3831 // definition if we can find a member of it. 3832 if (!FD->getParent()->isCompleteDefinition()) { 3833 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3834 << E->getSourceRange(); 3835 return true; 3836 } 3837 3838 // Otherwise, if it's a field, and the field doesn't have 3839 // reference type, then it must have a complete type (or be a 3840 // flexible array member, which we explicitly want to 3841 // white-list anyway), which makes the following checks trivial. 3842 if (!FD->getType()->isReferenceType()) 3843 return false; 3844 } 3845 3846 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3847 } 3848 3849 bool Sema::CheckVecStepExpr(Expr *E) { 3850 E = E->IgnoreParens(); 3851 3852 // Cannot know anything else if the expression is dependent. 3853 if (E->isTypeDependent()) 3854 return false; 3855 3856 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3857 } 3858 3859 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3860 CapturingScopeInfo *CSI) { 3861 assert(T->isVariablyModifiedType()); 3862 assert(CSI != nullptr); 3863 3864 // We're going to walk down into the type and look for VLA expressions. 3865 do { 3866 const Type *Ty = T.getTypePtr(); 3867 switch (Ty->getTypeClass()) { 3868 #define TYPE(Class, Base) 3869 #define ABSTRACT_TYPE(Class, Base) 3870 #define NON_CANONICAL_TYPE(Class, Base) 3871 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3872 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3873 #include "clang/AST/TypeNodes.def" 3874 T = QualType(); 3875 break; 3876 // These types are never variably-modified. 3877 case Type::Builtin: 3878 case Type::Complex: 3879 case Type::Vector: 3880 case Type::ExtVector: 3881 case Type::Record: 3882 case Type::Enum: 3883 case Type::Elaborated: 3884 case Type::TemplateSpecialization: 3885 case Type::ObjCObject: 3886 case Type::ObjCInterface: 3887 case Type::ObjCObjectPointer: 3888 case Type::ObjCTypeParam: 3889 case Type::Pipe: 3890 llvm_unreachable("type class is never variably-modified!"); 3891 case Type::Adjusted: 3892 T = cast<AdjustedType>(Ty)->getOriginalType(); 3893 break; 3894 case Type::Decayed: 3895 T = cast<DecayedType>(Ty)->getPointeeType(); 3896 break; 3897 case Type::Pointer: 3898 T = cast<PointerType>(Ty)->getPointeeType(); 3899 break; 3900 case Type::BlockPointer: 3901 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3902 break; 3903 case Type::LValueReference: 3904 case Type::RValueReference: 3905 T = cast<ReferenceType>(Ty)->getPointeeType(); 3906 break; 3907 case Type::MemberPointer: 3908 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3909 break; 3910 case Type::ConstantArray: 3911 case Type::IncompleteArray: 3912 // Losing element qualification here is fine. 3913 T = cast<ArrayType>(Ty)->getElementType(); 3914 break; 3915 case Type::VariableArray: { 3916 // Losing element qualification here is fine. 3917 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3918 3919 // Unknown size indication requires no size computation. 3920 // Otherwise, evaluate and record it. 3921 if (auto Size = VAT->getSizeExpr()) { 3922 if (!CSI->isVLATypeCaptured(VAT)) { 3923 RecordDecl *CapRecord = nullptr; 3924 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3925 CapRecord = LSI->Lambda; 3926 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3927 CapRecord = CRSI->TheRecordDecl; 3928 } 3929 if (CapRecord) { 3930 auto ExprLoc = Size->getExprLoc(); 3931 auto SizeType = Context.getSizeType(); 3932 // Build the non-static data member. 3933 auto Field = 3934 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3935 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3936 /*BW*/ nullptr, /*Mutable*/ false, 3937 /*InitStyle*/ ICIS_NoInit); 3938 Field->setImplicit(true); 3939 Field->setAccess(AS_private); 3940 Field->setCapturedVLAType(VAT); 3941 CapRecord->addDecl(Field); 3942 3943 CSI->addVLATypeCapture(ExprLoc, SizeType); 3944 } 3945 } 3946 } 3947 T = VAT->getElementType(); 3948 break; 3949 } 3950 case Type::FunctionProto: 3951 case Type::FunctionNoProto: 3952 T = cast<FunctionType>(Ty)->getReturnType(); 3953 break; 3954 case Type::Paren: 3955 case Type::TypeOf: 3956 case Type::UnaryTransform: 3957 case Type::Attributed: 3958 case Type::SubstTemplateTypeParm: 3959 case Type::PackExpansion: 3960 // Keep walking after single level desugaring. 3961 T = T.getSingleStepDesugaredType(Context); 3962 break; 3963 case Type::Typedef: 3964 T = cast<TypedefType>(Ty)->desugar(); 3965 break; 3966 case Type::Decltype: 3967 T = cast<DecltypeType>(Ty)->desugar(); 3968 break; 3969 case Type::Auto: 3970 case Type::DeducedTemplateSpecialization: 3971 T = cast<DeducedType>(Ty)->getDeducedType(); 3972 break; 3973 case Type::TypeOfExpr: 3974 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3975 break; 3976 case Type::Atomic: 3977 T = cast<AtomicType>(Ty)->getValueType(); 3978 break; 3979 } 3980 } while (!T.isNull() && T->isVariablyModifiedType()); 3981 } 3982 3983 /// \brief Build a sizeof or alignof expression given a type operand. 3984 ExprResult 3985 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3986 SourceLocation OpLoc, 3987 UnaryExprOrTypeTrait ExprKind, 3988 SourceRange R) { 3989 if (!TInfo) 3990 return ExprError(); 3991 3992 QualType T = TInfo->getType(); 3993 3994 if (!T->isDependentType() && 3995 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3996 return ExprError(); 3997 3998 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3999 if (auto *TT = T->getAs<TypedefType>()) { 4000 for (auto I = FunctionScopes.rbegin(), 4001 E = std::prev(FunctionScopes.rend()); 4002 I != E; ++I) { 4003 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4004 if (CSI == nullptr) 4005 break; 4006 DeclContext *DC = nullptr; 4007 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4008 DC = LSI->CallOperator; 4009 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4010 DC = CRSI->TheCapturedDecl; 4011 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4012 DC = BSI->TheDecl; 4013 if (DC) { 4014 if (DC->containsDecl(TT->getDecl())) 4015 break; 4016 captureVariablyModifiedType(Context, T, CSI); 4017 } 4018 } 4019 } 4020 } 4021 4022 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4023 return new (Context) UnaryExprOrTypeTraitExpr( 4024 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4025 } 4026 4027 /// \brief Build a sizeof or alignof expression given an expression 4028 /// operand. 4029 ExprResult 4030 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4031 UnaryExprOrTypeTrait ExprKind) { 4032 ExprResult PE = CheckPlaceholderExpr(E); 4033 if (PE.isInvalid()) 4034 return ExprError(); 4035 4036 E = PE.get(); 4037 4038 // Verify that the operand is valid. 4039 bool isInvalid = false; 4040 if (E->isTypeDependent()) { 4041 // Delay type-checking for type-dependent expressions. 4042 } else if (ExprKind == UETT_AlignOf) { 4043 isInvalid = CheckAlignOfExpr(*this, E); 4044 } else if (ExprKind == UETT_VecStep) { 4045 isInvalid = CheckVecStepExpr(E); 4046 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4047 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4048 isInvalid = true; 4049 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4050 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4051 isInvalid = true; 4052 } else { 4053 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4054 } 4055 4056 if (isInvalid) 4057 return ExprError(); 4058 4059 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4060 PE = TransformToPotentiallyEvaluated(E); 4061 if (PE.isInvalid()) return ExprError(); 4062 E = PE.get(); 4063 } 4064 4065 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4066 return new (Context) UnaryExprOrTypeTraitExpr( 4067 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4068 } 4069 4070 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4071 /// expr and the same for @c alignof and @c __alignof 4072 /// Note that the ArgRange is invalid if isType is false. 4073 ExprResult 4074 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4075 UnaryExprOrTypeTrait ExprKind, bool IsType, 4076 void *TyOrEx, SourceRange ArgRange) { 4077 // If error parsing type, ignore. 4078 if (!TyOrEx) return ExprError(); 4079 4080 if (IsType) { 4081 TypeSourceInfo *TInfo; 4082 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4083 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4084 } 4085 4086 Expr *ArgEx = (Expr *)TyOrEx; 4087 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4088 return Result; 4089 } 4090 4091 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4092 bool IsReal) { 4093 if (V.get()->isTypeDependent()) 4094 return S.Context.DependentTy; 4095 4096 // _Real and _Imag are only l-values for normal l-values. 4097 if (V.get()->getObjectKind() != OK_Ordinary) { 4098 V = S.DefaultLvalueConversion(V.get()); 4099 if (V.isInvalid()) 4100 return QualType(); 4101 } 4102 4103 // These operators return the element type of a complex type. 4104 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4105 return CT->getElementType(); 4106 4107 // Otherwise they pass through real integer and floating point types here. 4108 if (V.get()->getType()->isArithmeticType()) 4109 return V.get()->getType(); 4110 4111 // Test for placeholders. 4112 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4113 if (PR.isInvalid()) return QualType(); 4114 if (PR.get() != V.get()) { 4115 V = PR; 4116 return CheckRealImagOperand(S, V, Loc, IsReal); 4117 } 4118 4119 // Reject anything else. 4120 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4121 << (IsReal ? "__real" : "__imag"); 4122 return QualType(); 4123 } 4124 4125 4126 4127 ExprResult 4128 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4129 tok::TokenKind Kind, Expr *Input) { 4130 UnaryOperatorKind Opc; 4131 switch (Kind) { 4132 default: llvm_unreachable("Unknown unary op!"); 4133 case tok::plusplus: Opc = UO_PostInc; break; 4134 case tok::minusminus: Opc = UO_PostDec; break; 4135 } 4136 4137 // Since this might is a postfix expression, get rid of ParenListExprs. 4138 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4139 if (Result.isInvalid()) return ExprError(); 4140 Input = Result.get(); 4141 4142 return BuildUnaryOp(S, OpLoc, Opc, Input); 4143 } 4144 4145 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4146 /// 4147 /// \return true on error 4148 static bool checkArithmeticOnObjCPointer(Sema &S, 4149 SourceLocation opLoc, 4150 Expr *op) { 4151 assert(op->getType()->isObjCObjectPointerType()); 4152 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4153 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4154 return false; 4155 4156 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4157 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4158 << op->getSourceRange(); 4159 return true; 4160 } 4161 4162 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4163 auto *BaseNoParens = Base->IgnoreParens(); 4164 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4165 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4166 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4167 } 4168 4169 ExprResult 4170 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4171 Expr *idx, SourceLocation rbLoc) { 4172 if (base && !base->getType().isNull() && 4173 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4174 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4175 /*Length=*/nullptr, rbLoc); 4176 4177 // Since this might be a postfix expression, get rid of ParenListExprs. 4178 if (isa<ParenListExpr>(base)) { 4179 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4180 if (result.isInvalid()) return ExprError(); 4181 base = result.get(); 4182 } 4183 4184 // Handle any non-overload placeholder types in the base and index 4185 // expressions. We can't handle overloads here because the other 4186 // operand might be an overloadable type, in which case the overload 4187 // resolution for the operator overload should get the first crack 4188 // at the overload. 4189 bool IsMSPropertySubscript = false; 4190 if (base->getType()->isNonOverloadPlaceholderType()) { 4191 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4192 if (!IsMSPropertySubscript) { 4193 ExprResult result = CheckPlaceholderExpr(base); 4194 if (result.isInvalid()) 4195 return ExprError(); 4196 base = result.get(); 4197 } 4198 } 4199 if (idx->getType()->isNonOverloadPlaceholderType()) { 4200 ExprResult result = CheckPlaceholderExpr(idx); 4201 if (result.isInvalid()) return ExprError(); 4202 idx = result.get(); 4203 } 4204 4205 // Build an unanalyzed expression if either operand is type-dependent. 4206 if (getLangOpts().CPlusPlus && 4207 (base->isTypeDependent() || idx->isTypeDependent())) { 4208 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4209 VK_LValue, OK_Ordinary, rbLoc); 4210 } 4211 4212 // MSDN, property (C++) 4213 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4214 // This attribute can also be used in the declaration of an empty array in a 4215 // class or structure definition. For example: 4216 // __declspec(property(get=GetX, put=PutX)) int x[]; 4217 // The above statement indicates that x[] can be used with one or more array 4218 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4219 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4220 if (IsMSPropertySubscript) { 4221 // Build MS property subscript expression if base is MS property reference 4222 // or MS property subscript. 4223 return new (Context) MSPropertySubscriptExpr( 4224 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4225 } 4226 4227 // Use C++ overloaded-operator rules if either operand has record 4228 // type. The spec says to do this if either type is *overloadable*, 4229 // but enum types can't declare subscript operators or conversion 4230 // operators, so there's nothing interesting for overload resolution 4231 // to do if there aren't any record types involved. 4232 // 4233 // ObjC pointers have their own subscripting logic that is not tied 4234 // to overload resolution and so should not take this path. 4235 if (getLangOpts().CPlusPlus && 4236 (base->getType()->isRecordType() || 4237 (!base->getType()->isObjCObjectPointerType() && 4238 idx->getType()->isRecordType()))) { 4239 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4240 } 4241 4242 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4243 } 4244 4245 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4246 Expr *LowerBound, 4247 SourceLocation ColonLoc, Expr *Length, 4248 SourceLocation RBLoc) { 4249 if (Base->getType()->isPlaceholderType() && 4250 !Base->getType()->isSpecificPlaceholderType( 4251 BuiltinType::OMPArraySection)) { 4252 ExprResult Result = CheckPlaceholderExpr(Base); 4253 if (Result.isInvalid()) 4254 return ExprError(); 4255 Base = Result.get(); 4256 } 4257 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4258 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4259 if (Result.isInvalid()) 4260 return ExprError(); 4261 Result = DefaultLvalueConversion(Result.get()); 4262 if (Result.isInvalid()) 4263 return ExprError(); 4264 LowerBound = Result.get(); 4265 } 4266 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4267 ExprResult Result = CheckPlaceholderExpr(Length); 4268 if (Result.isInvalid()) 4269 return ExprError(); 4270 Result = DefaultLvalueConversion(Result.get()); 4271 if (Result.isInvalid()) 4272 return ExprError(); 4273 Length = Result.get(); 4274 } 4275 4276 // Build an unanalyzed expression if either operand is type-dependent. 4277 if (Base->isTypeDependent() || 4278 (LowerBound && 4279 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4280 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4281 return new (Context) 4282 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4283 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4284 } 4285 4286 // Perform default conversions. 4287 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4288 QualType ResultTy; 4289 if (OriginalTy->isAnyPointerType()) { 4290 ResultTy = OriginalTy->getPointeeType(); 4291 } else if (OriginalTy->isArrayType()) { 4292 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4293 } else { 4294 return ExprError( 4295 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4296 << Base->getSourceRange()); 4297 } 4298 // C99 6.5.2.1p1 4299 if (LowerBound) { 4300 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4301 LowerBound); 4302 if (Res.isInvalid()) 4303 return ExprError(Diag(LowerBound->getExprLoc(), 4304 diag::err_omp_typecheck_section_not_integer) 4305 << 0 << LowerBound->getSourceRange()); 4306 LowerBound = Res.get(); 4307 4308 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4309 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4310 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4311 << 0 << LowerBound->getSourceRange(); 4312 } 4313 if (Length) { 4314 auto Res = 4315 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4316 if (Res.isInvalid()) 4317 return ExprError(Diag(Length->getExprLoc(), 4318 diag::err_omp_typecheck_section_not_integer) 4319 << 1 << Length->getSourceRange()); 4320 Length = Res.get(); 4321 4322 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4323 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4324 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4325 << 1 << Length->getSourceRange(); 4326 } 4327 4328 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4329 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4330 // type. Note that functions are not objects, and that (in C99 parlance) 4331 // incomplete types are not object types. 4332 if (ResultTy->isFunctionType()) { 4333 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4334 << ResultTy << Base->getSourceRange(); 4335 return ExprError(); 4336 } 4337 4338 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4339 diag::err_omp_section_incomplete_type, Base)) 4340 return ExprError(); 4341 4342 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4343 llvm::APSInt LowerBoundValue; 4344 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4345 // OpenMP 4.5, [2.4 Array Sections] 4346 // The array section must be a subset of the original array. 4347 if (LowerBoundValue.isNegative()) { 4348 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4349 << LowerBound->getSourceRange(); 4350 return ExprError(); 4351 } 4352 } 4353 } 4354 4355 if (Length) { 4356 llvm::APSInt LengthValue; 4357 if (Length->EvaluateAsInt(LengthValue, Context)) { 4358 // OpenMP 4.5, [2.4 Array Sections] 4359 // The length must evaluate to non-negative integers. 4360 if (LengthValue.isNegative()) { 4361 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4362 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4363 << Length->getSourceRange(); 4364 return ExprError(); 4365 } 4366 } 4367 } else if (ColonLoc.isValid() && 4368 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4369 !OriginalTy->isVariableArrayType()))) { 4370 // OpenMP 4.5, [2.4 Array Sections] 4371 // When the size of the array dimension is not known, the length must be 4372 // specified explicitly. 4373 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4374 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4375 return ExprError(); 4376 } 4377 4378 if (!Base->getType()->isSpecificPlaceholderType( 4379 BuiltinType::OMPArraySection)) { 4380 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4381 if (Result.isInvalid()) 4382 return ExprError(); 4383 Base = Result.get(); 4384 } 4385 return new (Context) 4386 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4387 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4388 } 4389 4390 ExprResult 4391 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4392 Expr *Idx, SourceLocation RLoc) { 4393 Expr *LHSExp = Base; 4394 Expr *RHSExp = Idx; 4395 4396 ExprValueKind VK = VK_LValue; 4397 ExprObjectKind OK = OK_Ordinary; 4398 4399 // Per C++ core issue 1213, the result is an xvalue if either operand is 4400 // a non-lvalue array, and an lvalue otherwise. 4401 if (getLangOpts().CPlusPlus11 && 4402 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4403 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4404 VK = VK_XValue; 4405 4406 // Perform default conversions. 4407 if (!LHSExp->getType()->getAs<VectorType>()) { 4408 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4409 if (Result.isInvalid()) 4410 return ExprError(); 4411 LHSExp = Result.get(); 4412 } 4413 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4414 if (Result.isInvalid()) 4415 return ExprError(); 4416 RHSExp = Result.get(); 4417 4418 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4419 4420 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4421 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4422 // in the subscript position. As a result, we need to derive the array base 4423 // and index from the expression types. 4424 Expr *BaseExpr, *IndexExpr; 4425 QualType ResultType; 4426 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4427 BaseExpr = LHSExp; 4428 IndexExpr = RHSExp; 4429 ResultType = Context.DependentTy; 4430 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4431 BaseExpr = LHSExp; 4432 IndexExpr = RHSExp; 4433 ResultType = PTy->getPointeeType(); 4434 } else if (const ObjCObjectPointerType *PTy = 4435 LHSTy->getAs<ObjCObjectPointerType>()) { 4436 BaseExpr = LHSExp; 4437 IndexExpr = RHSExp; 4438 4439 // Use custom logic if this should be the pseudo-object subscript 4440 // expression. 4441 if (!LangOpts.isSubscriptPointerArithmetic()) 4442 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4443 nullptr); 4444 4445 ResultType = PTy->getPointeeType(); 4446 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4447 // Handle the uncommon case of "123[Ptr]". 4448 BaseExpr = RHSExp; 4449 IndexExpr = LHSExp; 4450 ResultType = PTy->getPointeeType(); 4451 } else if (const ObjCObjectPointerType *PTy = 4452 RHSTy->getAs<ObjCObjectPointerType>()) { 4453 // Handle the uncommon case of "123[Ptr]". 4454 BaseExpr = RHSExp; 4455 IndexExpr = LHSExp; 4456 ResultType = PTy->getPointeeType(); 4457 if (!LangOpts.isSubscriptPointerArithmetic()) { 4458 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4459 << ResultType << BaseExpr->getSourceRange(); 4460 return ExprError(); 4461 } 4462 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4463 BaseExpr = LHSExp; // vectors: V[123] 4464 IndexExpr = RHSExp; 4465 VK = LHSExp->getValueKind(); 4466 if (VK != VK_RValue) 4467 OK = OK_VectorComponent; 4468 4469 // FIXME: need to deal with const... 4470 ResultType = VTy->getElementType(); 4471 } else if (LHSTy->isArrayType()) { 4472 // If we see an array that wasn't promoted by 4473 // DefaultFunctionArrayLvalueConversion, it must be an array that 4474 // wasn't promoted because of the C90 rule that doesn't 4475 // allow promoting non-lvalue arrays. Warn, then 4476 // force the promotion here. 4477 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4478 LHSExp->getSourceRange(); 4479 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4480 CK_ArrayToPointerDecay).get(); 4481 LHSTy = LHSExp->getType(); 4482 4483 BaseExpr = LHSExp; 4484 IndexExpr = RHSExp; 4485 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4486 } else if (RHSTy->isArrayType()) { 4487 // Same as previous, except for 123[f().a] case 4488 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4489 RHSExp->getSourceRange(); 4490 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4491 CK_ArrayToPointerDecay).get(); 4492 RHSTy = RHSExp->getType(); 4493 4494 BaseExpr = RHSExp; 4495 IndexExpr = LHSExp; 4496 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4497 } else { 4498 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4499 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4500 } 4501 // C99 6.5.2.1p1 4502 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4503 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4504 << IndexExpr->getSourceRange()); 4505 4506 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4507 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4508 && !IndexExpr->isTypeDependent()) 4509 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4510 4511 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4512 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4513 // type. Note that Functions are not objects, and that (in C99 parlance) 4514 // incomplete types are not object types. 4515 if (ResultType->isFunctionType()) { 4516 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4517 << ResultType << BaseExpr->getSourceRange(); 4518 return ExprError(); 4519 } 4520 4521 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4522 // GNU extension: subscripting on pointer to void 4523 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4524 << BaseExpr->getSourceRange(); 4525 4526 // C forbids expressions of unqualified void type from being l-values. 4527 // See IsCForbiddenLValueType. 4528 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4529 } else if (!ResultType->isDependentType() && 4530 RequireCompleteType(LLoc, ResultType, 4531 diag::err_subscript_incomplete_type, BaseExpr)) 4532 return ExprError(); 4533 4534 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4535 !ResultType.isCForbiddenLValueType()); 4536 4537 return new (Context) 4538 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4539 } 4540 4541 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4542 ParmVarDecl *Param) { 4543 if (Param->hasUnparsedDefaultArg()) { 4544 Diag(CallLoc, 4545 diag::err_use_of_default_argument_to_function_declared_later) << 4546 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4547 Diag(UnparsedDefaultArgLocs[Param], 4548 diag::note_default_argument_declared_here); 4549 return true; 4550 } 4551 4552 if (Param->hasUninstantiatedDefaultArg()) { 4553 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4554 4555 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4556 Param); 4557 4558 // Instantiate the expression. 4559 MultiLevelTemplateArgumentList MutiLevelArgList 4560 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4561 4562 InstantiatingTemplate Inst(*this, CallLoc, Param, 4563 MutiLevelArgList.getInnermost()); 4564 if (Inst.isInvalid()) 4565 return true; 4566 if (Inst.isAlreadyInstantiating()) { 4567 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4568 Param->setInvalidDecl(); 4569 return true; 4570 } 4571 4572 ExprResult Result; 4573 { 4574 // C++ [dcl.fct.default]p5: 4575 // The names in the [default argument] expression are bound, and 4576 // the semantic constraints are checked, at the point where the 4577 // default argument expression appears. 4578 ContextRAII SavedContext(*this, FD); 4579 LocalInstantiationScope Local(*this); 4580 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4581 /*DirectInit*/false); 4582 } 4583 if (Result.isInvalid()) 4584 return true; 4585 4586 // Check the expression as an initializer for the parameter. 4587 InitializedEntity Entity 4588 = InitializedEntity::InitializeParameter(Context, Param); 4589 InitializationKind Kind 4590 = InitializationKind::CreateCopy(Param->getLocation(), 4591 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4592 Expr *ResultE = Result.getAs<Expr>(); 4593 4594 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4595 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4596 if (Result.isInvalid()) 4597 return true; 4598 4599 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4600 Param->getOuterLocStart()); 4601 if (Result.isInvalid()) 4602 return true; 4603 4604 // Remember the instantiated default argument. 4605 Param->setDefaultArg(Result.getAs<Expr>()); 4606 if (ASTMutationListener *L = getASTMutationListener()) { 4607 L->DefaultArgumentInstantiated(Param); 4608 } 4609 } 4610 4611 // If the default argument expression is not set yet, we are building it now. 4612 if (!Param->hasInit()) { 4613 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4614 Param->setInvalidDecl(); 4615 return true; 4616 } 4617 4618 // If the default expression creates temporaries, we need to 4619 // push them to the current stack of expression temporaries so they'll 4620 // be properly destroyed. 4621 // FIXME: We should really be rebuilding the default argument with new 4622 // bound temporaries; see the comment in PR5810. 4623 // We don't need to do that with block decls, though, because 4624 // blocks in default argument expression can never capture anything. 4625 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4626 // Set the "needs cleanups" bit regardless of whether there are 4627 // any explicit objects. 4628 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4629 4630 // Append all the objects to the cleanup list. Right now, this 4631 // should always be a no-op, because blocks in default argument 4632 // expressions should never be able to capture anything. 4633 assert(!Init->getNumObjects() && 4634 "default argument expression has capturing blocks?"); 4635 } 4636 4637 // We already type-checked the argument, so we know it works. 4638 // Just mark all of the declarations in this potentially-evaluated expression 4639 // as being "referenced". 4640 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4641 /*SkipLocalVariables=*/true); 4642 return false; 4643 } 4644 4645 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4646 FunctionDecl *FD, ParmVarDecl *Param) { 4647 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4648 return ExprError(); 4649 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4650 } 4651 4652 Sema::VariadicCallType 4653 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4654 Expr *Fn) { 4655 if (Proto && Proto->isVariadic()) { 4656 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4657 return VariadicConstructor; 4658 else if (Fn && Fn->getType()->isBlockPointerType()) 4659 return VariadicBlock; 4660 else if (FDecl) { 4661 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4662 if (Method->isInstance()) 4663 return VariadicMethod; 4664 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4665 return VariadicMethod; 4666 return VariadicFunction; 4667 } 4668 return VariadicDoesNotApply; 4669 } 4670 4671 namespace { 4672 class FunctionCallCCC : public FunctionCallFilterCCC { 4673 public: 4674 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4675 unsigned NumArgs, MemberExpr *ME) 4676 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4677 FunctionName(FuncName) {} 4678 4679 bool ValidateCandidate(const TypoCorrection &candidate) override { 4680 if (!candidate.getCorrectionSpecifier() || 4681 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4682 return false; 4683 } 4684 4685 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4686 } 4687 4688 private: 4689 const IdentifierInfo *const FunctionName; 4690 }; 4691 } 4692 4693 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4694 FunctionDecl *FDecl, 4695 ArrayRef<Expr *> Args) { 4696 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4697 DeclarationName FuncName = FDecl->getDeclName(); 4698 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4699 4700 if (TypoCorrection Corrected = S.CorrectTypo( 4701 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4702 S.getScopeForContext(S.CurContext), nullptr, 4703 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4704 Args.size(), ME), 4705 Sema::CTK_ErrorRecovery)) { 4706 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4707 if (Corrected.isOverloaded()) { 4708 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4709 OverloadCandidateSet::iterator Best; 4710 for (NamedDecl *CD : Corrected) { 4711 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4712 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4713 OCS); 4714 } 4715 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4716 case OR_Success: 4717 ND = Best->FoundDecl; 4718 Corrected.setCorrectionDecl(ND); 4719 break; 4720 default: 4721 break; 4722 } 4723 } 4724 ND = ND->getUnderlyingDecl(); 4725 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4726 return Corrected; 4727 } 4728 } 4729 return TypoCorrection(); 4730 } 4731 4732 /// ConvertArgumentsForCall - Converts the arguments specified in 4733 /// Args/NumArgs to the parameter types of the function FDecl with 4734 /// function prototype Proto. Call is the call expression itself, and 4735 /// Fn is the function expression. For a C++ member function, this 4736 /// routine does not attempt to convert the object argument. Returns 4737 /// true if the call is ill-formed. 4738 bool 4739 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4740 FunctionDecl *FDecl, 4741 const FunctionProtoType *Proto, 4742 ArrayRef<Expr *> Args, 4743 SourceLocation RParenLoc, 4744 bool IsExecConfig) { 4745 // Bail out early if calling a builtin with custom typechecking. 4746 if (FDecl) 4747 if (unsigned ID = FDecl->getBuiltinID()) 4748 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4749 return false; 4750 4751 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4752 // assignment, to the types of the corresponding parameter, ... 4753 unsigned NumParams = Proto->getNumParams(); 4754 bool Invalid = false; 4755 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4756 unsigned FnKind = Fn->getType()->isBlockPointerType() 4757 ? 1 /* block */ 4758 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4759 : 0 /* function */); 4760 4761 // If too few arguments are available (and we don't have default 4762 // arguments for the remaining parameters), don't make the call. 4763 if (Args.size() < NumParams) { 4764 if (Args.size() < MinArgs) { 4765 TypoCorrection TC; 4766 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4767 unsigned diag_id = 4768 MinArgs == NumParams && !Proto->isVariadic() 4769 ? diag::err_typecheck_call_too_few_args_suggest 4770 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4771 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4772 << static_cast<unsigned>(Args.size()) 4773 << TC.getCorrectionRange()); 4774 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4775 Diag(RParenLoc, 4776 MinArgs == NumParams && !Proto->isVariadic() 4777 ? diag::err_typecheck_call_too_few_args_one 4778 : diag::err_typecheck_call_too_few_args_at_least_one) 4779 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4780 else 4781 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4782 ? diag::err_typecheck_call_too_few_args 4783 : diag::err_typecheck_call_too_few_args_at_least) 4784 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4785 << Fn->getSourceRange(); 4786 4787 // Emit the location of the prototype. 4788 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4789 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4790 << FDecl; 4791 4792 return true; 4793 } 4794 Call->setNumArgs(Context, NumParams); 4795 } 4796 4797 // If too many are passed and not variadic, error on the extras and drop 4798 // them. 4799 if (Args.size() > NumParams) { 4800 if (!Proto->isVariadic()) { 4801 TypoCorrection TC; 4802 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4803 unsigned diag_id = 4804 MinArgs == NumParams && !Proto->isVariadic() 4805 ? diag::err_typecheck_call_too_many_args_suggest 4806 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4807 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4808 << static_cast<unsigned>(Args.size()) 4809 << TC.getCorrectionRange()); 4810 } else if (NumParams == 1 && FDecl && 4811 FDecl->getParamDecl(0)->getDeclName()) 4812 Diag(Args[NumParams]->getLocStart(), 4813 MinArgs == NumParams 4814 ? diag::err_typecheck_call_too_many_args_one 4815 : diag::err_typecheck_call_too_many_args_at_most_one) 4816 << FnKind << FDecl->getParamDecl(0) 4817 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4818 << SourceRange(Args[NumParams]->getLocStart(), 4819 Args.back()->getLocEnd()); 4820 else 4821 Diag(Args[NumParams]->getLocStart(), 4822 MinArgs == NumParams 4823 ? diag::err_typecheck_call_too_many_args 4824 : diag::err_typecheck_call_too_many_args_at_most) 4825 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4826 << Fn->getSourceRange() 4827 << SourceRange(Args[NumParams]->getLocStart(), 4828 Args.back()->getLocEnd()); 4829 4830 // Emit the location of the prototype. 4831 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4832 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4833 << FDecl; 4834 4835 // This deletes the extra arguments. 4836 Call->setNumArgs(Context, NumParams); 4837 return true; 4838 } 4839 } 4840 SmallVector<Expr *, 8> AllArgs; 4841 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4842 4843 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4844 Proto, 0, Args, AllArgs, CallType); 4845 if (Invalid) 4846 return true; 4847 unsigned TotalNumArgs = AllArgs.size(); 4848 for (unsigned i = 0; i < TotalNumArgs; ++i) 4849 Call->setArg(i, AllArgs[i]); 4850 4851 return false; 4852 } 4853 4854 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4855 const FunctionProtoType *Proto, 4856 unsigned FirstParam, ArrayRef<Expr *> Args, 4857 SmallVectorImpl<Expr *> &AllArgs, 4858 VariadicCallType CallType, bool AllowExplicit, 4859 bool IsListInitialization) { 4860 unsigned NumParams = Proto->getNumParams(); 4861 bool Invalid = false; 4862 size_t ArgIx = 0; 4863 // Continue to check argument types (even if we have too few/many args). 4864 for (unsigned i = FirstParam; i < NumParams; i++) { 4865 QualType ProtoArgType = Proto->getParamType(i); 4866 4867 Expr *Arg; 4868 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4869 if (ArgIx < Args.size()) { 4870 Arg = Args[ArgIx++]; 4871 4872 if (RequireCompleteType(Arg->getLocStart(), 4873 ProtoArgType, 4874 diag::err_call_incomplete_argument, Arg)) 4875 return true; 4876 4877 // Strip the unbridged-cast placeholder expression off, if applicable. 4878 bool CFAudited = false; 4879 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4880 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4881 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4882 Arg = stripARCUnbridgedCast(Arg); 4883 else if (getLangOpts().ObjCAutoRefCount && 4884 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4885 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4886 CFAudited = true; 4887 4888 InitializedEntity Entity = 4889 Param ? InitializedEntity::InitializeParameter(Context, Param, 4890 ProtoArgType) 4891 : InitializedEntity::InitializeParameter( 4892 Context, ProtoArgType, Proto->isParamConsumed(i)); 4893 4894 // Remember that parameter belongs to a CF audited API. 4895 if (CFAudited) 4896 Entity.setParameterCFAudited(); 4897 4898 ExprResult ArgE = PerformCopyInitialization( 4899 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4900 if (ArgE.isInvalid()) 4901 return true; 4902 4903 Arg = ArgE.getAs<Expr>(); 4904 } else { 4905 assert(Param && "can't use default arguments without a known callee"); 4906 4907 ExprResult ArgExpr = 4908 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4909 if (ArgExpr.isInvalid()) 4910 return true; 4911 4912 Arg = ArgExpr.getAs<Expr>(); 4913 } 4914 4915 // Check for array bounds violations for each argument to the call. This 4916 // check only triggers warnings when the argument isn't a more complex Expr 4917 // with its own checking, such as a BinaryOperator. 4918 CheckArrayAccess(Arg); 4919 4920 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4921 CheckStaticArrayArgument(CallLoc, Param, Arg); 4922 4923 AllArgs.push_back(Arg); 4924 } 4925 4926 // If this is a variadic call, handle args passed through "...". 4927 if (CallType != VariadicDoesNotApply) { 4928 // Assume that extern "C" functions with variadic arguments that 4929 // return __unknown_anytype aren't *really* variadic. 4930 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4931 FDecl->isExternC()) { 4932 for (Expr *A : Args.slice(ArgIx)) { 4933 QualType paramType; // ignored 4934 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4935 Invalid |= arg.isInvalid(); 4936 AllArgs.push_back(arg.get()); 4937 } 4938 4939 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4940 } else { 4941 for (Expr *A : Args.slice(ArgIx)) { 4942 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4943 Invalid |= Arg.isInvalid(); 4944 AllArgs.push_back(Arg.get()); 4945 } 4946 } 4947 4948 // Check for array bounds violations. 4949 for (Expr *A : Args.slice(ArgIx)) 4950 CheckArrayAccess(A); 4951 } 4952 return Invalid; 4953 } 4954 4955 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4956 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4957 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4958 TL = DTL.getOriginalLoc(); 4959 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4960 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4961 << ATL.getLocalSourceRange(); 4962 } 4963 4964 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4965 /// array parameter, check that it is non-null, and that if it is formed by 4966 /// array-to-pointer decay, the underlying array is sufficiently large. 4967 /// 4968 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4969 /// array type derivation, then for each call to the function, the value of the 4970 /// corresponding actual argument shall provide access to the first element of 4971 /// an array with at least as many elements as specified by the size expression. 4972 void 4973 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4974 ParmVarDecl *Param, 4975 const Expr *ArgExpr) { 4976 // Static array parameters are not supported in C++. 4977 if (!Param || getLangOpts().CPlusPlus) 4978 return; 4979 4980 QualType OrigTy = Param->getOriginalType(); 4981 4982 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4983 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4984 return; 4985 4986 if (ArgExpr->isNullPointerConstant(Context, 4987 Expr::NPC_NeverValueDependent)) { 4988 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4989 DiagnoseCalleeStaticArrayParam(*this, Param); 4990 return; 4991 } 4992 4993 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4994 if (!CAT) 4995 return; 4996 4997 const ConstantArrayType *ArgCAT = 4998 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4999 if (!ArgCAT) 5000 return; 5001 5002 if (ArgCAT->getSize().ult(CAT->getSize())) { 5003 Diag(CallLoc, diag::warn_static_array_too_small) 5004 << ArgExpr->getSourceRange() 5005 << (unsigned) ArgCAT->getSize().getZExtValue() 5006 << (unsigned) CAT->getSize().getZExtValue(); 5007 DiagnoseCalleeStaticArrayParam(*this, Param); 5008 } 5009 } 5010 5011 /// Given a function expression of unknown-any type, try to rebuild it 5012 /// to have a function type. 5013 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5014 5015 /// Is the given type a placeholder that we need to lower out 5016 /// immediately during argument processing? 5017 static bool isPlaceholderToRemoveAsArg(QualType type) { 5018 // Placeholders are never sugared. 5019 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5020 if (!placeholder) return false; 5021 5022 switch (placeholder->getKind()) { 5023 // Ignore all the non-placeholder types. 5024 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5025 case BuiltinType::Id: 5026 #include "clang/Basic/OpenCLImageTypes.def" 5027 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5028 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5029 #include "clang/AST/BuiltinTypes.def" 5030 return false; 5031 5032 // We cannot lower out overload sets; they might validly be resolved 5033 // by the call machinery. 5034 case BuiltinType::Overload: 5035 return false; 5036 5037 // Unbridged casts in ARC can be handled in some call positions and 5038 // should be left in place. 5039 case BuiltinType::ARCUnbridgedCast: 5040 return false; 5041 5042 // Pseudo-objects should be converted as soon as possible. 5043 case BuiltinType::PseudoObject: 5044 return true; 5045 5046 // The debugger mode could theoretically but currently does not try 5047 // to resolve unknown-typed arguments based on known parameter types. 5048 case BuiltinType::UnknownAny: 5049 return true; 5050 5051 // These are always invalid as call arguments and should be reported. 5052 case BuiltinType::BoundMember: 5053 case BuiltinType::BuiltinFn: 5054 case BuiltinType::OMPArraySection: 5055 return true; 5056 5057 } 5058 llvm_unreachable("bad builtin type kind"); 5059 } 5060 5061 /// Check an argument list for placeholders that we won't try to 5062 /// handle later. 5063 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5064 // Apply this processing to all the arguments at once instead of 5065 // dying at the first failure. 5066 bool hasInvalid = false; 5067 for (size_t i = 0, e = args.size(); i != e; i++) { 5068 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5069 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5070 if (result.isInvalid()) hasInvalid = true; 5071 else args[i] = result.get(); 5072 } else if (hasInvalid) { 5073 (void)S.CorrectDelayedTyposInExpr(args[i]); 5074 } 5075 } 5076 return hasInvalid; 5077 } 5078 5079 /// If a builtin function has a pointer argument with no explicit address 5080 /// space, then it should be able to accept a pointer to any address 5081 /// space as input. In order to do this, we need to replace the 5082 /// standard builtin declaration with one that uses the same address space 5083 /// as the call. 5084 /// 5085 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5086 /// it does not contain any pointer arguments without 5087 /// an address space qualifer. Otherwise the rewritten 5088 /// FunctionDecl is returned. 5089 /// TODO: Handle pointer return types. 5090 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5091 const FunctionDecl *FDecl, 5092 MultiExprArg ArgExprs) { 5093 5094 QualType DeclType = FDecl->getType(); 5095 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5096 5097 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5098 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5099 return nullptr; 5100 5101 bool NeedsNewDecl = false; 5102 unsigned i = 0; 5103 SmallVector<QualType, 8> OverloadParams; 5104 5105 for (QualType ParamType : FT->param_types()) { 5106 5107 // Convert array arguments to pointer to simplify type lookup. 5108 ExprResult ArgRes = 5109 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5110 if (ArgRes.isInvalid()) 5111 return nullptr; 5112 Expr *Arg = ArgRes.get(); 5113 QualType ArgType = Arg->getType(); 5114 if (!ParamType->isPointerType() || 5115 ParamType.getQualifiers().hasAddressSpace() || 5116 !ArgType->isPointerType() || 5117 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5118 OverloadParams.push_back(ParamType); 5119 continue; 5120 } 5121 5122 NeedsNewDecl = true; 5123 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5124 5125 QualType PointeeType = ParamType->getPointeeType(); 5126 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5127 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5128 } 5129 5130 if (!NeedsNewDecl) 5131 return nullptr; 5132 5133 FunctionProtoType::ExtProtoInfo EPI; 5134 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5135 OverloadParams, EPI); 5136 DeclContext *Parent = Context.getTranslationUnitDecl(); 5137 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5138 FDecl->getLocation(), 5139 FDecl->getLocation(), 5140 FDecl->getIdentifier(), 5141 OverloadTy, 5142 /*TInfo=*/nullptr, 5143 SC_Extern, false, 5144 /*hasPrototype=*/true); 5145 SmallVector<ParmVarDecl*, 16> Params; 5146 FT = cast<FunctionProtoType>(OverloadTy); 5147 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5148 QualType ParamType = FT->getParamType(i); 5149 ParmVarDecl *Parm = 5150 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5151 SourceLocation(), nullptr, ParamType, 5152 /*TInfo=*/nullptr, SC_None, nullptr); 5153 Parm->setScopeInfo(0, i); 5154 Params.push_back(Parm); 5155 } 5156 OverloadDecl->setParams(Params); 5157 return OverloadDecl; 5158 } 5159 5160 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5161 FunctionDecl *Callee, 5162 MultiExprArg ArgExprs) { 5163 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5164 // similar attributes) really don't like it when functions are called with an 5165 // invalid number of args. 5166 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5167 /*PartialOverloading=*/false) && 5168 !Callee->isVariadic()) 5169 return; 5170 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5171 return; 5172 5173 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5174 S.Diag(Fn->getLocStart(), 5175 isa<CXXMethodDecl>(Callee) 5176 ? diag::err_ovl_no_viable_member_function_in_call 5177 : diag::err_ovl_no_viable_function_in_call) 5178 << Callee << Callee->getSourceRange(); 5179 S.Diag(Callee->getLocation(), 5180 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5181 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5182 return; 5183 } 5184 } 5185 5186 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5187 /// This provides the location of the left/right parens and a list of comma 5188 /// locations. 5189 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5190 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5191 Expr *ExecConfig, bool IsExecConfig) { 5192 // Since this might be a postfix expression, get rid of ParenListExprs. 5193 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5194 if (Result.isInvalid()) return ExprError(); 5195 Fn = Result.get(); 5196 5197 if (checkArgsForPlaceholders(*this, ArgExprs)) 5198 return ExprError(); 5199 5200 if (getLangOpts().CPlusPlus) { 5201 // If this is a pseudo-destructor expression, build the call immediately. 5202 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5203 if (!ArgExprs.empty()) { 5204 // Pseudo-destructor calls should not have any arguments. 5205 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5206 << FixItHint::CreateRemoval( 5207 SourceRange(ArgExprs.front()->getLocStart(), 5208 ArgExprs.back()->getLocEnd())); 5209 } 5210 5211 return new (Context) 5212 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5213 } 5214 if (Fn->getType() == Context.PseudoObjectTy) { 5215 ExprResult result = CheckPlaceholderExpr(Fn); 5216 if (result.isInvalid()) return ExprError(); 5217 Fn = result.get(); 5218 } 5219 5220 // Determine whether this is a dependent call inside a C++ template, 5221 // in which case we won't do any semantic analysis now. 5222 bool Dependent = false; 5223 if (Fn->isTypeDependent()) 5224 Dependent = true; 5225 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5226 Dependent = true; 5227 5228 if (Dependent) { 5229 if (ExecConfig) { 5230 return new (Context) CUDAKernelCallExpr( 5231 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5232 Context.DependentTy, VK_RValue, RParenLoc); 5233 } else { 5234 return new (Context) CallExpr( 5235 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5236 } 5237 } 5238 5239 // Determine whether this is a call to an object (C++ [over.call.object]). 5240 if (Fn->getType()->isRecordType()) 5241 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5242 RParenLoc); 5243 5244 if (Fn->getType() == Context.UnknownAnyTy) { 5245 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5246 if (result.isInvalid()) return ExprError(); 5247 Fn = result.get(); 5248 } 5249 5250 if (Fn->getType() == Context.BoundMemberTy) { 5251 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5252 RParenLoc); 5253 } 5254 } 5255 5256 // Check for overloaded calls. This can happen even in C due to extensions. 5257 if (Fn->getType() == Context.OverloadTy) { 5258 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5259 5260 // We aren't supposed to apply this logic for if there'Scope an '&' 5261 // involved. 5262 if (!find.HasFormOfMemberPointer) { 5263 OverloadExpr *ovl = find.Expression; 5264 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5265 return BuildOverloadedCallExpr( 5266 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5267 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5268 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5269 RParenLoc); 5270 } 5271 } 5272 5273 // If we're directly calling a function, get the appropriate declaration. 5274 if (Fn->getType() == Context.UnknownAnyTy) { 5275 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5276 if (result.isInvalid()) return ExprError(); 5277 Fn = result.get(); 5278 } 5279 5280 Expr *NakedFn = Fn->IgnoreParens(); 5281 5282 bool CallingNDeclIndirectly = false; 5283 NamedDecl *NDecl = nullptr; 5284 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5285 if (UnOp->getOpcode() == UO_AddrOf) { 5286 CallingNDeclIndirectly = true; 5287 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5288 } 5289 } 5290 5291 if (isa<DeclRefExpr>(NakedFn)) { 5292 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5293 5294 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5295 if (FDecl && FDecl->getBuiltinID()) { 5296 // Rewrite the function decl for this builtin by replacing parameters 5297 // with no explicit address space with the address space of the arguments 5298 // in ArgExprs. 5299 if ((FDecl = 5300 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5301 NDecl = FDecl; 5302 Fn = DeclRefExpr::Create( 5303 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5304 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5305 } 5306 } 5307 } else if (isa<MemberExpr>(NakedFn)) 5308 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5309 5310 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5311 if (CallingNDeclIndirectly && 5312 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5313 Fn->getLocStart())) 5314 return ExprError(); 5315 5316 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5317 return ExprError(); 5318 5319 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5320 } 5321 5322 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5323 ExecConfig, IsExecConfig); 5324 } 5325 5326 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5327 /// 5328 /// __builtin_astype( value, dst type ) 5329 /// 5330 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5331 SourceLocation BuiltinLoc, 5332 SourceLocation RParenLoc) { 5333 ExprValueKind VK = VK_RValue; 5334 ExprObjectKind OK = OK_Ordinary; 5335 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5336 QualType SrcTy = E->getType(); 5337 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5338 return ExprError(Diag(BuiltinLoc, 5339 diag::err_invalid_astype_of_different_size) 5340 << DstTy 5341 << SrcTy 5342 << E->getSourceRange()); 5343 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5344 } 5345 5346 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5347 /// provided arguments. 5348 /// 5349 /// __builtin_convertvector( value, dst type ) 5350 /// 5351 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5352 SourceLocation BuiltinLoc, 5353 SourceLocation RParenLoc) { 5354 TypeSourceInfo *TInfo; 5355 GetTypeFromParser(ParsedDestTy, &TInfo); 5356 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5357 } 5358 5359 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5360 /// i.e. an expression not of \p OverloadTy. The expression should 5361 /// unary-convert to an expression of function-pointer or 5362 /// block-pointer type. 5363 /// 5364 /// \param NDecl the declaration being called, if available 5365 ExprResult 5366 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5367 SourceLocation LParenLoc, 5368 ArrayRef<Expr *> Args, 5369 SourceLocation RParenLoc, 5370 Expr *Config, bool IsExecConfig) { 5371 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5372 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5373 5374 // Functions with 'interrupt' attribute cannot be called directly. 5375 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5376 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5377 return ExprError(); 5378 } 5379 5380 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5381 // so there's some risk when calling out to non-interrupt handler functions 5382 // that the callee might not preserve them. This is easy to diagnose here, 5383 // but can be very challenging to debug. 5384 if (auto *Caller = getCurFunctionDecl()) 5385 if (Caller->hasAttr<ARMInterruptAttr>()) 5386 if (!FDecl->hasAttr<ARMInterruptAttr>()) 5387 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5388 5389 // Promote the function operand. 5390 // We special-case function promotion here because we only allow promoting 5391 // builtin functions to function pointers in the callee of a call. 5392 ExprResult Result; 5393 if (BuiltinID && 5394 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5395 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5396 CK_BuiltinFnToFnPtr).get(); 5397 } else { 5398 Result = CallExprUnaryConversions(Fn); 5399 } 5400 if (Result.isInvalid()) 5401 return ExprError(); 5402 Fn = Result.get(); 5403 5404 // Make the call expr early, before semantic checks. This guarantees cleanup 5405 // of arguments and function on error. 5406 CallExpr *TheCall; 5407 if (Config) 5408 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5409 cast<CallExpr>(Config), Args, 5410 Context.BoolTy, VK_RValue, 5411 RParenLoc); 5412 else 5413 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5414 VK_RValue, RParenLoc); 5415 5416 if (!getLangOpts().CPlusPlus) { 5417 // C cannot always handle TypoExpr nodes in builtin calls and direct 5418 // function calls as their argument checking don't necessarily handle 5419 // dependent types properly, so make sure any TypoExprs have been 5420 // dealt with. 5421 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5422 if (!Result.isUsable()) return ExprError(); 5423 TheCall = dyn_cast<CallExpr>(Result.get()); 5424 if (!TheCall) return Result; 5425 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5426 } 5427 5428 // Bail out early if calling a builtin with custom typechecking. 5429 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5430 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5431 5432 retry: 5433 const FunctionType *FuncT; 5434 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5435 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5436 // have type pointer to function". 5437 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5438 if (!FuncT) 5439 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5440 << Fn->getType() << Fn->getSourceRange()); 5441 } else if (const BlockPointerType *BPT = 5442 Fn->getType()->getAs<BlockPointerType>()) { 5443 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5444 } else { 5445 // Handle calls to expressions of unknown-any type. 5446 if (Fn->getType() == Context.UnknownAnyTy) { 5447 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5448 if (rewrite.isInvalid()) return ExprError(); 5449 Fn = rewrite.get(); 5450 TheCall->setCallee(Fn); 5451 goto retry; 5452 } 5453 5454 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5455 << Fn->getType() << Fn->getSourceRange()); 5456 } 5457 5458 if (getLangOpts().CUDA) { 5459 if (Config) { 5460 // CUDA: Kernel calls must be to global functions 5461 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5462 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5463 << FDecl->getName() << Fn->getSourceRange()); 5464 5465 // CUDA: Kernel function must have 'void' return type 5466 if (!FuncT->getReturnType()->isVoidType()) 5467 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5468 << Fn->getType() << Fn->getSourceRange()); 5469 } else { 5470 // CUDA: Calls to global functions must be configured 5471 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5472 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5473 << FDecl->getName() << Fn->getSourceRange()); 5474 } 5475 } 5476 5477 // Check for a valid return type 5478 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5479 FDecl)) 5480 return ExprError(); 5481 5482 // We know the result type of the call, set it. 5483 TheCall->setType(FuncT->getCallResultType(Context)); 5484 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5485 5486 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5487 if (Proto) { 5488 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5489 IsExecConfig)) 5490 return ExprError(); 5491 } else { 5492 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5493 5494 if (FDecl) { 5495 // Check if we have too few/too many template arguments, based 5496 // on our knowledge of the function definition. 5497 const FunctionDecl *Def = nullptr; 5498 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5499 Proto = Def->getType()->getAs<FunctionProtoType>(); 5500 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5501 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5502 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5503 } 5504 5505 // If the function we're calling isn't a function prototype, but we have 5506 // a function prototype from a prior declaratiom, use that prototype. 5507 if (!FDecl->hasPrototype()) 5508 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5509 } 5510 5511 // Promote the arguments (C99 6.5.2.2p6). 5512 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5513 Expr *Arg = Args[i]; 5514 5515 if (Proto && i < Proto->getNumParams()) { 5516 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5517 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5518 ExprResult ArgE = 5519 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5520 if (ArgE.isInvalid()) 5521 return true; 5522 5523 Arg = ArgE.getAs<Expr>(); 5524 5525 } else { 5526 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5527 5528 if (ArgE.isInvalid()) 5529 return true; 5530 5531 Arg = ArgE.getAs<Expr>(); 5532 } 5533 5534 if (RequireCompleteType(Arg->getLocStart(), 5535 Arg->getType(), 5536 diag::err_call_incomplete_argument, Arg)) 5537 return ExprError(); 5538 5539 TheCall->setArg(i, Arg); 5540 } 5541 } 5542 5543 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5544 if (!Method->isStatic()) 5545 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5546 << Fn->getSourceRange()); 5547 5548 // Check for sentinels 5549 if (NDecl) 5550 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5551 5552 // Do special checking on direct calls to functions. 5553 if (FDecl) { 5554 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5555 return ExprError(); 5556 5557 if (BuiltinID) 5558 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5559 } else if (NDecl) { 5560 if (CheckPointerCall(NDecl, TheCall, Proto)) 5561 return ExprError(); 5562 } else { 5563 if (CheckOtherCall(TheCall, Proto)) 5564 return ExprError(); 5565 } 5566 5567 return MaybeBindToTemporary(TheCall); 5568 } 5569 5570 ExprResult 5571 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5572 SourceLocation RParenLoc, Expr *InitExpr) { 5573 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5574 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5575 5576 TypeSourceInfo *TInfo; 5577 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5578 if (!TInfo) 5579 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5580 5581 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5582 } 5583 5584 ExprResult 5585 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5586 SourceLocation RParenLoc, Expr *LiteralExpr) { 5587 QualType literalType = TInfo->getType(); 5588 5589 if (literalType->isArrayType()) { 5590 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5591 diag::err_illegal_decl_array_incomplete_type, 5592 SourceRange(LParenLoc, 5593 LiteralExpr->getSourceRange().getEnd()))) 5594 return ExprError(); 5595 if (literalType->isVariableArrayType()) 5596 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5597 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5598 } else if (!literalType->isDependentType() && 5599 RequireCompleteType(LParenLoc, literalType, 5600 diag::err_typecheck_decl_incomplete_type, 5601 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5602 return ExprError(); 5603 5604 InitializedEntity Entity 5605 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5606 InitializationKind Kind 5607 = InitializationKind::CreateCStyleCast(LParenLoc, 5608 SourceRange(LParenLoc, RParenLoc), 5609 /*InitList=*/true); 5610 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5611 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5612 &literalType); 5613 if (Result.isInvalid()) 5614 return ExprError(); 5615 LiteralExpr = Result.get(); 5616 5617 bool isFileScope = !CurContext->isFunctionOrMethod(); 5618 if (isFileScope && 5619 !LiteralExpr->isTypeDependent() && 5620 !LiteralExpr->isValueDependent() && 5621 !literalType->isDependentType()) { // 6.5.2.5p3 5622 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5623 return ExprError(); 5624 } 5625 5626 // In C, compound literals are l-values for some reason. 5627 // For GCC compatibility, in C++, file-scope array compound literals with 5628 // constant initializers are also l-values, and compound literals are 5629 // otherwise prvalues. 5630 // 5631 // (GCC also treats C++ list-initialized file-scope array prvalues with 5632 // constant initializers as l-values, but that's non-conforming, so we don't 5633 // follow it there.) 5634 // 5635 // FIXME: It would be better to handle the lvalue cases as materializing and 5636 // lifetime-extending a temporary object, but our materialized temporaries 5637 // representation only supports lifetime extension from a variable, not "out 5638 // of thin air". 5639 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5640 // is bound to the result of applying array-to-pointer decay to the compound 5641 // literal. 5642 // FIXME: GCC supports compound literals of reference type, which should 5643 // obviously have a value kind derived from the kind of reference involved. 5644 ExprValueKind VK = 5645 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5646 ? VK_RValue 5647 : VK_LValue; 5648 5649 return MaybeBindToTemporary( 5650 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5651 VK, LiteralExpr, isFileScope)); 5652 } 5653 5654 ExprResult 5655 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5656 SourceLocation RBraceLoc) { 5657 // Immediately handle non-overload placeholders. Overloads can be 5658 // resolved contextually, but everything else here can't. 5659 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5660 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5661 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5662 5663 // Ignore failures; dropping the entire initializer list because 5664 // of one failure would be terrible for indexing/etc. 5665 if (result.isInvalid()) continue; 5666 5667 InitArgList[I] = result.get(); 5668 } 5669 } 5670 5671 // Semantic analysis for initializers is done by ActOnDeclarator() and 5672 // CheckInitializer() - it requires knowledge of the object being intialized. 5673 5674 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5675 RBraceLoc); 5676 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5677 return E; 5678 } 5679 5680 /// Do an explicit extend of the given block pointer if we're in ARC. 5681 void Sema::maybeExtendBlockObject(ExprResult &E) { 5682 assert(E.get()->getType()->isBlockPointerType()); 5683 assert(E.get()->isRValue()); 5684 5685 // Only do this in an r-value context. 5686 if (!getLangOpts().ObjCAutoRefCount) return; 5687 5688 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5689 CK_ARCExtendBlockObject, E.get(), 5690 /*base path*/ nullptr, VK_RValue); 5691 Cleanup.setExprNeedsCleanups(true); 5692 } 5693 5694 /// Prepare a conversion of the given expression to an ObjC object 5695 /// pointer type. 5696 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5697 QualType type = E.get()->getType(); 5698 if (type->isObjCObjectPointerType()) { 5699 return CK_BitCast; 5700 } else if (type->isBlockPointerType()) { 5701 maybeExtendBlockObject(E); 5702 return CK_BlockPointerToObjCPointerCast; 5703 } else { 5704 assert(type->isPointerType()); 5705 return CK_CPointerToObjCPointerCast; 5706 } 5707 } 5708 5709 /// Prepares for a scalar cast, performing all the necessary stages 5710 /// except the final cast and returning the kind required. 5711 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5712 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5713 // Also, callers should have filtered out the invalid cases with 5714 // pointers. Everything else should be possible. 5715 5716 QualType SrcTy = Src.get()->getType(); 5717 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5718 return CK_NoOp; 5719 5720 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5721 case Type::STK_MemberPointer: 5722 llvm_unreachable("member pointer type in C"); 5723 5724 case Type::STK_CPointer: 5725 case Type::STK_BlockPointer: 5726 case Type::STK_ObjCObjectPointer: 5727 switch (DestTy->getScalarTypeKind()) { 5728 case Type::STK_CPointer: { 5729 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5730 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5731 if (SrcAS != DestAS) 5732 return CK_AddressSpaceConversion; 5733 return CK_BitCast; 5734 } 5735 case Type::STK_BlockPointer: 5736 return (SrcKind == Type::STK_BlockPointer 5737 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5738 case Type::STK_ObjCObjectPointer: 5739 if (SrcKind == Type::STK_ObjCObjectPointer) 5740 return CK_BitCast; 5741 if (SrcKind == Type::STK_CPointer) 5742 return CK_CPointerToObjCPointerCast; 5743 maybeExtendBlockObject(Src); 5744 return CK_BlockPointerToObjCPointerCast; 5745 case Type::STK_Bool: 5746 return CK_PointerToBoolean; 5747 case Type::STK_Integral: 5748 return CK_PointerToIntegral; 5749 case Type::STK_Floating: 5750 case Type::STK_FloatingComplex: 5751 case Type::STK_IntegralComplex: 5752 case Type::STK_MemberPointer: 5753 llvm_unreachable("illegal cast from pointer"); 5754 } 5755 llvm_unreachable("Should have returned before this"); 5756 5757 case Type::STK_Bool: // casting from bool is like casting from an integer 5758 case Type::STK_Integral: 5759 switch (DestTy->getScalarTypeKind()) { 5760 case Type::STK_CPointer: 5761 case Type::STK_ObjCObjectPointer: 5762 case Type::STK_BlockPointer: 5763 if (Src.get()->isNullPointerConstant(Context, 5764 Expr::NPC_ValueDependentIsNull)) 5765 return CK_NullToPointer; 5766 return CK_IntegralToPointer; 5767 case Type::STK_Bool: 5768 return CK_IntegralToBoolean; 5769 case Type::STK_Integral: 5770 return CK_IntegralCast; 5771 case Type::STK_Floating: 5772 return CK_IntegralToFloating; 5773 case Type::STK_IntegralComplex: 5774 Src = ImpCastExprToType(Src.get(), 5775 DestTy->castAs<ComplexType>()->getElementType(), 5776 CK_IntegralCast); 5777 return CK_IntegralRealToComplex; 5778 case Type::STK_FloatingComplex: 5779 Src = ImpCastExprToType(Src.get(), 5780 DestTy->castAs<ComplexType>()->getElementType(), 5781 CK_IntegralToFloating); 5782 return CK_FloatingRealToComplex; 5783 case Type::STK_MemberPointer: 5784 llvm_unreachable("member pointer type in C"); 5785 } 5786 llvm_unreachable("Should have returned before this"); 5787 5788 case Type::STK_Floating: 5789 switch (DestTy->getScalarTypeKind()) { 5790 case Type::STK_Floating: 5791 return CK_FloatingCast; 5792 case Type::STK_Bool: 5793 return CK_FloatingToBoolean; 5794 case Type::STK_Integral: 5795 return CK_FloatingToIntegral; 5796 case Type::STK_FloatingComplex: 5797 Src = ImpCastExprToType(Src.get(), 5798 DestTy->castAs<ComplexType>()->getElementType(), 5799 CK_FloatingCast); 5800 return CK_FloatingRealToComplex; 5801 case Type::STK_IntegralComplex: 5802 Src = ImpCastExprToType(Src.get(), 5803 DestTy->castAs<ComplexType>()->getElementType(), 5804 CK_FloatingToIntegral); 5805 return CK_IntegralRealToComplex; 5806 case Type::STK_CPointer: 5807 case Type::STK_ObjCObjectPointer: 5808 case Type::STK_BlockPointer: 5809 llvm_unreachable("valid float->pointer cast?"); 5810 case Type::STK_MemberPointer: 5811 llvm_unreachable("member pointer type in C"); 5812 } 5813 llvm_unreachable("Should have returned before this"); 5814 5815 case Type::STK_FloatingComplex: 5816 switch (DestTy->getScalarTypeKind()) { 5817 case Type::STK_FloatingComplex: 5818 return CK_FloatingComplexCast; 5819 case Type::STK_IntegralComplex: 5820 return CK_FloatingComplexToIntegralComplex; 5821 case Type::STK_Floating: { 5822 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5823 if (Context.hasSameType(ET, DestTy)) 5824 return CK_FloatingComplexToReal; 5825 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5826 return CK_FloatingCast; 5827 } 5828 case Type::STK_Bool: 5829 return CK_FloatingComplexToBoolean; 5830 case Type::STK_Integral: 5831 Src = ImpCastExprToType(Src.get(), 5832 SrcTy->castAs<ComplexType>()->getElementType(), 5833 CK_FloatingComplexToReal); 5834 return CK_FloatingToIntegral; 5835 case Type::STK_CPointer: 5836 case Type::STK_ObjCObjectPointer: 5837 case Type::STK_BlockPointer: 5838 llvm_unreachable("valid complex float->pointer cast?"); 5839 case Type::STK_MemberPointer: 5840 llvm_unreachable("member pointer type in C"); 5841 } 5842 llvm_unreachable("Should have returned before this"); 5843 5844 case Type::STK_IntegralComplex: 5845 switch (DestTy->getScalarTypeKind()) { 5846 case Type::STK_FloatingComplex: 5847 return CK_IntegralComplexToFloatingComplex; 5848 case Type::STK_IntegralComplex: 5849 return CK_IntegralComplexCast; 5850 case Type::STK_Integral: { 5851 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5852 if (Context.hasSameType(ET, DestTy)) 5853 return CK_IntegralComplexToReal; 5854 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5855 return CK_IntegralCast; 5856 } 5857 case Type::STK_Bool: 5858 return CK_IntegralComplexToBoolean; 5859 case Type::STK_Floating: 5860 Src = ImpCastExprToType(Src.get(), 5861 SrcTy->castAs<ComplexType>()->getElementType(), 5862 CK_IntegralComplexToReal); 5863 return CK_IntegralToFloating; 5864 case Type::STK_CPointer: 5865 case Type::STK_ObjCObjectPointer: 5866 case Type::STK_BlockPointer: 5867 llvm_unreachable("valid complex int->pointer cast?"); 5868 case Type::STK_MemberPointer: 5869 llvm_unreachable("member pointer type in C"); 5870 } 5871 llvm_unreachable("Should have returned before this"); 5872 } 5873 5874 llvm_unreachable("Unhandled scalar cast"); 5875 } 5876 5877 static bool breakDownVectorType(QualType type, uint64_t &len, 5878 QualType &eltType) { 5879 // Vectors are simple. 5880 if (const VectorType *vecType = type->getAs<VectorType>()) { 5881 len = vecType->getNumElements(); 5882 eltType = vecType->getElementType(); 5883 assert(eltType->isScalarType()); 5884 return true; 5885 } 5886 5887 // We allow lax conversion to and from non-vector types, but only if 5888 // they're real types (i.e. non-complex, non-pointer scalar types). 5889 if (!type->isRealType()) return false; 5890 5891 len = 1; 5892 eltType = type; 5893 return true; 5894 } 5895 5896 /// Are the two types lax-compatible vector types? That is, given 5897 /// that one of them is a vector, do they have equal storage sizes, 5898 /// where the storage size is the number of elements times the element 5899 /// size? 5900 /// 5901 /// This will also return false if either of the types is neither a 5902 /// vector nor a real type. 5903 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5904 assert(destTy->isVectorType() || srcTy->isVectorType()); 5905 5906 // Disallow lax conversions between scalars and ExtVectors (these 5907 // conversions are allowed for other vector types because common headers 5908 // depend on them). Most scalar OP ExtVector cases are handled by the 5909 // splat path anyway, which does what we want (convert, not bitcast). 5910 // What this rules out for ExtVectors is crazy things like char4*float. 5911 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5912 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5913 5914 uint64_t srcLen, destLen; 5915 QualType srcEltTy, destEltTy; 5916 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5917 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5918 5919 // ASTContext::getTypeSize will return the size rounded up to a 5920 // power of 2, so instead of using that, we need to use the raw 5921 // element size multiplied by the element count. 5922 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5923 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5924 5925 return (srcLen * srcEltSize == destLen * destEltSize); 5926 } 5927 5928 /// Is this a legal conversion between two types, one of which is 5929 /// known to be a vector type? 5930 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5931 assert(destTy->isVectorType() || srcTy->isVectorType()); 5932 5933 if (!Context.getLangOpts().LaxVectorConversions) 5934 return false; 5935 return areLaxCompatibleVectorTypes(srcTy, destTy); 5936 } 5937 5938 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5939 CastKind &Kind) { 5940 assert(VectorTy->isVectorType() && "Not a vector type!"); 5941 5942 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5943 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5944 return Diag(R.getBegin(), 5945 Ty->isVectorType() ? 5946 diag::err_invalid_conversion_between_vectors : 5947 diag::err_invalid_conversion_between_vector_and_integer) 5948 << VectorTy << Ty << R; 5949 } else 5950 return Diag(R.getBegin(), 5951 diag::err_invalid_conversion_between_vector_and_scalar) 5952 << VectorTy << Ty << R; 5953 5954 Kind = CK_BitCast; 5955 return false; 5956 } 5957 5958 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5959 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5960 5961 if (DestElemTy == SplattedExpr->getType()) 5962 return SplattedExpr; 5963 5964 assert(DestElemTy->isFloatingType() || 5965 DestElemTy->isIntegralOrEnumerationType()); 5966 5967 CastKind CK; 5968 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5969 // OpenCL requires that we convert `true` boolean expressions to -1, but 5970 // only when splatting vectors. 5971 if (DestElemTy->isFloatingType()) { 5972 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5973 // in two steps: boolean to signed integral, then to floating. 5974 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5975 CK_BooleanToSignedIntegral); 5976 SplattedExpr = CastExprRes.get(); 5977 CK = CK_IntegralToFloating; 5978 } else { 5979 CK = CK_BooleanToSignedIntegral; 5980 } 5981 } else { 5982 ExprResult CastExprRes = SplattedExpr; 5983 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5984 if (CastExprRes.isInvalid()) 5985 return ExprError(); 5986 SplattedExpr = CastExprRes.get(); 5987 } 5988 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5989 } 5990 5991 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5992 Expr *CastExpr, CastKind &Kind) { 5993 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5994 5995 QualType SrcTy = CastExpr->getType(); 5996 5997 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5998 // an ExtVectorType. 5999 // In OpenCL, casts between vectors of different types are not allowed. 6000 // (See OpenCL 6.2). 6001 if (SrcTy->isVectorType()) { 6002 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 6003 || (getLangOpts().OpenCL && 6004 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 6005 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6006 << DestTy << SrcTy << R; 6007 return ExprError(); 6008 } 6009 Kind = CK_BitCast; 6010 return CastExpr; 6011 } 6012 6013 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6014 // conversion will take place first from scalar to elt type, and then 6015 // splat from elt type to vector. 6016 if (SrcTy->isPointerType()) 6017 return Diag(R.getBegin(), 6018 diag::err_invalid_conversion_between_vector_and_scalar) 6019 << DestTy << SrcTy << R; 6020 6021 Kind = CK_VectorSplat; 6022 return prepareVectorSplat(DestTy, CastExpr); 6023 } 6024 6025 ExprResult 6026 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6027 Declarator &D, ParsedType &Ty, 6028 SourceLocation RParenLoc, Expr *CastExpr) { 6029 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6030 "ActOnCastExpr(): missing type or expr"); 6031 6032 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6033 if (D.isInvalidType()) 6034 return ExprError(); 6035 6036 if (getLangOpts().CPlusPlus) { 6037 // Check that there are no default arguments (C++ only). 6038 CheckExtraCXXDefaultArguments(D); 6039 } else { 6040 // Make sure any TypoExprs have been dealt with. 6041 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6042 if (!Res.isUsable()) 6043 return ExprError(); 6044 CastExpr = Res.get(); 6045 } 6046 6047 checkUnusedDeclAttributes(D); 6048 6049 QualType castType = castTInfo->getType(); 6050 Ty = CreateParsedType(castType, castTInfo); 6051 6052 bool isVectorLiteral = false; 6053 6054 // Check for an altivec or OpenCL literal, 6055 // i.e. all the elements are integer constants. 6056 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6057 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6058 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6059 && castType->isVectorType() && (PE || PLE)) { 6060 if (PLE && PLE->getNumExprs() == 0) { 6061 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6062 return ExprError(); 6063 } 6064 if (PE || PLE->getNumExprs() == 1) { 6065 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6066 if (!E->getType()->isVectorType()) 6067 isVectorLiteral = true; 6068 } 6069 else 6070 isVectorLiteral = true; 6071 } 6072 6073 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6074 // then handle it as such. 6075 if (isVectorLiteral) 6076 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6077 6078 // If the Expr being casted is a ParenListExpr, handle it specially. 6079 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6080 // sequence of BinOp comma operators. 6081 if (isa<ParenListExpr>(CastExpr)) { 6082 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6083 if (Result.isInvalid()) return ExprError(); 6084 CastExpr = Result.get(); 6085 } 6086 6087 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6088 !getSourceManager().isInSystemMacro(LParenLoc)) 6089 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6090 6091 CheckTollFreeBridgeCast(castType, CastExpr); 6092 6093 CheckObjCBridgeRelatedCast(castType, CastExpr); 6094 6095 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6096 6097 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6098 } 6099 6100 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6101 SourceLocation RParenLoc, Expr *E, 6102 TypeSourceInfo *TInfo) { 6103 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6104 "Expected paren or paren list expression"); 6105 6106 Expr **exprs; 6107 unsigned numExprs; 6108 Expr *subExpr; 6109 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6110 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6111 LiteralLParenLoc = PE->getLParenLoc(); 6112 LiteralRParenLoc = PE->getRParenLoc(); 6113 exprs = PE->getExprs(); 6114 numExprs = PE->getNumExprs(); 6115 } else { // isa<ParenExpr> by assertion at function entrance 6116 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6117 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6118 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6119 exprs = &subExpr; 6120 numExprs = 1; 6121 } 6122 6123 QualType Ty = TInfo->getType(); 6124 assert(Ty->isVectorType() && "Expected vector type"); 6125 6126 SmallVector<Expr *, 8> initExprs; 6127 const VectorType *VTy = Ty->getAs<VectorType>(); 6128 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6129 6130 // '(...)' form of vector initialization in AltiVec: the number of 6131 // initializers must be one or must match the size of the vector. 6132 // If a single value is specified in the initializer then it will be 6133 // replicated to all the components of the vector 6134 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6135 // The number of initializers must be one or must match the size of the 6136 // vector. If a single value is specified in the initializer then it will 6137 // be replicated to all the components of the vector 6138 if (numExprs == 1) { 6139 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6140 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6141 if (Literal.isInvalid()) 6142 return ExprError(); 6143 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6144 PrepareScalarCast(Literal, ElemTy)); 6145 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6146 } 6147 else if (numExprs < numElems) { 6148 Diag(E->getExprLoc(), 6149 diag::err_incorrect_number_of_vector_initializers); 6150 return ExprError(); 6151 } 6152 else 6153 initExprs.append(exprs, exprs + numExprs); 6154 } 6155 else { 6156 // For OpenCL, when the number of initializers is a single value, 6157 // it will be replicated to all components of the vector. 6158 if (getLangOpts().OpenCL && 6159 VTy->getVectorKind() == VectorType::GenericVector && 6160 numExprs == 1) { 6161 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6162 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6163 if (Literal.isInvalid()) 6164 return ExprError(); 6165 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6166 PrepareScalarCast(Literal, ElemTy)); 6167 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6168 } 6169 6170 initExprs.append(exprs, exprs + numExprs); 6171 } 6172 // FIXME: This means that pretty-printing the final AST will produce curly 6173 // braces instead of the original commas. 6174 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6175 initExprs, LiteralRParenLoc); 6176 initE->setType(Ty); 6177 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6178 } 6179 6180 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6181 /// the ParenListExpr into a sequence of comma binary operators. 6182 ExprResult 6183 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6184 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6185 if (!E) 6186 return OrigExpr; 6187 6188 ExprResult Result(E->getExpr(0)); 6189 6190 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6191 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6192 E->getExpr(i)); 6193 6194 if (Result.isInvalid()) return ExprError(); 6195 6196 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6197 } 6198 6199 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6200 SourceLocation R, 6201 MultiExprArg Val) { 6202 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6203 return expr; 6204 } 6205 6206 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6207 /// constant and the other is not a pointer. Returns true if a diagnostic is 6208 /// emitted. 6209 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6210 SourceLocation QuestionLoc) { 6211 Expr *NullExpr = LHSExpr; 6212 Expr *NonPointerExpr = RHSExpr; 6213 Expr::NullPointerConstantKind NullKind = 6214 NullExpr->isNullPointerConstant(Context, 6215 Expr::NPC_ValueDependentIsNotNull); 6216 6217 if (NullKind == Expr::NPCK_NotNull) { 6218 NullExpr = RHSExpr; 6219 NonPointerExpr = LHSExpr; 6220 NullKind = 6221 NullExpr->isNullPointerConstant(Context, 6222 Expr::NPC_ValueDependentIsNotNull); 6223 } 6224 6225 if (NullKind == Expr::NPCK_NotNull) 6226 return false; 6227 6228 if (NullKind == Expr::NPCK_ZeroExpression) 6229 return false; 6230 6231 if (NullKind == Expr::NPCK_ZeroLiteral) { 6232 // In this case, check to make sure that we got here from a "NULL" 6233 // string in the source code. 6234 NullExpr = NullExpr->IgnoreParenImpCasts(); 6235 SourceLocation loc = NullExpr->getExprLoc(); 6236 if (!findMacroSpelling(loc, "NULL")) 6237 return false; 6238 } 6239 6240 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6241 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6242 << NonPointerExpr->getType() << DiagType 6243 << NonPointerExpr->getSourceRange(); 6244 return true; 6245 } 6246 6247 /// \brief Return false if the condition expression is valid, true otherwise. 6248 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6249 QualType CondTy = Cond->getType(); 6250 6251 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6252 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6253 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6254 << CondTy << Cond->getSourceRange(); 6255 return true; 6256 } 6257 6258 // C99 6.5.15p2 6259 if (CondTy->isScalarType()) return false; 6260 6261 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6262 << CondTy << Cond->getSourceRange(); 6263 return true; 6264 } 6265 6266 /// \brief Handle when one or both operands are void type. 6267 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6268 ExprResult &RHS) { 6269 Expr *LHSExpr = LHS.get(); 6270 Expr *RHSExpr = RHS.get(); 6271 6272 if (!LHSExpr->getType()->isVoidType()) 6273 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6274 << RHSExpr->getSourceRange(); 6275 if (!RHSExpr->getType()->isVoidType()) 6276 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6277 << LHSExpr->getSourceRange(); 6278 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6279 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6280 return S.Context.VoidTy; 6281 } 6282 6283 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6284 /// true otherwise. 6285 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6286 QualType PointerTy) { 6287 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6288 !NullExpr.get()->isNullPointerConstant(S.Context, 6289 Expr::NPC_ValueDependentIsNull)) 6290 return true; 6291 6292 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6293 return false; 6294 } 6295 6296 /// \brief Checks compatibility between two pointers and return the resulting 6297 /// type. 6298 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6299 ExprResult &RHS, 6300 SourceLocation Loc) { 6301 QualType LHSTy = LHS.get()->getType(); 6302 QualType RHSTy = RHS.get()->getType(); 6303 6304 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6305 // Two identical pointers types are always compatible. 6306 return LHSTy; 6307 } 6308 6309 QualType lhptee, rhptee; 6310 6311 // Get the pointee types. 6312 bool IsBlockPointer = false; 6313 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6314 lhptee = LHSBTy->getPointeeType(); 6315 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6316 IsBlockPointer = true; 6317 } else { 6318 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6319 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6320 } 6321 6322 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6323 // differently qualified versions of compatible types, the result type is 6324 // a pointer to an appropriately qualified version of the composite 6325 // type. 6326 6327 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6328 // clause doesn't make sense for our extensions. E.g. address space 2 should 6329 // be incompatible with address space 3: they may live on different devices or 6330 // anything. 6331 Qualifiers lhQual = lhptee.getQualifiers(); 6332 Qualifiers rhQual = rhptee.getQualifiers(); 6333 6334 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6335 lhQual.removeCVRQualifiers(); 6336 rhQual.removeCVRQualifiers(); 6337 6338 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6339 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6340 6341 // For OpenCL: 6342 // 1. If LHS and RHS types match exactly and: 6343 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6344 // (b) AS overlap => generate addrspacecast 6345 // (c) AS don't overlap => give an error 6346 // 2. if LHS and RHS types don't match: 6347 // (a) AS match => use standard C rules, generate bitcast 6348 // (b) AS overlap => generate addrspacecast instead of bitcast 6349 // (c) AS don't overlap => give an error 6350 6351 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6352 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6353 6354 // OpenCL cases 1c, 2a, 2b, and 2c. 6355 if (CompositeTy.isNull()) { 6356 // In this situation, we assume void* type. No especially good 6357 // reason, but this is what gcc does, and we do have to pick 6358 // to get a consistent AST. 6359 QualType incompatTy; 6360 if (S.getLangOpts().OpenCL) { 6361 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6362 // spaces is disallowed. 6363 unsigned ResultAddrSpace; 6364 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6365 // Cases 2a and 2b. 6366 ResultAddrSpace = lhQual.getAddressSpace(); 6367 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6368 // Cases 2a and 2b. 6369 ResultAddrSpace = rhQual.getAddressSpace(); 6370 } else { 6371 // Cases 1c and 2c. 6372 S.Diag(Loc, 6373 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6374 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6375 << RHS.get()->getSourceRange(); 6376 return QualType(); 6377 } 6378 6379 // Continue handling cases 2a and 2b. 6380 incompatTy = S.Context.getPointerType( 6381 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6382 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6383 (lhQual.getAddressSpace() != ResultAddrSpace) 6384 ? CK_AddressSpaceConversion /* 2b */ 6385 : CK_BitCast /* 2a */); 6386 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6387 (rhQual.getAddressSpace() != ResultAddrSpace) 6388 ? CK_AddressSpaceConversion /* 2b */ 6389 : CK_BitCast /* 2a */); 6390 } else { 6391 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6392 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6393 << RHS.get()->getSourceRange(); 6394 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6395 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6396 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6397 } 6398 return incompatTy; 6399 } 6400 6401 // The pointer types are compatible. 6402 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6403 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6404 if (IsBlockPointer) 6405 ResultTy = S.Context.getBlockPointerType(ResultTy); 6406 else { 6407 // Cases 1a and 1b for OpenCL. 6408 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6409 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6410 ? CK_BitCast /* 1a */ 6411 : CK_AddressSpaceConversion /* 1b */; 6412 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6413 ? CK_BitCast /* 1a */ 6414 : CK_AddressSpaceConversion /* 1b */; 6415 ResultTy = S.Context.getPointerType(ResultTy); 6416 } 6417 6418 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6419 // if the target type does not change. 6420 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6421 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6422 return ResultTy; 6423 } 6424 6425 /// \brief Return the resulting type when the operands are both block pointers. 6426 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6427 ExprResult &LHS, 6428 ExprResult &RHS, 6429 SourceLocation Loc) { 6430 QualType LHSTy = LHS.get()->getType(); 6431 QualType RHSTy = RHS.get()->getType(); 6432 6433 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6434 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6435 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6436 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6437 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6438 return destType; 6439 } 6440 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6441 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6442 << RHS.get()->getSourceRange(); 6443 return QualType(); 6444 } 6445 6446 // We have 2 block pointer types. 6447 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6448 } 6449 6450 /// \brief Return the resulting type when the operands are both pointers. 6451 static QualType 6452 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6453 ExprResult &RHS, 6454 SourceLocation Loc) { 6455 // get the pointer types 6456 QualType LHSTy = LHS.get()->getType(); 6457 QualType RHSTy = RHS.get()->getType(); 6458 6459 // get the "pointed to" types 6460 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6461 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6462 6463 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6464 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6465 // Figure out necessary qualifiers (C99 6.5.15p6) 6466 QualType destPointee 6467 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6468 QualType destType = S.Context.getPointerType(destPointee); 6469 // Add qualifiers if necessary. 6470 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6471 // Promote to void*. 6472 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6473 return destType; 6474 } 6475 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6476 QualType destPointee 6477 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6478 QualType destType = S.Context.getPointerType(destPointee); 6479 // Add qualifiers if necessary. 6480 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6481 // Promote to void*. 6482 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6483 return destType; 6484 } 6485 6486 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6487 } 6488 6489 /// \brief Return false if the first expression is not an integer and the second 6490 /// expression is not a pointer, true otherwise. 6491 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6492 Expr* PointerExpr, SourceLocation Loc, 6493 bool IsIntFirstExpr) { 6494 if (!PointerExpr->getType()->isPointerType() || 6495 !Int.get()->getType()->isIntegerType()) 6496 return false; 6497 6498 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6499 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6500 6501 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6502 << Expr1->getType() << Expr2->getType() 6503 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6504 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6505 CK_IntegralToPointer); 6506 return true; 6507 } 6508 6509 /// \brief Simple conversion between integer and floating point types. 6510 /// 6511 /// Used when handling the OpenCL conditional operator where the 6512 /// condition is a vector while the other operands are scalar. 6513 /// 6514 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6515 /// types are either integer or floating type. Between the two 6516 /// operands, the type with the higher rank is defined as the "result 6517 /// type". The other operand needs to be promoted to the same type. No 6518 /// other type promotion is allowed. We cannot use 6519 /// UsualArithmeticConversions() for this purpose, since it always 6520 /// promotes promotable types. 6521 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6522 ExprResult &RHS, 6523 SourceLocation QuestionLoc) { 6524 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6525 if (LHS.isInvalid()) 6526 return QualType(); 6527 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6528 if (RHS.isInvalid()) 6529 return QualType(); 6530 6531 // For conversion purposes, we ignore any qualifiers. 6532 // For example, "const float" and "float" are equivalent. 6533 QualType LHSType = 6534 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6535 QualType RHSType = 6536 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6537 6538 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6539 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6540 << LHSType << LHS.get()->getSourceRange(); 6541 return QualType(); 6542 } 6543 6544 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6545 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6546 << RHSType << RHS.get()->getSourceRange(); 6547 return QualType(); 6548 } 6549 6550 // If both types are identical, no conversion is needed. 6551 if (LHSType == RHSType) 6552 return LHSType; 6553 6554 // Now handle "real" floating types (i.e. float, double, long double). 6555 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6556 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6557 /*IsCompAssign = */ false); 6558 6559 // Finally, we have two differing integer types. 6560 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6561 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6562 } 6563 6564 /// \brief Convert scalar operands to a vector that matches the 6565 /// condition in length. 6566 /// 6567 /// Used when handling the OpenCL conditional operator where the 6568 /// condition is a vector while the other operands are scalar. 6569 /// 6570 /// We first compute the "result type" for the scalar operands 6571 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6572 /// into a vector of that type where the length matches the condition 6573 /// vector type. s6.11.6 requires that the element types of the result 6574 /// and the condition must have the same number of bits. 6575 static QualType 6576 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6577 QualType CondTy, SourceLocation QuestionLoc) { 6578 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6579 if (ResTy.isNull()) return QualType(); 6580 6581 const VectorType *CV = CondTy->getAs<VectorType>(); 6582 assert(CV); 6583 6584 // Determine the vector result type 6585 unsigned NumElements = CV->getNumElements(); 6586 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6587 6588 // Ensure that all types have the same number of bits 6589 if (S.Context.getTypeSize(CV->getElementType()) 6590 != S.Context.getTypeSize(ResTy)) { 6591 // Since VectorTy is created internally, it does not pretty print 6592 // with an OpenCL name. Instead, we just print a description. 6593 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6594 SmallString<64> Str; 6595 llvm::raw_svector_ostream OS(Str); 6596 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6597 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6598 << CondTy << OS.str(); 6599 return QualType(); 6600 } 6601 6602 // Convert operands to the vector result type 6603 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6604 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6605 6606 return VectorTy; 6607 } 6608 6609 /// \brief Return false if this is a valid OpenCL condition vector 6610 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6611 SourceLocation QuestionLoc) { 6612 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6613 // integral type. 6614 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6615 assert(CondTy); 6616 QualType EleTy = CondTy->getElementType(); 6617 if (EleTy->isIntegerType()) return false; 6618 6619 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6620 << Cond->getType() << Cond->getSourceRange(); 6621 return true; 6622 } 6623 6624 /// \brief Return false if the vector condition type and the vector 6625 /// result type are compatible. 6626 /// 6627 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6628 /// number of elements, and their element types have the same number 6629 /// of bits. 6630 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6631 SourceLocation QuestionLoc) { 6632 const VectorType *CV = CondTy->getAs<VectorType>(); 6633 const VectorType *RV = VecResTy->getAs<VectorType>(); 6634 assert(CV && RV); 6635 6636 if (CV->getNumElements() != RV->getNumElements()) { 6637 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6638 << CondTy << VecResTy; 6639 return true; 6640 } 6641 6642 QualType CVE = CV->getElementType(); 6643 QualType RVE = RV->getElementType(); 6644 6645 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6646 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6647 << CondTy << VecResTy; 6648 return true; 6649 } 6650 6651 return false; 6652 } 6653 6654 /// \brief Return the resulting type for the conditional operator in 6655 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6656 /// s6.3.i) when the condition is a vector type. 6657 static QualType 6658 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6659 ExprResult &LHS, ExprResult &RHS, 6660 SourceLocation QuestionLoc) { 6661 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6662 if (Cond.isInvalid()) 6663 return QualType(); 6664 QualType CondTy = Cond.get()->getType(); 6665 6666 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6667 return QualType(); 6668 6669 // If either operand is a vector then find the vector type of the 6670 // result as specified in OpenCL v1.1 s6.3.i. 6671 if (LHS.get()->getType()->isVectorType() || 6672 RHS.get()->getType()->isVectorType()) { 6673 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6674 /*isCompAssign*/false, 6675 /*AllowBothBool*/true, 6676 /*AllowBoolConversions*/false); 6677 if (VecResTy.isNull()) return QualType(); 6678 // The result type must match the condition type as specified in 6679 // OpenCL v1.1 s6.11.6. 6680 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6681 return QualType(); 6682 return VecResTy; 6683 } 6684 6685 // Both operands are scalar. 6686 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6687 } 6688 6689 /// \brief Return true if the Expr is block type 6690 static bool checkBlockType(Sema &S, const Expr *E) { 6691 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6692 QualType Ty = CE->getCallee()->getType(); 6693 if (Ty->isBlockPointerType()) { 6694 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6695 return true; 6696 } 6697 } 6698 return false; 6699 } 6700 6701 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6702 /// In that case, LHS = cond. 6703 /// C99 6.5.15 6704 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6705 ExprResult &RHS, ExprValueKind &VK, 6706 ExprObjectKind &OK, 6707 SourceLocation QuestionLoc) { 6708 6709 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6710 if (!LHSResult.isUsable()) return QualType(); 6711 LHS = LHSResult; 6712 6713 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6714 if (!RHSResult.isUsable()) return QualType(); 6715 RHS = RHSResult; 6716 6717 // C++ is sufficiently different to merit its own checker. 6718 if (getLangOpts().CPlusPlus) 6719 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6720 6721 VK = VK_RValue; 6722 OK = OK_Ordinary; 6723 6724 // The OpenCL operator with a vector condition is sufficiently 6725 // different to merit its own checker. 6726 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6727 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6728 6729 // First, check the condition. 6730 Cond = UsualUnaryConversions(Cond.get()); 6731 if (Cond.isInvalid()) 6732 return QualType(); 6733 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6734 return QualType(); 6735 6736 // Now check the two expressions. 6737 if (LHS.get()->getType()->isVectorType() || 6738 RHS.get()->getType()->isVectorType()) 6739 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6740 /*AllowBothBool*/true, 6741 /*AllowBoolConversions*/false); 6742 6743 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6744 if (LHS.isInvalid() || RHS.isInvalid()) 6745 return QualType(); 6746 6747 QualType LHSTy = LHS.get()->getType(); 6748 QualType RHSTy = RHS.get()->getType(); 6749 6750 // Diagnose attempts to convert between __float128 and long double where 6751 // such conversions currently can't be handled. 6752 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6753 Diag(QuestionLoc, 6754 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6755 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6756 return QualType(); 6757 } 6758 6759 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6760 // selection operator (?:). 6761 if (getLangOpts().OpenCL && 6762 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6763 return QualType(); 6764 } 6765 6766 // If both operands have arithmetic type, do the usual arithmetic conversions 6767 // to find a common type: C99 6.5.15p3,5. 6768 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6769 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6770 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6771 6772 return ResTy; 6773 } 6774 6775 // If both operands are the same structure or union type, the result is that 6776 // type. 6777 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6778 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6779 if (LHSRT->getDecl() == RHSRT->getDecl()) 6780 // "If both the operands have structure or union type, the result has 6781 // that type." This implies that CV qualifiers are dropped. 6782 return LHSTy.getUnqualifiedType(); 6783 // FIXME: Type of conditional expression must be complete in C mode. 6784 } 6785 6786 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6787 // The following || allows only one side to be void (a GCC-ism). 6788 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6789 return checkConditionalVoidType(*this, LHS, RHS); 6790 } 6791 6792 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6793 // the type of the other operand." 6794 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6795 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6796 6797 // All objective-c pointer type analysis is done here. 6798 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6799 QuestionLoc); 6800 if (LHS.isInvalid() || RHS.isInvalid()) 6801 return QualType(); 6802 if (!compositeType.isNull()) 6803 return compositeType; 6804 6805 6806 // Handle block pointer types. 6807 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6808 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6809 QuestionLoc); 6810 6811 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6812 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6813 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6814 QuestionLoc); 6815 6816 // GCC compatibility: soften pointer/integer mismatch. Note that 6817 // null pointers have been filtered out by this point. 6818 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6819 /*isIntFirstExpr=*/true)) 6820 return RHSTy; 6821 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6822 /*isIntFirstExpr=*/false)) 6823 return LHSTy; 6824 6825 // Emit a better diagnostic if one of the expressions is a null pointer 6826 // constant and the other is not a pointer type. In this case, the user most 6827 // likely forgot to take the address of the other expression. 6828 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6829 return QualType(); 6830 6831 // Otherwise, the operands are not compatible. 6832 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6833 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6834 << RHS.get()->getSourceRange(); 6835 return QualType(); 6836 } 6837 6838 /// FindCompositeObjCPointerType - Helper method to find composite type of 6839 /// two objective-c pointer types of the two input expressions. 6840 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6841 SourceLocation QuestionLoc) { 6842 QualType LHSTy = LHS.get()->getType(); 6843 QualType RHSTy = RHS.get()->getType(); 6844 6845 // Handle things like Class and struct objc_class*. Here we case the result 6846 // to the pseudo-builtin, because that will be implicitly cast back to the 6847 // redefinition type if an attempt is made to access its fields. 6848 if (LHSTy->isObjCClassType() && 6849 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6850 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6851 return LHSTy; 6852 } 6853 if (RHSTy->isObjCClassType() && 6854 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6855 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6856 return RHSTy; 6857 } 6858 // And the same for struct objc_object* / id 6859 if (LHSTy->isObjCIdType() && 6860 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6861 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6862 return LHSTy; 6863 } 6864 if (RHSTy->isObjCIdType() && 6865 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6866 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6867 return RHSTy; 6868 } 6869 // And the same for struct objc_selector* / SEL 6870 if (Context.isObjCSelType(LHSTy) && 6871 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6872 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6873 return LHSTy; 6874 } 6875 if (Context.isObjCSelType(RHSTy) && 6876 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6877 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6878 return RHSTy; 6879 } 6880 // Check constraints for Objective-C object pointers types. 6881 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6882 6883 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6884 // Two identical object pointer types are always compatible. 6885 return LHSTy; 6886 } 6887 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6888 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6889 QualType compositeType = LHSTy; 6890 6891 // If both operands are interfaces and either operand can be 6892 // assigned to the other, use that type as the composite 6893 // type. This allows 6894 // xxx ? (A*) a : (B*) b 6895 // where B is a subclass of A. 6896 // 6897 // Additionally, as for assignment, if either type is 'id' 6898 // allow silent coercion. Finally, if the types are 6899 // incompatible then make sure to use 'id' as the composite 6900 // type so the result is acceptable for sending messages to. 6901 6902 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6903 // It could return the composite type. 6904 if (!(compositeType = 6905 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6906 // Nothing more to do. 6907 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6908 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6909 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6910 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6911 } else if ((LHSTy->isObjCQualifiedIdType() || 6912 RHSTy->isObjCQualifiedIdType()) && 6913 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6914 // Need to handle "id<xx>" explicitly. 6915 // GCC allows qualified id and any Objective-C type to devolve to 6916 // id. Currently localizing to here until clear this should be 6917 // part of ObjCQualifiedIdTypesAreCompatible. 6918 compositeType = Context.getObjCIdType(); 6919 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6920 compositeType = Context.getObjCIdType(); 6921 } else { 6922 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6923 << LHSTy << RHSTy 6924 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6925 QualType incompatTy = Context.getObjCIdType(); 6926 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6927 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6928 return incompatTy; 6929 } 6930 // The object pointer types are compatible. 6931 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6932 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6933 return compositeType; 6934 } 6935 // Check Objective-C object pointer types and 'void *' 6936 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6937 if (getLangOpts().ObjCAutoRefCount) { 6938 // ARC forbids the implicit conversion of object pointers to 'void *', 6939 // so these types are not compatible. 6940 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6941 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6942 LHS = RHS = true; 6943 return QualType(); 6944 } 6945 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6946 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6947 QualType destPointee 6948 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6949 QualType destType = Context.getPointerType(destPointee); 6950 // Add qualifiers if necessary. 6951 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6952 // Promote to void*. 6953 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6954 return destType; 6955 } 6956 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6957 if (getLangOpts().ObjCAutoRefCount) { 6958 // ARC forbids the implicit conversion of object pointers to 'void *', 6959 // so these types are not compatible. 6960 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6961 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6962 LHS = RHS = true; 6963 return QualType(); 6964 } 6965 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6966 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6967 QualType destPointee 6968 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6969 QualType destType = Context.getPointerType(destPointee); 6970 // Add qualifiers if necessary. 6971 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6972 // Promote to void*. 6973 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6974 return destType; 6975 } 6976 return QualType(); 6977 } 6978 6979 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6980 /// ParenRange in parentheses. 6981 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6982 const PartialDiagnostic &Note, 6983 SourceRange ParenRange) { 6984 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6985 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6986 EndLoc.isValid()) { 6987 Self.Diag(Loc, Note) 6988 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6989 << FixItHint::CreateInsertion(EndLoc, ")"); 6990 } else { 6991 // We can't display the parentheses, so just show the bare note. 6992 Self.Diag(Loc, Note) << ParenRange; 6993 } 6994 } 6995 6996 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6997 return BinaryOperator::isAdditiveOp(Opc) || 6998 BinaryOperator::isMultiplicativeOp(Opc) || 6999 BinaryOperator::isShiftOp(Opc); 7000 } 7001 7002 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7003 /// expression, either using a built-in or overloaded operator, 7004 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7005 /// expression. 7006 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7007 Expr **RHSExprs) { 7008 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7009 E = E->IgnoreImpCasts(); 7010 E = E->IgnoreConversionOperator(); 7011 E = E->IgnoreImpCasts(); 7012 7013 // Built-in binary operator. 7014 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7015 if (IsArithmeticOp(OP->getOpcode())) { 7016 *Opcode = OP->getOpcode(); 7017 *RHSExprs = OP->getRHS(); 7018 return true; 7019 } 7020 } 7021 7022 // Overloaded operator. 7023 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7024 if (Call->getNumArgs() != 2) 7025 return false; 7026 7027 // Make sure this is really a binary operator that is safe to pass into 7028 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7029 OverloadedOperatorKind OO = Call->getOperator(); 7030 if (OO < OO_Plus || OO > OO_Arrow || 7031 OO == OO_PlusPlus || OO == OO_MinusMinus) 7032 return false; 7033 7034 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7035 if (IsArithmeticOp(OpKind)) { 7036 *Opcode = OpKind; 7037 *RHSExprs = Call->getArg(1); 7038 return true; 7039 } 7040 } 7041 7042 return false; 7043 } 7044 7045 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7046 /// or is a logical expression such as (x==y) which has int type, but is 7047 /// commonly interpreted as boolean. 7048 static bool ExprLooksBoolean(Expr *E) { 7049 E = E->IgnoreParenImpCasts(); 7050 7051 if (E->getType()->isBooleanType()) 7052 return true; 7053 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7054 return OP->isComparisonOp() || OP->isLogicalOp(); 7055 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7056 return OP->getOpcode() == UO_LNot; 7057 if (E->getType()->isPointerType()) 7058 return true; 7059 7060 return false; 7061 } 7062 7063 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7064 /// and binary operator are mixed in a way that suggests the programmer assumed 7065 /// the conditional operator has higher precedence, for example: 7066 /// "int x = a + someBinaryCondition ? 1 : 2". 7067 static void DiagnoseConditionalPrecedence(Sema &Self, 7068 SourceLocation OpLoc, 7069 Expr *Condition, 7070 Expr *LHSExpr, 7071 Expr *RHSExpr) { 7072 BinaryOperatorKind CondOpcode; 7073 Expr *CondRHS; 7074 7075 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7076 return; 7077 if (!ExprLooksBoolean(CondRHS)) 7078 return; 7079 7080 // The condition is an arithmetic binary expression, with a right- 7081 // hand side that looks boolean, so warn. 7082 7083 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7084 << Condition->getSourceRange() 7085 << BinaryOperator::getOpcodeStr(CondOpcode); 7086 7087 SuggestParentheses(Self, OpLoc, 7088 Self.PDiag(diag::note_precedence_silence) 7089 << BinaryOperator::getOpcodeStr(CondOpcode), 7090 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7091 7092 SuggestParentheses(Self, OpLoc, 7093 Self.PDiag(diag::note_precedence_conditional_first), 7094 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7095 } 7096 7097 /// Compute the nullability of a conditional expression. 7098 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7099 QualType LHSTy, QualType RHSTy, 7100 ASTContext &Ctx) { 7101 if (!ResTy->isAnyPointerType()) 7102 return ResTy; 7103 7104 auto GetNullability = [&Ctx](QualType Ty) { 7105 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7106 if (Kind) 7107 return *Kind; 7108 return NullabilityKind::Unspecified; 7109 }; 7110 7111 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7112 NullabilityKind MergedKind; 7113 7114 // Compute nullability of a binary conditional expression. 7115 if (IsBin) { 7116 if (LHSKind == NullabilityKind::NonNull) 7117 MergedKind = NullabilityKind::NonNull; 7118 else 7119 MergedKind = RHSKind; 7120 // Compute nullability of a normal conditional expression. 7121 } else { 7122 if (LHSKind == NullabilityKind::Nullable || 7123 RHSKind == NullabilityKind::Nullable) 7124 MergedKind = NullabilityKind::Nullable; 7125 else if (LHSKind == NullabilityKind::NonNull) 7126 MergedKind = RHSKind; 7127 else if (RHSKind == NullabilityKind::NonNull) 7128 MergedKind = LHSKind; 7129 else 7130 MergedKind = NullabilityKind::Unspecified; 7131 } 7132 7133 // Return if ResTy already has the correct nullability. 7134 if (GetNullability(ResTy) == MergedKind) 7135 return ResTy; 7136 7137 // Strip all nullability from ResTy. 7138 while (ResTy->getNullability(Ctx)) 7139 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7140 7141 // Create a new AttributedType with the new nullability kind. 7142 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7143 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7144 } 7145 7146 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7147 /// in the case of a the GNU conditional expr extension. 7148 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7149 SourceLocation ColonLoc, 7150 Expr *CondExpr, Expr *LHSExpr, 7151 Expr *RHSExpr) { 7152 if (!getLangOpts().CPlusPlus) { 7153 // C cannot handle TypoExpr nodes in the condition because it 7154 // doesn't handle dependent types properly, so make sure any TypoExprs have 7155 // been dealt with before checking the operands. 7156 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7157 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7158 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7159 7160 if (!CondResult.isUsable()) 7161 return ExprError(); 7162 7163 if (LHSExpr) { 7164 if (!LHSResult.isUsable()) 7165 return ExprError(); 7166 } 7167 7168 if (!RHSResult.isUsable()) 7169 return ExprError(); 7170 7171 CondExpr = CondResult.get(); 7172 LHSExpr = LHSResult.get(); 7173 RHSExpr = RHSResult.get(); 7174 } 7175 7176 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7177 // was the condition. 7178 OpaqueValueExpr *opaqueValue = nullptr; 7179 Expr *commonExpr = nullptr; 7180 if (!LHSExpr) { 7181 commonExpr = CondExpr; 7182 // Lower out placeholder types first. This is important so that we don't 7183 // try to capture a placeholder. This happens in few cases in C++; such 7184 // as Objective-C++'s dictionary subscripting syntax. 7185 if (commonExpr->hasPlaceholderType()) { 7186 ExprResult result = CheckPlaceholderExpr(commonExpr); 7187 if (!result.isUsable()) return ExprError(); 7188 commonExpr = result.get(); 7189 } 7190 // We usually want to apply unary conversions *before* saving, except 7191 // in the special case of a C++ l-value conditional. 7192 if (!(getLangOpts().CPlusPlus 7193 && !commonExpr->isTypeDependent() 7194 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7195 && commonExpr->isGLValue() 7196 && commonExpr->isOrdinaryOrBitFieldObject() 7197 && RHSExpr->isOrdinaryOrBitFieldObject() 7198 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7199 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7200 if (commonRes.isInvalid()) 7201 return ExprError(); 7202 commonExpr = commonRes.get(); 7203 } 7204 7205 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7206 commonExpr->getType(), 7207 commonExpr->getValueKind(), 7208 commonExpr->getObjectKind(), 7209 commonExpr); 7210 LHSExpr = CondExpr = opaqueValue; 7211 } 7212 7213 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7214 ExprValueKind VK = VK_RValue; 7215 ExprObjectKind OK = OK_Ordinary; 7216 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7217 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7218 VK, OK, QuestionLoc); 7219 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7220 RHS.isInvalid()) 7221 return ExprError(); 7222 7223 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7224 RHS.get()); 7225 7226 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7227 7228 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7229 Context); 7230 7231 if (!commonExpr) 7232 return new (Context) 7233 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7234 RHS.get(), result, VK, OK); 7235 7236 return new (Context) BinaryConditionalOperator( 7237 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7238 ColonLoc, result, VK, OK); 7239 } 7240 7241 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7242 // being closely modeled after the C99 spec:-). The odd characteristic of this 7243 // routine is it effectively iqnores the qualifiers on the top level pointee. 7244 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7245 // FIXME: add a couple examples in this comment. 7246 static Sema::AssignConvertType 7247 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7248 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7249 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7250 7251 // get the "pointed to" type (ignoring qualifiers at the top level) 7252 const Type *lhptee, *rhptee; 7253 Qualifiers lhq, rhq; 7254 std::tie(lhptee, lhq) = 7255 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7256 std::tie(rhptee, rhq) = 7257 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7258 7259 Sema::AssignConvertType ConvTy = Sema::Compatible; 7260 7261 // C99 6.5.16.1p1: This following citation is common to constraints 7262 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7263 // qualifiers of the type *pointed to* by the right; 7264 7265 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7266 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7267 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7268 // Ignore lifetime for further calculation. 7269 lhq.removeObjCLifetime(); 7270 rhq.removeObjCLifetime(); 7271 } 7272 7273 if (!lhq.compatiblyIncludes(rhq)) { 7274 // Treat address-space mismatches as fatal. TODO: address subspaces 7275 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7276 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7277 7278 // It's okay to add or remove GC or lifetime qualifiers when converting to 7279 // and from void*. 7280 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7281 .compatiblyIncludes( 7282 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7283 && (lhptee->isVoidType() || rhptee->isVoidType())) 7284 ; // keep old 7285 7286 // Treat lifetime mismatches as fatal. 7287 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7288 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7289 7290 // For GCC/MS compatibility, other qualifier mismatches are treated 7291 // as still compatible in C. 7292 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7293 } 7294 7295 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7296 // incomplete type and the other is a pointer to a qualified or unqualified 7297 // version of void... 7298 if (lhptee->isVoidType()) { 7299 if (rhptee->isIncompleteOrObjectType()) 7300 return ConvTy; 7301 7302 // As an extension, we allow cast to/from void* to function pointer. 7303 assert(rhptee->isFunctionType()); 7304 return Sema::FunctionVoidPointer; 7305 } 7306 7307 if (rhptee->isVoidType()) { 7308 if (lhptee->isIncompleteOrObjectType()) 7309 return ConvTy; 7310 7311 // As an extension, we allow cast to/from void* to function pointer. 7312 assert(lhptee->isFunctionType()); 7313 return Sema::FunctionVoidPointer; 7314 } 7315 7316 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7317 // unqualified versions of compatible types, ... 7318 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7319 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7320 // Check if the pointee types are compatible ignoring the sign. 7321 // We explicitly check for char so that we catch "char" vs 7322 // "unsigned char" on systems where "char" is unsigned. 7323 if (lhptee->isCharType()) 7324 ltrans = S.Context.UnsignedCharTy; 7325 else if (lhptee->hasSignedIntegerRepresentation()) 7326 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7327 7328 if (rhptee->isCharType()) 7329 rtrans = S.Context.UnsignedCharTy; 7330 else if (rhptee->hasSignedIntegerRepresentation()) 7331 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7332 7333 if (ltrans == rtrans) { 7334 // Types are compatible ignoring the sign. Qualifier incompatibility 7335 // takes priority over sign incompatibility because the sign 7336 // warning can be disabled. 7337 if (ConvTy != Sema::Compatible) 7338 return ConvTy; 7339 7340 return Sema::IncompatiblePointerSign; 7341 } 7342 7343 // If we are a multi-level pointer, it's possible that our issue is simply 7344 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7345 // the eventual target type is the same and the pointers have the same 7346 // level of indirection, this must be the issue. 7347 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7348 do { 7349 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7350 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7351 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7352 7353 if (lhptee == rhptee) 7354 return Sema::IncompatibleNestedPointerQualifiers; 7355 } 7356 7357 // General pointer incompatibility takes priority over qualifiers. 7358 return Sema::IncompatiblePointer; 7359 } 7360 if (!S.getLangOpts().CPlusPlus && 7361 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7362 return Sema::IncompatiblePointer; 7363 return ConvTy; 7364 } 7365 7366 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7367 /// block pointer types are compatible or whether a block and normal pointer 7368 /// are compatible. It is more restrict than comparing two function pointer 7369 // types. 7370 static Sema::AssignConvertType 7371 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7372 QualType RHSType) { 7373 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7374 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7375 7376 QualType lhptee, rhptee; 7377 7378 // get the "pointed to" type (ignoring qualifiers at the top level) 7379 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7380 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7381 7382 // In C++, the types have to match exactly. 7383 if (S.getLangOpts().CPlusPlus) 7384 return Sema::IncompatibleBlockPointer; 7385 7386 Sema::AssignConvertType ConvTy = Sema::Compatible; 7387 7388 // For blocks we enforce that qualifiers are identical. 7389 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7390 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7391 if (S.getLangOpts().OpenCL) { 7392 LQuals.removeAddressSpace(); 7393 RQuals.removeAddressSpace(); 7394 } 7395 if (LQuals != RQuals) 7396 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7397 7398 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7399 return Sema::IncompatibleBlockPointer; 7400 7401 return ConvTy; 7402 } 7403 7404 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7405 /// for assignment compatibility. 7406 static Sema::AssignConvertType 7407 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7408 QualType RHSType) { 7409 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7410 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7411 7412 if (LHSType->isObjCBuiltinType()) { 7413 // Class is not compatible with ObjC object pointers. 7414 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7415 !RHSType->isObjCQualifiedClassType()) 7416 return Sema::IncompatiblePointer; 7417 return Sema::Compatible; 7418 } 7419 if (RHSType->isObjCBuiltinType()) { 7420 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7421 !LHSType->isObjCQualifiedClassType()) 7422 return Sema::IncompatiblePointer; 7423 return Sema::Compatible; 7424 } 7425 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7426 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7427 7428 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7429 // make an exception for id<P> 7430 !LHSType->isObjCQualifiedIdType()) 7431 return Sema::CompatiblePointerDiscardsQualifiers; 7432 7433 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7434 return Sema::Compatible; 7435 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7436 return Sema::IncompatibleObjCQualifiedId; 7437 return Sema::IncompatiblePointer; 7438 } 7439 7440 Sema::AssignConvertType 7441 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7442 QualType LHSType, QualType RHSType) { 7443 // Fake up an opaque expression. We don't actually care about what 7444 // cast operations are required, so if CheckAssignmentConstraints 7445 // adds casts to this they'll be wasted, but fortunately that doesn't 7446 // usually happen on valid code. 7447 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7448 ExprResult RHSPtr = &RHSExpr; 7449 CastKind K = CK_Invalid; 7450 7451 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7452 } 7453 7454 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7455 /// has code to accommodate several GCC extensions when type checking 7456 /// pointers. Here are some objectionable examples that GCC considers warnings: 7457 /// 7458 /// int a, *pint; 7459 /// short *pshort; 7460 /// struct foo *pfoo; 7461 /// 7462 /// pint = pshort; // warning: assignment from incompatible pointer type 7463 /// a = pint; // warning: assignment makes integer from pointer without a cast 7464 /// pint = a; // warning: assignment makes pointer from integer without a cast 7465 /// pint = pfoo; // warning: assignment from incompatible pointer type 7466 /// 7467 /// As a result, the code for dealing with pointers is more complex than the 7468 /// C99 spec dictates. 7469 /// 7470 /// Sets 'Kind' for any result kind except Incompatible. 7471 Sema::AssignConvertType 7472 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7473 CastKind &Kind, bool ConvertRHS) { 7474 QualType RHSType = RHS.get()->getType(); 7475 QualType OrigLHSType = LHSType; 7476 7477 // Get canonical types. We're not formatting these types, just comparing 7478 // them. 7479 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7480 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7481 7482 // Common case: no conversion required. 7483 if (LHSType == RHSType) { 7484 Kind = CK_NoOp; 7485 return Compatible; 7486 } 7487 7488 // If we have an atomic type, try a non-atomic assignment, then just add an 7489 // atomic qualification step. 7490 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7491 Sema::AssignConvertType result = 7492 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7493 if (result != Compatible) 7494 return result; 7495 if (Kind != CK_NoOp && ConvertRHS) 7496 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7497 Kind = CK_NonAtomicToAtomic; 7498 return Compatible; 7499 } 7500 7501 // If the left-hand side is a reference type, then we are in a 7502 // (rare!) case where we've allowed the use of references in C, 7503 // e.g., as a parameter type in a built-in function. In this case, 7504 // just make sure that the type referenced is compatible with the 7505 // right-hand side type. The caller is responsible for adjusting 7506 // LHSType so that the resulting expression does not have reference 7507 // type. 7508 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7509 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7510 Kind = CK_LValueBitCast; 7511 return Compatible; 7512 } 7513 return Incompatible; 7514 } 7515 7516 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7517 // to the same ExtVector type. 7518 if (LHSType->isExtVectorType()) { 7519 if (RHSType->isExtVectorType()) 7520 return Incompatible; 7521 if (RHSType->isArithmeticType()) { 7522 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7523 if (ConvertRHS) 7524 RHS = prepareVectorSplat(LHSType, RHS.get()); 7525 Kind = CK_VectorSplat; 7526 return Compatible; 7527 } 7528 } 7529 7530 // Conversions to or from vector type. 7531 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7532 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7533 // Allow assignments of an AltiVec vector type to an equivalent GCC 7534 // vector type and vice versa 7535 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7536 Kind = CK_BitCast; 7537 return Compatible; 7538 } 7539 7540 // If we are allowing lax vector conversions, and LHS and RHS are both 7541 // vectors, the total size only needs to be the same. This is a bitcast; 7542 // no bits are changed but the result type is different. 7543 if (isLaxVectorConversion(RHSType, LHSType)) { 7544 Kind = CK_BitCast; 7545 return IncompatibleVectors; 7546 } 7547 } 7548 7549 // When the RHS comes from another lax conversion (e.g. binops between 7550 // scalars and vectors) the result is canonicalized as a vector. When the 7551 // LHS is also a vector, the lax is allowed by the condition above. Handle 7552 // the case where LHS is a scalar. 7553 if (LHSType->isScalarType()) { 7554 const VectorType *VecType = RHSType->getAs<VectorType>(); 7555 if (VecType && VecType->getNumElements() == 1 && 7556 isLaxVectorConversion(RHSType, LHSType)) { 7557 ExprResult *VecExpr = &RHS; 7558 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7559 Kind = CK_BitCast; 7560 return Compatible; 7561 } 7562 } 7563 7564 return Incompatible; 7565 } 7566 7567 // Diagnose attempts to convert between __float128 and long double where 7568 // such conversions currently can't be handled. 7569 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7570 return Incompatible; 7571 7572 // Arithmetic conversions. 7573 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7574 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7575 if (ConvertRHS) 7576 Kind = PrepareScalarCast(RHS, LHSType); 7577 return Compatible; 7578 } 7579 7580 // Conversions to normal pointers. 7581 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7582 // U* -> T* 7583 if (isa<PointerType>(RHSType)) { 7584 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7585 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7586 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7587 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7588 } 7589 7590 // int -> T* 7591 if (RHSType->isIntegerType()) { 7592 Kind = CK_IntegralToPointer; // FIXME: null? 7593 return IntToPointer; 7594 } 7595 7596 // C pointers are not compatible with ObjC object pointers, 7597 // with two exceptions: 7598 if (isa<ObjCObjectPointerType>(RHSType)) { 7599 // - conversions to void* 7600 if (LHSPointer->getPointeeType()->isVoidType()) { 7601 Kind = CK_BitCast; 7602 return Compatible; 7603 } 7604 7605 // - conversions from 'Class' to the redefinition type 7606 if (RHSType->isObjCClassType() && 7607 Context.hasSameType(LHSType, 7608 Context.getObjCClassRedefinitionType())) { 7609 Kind = CK_BitCast; 7610 return Compatible; 7611 } 7612 7613 Kind = CK_BitCast; 7614 return IncompatiblePointer; 7615 } 7616 7617 // U^ -> void* 7618 if (RHSType->getAs<BlockPointerType>()) { 7619 if (LHSPointer->getPointeeType()->isVoidType()) { 7620 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7621 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7622 ->getPointeeType() 7623 .getAddressSpace(); 7624 Kind = 7625 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7626 return Compatible; 7627 } 7628 } 7629 7630 return Incompatible; 7631 } 7632 7633 // Conversions to block pointers. 7634 if (isa<BlockPointerType>(LHSType)) { 7635 // U^ -> T^ 7636 if (RHSType->isBlockPointerType()) { 7637 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>() 7638 ->getPointeeType() 7639 .getAddressSpace(); 7640 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7641 ->getPointeeType() 7642 .getAddressSpace(); 7643 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7644 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7645 } 7646 7647 // int or null -> T^ 7648 if (RHSType->isIntegerType()) { 7649 Kind = CK_IntegralToPointer; // FIXME: null 7650 return IntToBlockPointer; 7651 } 7652 7653 // id -> T^ 7654 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7655 Kind = CK_AnyPointerToBlockPointerCast; 7656 return Compatible; 7657 } 7658 7659 // void* -> T^ 7660 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7661 if (RHSPT->getPointeeType()->isVoidType()) { 7662 Kind = CK_AnyPointerToBlockPointerCast; 7663 return Compatible; 7664 } 7665 7666 return Incompatible; 7667 } 7668 7669 // Conversions to Objective-C pointers. 7670 if (isa<ObjCObjectPointerType>(LHSType)) { 7671 // A* -> B* 7672 if (RHSType->isObjCObjectPointerType()) { 7673 Kind = CK_BitCast; 7674 Sema::AssignConvertType result = 7675 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7676 if (getLangOpts().ObjCAutoRefCount && 7677 result == Compatible && 7678 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7679 result = IncompatibleObjCWeakRef; 7680 return result; 7681 } 7682 7683 // int or null -> A* 7684 if (RHSType->isIntegerType()) { 7685 Kind = CK_IntegralToPointer; // FIXME: null 7686 return IntToPointer; 7687 } 7688 7689 // In general, C pointers are not compatible with ObjC object pointers, 7690 // with two exceptions: 7691 if (isa<PointerType>(RHSType)) { 7692 Kind = CK_CPointerToObjCPointerCast; 7693 7694 // - conversions from 'void*' 7695 if (RHSType->isVoidPointerType()) { 7696 return Compatible; 7697 } 7698 7699 // - conversions to 'Class' from its redefinition type 7700 if (LHSType->isObjCClassType() && 7701 Context.hasSameType(RHSType, 7702 Context.getObjCClassRedefinitionType())) { 7703 return Compatible; 7704 } 7705 7706 return IncompatiblePointer; 7707 } 7708 7709 // Only under strict condition T^ is compatible with an Objective-C pointer. 7710 if (RHSType->isBlockPointerType() && 7711 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7712 if (ConvertRHS) 7713 maybeExtendBlockObject(RHS); 7714 Kind = CK_BlockPointerToObjCPointerCast; 7715 return Compatible; 7716 } 7717 7718 return Incompatible; 7719 } 7720 7721 // Conversions from pointers that are not covered by the above. 7722 if (isa<PointerType>(RHSType)) { 7723 // T* -> _Bool 7724 if (LHSType == Context.BoolTy) { 7725 Kind = CK_PointerToBoolean; 7726 return Compatible; 7727 } 7728 7729 // T* -> int 7730 if (LHSType->isIntegerType()) { 7731 Kind = CK_PointerToIntegral; 7732 return PointerToInt; 7733 } 7734 7735 return Incompatible; 7736 } 7737 7738 // Conversions from Objective-C pointers that are not covered by the above. 7739 if (isa<ObjCObjectPointerType>(RHSType)) { 7740 // T* -> _Bool 7741 if (LHSType == Context.BoolTy) { 7742 Kind = CK_PointerToBoolean; 7743 return Compatible; 7744 } 7745 7746 // T* -> int 7747 if (LHSType->isIntegerType()) { 7748 Kind = CK_PointerToIntegral; 7749 return PointerToInt; 7750 } 7751 7752 return Incompatible; 7753 } 7754 7755 // struct A -> struct B 7756 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7757 if (Context.typesAreCompatible(LHSType, RHSType)) { 7758 Kind = CK_NoOp; 7759 return Compatible; 7760 } 7761 } 7762 7763 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7764 Kind = CK_IntToOCLSampler; 7765 return Compatible; 7766 } 7767 7768 return Incompatible; 7769 } 7770 7771 /// \brief Constructs a transparent union from an expression that is 7772 /// used to initialize the transparent union. 7773 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7774 ExprResult &EResult, QualType UnionType, 7775 FieldDecl *Field) { 7776 // Build an initializer list that designates the appropriate member 7777 // of the transparent union. 7778 Expr *E = EResult.get(); 7779 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7780 E, SourceLocation()); 7781 Initializer->setType(UnionType); 7782 Initializer->setInitializedFieldInUnion(Field); 7783 7784 // Build a compound literal constructing a value of the transparent 7785 // union type from this initializer list. 7786 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7787 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7788 VK_RValue, Initializer, false); 7789 } 7790 7791 Sema::AssignConvertType 7792 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7793 ExprResult &RHS) { 7794 QualType RHSType = RHS.get()->getType(); 7795 7796 // If the ArgType is a Union type, we want to handle a potential 7797 // transparent_union GCC extension. 7798 const RecordType *UT = ArgType->getAsUnionType(); 7799 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7800 return Incompatible; 7801 7802 // The field to initialize within the transparent union. 7803 RecordDecl *UD = UT->getDecl(); 7804 FieldDecl *InitField = nullptr; 7805 // It's compatible if the expression matches any of the fields. 7806 for (auto *it : UD->fields()) { 7807 if (it->getType()->isPointerType()) { 7808 // If the transparent union contains a pointer type, we allow: 7809 // 1) void pointer 7810 // 2) null pointer constant 7811 if (RHSType->isPointerType()) 7812 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7813 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7814 InitField = it; 7815 break; 7816 } 7817 7818 if (RHS.get()->isNullPointerConstant(Context, 7819 Expr::NPC_ValueDependentIsNull)) { 7820 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7821 CK_NullToPointer); 7822 InitField = it; 7823 break; 7824 } 7825 } 7826 7827 CastKind Kind = CK_Invalid; 7828 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7829 == Compatible) { 7830 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7831 InitField = it; 7832 break; 7833 } 7834 } 7835 7836 if (!InitField) 7837 return Incompatible; 7838 7839 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7840 return Compatible; 7841 } 7842 7843 Sema::AssignConvertType 7844 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7845 bool Diagnose, 7846 bool DiagnoseCFAudited, 7847 bool ConvertRHS) { 7848 // We need to be able to tell the caller whether we diagnosed a problem, if 7849 // they ask us to issue diagnostics. 7850 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7851 7852 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7853 // we can't avoid *all* modifications at the moment, so we need some somewhere 7854 // to put the updated value. 7855 ExprResult LocalRHS = CallerRHS; 7856 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7857 7858 if (getLangOpts().CPlusPlus) { 7859 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7860 // C++ 5.17p3: If the left operand is not of class type, the 7861 // expression is implicitly converted (C++ 4) to the 7862 // cv-unqualified type of the left operand. 7863 QualType RHSType = RHS.get()->getType(); 7864 if (Diagnose) { 7865 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7866 AA_Assigning); 7867 } else { 7868 ImplicitConversionSequence ICS = 7869 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7870 /*SuppressUserConversions=*/false, 7871 /*AllowExplicit=*/false, 7872 /*InOverloadResolution=*/false, 7873 /*CStyle=*/false, 7874 /*AllowObjCWritebackConversion=*/false); 7875 if (ICS.isFailure()) 7876 return Incompatible; 7877 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7878 ICS, AA_Assigning); 7879 } 7880 if (RHS.isInvalid()) 7881 return Incompatible; 7882 Sema::AssignConvertType result = Compatible; 7883 if (getLangOpts().ObjCAutoRefCount && 7884 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7885 result = IncompatibleObjCWeakRef; 7886 return result; 7887 } 7888 7889 // FIXME: Currently, we fall through and treat C++ classes like C 7890 // structures. 7891 // FIXME: We also fall through for atomics; not sure what should 7892 // happen there, though. 7893 } else if (RHS.get()->getType() == Context.OverloadTy) { 7894 // As a set of extensions to C, we support overloading on functions. These 7895 // functions need to be resolved here. 7896 DeclAccessPair DAP; 7897 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7898 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7899 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7900 else 7901 return Incompatible; 7902 } 7903 7904 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7905 // a null pointer constant. 7906 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7907 LHSType->isBlockPointerType()) && 7908 RHS.get()->isNullPointerConstant(Context, 7909 Expr::NPC_ValueDependentIsNull)) { 7910 if (Diagnose || ConvertRHS) { 7911 CastKind Kind; 7912 CXXCastPath Path; 7913 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7914 /*IgnoreBaseAccess=*/false, Diagnose); 7915 if (ConvertRHS) 7916 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7917 } 7918 return Compatible; 7919 } 7920 7921 // This check seems unnatural, however it is necessary to ensure the proper 7922 // conversion of functions/arrays. If the conversion were done for all 7923 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7924 // expressions that suppress this implicit conversion (&, sizeof). 7925 // 7926 // Suppress this for references: C++ 8.5.3p5. 7927 if (!LHSType->isReferenceType()) { 7928 // FIXME: We potentially allocate here even if ConvertRHS is false. 7929 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7930 if (RHS.isInvalid()) 7931 return Incompatible; 7932 } 7933 7934 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7935 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7936 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7937 if (PDecl && !PDecl->hasDefinition()) { 7938 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7939 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7940 } 7941 } 7942 7943 CastKind Kind = CK_Invalid; 7944 Sema::AssignConvertType result = 7945 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7946 7947 // C99 6.5.16.1p2: The value of the right operand is converted to the 7948 // type of the assignment expression. 7949 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7950 // so that we can use references in built-in functions even in C. 7951 // The getNonReferenceType() call makes sure that the resulting expression 7952 // does not have reference type. 7953 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7954 QualType Ty = LHSType.getNonLValueExprType(Context); 7955 Expr *E = RHS.get(); 7956 7957 // Check for various Objective-C errors. If we are not reporting 7958 // diagnostics and just checking for errors, e.g., during overload 7959 // resolution, return Incompatible to indicate the failure. 7960 if (getLangOpts().ObjCAutoRefCount && 7961 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7962 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7963 if (!Diagnose) 7964 return Incompatible; 7965 } 7966 if (getLangOpts().ObjC1 && 7967 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7968 E->getType(), E, Diagnose) || 7969 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7970 if (!Diagnose) 7971 return Incompatible; 7972 // Replace the expression with a corrected version and continue so we 7973 // can find further errors. 7974 RHS = E; 7975 return Compatible; 7976 } 7977 7978 if (ConvertRHS) 7979 RHS = ImpCastExprToType(E, Ty, Kind); 7980 } 7981 return result; 7982 } 7983 7984 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7985 ExprResult &RHS) { 7986 Diag(Loc, diag::err_typecheck_invalid_operands) 7987 << LHS.get()->getType() << RHS.get()->getType() 7988 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7989 return QualType(); 7990 } 7991 7992 /// Try to convert a value of non-vector type to a vector type by converting 7993 /// the type to the element type of the vector and then performing a splat. 7994 /// If the language is OpenCL, we only use conversions that promote scalar 7995 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7996 /// for float->int. 7997 /// 7998 /// \param scalar - if non-null, actually perform the conversions 7999 /// \return true if the operation fails (but without diagnosing the failure) 8000 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8001 QualType scalarTy, 8002 QualType vectorEltTy, 8003 QualType vectorTy) { 8004 // The conversion to apply to the scalar before splatting it, 8005 // if necessary. 8006 CastKind scalarCast = CK_Invalid; 8007 8008 if (vectorEltTy->isIntegralType(S.Context)) { 8009 if (!scalarTy->isIntegralType(S.Context)) 8010 return true; 8011 if (S.getLangOpts().OpenCL && 8012 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 8013 return true; 8014 scalarCast = CK_IntegralCast; 8015 } else if (vectorEltTy->isRealFloatingType()) { 8016 if (scalarTy->isRealFloatingType()) { 8017 if (S.getLangOpts().OpenCL && 8018 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 8019 return true; 8020 scalarCast = CK_FloatingCast; 8021 } 8022 else if (scalarTy->isIntegralType(S.Context)) 8023 scalarCast = CK_IntegralToFloating; 8024 else 8025 return true; 8026 } else { 8027 return true; 8028 } 8029 8030 // Adjust scalar if desired. 8031 if (scalar) { 8032 if (scalarCast != CK_Invalid) 8033 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8034 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8035 } 8036 return false; 8037 } 8038 8039 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8040 SourceLocation Loc, bool IsCompAssign, 8041 bool AllowBothBool, 8042 bool AllowBoolConversions) { 8043 if (!IsCompAssign) { 8044 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8045 if (LHS.isInvalid()) 8046 return QualType(); 8047 } 8048 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8049 if (RHS.isInvalid()) 8050 return QualType(); 8051 8052 // For conversion purposes, we ignore any qualifiers. 8053 // For example, "const float" and "float" are equivalent. 8054 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8055 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8056 8057 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8058 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8059 assert(LHSVecType || RHSVecType); 8060 8061 // AltiVec-style "vector bool op vector bool" combinations are allowed 8062 // for some operators but not others. 8063 if (!AllowBothBool && 8064 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8065 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8066 return InvalidOperands(Loc, LHS, RHS); 8067 8068 // If the vector types are identical, return. 8069 if (Context.hasSameType(LHSType, RHSType)) 8070 return LHSType; 8071 8072 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8073 if (LHSVecType && RHSVecType && 8074 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8075 if (isa<ExtVectorType>(LHSVecType)) { 8076 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8077 return LHSType; 8078 } 8079 8080 if (!IsCompAssign) 8081 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8082 return RHSType; 8083 } 8084 8085 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8086 // can be mixed, with the result being the non-bool type. The non-bool 8087 // operand must have integer element type. 8088 if (AllowBoolConversions && LHSVecType && RHSVecType && 8089 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8090 (Context.getTypeSize(LHSVecType->getElementType()) == 8091 Context.getTypeSize(RHSVecType->getElementType()))) { 8092 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8093 LHSVecType->getElementType()->isIntegerType() && 8094 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8095 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8096 return LHSType; 8097 } 8098 if (!IsCompAssign && 8099 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8100 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8101 RHSVecType->getElementType()->isIntegerType()) { 8102 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8103 return RHSType; 8104 } 8105 } 8106 8107 // If there's an ext-vector type and a scalar, try to convert the scalar to 8108 // the vector element type and splat. 8109 // FIXME: this should also work for regular vector types as supported in GCC. 8110 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8111 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8112 LHSVecType->getElementType(), LHSType)) 8113 return LHSType; 8114 } 8115 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8116 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8117 LHSType, RHSVecType->getElementType(), 8118 RHSType)) 8119 return RHSType; 8120 } 8121 8122 // FIXME: The code below also handles convertion between vectors and 8123 // non-scalars, we should break this down into fine grained specific checks 8124 // and emit proper diagnostics. 8125 QualType VecType = LHSVecType ? LHSType : RHSType; 8126 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8127 QualType OtherType = LHSVecType ? RHSType : LHSType; 8128 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8129 if (isLaxVectorConversion(OtherType, VecType)) { 8130 // If we're allowing lax vector conversions, only the total (data) size 8131 // needs to be the same. For non compound assignment, if one of the types is 8132 // scalar, the result is always the vector type. 8133 if (!IsCompAssign) { 8134 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8135 return VecType; 8136 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8137 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8138 // type. Note that this is already done by non-compound assignments in 8139 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8140 // <1 x T> -> T. The result is also a vector type. 8141 } else if (OtherType->isExtVectorType() || 8142 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8143 ExprResult *RHSExpr = &RHS; 8144 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8145 return VecType; 8146 } 8147 } 8148 8149 // Okay, the expression is invalid. 8150 8151 // If there's a non-vector, non-real operand, diagnose that. 8152 if ((!RHSVecType && !RHSType->isRealType()) || 8153 (!LHSVecType && !LHSType->isRealType())) { 8154 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8155 << LHSType << RHSType 8156 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8157 return QualType(); 8158 } 8159 8160 // OpenCL V1.1 6.2.6.p1: 8161 // If the operands are of more than one vector type, then an error shall 8162 // occur. Implicit conversions between vector types are not permitted, per 8163 // section 6.2.1. 8164 if (getLangOpts().OpenCL && 8165 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8166 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8167 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8168 << RHSType; 8169 return QualType(); 8170 } 8171 8172 // Otherwise, use the generic diagnostic. 8173 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8174 << LHSType << RHSType 8175 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8176 return QualType(); 8177 } 8178 8179 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8180 // expression. These are mainly cases where the null pointer is used as an 8181 // integer instead of a pointer. 8182 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8183 SourceLocation Loc, bool IsCompare) { 8184 // The canonical way to check for a GNU null is with isNullPointerConstant, 8185 // but we use a bit of a hack here for speed; this is a relatively 8186 // hot path, and isNullPointerConstant is slow. 8187 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8188 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8189 8190 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8191 8192 // Avoid analyzing cases where the result will either be invalid (and 8193 // diagnosed as such) or entirely valid and not something to warn about. 8194 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8195 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8196 return; 8197 8198 // Comparison operations would not make sense with a null pointer no matter 8199 // what the other expression is. 8200 if (!IsCompare) { 8201 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8202 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8203 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8204 return; 8205 } 8206 8207 // The rest of the operations only make sense with a null pointer 8208 // if the other expression is a pointer. 8209 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8210 NonNullType->canDecayToPointerType()) 8211 return; 8212 8213 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8214 << LHSNull /* LHS is NULL */ << NonNullType 8215 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8216 } 8217 8218 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8219 ExprResult &RHS, 8220 SourceLocation Loc, bool IsDiv) { 8221 // Check for division/remainder by zero. 8222 llvm::APSInt RHSValue; 8223 if (!RHS.get()->isValueDependent() && 8224 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8225 S.DiagRuntimeBehavior(Loc, RHS.get(), 8226 S.PDiag(diag::warn_remainder_division_by_zero) 8227 << IsDiv << RHS.get()->getSourceRange()); 8228 } 8229 8230 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8231 SourceLocation Loc, 8232 bool IsCompAssign, bool IsDiv) { 8233 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8234 8235 if (LHS.get()->getType()->isVectorType() || 8236 RHS.get()->getType()->isVectorType()) 8237 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8238 /*AllowBothBool*/getLangOpts().AltiVec, 8239 /*AllowBoolConversions*/false); 8240 8241 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8242 if (LHS.isInvalid() || RHS.isInvalid()) 8243 return QualType(); 8244 8245 8246 if (compType.isNull() || !compType->isArithmeticType()) 8247 return InvalidOperands(Loc, LHS, RHS); 8248 if (IsDiv) 8249 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8250 return compType; 8251 } 8252 8253 QualType Sema::CheckRemainderOperands( 8254 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8255 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8256 8257 if (LHS.get()->getType()->isVectorType() || 8258 RHS.get()->getType()->isVectorType()) { 8259 if (LHS.get()->getType()->hasIntegerRepresentation() && 8260 RHS.get()->getType()->hasIntegerRepresentation()) 8261 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8262 /*AllowBothBool*/getLangOpts().AltiVec, 8263 /*AllowBoolConversions*/false); 8264 return InvalidOperands(Loc, LHS, RHS); 8265 } 8266 8267 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8268 if (LHS.isInvalid() || RHS.isInvalid()) 8269 return QualType(); 8270 8271 if (compType.isNull() || !compType->isIntegerType()) 8272 return InvalidOperands(Loc, LHS, RHS); 8273 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8274 return compType; 8275 } 8276 8277 /// \brief Diagnose invalid arithmetic on two void pointers. 8278 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8279 Expr *LHSExpr, Expr *RHSExpr) { 8280 S.Diag(Loc, S.getLangOpts().CPlusPlus 8281 ? diag::err_typecheck_pointer_arith_void_type 8282 : diag::ext_gnu_void_ptr) 8283 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8284 << RHSExpr->getSourceRange(); 8285 } 8286 8287 /// \brief Diagnose invalid arithmetic on a void pointer. 8288 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8289 Expr *Pointer) { 8290 S.Diag(Loc, S.getLangOpts().CPlusPlus 8291 ? diag::err_typecheck_pointer_arith_void_type 8292 : diag::ext_gnu_void_ptr) 8293 << 0 /* one pointer */ << Pointer->getSourceRange(); 8294 } 8295 8296 /// \brief Diagnose invalid arithmetic on two function pointers. 8297 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8298 Expr *LHS, Expr *RHS) { 8299 assert(LHS->getType()->isAnyPointerType()); 8300 assert(RHS->getType()->isAnyPointerType()); 8301 S.Diag(Loc, S.getLangOpts().CPlusPlus 8302 ? diag::err_typecheck_pointer_arith_function_type 8303 : diag::ext_gnu_ptr_func_arith) 8304 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8305 // We only show the second type if it differs from the first. 8306 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8307 RHS->getType()) 8308 << RHS->getType()->getPointeeType() 8309 << LHS->getSourceRange() << RHS->getSourceRange(); 8310 } 8311 8312 /// \brief Diagnose invalid arithmetic on a function pointer. 8313 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8314 Expr *Pointer) { 8315 assert(Pointer->getType()->isAnyPointerType()); 8316 S.Diag(Loc, S.getLangOpts().CPlusPlus 8317 ? diag::err_typecheck_pointer_arith_function_type 8318 : diag::ext_gnu_ptr_func_arith) 8319 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8320 << 0 /* one pointer, so only one type */ 8321 << Pointer->getSourceRange(); 8322 } 8323 8324 /// \brief Emit error if Operand is incomplete pointer type 8325 /// 8326 /// \returns True if pointer has incomplete type 8327 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8328 Expr *Operand) { 8329 QualType ResType = Operand->getType(); 8330 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8331 ResType = ResAtomicType->getValueType(); 8332 8333 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8334 QualType PointeeTy = ResType->getPointeeType(); 8335 return S.RequireCompleteType(Loc, PointeeTy, 8336 diag::err_typecheck_arithmetic_incomplete_type, 8337 PointeeTy, Operand->getSourceRange()); 8338 } 8339 8340 /// \brief Check the validity of an arithmetic pointer operand. 8341 /// 8342 /// If the operand has pointer type, this code will check for pointer types 8343 /// which are invalid in arithmetic operations. These will be diagnosed 8344 /// appropriately, including whether or not the use is supported as an 8345 /// extension. 8346 /// 8347 /// \returns True when the operand is valid to use (even if as an extension). 8348 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8349 Expr *Operand) { 8350 QualType ResType = Operand->getType(); 8351 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8352 ResType = ResAtomicType->getValueType(); 8353 8354 if (!ResType->isAnyPointerType()) return true; 8355 8356 QualType PointeeTy = ResType->getPointeeType(); 8357 if (PointeeTy->isVoidType()) { 8358 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8359 return !S.getLangOpts().CPlusPlus; 8360 } 8361 if (PointeeTy->isFunctionType()) { 8362 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8363 return !S.getLangOpts().CPlusPlus; 8364 } 8365 8366 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8367 8368 return true; 8369 } 8370 8371 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8372 /// operands. 8373 /// 8374 /// This routine will diagnose any invalid arithmetic on pointer operands much 8375 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8376 /// for emitting a single diagnostic even for operations where both LHS and RHS 8377 /// are (potentially problematic) pointers. 8378 /// 8379 /// \returns True when the operand is valid to use (even if as an extension). 8380 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8381 Expr *LHSExpr, Expr *RHSExpr) { 8382 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8383 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8384 if (!isLHSPointer && !isRHSPointer) return true; 8385 8386 QualType LHSPointeeTy, RHSPointeeTy; 8387 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8388 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8389 8390 // if both are pointers check if operation is valid wrt address spaces 8391 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8392 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8393 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8394 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8395 S.Diag(Loc, 8396 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8397 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8398 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8399 return false; 8400 } 8401 } 8402 8403 // Check for arithmetic on pointers to incomplete types. 8404 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8405 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8406 if (isLHSVoidPtr || isRHSVoidPtr) { 8407 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8408 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8409 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8410 8411 return !S.getLangOpts().CPlusPlus; 8412 } 8413 8414 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8415 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8416 if (isLHSFuncPtr || isRHSFuncPtr) { 8417 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8418 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8419 RHSExpr); 8420 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8421 8422 return !S.getLangOpts().CPlusPlus; 8423 } 8424 8425 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8426 return false; 8427 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8428 return false; 8429 8430 return true; 8431 } 8432 8433 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8434 /// literal. 8435 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8436 Expr *LHSExpr, Expr *RHSExpr) { 8437 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8438 Expr* IndexExpr = RHSExpr; 8439 if (!StrExpr) { 8440 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8441 IndexExpr = LHSExpr; 8442 } 8443 8444 bool IsStringPlusInt = StrExpr && 8445 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8446 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8447 return; 8448 8449 llvm::APSInt index; 8450 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8451 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8452 if (index.isNonNegative() && 8453 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8454 index.isUnsigned())) 8455 return; 8456 } 8457 8458 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8459 Self.Diag(OpLoc, diag::warn_string_plus_int) 8460 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8461 8462 // Only print a fixit for "str" + int, not for int + "str". 8463 if (IndexExpr == RHSExpr) { 8464 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8465 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8466 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8467 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8468 << FixItHint::CreateInsertion(EndLoc, "]"); 8469 } else 8470 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8471 } 8472 8473 /// \brief Emit a warning when adding a char literal to a string. 8474 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8475 Expr *LHSExpr, Expr *RHSExpr) { 8476 const Expr *StringRefExpr = LHSExpr; 8477 const CharacterLiteral *CharExpr = 8478 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8479 8480 if (!CharExpr) { 8481 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8482 StringRefExpr = RHSExpr; 8483 } 8484 8485 if (!CharExpr || !StringRefExpr) 8486 return; 8487 8488 const QualType StringType = StringRefExpr->getType(); 8489 8490 // Return if not a PointerType. 8491 if (!StringType->isAnyPointerType()) 8492 return; 8493 8494 // Return if not a CharacterType. 8495 if (!StringType->getPointeeType()->isAnyCharacterType()) 8496 return; 8497 8498 ASTContext &Ctx = Self.getASTContext(); 8499 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8500 8501 const QualType CharType = CharExpr->getType(); 8502 if (!CharType->isAnyCharacterType() && 8503 CharType->isIntegerType() && 8504 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8505 Self.Diag(OpLoc, diag::warn_string_plus_char) 8506 << DiagRange << Ctx.CharTy; 8507 } else { 8508 Self.Diag(OpLoc, diag::warn_string_plus_char) 8509 << DiagRange << CharExpr->getType(); 8510 } 8511 8512 // Only print a fixit for str + char, not for char + str. 8513 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8514 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8515 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8516 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8517 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8518 << FixItHint::CreateInsertion(EndLoc, "]"); 8519 } else { 8520 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8521 } 8522 } 8523 8524 /// \brief Emit error when two pointers are incompatible. 8525 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8526 Expr *LHSExpr, Expr *RHSExpr) { 8527 assert(LHSExpr->getType()->isAnyPointerType()); 8528 assert(RHSExpr->getType()->isAnyPointerType()); 8529 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8530 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8531 << RHSExpr->getSourceRange(); 8532 } 8533 8534 // C99 6.5.6 8535 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8536 SourceLocation Loc, BinaryOperatorKind Opc, 8537 QualType* CompLHSTy) { 8538 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8539 8540 if (LHS.get()->getType()->isVectorType() || 8541 RHS.get()->getType()->isVectorType()) { 8542 QualType compType = CheckVectorOperands( 8543 LHS, RHS, Loc, CompLHSTy, 8544 /*AllowBothBool*/getLangOpts().AltiVec, 8545 /*AllowBoolConversions*/getLangOpts().ZVector); 8546 if (CompLHSTy) *CompLHSTy = compType; 8547 return compType; 8548 } 8549 8550 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8551 if (LHS.isInvalid() || RHS.isInvalid()) 8552 return QualType(); 8553 8554 // Diagnose "string literal" '+' int and string '+' "char literal". 8555 if (Opc == BO_Add) { 8556 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8557 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8558 } 8559 8560 // handle the common case first (both operands are arithmetic). 8561 if (!compType.isNull() && compType->isArithmeticType()) { 8562 if (CompLHSTy) *CompLHSTy = compType; 8563 return compType; 8564 } 8565 8566 // Type-checking. Ultimately the pointer's going to be in PExp; 8567 // note that we bias towards the LHS being the pointer. 8568 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8569 8570 bool isObjCPointer; 8571 if (PExp->getType()->isPointerType()) { 8572 isObjCPointer = false; 8573 } else if (PExp->getType()->isObjCObjectPointerType()) { 8574 isObjCPointer = true; 8575 } else { 8576 std::swap(PExp, IExp); 8577 if (PExp->getType()->isPointerType()) { 8578 isObjCPointer = false; 8579 } else if (PExp->getType()->isObjCObjectPointerType()) { 8580 isObjCPointer = true; 8581 } else { 8582 return InvalidOperands(Loc, LHS, RHS); 8583 } 8584 } 8585 assert(PExp->getType()->isAnyPointerType()); 8586 8587 if (!IExp->getType()->isIntegerType()) 8588 return InvalidOperands(Loc, LHS, RHS); 8589 8590 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8591 return QualType(); 8592 8593 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8594 return QualType(); 8595 8596 // Check array bounds for pointer arithemtic 8597 CheckArrayAccess(PExp, IExp); 8598 8599 if (CompLHSTy) { 8600 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8601 if (LHSTy.isNull()) { 8602 LHSTy = LHS.get()->getType(); 8603 if (LHSTy->isPromotableIntegerType()) 8604 LHSTy = Context.getPromotedIntegerType(LHSTy); 8605 } 8606 *CompLHSTy = LHSTy; 8607 } 8608 8609 return PExp->getType(); 8610 } 8611 8612 // C99 6.5.6 8613 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8614 SourceLocation Loc, 8615 QualType* CompLHSTy) { 8616 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8617 8618 if (LHS.get()->getType()->isVectorType() || 8619 RHS.get()->getType()->isVectorType()) { 8620 QualType compType = CheckVectorOperands( 8621 LHS, RHS, Loc, CompLHSTy, 8622 /*AllowBothBool*/getLangOpts().AltiVec, 8623 /*AllowBoolConversions*/getLangOpts().ZVector); 8624 if (CompLHSTy) *CompLHSTy = compType; 8625 return compType; 8626 } 8627 8628 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8629 if (LHS.isInvalid() || RHS.isInvalid()) 8630 return QualType(); 8631 8632 // Enforce type constraints: C99 6.5.6p3. 8633 8634 // Handle the common case first (both operands are arithmetic). 8635 if (!compType.isNull() && compType->isArithmeticType()) { 8636 if (CompLHSTy) *CompLHSTy = compType; 8637 return compType; 8638 } 8639 8640 // Either ptr - int or ptr - ptr. 8641 if (LHS.get()->getType()->isAnyPointerType()) { 8642 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8643 8644 // Diagnose bad cases where we step over interface counts. 8645 if (LHS.get()->getType()->isObjCObjectPointerType() && 8646 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8647 return QualType(); 8648 8649 // The result type of a pointer-int computation is the pointer type. 8650 if (RHS.get()->getType()->isIntegerType()) { 8651 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8652 return QualType(); 8653 8654 // Check array bounds for pointer arithemtic 8655 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8656 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8657 8658 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8659 return LHS.get()->getType(); 8660 } 8661 8662 // Handle pointer-pointer subtractions. 8663 if (const PointerType *RHSPTy 8664 = RHS.get()->getType()->getAs<PointerType>()) { 8665 QualType rpointee = RHSPTy->getPointeeType(); 8666 8667 if (getLangOpts().CPlusPlus) { 8668 // Pointee types must be the same: C++ [expr.add] 8669 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8670 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8671 } 8672 } else { 8673 // Pointee types must be compatible C99 6.5.6p3 8674 if (!Context.typesAreCompatible( 8675 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8676 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8677 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8678 return QualType(); 8679 } 8680 } 8681 8682 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8683 LHS.get(), RHS.get())) 8684 return QualType(); 8685 8686 // The pointee type may have zero size. As an extension, a structure or 8687 // union may have zero size or an array may have zero length. In this 8688 // case subtraction does not make sense. 8689 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8690 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8691 if (ElementSize.isZero()) { 8692 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8693 << rpointee.getUnqualifiedType() 8694 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8695 } 8696 } 8697 8698 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8699 return Context.getPointerDiffType(); 8700 } 8701 } 8702 8703 return InvalidOperands(Loc, LHS, RHS); 8704 } 8705 8706 static bool isScopedEnumerationType(QualType T) { 8707 if (const EnumType *ET = T->getAs<EnumType>()) 8708 return ET->getDecl()->isScoped(); 8709 return false; 8710 } 8711 8712 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8713 SourceLocation Loc, BinaryOperatorKind Opc, 8714 QualType LHSType) { 8715 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8716 // so skip remaining warnings as we don't want to modify values within Sema. 8717 if (S.getLangOpts().OpenCL) 8718 return; 8719 8720 llvm::APSInt Right; 8721 // Check right/shifter operand 8722 if (RHS.get()->isValueDependent() || 8723 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8724 return; 8725 8726 if (Right.isNegative()) { 8727 S.DiagRuntimeBehavior(Loc, RHS.get(), 8728 S.PDiag(diag::warn_shift_negative) 8729 << RHS.get()->getSourceRange()); 8730 return; 8731 } 8732 llvm::APInt LeftBits(Right.getBitWidth(), 8733 S.Context.getTypeSize(LHS.get()->getType())); 8734 if (Right.uge(LeftBits)) { 8735 S.DiagRuntimeBehavior(Loc, RHS.get(), 8736 S.PDiag(diag::warn_shift_gt_typewidth) 8737 << RHS.get()->getSourceRange()); 8738 return; 8739 } 8740 if (Opc != BO_Shl) 8741 return; 8742 8743 // When left shifting an ICE which is signed, we can check for overflow which 8744 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8745 // integers have defined behavior modulo one more than the maximum value 8746 // representable in the result type, so never warn for those. 8747 llvm::APSInt Left; 8748 if (LHS.get()->isValueDependent() || 8749 LHSType->hasUnsignedIntegerRepresentation() || 8750 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8751 return; 8752 8753 // If LHS does not have a signed type and non-negative value 8754 // then, the behavior is undefined. Warn about it. 8755 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8756 S.DiagRuntimeBehavior(Loc, LHS.get(), 8757 S.PDiag(diag::warn_shift_lhs_negative) 8758 << LHS.get()->getSourceRange()); 8759 return; 8760 } 8761 8762 llvm::APInt ResultBits = 8763 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8764 if (LeftBits.uge(ResultBits)) 8765 return; 8766 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8767 Result = Result.shl(Right); 8768 8769 // Print the bit representation of the signed integer as an unsigned 8770 // hexadecimal number. 8771 SmallString<40> HexResult; 8772 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8773 8774 // If we are only missing a sign bit, this is less likely to result in actual 8775 // bugs -- if the result is cast back to an unsigned type, it will have the 8776 // expected value. Thus we place this behind a different warning that can be 8777 // turned off separately if needed. 8778 if (LeftBits == ResultBits - 1) { 8779 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8780 << HexResult << LHSType 8781 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8782 return; 8783 } 8784 8785 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8786 << HexResult.str() << Result.getMinSignedBits() << LHSType 8787 << Left.getBitWidth() << LHS.get()->getSourceRange() 8788 << RHS.get()->getSourceRange(); 8789 } 8790 8791 /// \brief Return the resulting type when a vector is shifted 8792 /// by a scalar or vector shift amount. 8793 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8794 SourceLocation Loc, bool IsCompAssign) { 8795 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8796 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8797 !LHS.get()->getType()->isVectorType()) { 8798 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8799 << RHS.get()->getType() << LHS.get()->getType() 8800 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8801 return QualType(); 8802 } 8803 8804 if (!IsCompAssign) { 8805 LHS = S.UsualUnaryConversions(LHS.get()); 8806 if (LHS.isInvalid()) return QualType(); 8807 } 8808 8809 RHS = S.UsualUnaryConversions(RHS.get()); 8810 if (RHS.isInvalid()) return QualType(); 8811 8812 QualType LHSType = LHS.get()->getType(); 8813 // Note that LHS might be a scalar because the routine calls not only in 8814 // OpenCL case. 8815 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8816 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8817 8818 // Note that RHS might not be a vector. 8819 QualType RHSType = RHS.get()->getType(); 8820 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8821 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8822 8823 // The operands need to be integers. 8824 if (!LHSEleType->isIntegerType()) { 8825 S.Diag(Loc, diag::err_typecheck_expect_int) 8826 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8827 return QualType(); 8828 } 8829 8830 if (!RHSEleType->isIntegerType()) { 8831 S.Diag(Loc, diag::err_typecheck_expect_int) 8832 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8833 return QualType(); 8834 } 8835 8836 if (!LHSVecTy) { 8837 assert(RHSVecTy); 8838 if (IsCompAssign) 8839 return RHSType; 8840 if (LHSEleType != RHSEleType) { 8841 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8842 LHSEleType = RHSEleType; 8843 } 8844 QualType VecTy = 8845 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8846 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8847 LHSType = VecTy; 8848 } else if (RHSVecTy) { 8849 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8850 // are applied component-wise. So if RHS is a vector, then ensure 8851 // that the number of elements is the same as LHS... 8852 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8853 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8854 << LHS.get()->getType() << RHS.get()->getType() 8855 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8856 return QualType(); 8857 } 8858 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 8859 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 8860 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 8861 if (LHSBT != RHSBT && 8862 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 8863 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 8864 << LHS.get()->getType() << RHS.get()->getType() 8865 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8866 } 8867 } 8868 } else { 8869 // ...else expand RHS to match the number of elements in LHS. 8870 QualType VecTy = 8871 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8872 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8873 } 8874 8875 return LHSType; 8876 } 8877 8878 // C99 6.5.7 8879 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8880 SourceLocation Loc, BinaryOperatorKind Opc, 8881 bool IsCompAssign) { 8882 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8883 8884 // Vector shifts promote their scalar inputs to vector type. 8885 if (LHS.get()->getType()->isVectorType() || 8886 RHS.get()->getType()->isVectorType()) { 8887 if (LangOpts.ZVector) { 8888 // The shift operators for the z vector extensions work basically 8889 // like general shifts, except that neither the LHS nor the RHS is 8890 // allowed to be a "vector bool". 8891 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8892 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8893 return InvalidOperands(Loc, LHS, RHS); 8894 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8895 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8896 return InvalidOperands(Loc, LHS, RHS); 8897 } 8898 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8899 } 8900 8901 // Shifts don't perform usual arithmetic conversions, they just do integer 8902 // promotions on each operand. C99 6.5.7p3 8903 8904 // For the LHS, do usual unary conversions, but then reset them away 8905 // if this is a compound assignment. 8906 ExprResult OldLHS = LHS; 8907 LHS = UsualUnaryConversions(LHS.get()); 8908 if (LHS.isInvalid()) 8909 return QualType(); 8910 QualType LHSType = LHS.get()->getType(); 8911 if (IsCompAssign) LHS = OldLHS; 8912 8913 // The RHS is simpler. 8914 RHS = UsualUnaryConversions(RHS.get()); 8915 if (RHS.isInvalid()) 8916 return QualType(); 8917 QualType RHSType = RHS.get()->getType(); 8918 8919 // C99 6.5.7p2: Each of the operands shall have integer type. 8920 if (!LHSType->hasIntegerRepresentation() || 8921 !RHSType->hasIntegerRepresentation()) 8922 return InvalidOperands(Loc, LHS, RHS); 8923 8924 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8925 // hasIntegerRepresentation() above instead of this. 8926 if (isScopedEnumerationType(LHSType) || 8927 isScopedEnumerationType(RHSType)) { 8928 return InvalidOperands(Loc, LHS, RHS); 8929 } 8930 // Sanity-check shift operands 8931 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8932 8933 // "The type of the result is that of the promoted left operand." 8934 return LHSType; 8935 } 8936 8937 static bool IsWithinTemplateSpecialization(Decl *D) { 8938 if (DeclContext *DC = D->getDeclContext()) { 8939 if (isa<ClassTemplateSpecializationDecl>(DC)) 8940 return true; 8941 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8942 return FD->isFunctionTemplateSpecialization(); 8943 } 8944 return false; 8945 } 8946 8947 /// If two different enums are compared, raise a warning. 8948 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8949 Expr *RHS) { 8950 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8951 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8952 8953 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8954 if (!LHSEnumType) 8955 return; 8956 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8957 if (!RHSEnumType) 8958 return; 8959 8960 // Ignore anonymous enums. 8961 if (!LHSEnumType->getDecl()->getIdentifier()) 8962 return; 8963 if (!RHSEnumType->getDecl()->getIdentifier()) 8964 return; 8965 8966 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8967 return; 8968 8969 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8970 << LHSStrippedType << RHSStrippedType 8971 << LHS->getSourceRange() << RHS->getSourceRange(); 8972 } 8973 8974 /// \brief Diagnose bad pointer comparisons. 8975 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8976 ExprResult &LHS, ExprResult &RHS, 8977 bool IsError) { 8978 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8979 : diag::ext_typecheck_comparison_of_distinct_pointers) 8980 << LHS.get()->getType() << RHS.get()->getType() 8981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8982 } 8983 8984 /// \brief Returns false if the pointers are converted to a composite type, 8985 /// true otherwise. 8986 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8987 ExprResult &LHS, ExprResult &RHS) { 8988 // C++ [expr.rel]p2: 8989 // [...] Pointer conversions (4.10) and qualification 8990 // conversions (4.4) are performed on pointer operands (or on 8991 // a pointer operand and a null pointer constant) to bring 8992 // them to their composite pointer type. [...] 8993 // 8994 // C++ [expr.eq]p1 uses the same notion for (in)equality 8995 // comparisons of pointers. 8996 8997 QualType LHSType = LHS.get()->getType(); 8998 QualType RHSType = RHS.get()->getType(); 8999 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9000 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9001 9002 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9003 if (T.isNull()) { 9004 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9005 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9006 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9007 else 9008 S.InvalidOperands(Loc, LHS, RHS); 9009 return true; 9010 } 9011 9012 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9013 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9014 return false; 9015 } 9016 9017 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9018 ExprResult &LHS, 9019 ExprResult &RHS, 9020 bool IsError) { 9021 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9022 : diag::ext_typecheck_comparison_of_fptr_to_void) 9023 << LHS.get()->getType() << RHS.get()->getType() 9024 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9025 } 9026 9027 static bool isObjCObjectLiteral(ExprResult &E) { 9028 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9029 case Stmt::ObjCArrayLiteralClass: 9030 case Stmt::ObjCDictionaryLiteralClass: 9031 case Stmt::ObjCStringLiteralClass: 9032 case Stmt::ObjCBoxedExprClass: 9033 return true; 9034 default: 9035 // Note that ObjCBoolLiteral is NOT an object literal! 9036 return false; 9037 } 9038 } 9039 9040 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9041 const ObjCObjectPointerType *Type = 9042 LHS->getType()->getAs<ObjCObjectPointerType>(); 9043 9044 // If this is not actually an Objective-C object, bail out. 9045 if (!Type) 9046 return false; 9047 9048 // Get the LHS object's interface type. 9049 QualType InterfaceType = Type->getPointeeType(); 9050 9051 // If the RHS isn't an Objective-C object, bail out. 9052 if (!RHS->getType()->isObjCObjectPointerType()) 9053 return false; 9054 9055 // Try to find the -isEqual: method. 9056 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9057 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9058 InterfaceType, 9059 /*instance=*/true); 9060 if (!Method) { 9061 if (Type->isObjCIdType()) { 9062 // For 'id', just check the global pool. 9063 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9064 /*receiverId=*/true); 9065 } else { 9066 // Check protocols. 9067 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9068 /*instance=*/true); 9069 } 9070 } 9071 9072 if (!Method) 9073 return false; 9074 9075 QualType T = Method->parameters()[0]->getType(); 9076 if (!T->isObjCObjectPointerType()) 9077 return false; 9078 9079 QualType R = Method->getReturnType(); 9080 if (!R->isScalarType()) 9081 return false; 9082 9083 return true; 9084 } 9085 9086 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9087 FromE = FromE->IgnoreParenImpCasts(); 9088 switch (FromE->getStmtClass()) { 9089 default: 9090 break; 9091 case Stmt::ObjCStringLiteralClass: 9092 // "string literal" 9093 return LK_String; 9094 case Stmt::ObjCArrayLiteralClass: 9095 // "array literal" 9096 return LK_Array; 9097 case Stmt::ObjCDictionaryLiteralClass: 9098 // "dictionary literal" 9099 return LK_Dictionary; 9100 case Stmt::BlockExprClass: 9101 return LK_Block; 9102 case Stmt::ObjCBoxedExprClass: { 9103 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9104 switch (Inner->getStmtClass()) { 9105 case Stmt::IntegerLiteralClass: 9106 case Stmt::FloatingLiteralClass: 9107 case Stmt::CharacterLiteralClass: 9108 case Stmt::ObjCBoolLiteralExprClass: 9109 case Stmt::CXXBoolLiteralExprClass: 9110 // "numeric literal" 9111 return LK_Numeric; 9112 case Stmt::ImplicitCastExprClass: { 9113 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9114 // Boolean literals can be represented by implicit casts. 9115 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9116 return LK_Numeric; 9117 break; 9118 } 9119 default: 9120 break; 9121 } 9122 return LK_Boxed; 9123 } 9124 } 9125 return LK_None; 9126 } 9127 9128 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9129 ExprResult &LHS, ExprResult &RHS, 9130 BinaryOperator::Opcode Opc){ 9131 Expr *Literal; 9132 Expr *Other; 9133 if (isObjCObjectLiteral(LHS)) { 9134 Literal = LHS.get(); 9135 Other = RHS.get(); 9136 } else { 9137 Literal = RHS.get(); 9138 Other = LHS.get(); 9139 } 9140 9141 // Don't warn on comparisons against nil. 9142 Other = Other->IgnoreParenCasts(); 9143 if (Other->isNullPointerConstant(S.getASTContext(), 9144 Expr::NPC_ValueDependentIsNotNull)) 9145 return; 9146 9147 // This should be kept in sync with warn_objc_literal_comparison. 9148 // LK_String should always be after the other literals, since it has its own 9149 // warning flag. 9150 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9151 assert(LiteralKind != Sema::LK_Block); 9152 if (LiteralKind == Sema::LK_None) { 9153 llvm_unreachable("Unknown Objective-C object literal kind"); 9154 } 9155 9156 if (LiteralKind == Sema::LK_String) 9157 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9158 << Literal->getSourceRange(); 9159 else 9160 S.Diag(Loc, diag::warn_objc_literal_comparison) 9161 << LiteralKind << Literal->getSourceRange(); 9162 9163 if (BinaryOperator::isEqualityOp(Opc) && 9164 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9165 SourceLocation Start = LHS.get()->getLocStart(); 9166 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9167 CharSourceRange OpRange = 9168 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9169 9170 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9171 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9172 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9173 << FixItHint::CreateInsertion(End, "]"); 9174 } 9175 } 9176 9177 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9178 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9179 ExprResult &RHS, SourceLocation Loc, 9180 BinaryOperatorKind Opc) { 9181 // Check that left hand side is !something. 9182 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9183 if (!UO || UO->getOpcode() != UO_LNot) return; 9184 9185 // Only check if the right hand side is non-bool arithmetic type. 9186 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9187 9188 // Make sure that the something in !something is not bool. 9189 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9190 if (SubExpr->isKnownToHaveBooleanValue()) return; 9191 9192 // Emit warning. 9193 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9194 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9195 << Loc << IsBitwiseOp; 9196 9197 // First note suggest !(x < y) 9198 SourceLocation FirstOpen = SubExpr->getLocStart(); 9199 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9200 FirstClose = S.getLocForEndOfToken(FirstClose); 9201 if (FirstClose.isInvalid()) 9202 FirstOpen = SourceLocation(); 9203 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9204 << IsBitwiseOp 9205 << FixItHint::CreateInsertion(FirstOpen, "(") 9206 << FixItHint::CreateInsertion(FirstClose, ")"); 9207 9208 // Second note suggests (!x) < y 9209 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9210 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9211 SecondClose = S.getLocForEndOfToken(SecondClose); 9212 if (SecondClose.isInvalid()) 9213 SecondOpen = SourceLocation(); 9214 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9215 << FixItHint::CreateInsertion(SecondOpen, "(") 9216 << FixItHint::CreateInsertion(SecondClose, ")"); 9217 } 9218 9219 // Get the decl for a simple expression: a reference to a variable, 9220 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9221 static ValueDecl *getCompareDecl(Expr *E) { 9222 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9223 return DR->getDecl(); 9224 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9225 if (Ivar->isFreeIvar()) 9226 return Ivar->getDecl(); 9227 } 9228 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9229 if (Mem->isImplicitAccess()) 9230 return Mem->getMemberDecl(); 9231 } 9232 return nullptr; 9233 } 9234 9235 // C99 6.5.8, C++ [expr.rel] 9236 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9237 SourceLocation Loc, BinaryOperatorKind Opc, 9238 bool IsRelational) { 9239 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9240 9241 // Handle vector comparisons separately. 9242 if (LHS.get()->getType()->isVectorType() || 9243 RHS.get()->getType()->isVectorType()) 9244 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9245 9246 QualType LHSType = LHS.get()->getType(); 9247 QualType RHSType = RHS.get()->getType(); 9248 9249 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9250 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9251 9252 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9253 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9254 9255 if (!LHSType->hasFloatingRepresentation() && 9256 !(LHSType->isBlockPointerType() && IsRelational) && 9257 !LHS.get()->getLocStart().isMacroID() && 9258 !RHS.get()->getLocStart().isMacroID() && 9259 ActiveTemplateInstantiations.empty()) { 9260 // For non-floating point types, check for self-comparisons of the form 9261 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9262 // often indicate logic errors in the program. 9263 // 9264 // NOTE: Don't warn about comparison expressions resulting from macro 9265 // expansion. Also don't warn about comparisons which are only self 9266 // comparisons within a template specialization. The warnings should catch 9267 // obvious cases in the definition of the template anyways. The idea is to 9268 // warn when the typed comparison operator will always evaluate to the same 9269 // result. 9270 ValueDecl *DL = getCompareDecl(LHSStripped); 9271 ValueDecl *DR = getCompareDecl(RHSStripped); 9272 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9273 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9274 << 0 // self- 9275 << (Opc == BO_EQ 9276 || Opc == BO_LE 9277 || Opc == BO_GE)); 9278 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9279 !DL->getType()->isReferenceType() && 9280 !DR->getType()->isReferenceType()) { 9281 // what is it always going to eval to? 9282 char always_evals_to; 9283 switch(Opc) { 9284 case BO_EQ: // e.g. array1 == array2 9285 always_evals_to = 0; // false 9286 break; 9287 case BO_NE: // e.g. array1 != array2 9288 always_evals_to = 1; // true 9289 break; 9290 default: 9291 // best we can say is 'a constant' 9292 always_evals_to = 2; // e.g. array1 <= array2 9293 break; 9294 } 9295 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9296 << 1 // array 9297 << always_evals_to); 9298 } 9299 9300 if (isa<CastExpr>(LHSStripped)) 9301 LHSStripped = LHSStripped->IgnoreParenCasts(); 9302 if (isa<CastExpr>(RHSStripped)) 9303 RHSStripped = RHSStripped->IgnoreParenCasts(); 9304 9305 // Warn about comparisons against a string constant (unless the other 9306 // operand is null), the user probably wants strcmp. 9307 Expr *literalString = nullptr; 9308 Expr *literalStringStripped = nullptr; 9309 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9310 !RHSStripped->isNullPointerConstant(Context, 9311 Expr::NPC_ValueDependentIsNull)) { 9312 literalString = LHS.get(); 9313 literalStringStripped = LHSStripped; 9314 } else if ((isa<StringLiteral>(RHSStripped) || 9315 isa<ObjCEncodeExpr>(RHSStripped)) && 9316 !LHSStripped->isNullPointerConstant(Context, 9317 Expr::NPC_ValueDependentIsNull)) { 9318 literalString = RHS.get(); 9319 literalStringStripped = RHSStripped; 9320 } 9321 9322 if (literalString) { 9323 DiagRuntimeBehavior(Loc, nullptr, 9324 PDiag(diag::warn_stringcompare) 9325 << isa<ObjCEncodeExpr>(literalStringStripped) 9326 << literalString->getSourceRange()); 9327 } 9328 } 9329 9330 // C99 6.5.8p3 / C99 6.5.9p4 9331 UsualArithmeticConversions(LHS, RHS); 9332 if (LHS.isInvalid() || RHS.isInvalid()) 9333 return QualType(); 9334 9335 LHSType = LHS.get()->getType(); 9336 RHSType = RHS.get()->getType(); 9337 9338 // The result of comparisons is 'bool' in C++, 'int' in C. 9339 QualType ResultTy = Context.getLogicalOperationType(); 9340 9341 if (IsRelational) { 9342 if (LHSType->isRealType() && RHSType->isRealType()) 9343 return ResultTy; 9344 } else { 9345 // Check for comparisons of floating point operands using != and ==. 9346 if (LHSType->hasFloatingRepresentation()) 9347 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9348 9349 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9350 return ResultTy; 9351 } 9352 9353 const Expr::NullPointerConstantKind LHSNullKind = 9354 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9355 const Expr::NullPointerConstantKind RHSNullKind = 9356 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9357 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9358 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9359 9360 if (!IsRelational && LHSIsNull != RHSIsNull) { 9361 bool IsEquality = Opc == BO_EQ; 9362 if (RHSIsNull) 9363 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9364 RHS.get()->getSourceRange()); 9365 else 9366 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9367 LHS.get()->getSourceRange()); 9368 } 9369 9370 if ((LHSType->isIntegerType() && !LHSIsNull) || 9371 (RHSType->isIntegerType() && !RHSIsNull)) { 9372 // Skip normal pointer conversion checks in this case; we have better 9373 // diagnostics for this below. 9374 } else if (getLangOpts().CPlusPlus) { 9375 // Equality comparison of a function pointer to a void pointer is invalid, 9376 // but we allow it as an extension. 9377 // FIXME: If we really want to allow this, should it be part of composite 9378 // pointer type computation so it works in conditionals too? 9379 if (!IsRelational && 9380 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9381 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9382 // This is a gcc extension compatibility comparison. 9383 // In a SFINAE context, we treat this as a hard error to maintain 9384 // conformance with the C++ standard. 9385 diagnoseFunctionPointerToVoidComparison( 9386 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9387 9388 if (isSFINAEContext()) 9389 return QualType(); 9390 9391 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9392 return ResultTy; 9393 } 9394 9395 // C++ [expr.eq]p2: 9396 // If at least one operand is a pointer [...] bring them to their 9397 // composite pointer type. 9398 // C++ [expr.rel]p2: 9399 // If both operands are pointers, [...] bring them to their composite 9400 // pointer type. 9401 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9402 (IsRelational ? 2 : 1)) { 9403 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9404 return QualType(); 9405 else 9406 return ResultTy; 9407 } 9408 } else if (LHSType->isPointerType() && 9409 RHSType->isPointerType()) { // C99 6.5.8p2 9410 // All of the following pointer-related warnings are GCC extensions, except 9411 // when handling null pointer constants. 9412 QualType LCanPointeeTy = 9413 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9414 QualType RCanPointeeTy = 9415 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9416 9417 // C99 6.5.9p2 and C99 6.5.8p2 9418 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9419 RCanPointeeTy.getUnqualifiedType())) { 9420 // Valid unless a relational comparison of function pointers 9421 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9422 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9423 << LHSType << RHSType << LHS.get()->getSourceRange() 9424 << RHS.get()->getSourceRange(); 9425 } 9426 } else if (!IsRelational && 9427 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9428 // Valid unless comparison between non-null pointer and function pointer 9429 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9430 && !LHSIsNull && !RHSIsNull) 9431 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9432 /*isError*/false); 9433 } else { 9434 // Invalid 9435 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9436 } 9437 if (LCanPointeeTy != RCanPointeeTy) { 9438 // Treat NULL constant as a special case in OpenCL. 9439 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9440 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9441 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9442 Diag(Loc, 9443 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9444 << LHSType << RHSType << 0 /* comparison */ 9445 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9446 } 9447 } 9448 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9449 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9450 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9451 : CK_BitCast; 9452 if (LHSIsNull && !RHSIsNull) 9453 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9454 else 9455 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9456 } 9457 return ResultTy; 9458 } 9459 9460 if (getLangOpts().CPlusPlus) { 9461 // C++ [expr.eq]p4: 9462 // Two operands of type std::nullptr_t or one operand of type 9463 // std::nullptr_t and the other a null pointer constant compare equal. 9464 if (!IsRelational && LHSIsNull && RHSIsNull) { 9465 if (LHSType->isNullPtrType()) { 9466 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9467 return ResultTy; 9468 } 9469 if (RHSType->isNullPtrType()) { 9470 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9471 return ResultTy; 9472 } 9473 } 9474 9475 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9476 // These aren't covered by the composite pointer type rules. 9477 if (!IsRelational && RHSType->isNullPtrType() && 9478 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9479 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9480 return ResultTy; 9481 } 9482 if (!IsRelational && LHSType->isNullPtrType() && 9483 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9484 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9485 return ResultTy; 9486 } 9487 9488 if (IsRelational && 9489 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9490 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9491 // HACK: Relational comparison of nullptr_t against a pointer type is 9492 // invalid per DR583, but we allow it within std::less<> and friends, 9493 // since otherwise common uses of it break. 9494 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9495 // friends to have std::nullptr_t overload candidates. 9496 DeclContext *DC = CurContext; 9497 if (isa<FunctionDecl>(DC)) 9498 DC = DC->getParent(); 9499 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9500 if (CTSD->isInStdNamespace() && 9501 llvm::StringSwitch<bool>(CTSD->getName()) 9502 .Cases("less", "less_equal", "greater", "greater_equal", true) 9503 .Default(false)) { 9504 if (RHSType->isNullPtrType()) 9505 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9506 else 9507 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9508 return ResultTy; 9509 } 9510 } 9511 } 9512 9513 // C++ [expr.eq]p2: 9514 // If at least one operand is a pointer to member, [...] bring them to 9515 // their composite pointer type. 9516 if (!IsRelational && 9517 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9518 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9519 return QualType(); 9520 else 9521 return ResultTy; 9522 } 9523 9524 // Handle scoped enumeration types specifically, since they don't promote 9525 // to integers. 9526 if (LHS.get()->getType()->isEnumeralType() && 9527 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9528 RHS.get()->getType())) 9529 return ResultTy; 9530 } 9531 9532 // Handle block pointer types. 9533 if (!IsRelational && LHSType->isBlockPointerType() && 9534 RHSType->isBlockPointerType()) { 9535 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9536 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9537 9538 if (!LHSIsNull && !RHSIsNull && 9539 !Context.typesAreCompatible(lpointee, rpointee)) { 9540 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9541 << LHSType << RHSType << LHS.get()->getSourceRange() 9542 << RHS.get()->getSourceRange(); 9543 } 9544 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9545 return ResultTy; 9546 } 9547 9548 // Allow block pointers to be compared with null pointer constants. 9549 if (!IsRelational 9550 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9551 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9552 if (!LHSIsNull && !RHSIsNull) { 9553 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9554 ->getPointeeType()->isVoidType()) 9555 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9556 ->getPointeeType()->isVoidType()))) 9557 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9558 << LHSType << RHSType << LHS.get()->getSourceRange() 9559 << RHS.get()->getSourceRange(); 9560 } 9561 if (LHSIsNull && !RHSIsNull) 9562 LHS = ImpCastExprToType(LHS.get(), RHSType, 9563 RHSType->isPointerType() ? CK_BitCast 9564 : CK_AnyPointerToBlockPointerCast); 9565 else 9566 RHS = ImpCastExprToType(RHS.get(), LHSType, 9567 LHSType->isPointerType() ? CK_BitCast 9568 : CK_AnyPointerToBlockPointerCast); 9569 return ResultTy; 9570 } 9571 9572 if (LHSType->isObjCObjectPointerType() || 9573 RHSType->isObjCObjectPointerType()) { 9574 const PointerType *LPT = LHSType->getAs<PointerType>(); 9575 const PointerType *RPT = RHSType->getAs<PointerType>(); 9576 if (LPT || RPT) { 9577 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9578 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9579 9580 if (!LPtrToVoid && !RPtrToVoid && 9581 !Context.typesAreCompatible(LHSType, RHSType)) { 9582 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9583 /*isError*/false); 9584 } 9585 if (LHSIsNull && !RHSIsNull) { 9586 Expr *E = LHS.get(); 9587 if (getLangOpts().ObjCAutoRefCount) 9588 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9589 LHS = ImpCastExprToType(E, RHSType, 9590 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9591 } 9592 else { 9593 Expr *E = RHS.get(); 9594 if (getLangOpts().ObjCAutoRefCount) 9595 CheckObjCARCConversion(SourceRange(), LHSType, E, 9596 CCK_ImplicitConversion, /*Diagnose=*/true, 9597 /*DiagnoseCFAudited=*/false, Opc); 9598 RHS = ImpCastExprToType(E, LHSType, 9599 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9600 } 9601 return ResultTy; 9602 } 9603 if (LHSType->isObjCObjectPointerType() && 9604 RHSType->isObjCObjectPointerType()) { 9605 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9606 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9607 /*isError*/false); 9608 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9609 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9610 9611 if (LHSIsNull && !RHSIsNull) 9612 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9613 else 9614 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9615 return ResultTy; 9616 } 9617 } 9618 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9619 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9620 unsigned DiagID = 0; 9621 bool isError = false; 9622 if (LangOpts.DebuggerSupport) { 9623 // Under a debugger, allow the comparison of pointers to integers, 9624 // since users tend to want to compare addresses. 9625 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9626 (RHSIsNull && RHSType->isIntegerType())) { 9627 if (IsRelational) { 9628 isError = getLangOpts().CPlusPlus; 9629 DiagID = 9630 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9631 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9632 } 9633 } else if (getLangOpts().CPlusPlus) { 9634 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9635 isError = true; 9636 } else if (IsRelational) 9637 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9638 else 9639 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9640 9641 if (DiagID) { 9642 Diag(Loc, DiagID) 9643 << LHSType << RHSType << LHS.get()->getSourceRange() 9644 << RHS.get()->getSourceRange(); 9645 if (isError) 9646 return QualType(); 9647 } 9648 9649 if (LHSType->isIntegerType()) 9650 LHS = ImpCastExprToType(LHS.get(), RHSType, 9651 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9652 else 9653 RHS = ImpCastExprToType(RHS.get(), LHSType, 9654 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9655 return ResultTy; 9656 } 9657 9658 // Handle block pointers. 9659 if (!IsRelational && RHSIsNull 9660 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9661 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9662 return ResultTy; 9663 } 9664 if (!IsRelational && LHSIsNull 9665 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9666 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9667 return ResultTy; 9668 } 9669 9670 if (getLangOpts().OpenCLVersion >= 200) { 9671 if (LHSIsNull && RHSType->isQueueT()) { 9672 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9673 return ResultTy; 9674 } 9675 9676 if (LHSType->isQueueT() && RHSIsNull) { 9677 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9678 return ResultTy; 9679 } 9680 } 9681 9682 return InvalidOperands(Loc, LHS, RHS); 9683 } 9684 9685 9686 // Return a signed type that is of identical size and number of elements. 9687 // For floating point vectors, return an integer type of identical size 9688 // and number of elements. 9689 QualType Sema::GetSignedVectorType(QualType V) { 9690 const VectorType *VTy = V->getAs<VectorType>(); 9691 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9692 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9693 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9694 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9695 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9696 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9697 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9698 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9699 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9700 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9701 "Unhandled vector element size in vector compare"); 9702 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9703 } 9704 9705 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9706 /// operates on extended vector types. Instead of producing an IntTy result, 9707 /// like a scalar comparison, a vector comparison produces a vector of integer 9708 /// types. 9709 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9710 SourceLocation Loc, 9711 bool IsRelational) { 9712 // Check to make sure we're operating on vectors of the same type and width, 9713 // Allowing one side to be a scalar of element type. 9714 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9715 /*AllowBothBool*/true, 9716 /*AllowBoolConversions*/getLangOpts().ZVector); 9717 if (vType.isNull()) 9718 return vType; 9719 9720 QualType LHSType = LHS.get()->getType(); 9721 9722 // If AltiVec, the comparison results in a numeric type, i.e. 9723 // bool for C++, int for C 9724 if (getLangOpts().AltiVec && 9725 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9726 return Context.getLogicalOperationType(); 9727 9728 // For non-floating point types, check for self-comparisons of the form 9729 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9730 // often indicate logic errors in the program. 9731 if (!LHSType->hasFloatingRepresentation() && 9732 ActiveTemplateInstantiations.empty()) { 9733 if (DeclRefExpr* DRL 9734 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9735 if (DeclRefExpr* DRR 9736 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9737 if (DRL->getDecl() == DRR->getDecl()) 9738 DiagRuntimeBehavior(Loc, nullptr, 9739 PDiag(diag::warn_comparison_always) 9740 << 0 // self- 9741 << 2 // "a constant" 9742 ); 9743 } 9744 9745 // Check for comparisons of floating point operands using != and ==. 9746 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9747 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9748 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9749 } 9750 9751 // Return a signed type for the vector. 9752 return GetSignedVectorType(vType); 9753 } 9754 9755 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9756 SourceLocation Loc) { 9757 // Ensure that either both operands are of the same vector type, or 9758 // one operand is of a vector type and the other is of its element type. 9759 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9760 /*AllowBothBool*/true, 9761 /*AllowBoolConversions*/false); 9762 if (vType.isNull()) 9763 return InvalidOperands(Loc, LHS, RHS); 9764 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9765 vType->hasFloatingRepresentation()) 9766 return InvalidOperands(Loc, LHS, RHS); 9767 9768 return GetSignedVectorType(LHS.get()->getType()); 9769 } 9770 9771 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 9772 SourceLocation Loc, 9773 BinaryOperatorKind Opc) { 9774 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9775 9776 bool IsCompAssign = 9777 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 9778 9779 if (LHS.get()->getType()->isVectorType() || 9780 RHS.get()->getType()->isVectorType()) { 9781 if (LHS.get()->getType()->hasIntegerRepresentation() && 9782 RHS.get()->getType()->hasIntegerRepresentation()) 9783 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9784 /*AllowBothBool*/true, 9785 /*AllowBoolConversions*/getLangOpts().ZVector); 9786 return InvalidOperands(Loc, LHS, RHS); 9787 } 9788 9789 if (Opc == BO_And) 9790 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9791 9792 ExprResult LHSResult = LHS, RHSResult = RHS; 9793 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9794 IsCompAssign); 9795 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9796 return QualType(); 9797 LHS = LHSResult.get(); 9798 RHS = RHSResult.get(); 9799 9800 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9801 return compType; 9802 return InvalidOperands(Loc, LHS, RHS); 9803 } 9804 9805 // C99 6.5.[13,14] 9806 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9807 SourceLocation Loc, 9808 BinaryOperatorKind Opc) { 9809 // Check vector operands differently. 9810 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9811 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9812 9813 // Diagnose cases where the user write a logical and/or but probably meant a 9814 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9815 // is a constant. 9816 if (LHS.get()->getType()->isIntegerType() && 9817 !LHS.get()->getType()->isBooleanType() && 9818 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9819 // Don't warn in macros or template instantiations. 9820 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9821 // If the RHS can be constant folded, and if it constant folds to something 9822 // that isn't 0 or 1 (which indicate a potential logical operation that 9823 // happened to fold to true/false) then warn. 9824 // Parens on the RHS are ignored. 9825 llvm::APSInt Result; 9826 if (RHS.get()->EvaluateAsInt(Result, Context)) 9827 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9828 !RHS.get()->getExprLoc().isMacroID()) || 9829 (Result != 0 && Result != 1)) { 9830 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9831 << RHS.get()->getSourceRange() 9832 << (Opc == BO_LAnd ? "&&" : "||"); 9833 // Suggest replacing the logical operator with the bitwise version 9834 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9835 << (Opc == BO_LAnd ? "&" : "|") 9836 << FixItHint::CreateReplacement(SourceRange( 9837 Loc, getLocForEndOfToken(Loc)), 9838 Opc == BO_LAnd ? "&" : "|"); 9839 if (Opc == BO_LAnd) 9840 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9841 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9842 << FixItHint::CreateRemoval( 9843 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9844 RHS.get()->getLocEnd())); 9845 } 9846 } 9847 9848 if (!Context.getLangOpts().CPlusPlus) { 9849 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9850 // not operate on the built-in scalar and vector float types. 9851 if (Context.getLangOpts().OpenCL && 9852 Context.getLangOpts().OpenCLVersion < 120) { 9853 if (LHS.get()->getType()->isFloatingType() || 9854 RHS.get()->getType()->isFloatingType()) 9855 return InvalidOperands(Loc, LHS, RHS); 9856 } 9857 9858 LHS = UsualUnaryConversions(LHS.get()); 9859 if (LHS.isInvalid()) 9860 return QualType(); 9861 9862 RHS = UsualUnaryConversions(RHS.get()); 9863 if (RHS.isInvalid()) 9864 return QualType(); 9865 9866 if (!LHS.get()->getType()->isScalarType() || 9867 !RHS.get()->getType()->isScalarType()) 9868 return InvalidOperands(Loc, LHS, RHS); 9869 9870 return Context.IntTy; 9871 } 9872 9873 // The following is safe because we only use this method for 9874 // non-overloadable operands. 9875 9876 // C++ [expr.log.and]p1 9877 // C++ [expr.log.or]p1 9878 // The operands are both contextually converted to type bool. 9879 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9880 if (LHSRes.isInvalid()) 9881 return InvalidOperands(Loc, LHS, RHS); 9882 LHS = LHSRes; 9883 9884 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9885 if (RHSRes.isInvalid()) 9886 return InvalidOperands(Loc, LHS, RHS); 9887 RHS = RHSRes; 9888 9889 // C++ [expr.log.and]p2 9890 // C++ [expr.log.or]p2 9891 // The result is a bool. 9892 return Context.BoolTy; 9893 } 9894 9895 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9896 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9897 if (!ME) return false; 9898 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9899 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 9900 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 9901 if (!Base) return false; 9902 return Base->getMethodDecl() != nullptr; 9903 } 9904 9905 /// Is the given expression (which must be 'const') a reference to a 9906 /// variable which was originally non-const, but which has become 9907 /// 'const' due to being captured within a block? 9908 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9909 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9910 assert(E->isLValue() && E->getType().isConstQualified()); 9911 E = E->IgnoreParens(); 9912 9913 // Must be a reference to a declaration from an enclosing scope. 9914 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9915 if (!DRE) return NCCK_None; 9916 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9917 9918 // The declaration must be a variable which is not declared 'const'. 9919 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9920 if (!var) return NCCK_None; 9921 if (var->getType().isConstQualified()) return NCCK_None; 9922 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9923 9924 // Decide whether the first capture was for a block or a lambda. 9925 DeclContext *DC = S.CurContext, *Prev = nullptr; 9926 // Decide whether the first capture was for a block or a lambda. 9927 while (DC) { 9928 // For init-capture, it is possible that the variable belongs to the 9929 // template pattern of the current context. 9930 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9931 if (var->isInitCapture() && 9932 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9933 break; 9934 if (DC == var->getDeclContext()) 9935 break; 9936 Prev = DC; 9937 DC = DC->getParent(); 9938 } 9939 // Unless we have an init-capture, we've gone one step too far. 9940 if (!var->isInitCapture()) 9941 DC = Prev; 9942 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9943 } 9944 9945 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9946 Ty = Ty.getNonReferenceType(); 9947 if (IsDereference && Ty->isPointerType()) 9948 Ty = Ty->getPointeeType(); 9949 return !Ty.isConstQualified(); 9950 } 9951 9952 /// Emit the "read-only variable not assignable" error and print notes to give 9953 /// more information about why the variable is not assignable, such as pointing 9954 /// to the declaration of a const variable, showing that a method is const, or 9955 /// that the function is returning a const reference. 9956 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9957 SourceLocation Loc) { 9958 // Update err_typecheck_assign_const and note_typecheck_assign_const 9959 // when this enum is changed. 9960 enum { 9961 ConstFunction, 9962 ConstVariable, 9963 ConstMember, 9964 ConstMethod, 9965 ConstUnknown, // Keep as last element 9966 }; 9967 9968 SourceRange ExprRange = E->getSourceRange(); 9969 9970 // Only emit one error on the first const found. All other consts will emit 9971 // a note to the error. 9972 bool DiagnosticEmitted = false; 9973 9974 // Track if the current expression is the result of a dereference, and if the 9975 // next checked expression is the result of a dereference. 9976 bool IsDereference = false; 9977 bool NextIsDereference = false; 9978 9979 // Loop to process MemberExpr chains. 9980 while (true) { 9981 IsDereference = NextIsDereference; 9982 9983 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 9984 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9985 NextIsDereference = ME->isArrow(); 9986 const ValueDecl *VD = ME->getMemberDecl(); 9987 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9988 // Mutable fields can be modified even if the class is const. 9989 if (Field->isMutable()) { 9990 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9991 break; 9992 } 9993 9994 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9995 if (!DiagnosticEmitted) { 9996 S.Diag(Loc, diag::err_typecheck_assign_const) 9997 << ExprRange << ConstMember << false /*static*/ << Field 9998 << Field->getType(); 9999 DiagnosticEmitted = true; 10000 } 10001 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10002 << ConstMember << false /*static*/ << Field << Field->getType() 10003 << Field->getSourceRange(); 10004 } 10005 E = ME->getBase(); 10006 continue; 10007 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10008 if (VDecl->getType().isConstQualified()) { 10009 if (!DiagnosticEmitted) { 10010 S.Diag(Loc, diag::err_typecheck_assign_const) 10011 << ExprRange << ConstMember << true /*static*/ << VDecl 10012 << VDecl->getType(); 10013 DiagnosticEmitted = true; 10014 } 10015 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10016 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10017 << VDecl->getSourceRange(); 10018 } 10019 // Static fields do not inherit constness from parents. 10020 break; 10021 } 10022 break; 10023 } // End MemberExpr 10024 break; 10025 } 10026 10027 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10028 // Function calls 10029 const FunctionDecl *FD = CE->getDirectCallee(); 10030 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10031 if (!DiagnosticEmitted) { 10032 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10033 << ConstFunction << FD; 10034 DiagnosticEmitted = true; 10035 } 10036 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10037 diag::note_typecheck_assign_const) 10038 << ConstFunction << FD << FD->getReturnType() 10039 << FD->getReturnTypeSourceRange(); 10040 } 10041 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10042 // Point to variable declaration. 10043 if (const ValueDecl *VD = DRE->getDecl()) { 10044 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10045 if (!DiagnosticEmitted) { 10046 S.Diag(Loc, diag::err_typecheck_assign_const) 10047 << ExprRange << ConstVariable << VD << VD->getType(); 10048 DiagnosticEmitted = true; 10049 } 10050 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10051 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10052 } 10053 } 10054 } else if (isa<CXXThisExpr>(E)) { 10055 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10056 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10057 if (MD->isConst()) { 10058 if (!DiagnosticEmitted) { 10059 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10060 << ConstMethod << MD; 10061 DiagnosticEmitted = true; 10062 } 10063 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10064 << ConstMethod << MD << MD->getSourceRange(); 10065 } 10066 } 10067 } 10068 } 10069 10070 if (DiagnosticEmitted) 10071 return; 10072 10073 // Can't determine a more specific message, so display the generic error. 10074 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10075 } 10076 10077 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10078 /// emit an error and return true. If so, return false. 10079 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10080 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10081 10082 S.CheckShadowingDeclModification(E, Loc); 10083 10084 SourceLocation OrigLoc = Loc; 10085 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10086 &Loc); 10087 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10088 IsLV = Expr::MLV_InvalidMessageExpression; 10089 if (IsLV == Expr::MLV_Valid) 10090 return false; 10091 10092 unsigned DiagID = 0; 10093 bool NeedType = false; 10094 switch (IsLV) { // C99 6.5.16p2 10095 case Expr::MLV_ConstQualified: 10096 // Use a specialized diagnostic when we're assigning to an object 10097 // from an enclosing function or block. 10098 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10099 if (NCCK == NCCK_Block) 10100 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10101 else 10102 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10103 break; 10104 } 10105 10106 // In ARC, use some specialized diagnostics for occasions where we 10107 // infer 'const'. These are always pseudo-strong variables. 10108 if (S.getLangOpts().ObjCAutoRefCount) { 10109 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10110 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10111 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10112 10113 // Use the normal diagnostic if it's pseudo-__strong but the 10114 // user actually wrote 'const'. 10115 if (var->isARCPseudoStrong() && 10116 (!var->getTypeSourceInfo() || 10117 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10118 // There are two pseudo-strong cases: 10119 // - self 10120 ObjCMethodDecl *method = S.getCurMethodDecl(); 10121 if (method && var == method->getSelfDecl()) 10122 DiagID = method->isClassMethod() 10123 ? diag::err_typecheck_arc_assign_self_class_method 10124 : diag::err_typecheck_arc_assign_self; 10125 10126 // - fast enumeration variables 10127 else 10128 DiagID = diag::err_typecheck_arr_assign_enumeration; 10129 10130 SourceRange Assign; 10131 if (Loc != OrigLoc) 10132 Assign = SourceRange(OrigLoc, OrigLoc); 10133 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10134 // We need to preserve the AST regardless, so migration tool 10135 // can do its job. 10136 return false; 10137 } 10138 } 10139 } 10140 10141 // If none of the special cases above are triggered, then this is a 10142 // simple const assignment. 10143 if (DiagID == 0) { 10144 DiagnoseConstAssignment(S, E, Loc); 10145 return true; 10146 } 10147 10148 break; 10149 case Expr::MLV_ConstAddrSpace: 10150 DiagnoseConstAssignment(S, E, Loc); 10151 return true; 10152 case Expr::MLV_ArrayType: 10153 case Expr::MLV_ArrayTemporary: 10154 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10155 NeedType = true; 10156 break; 10157 case Expr::MLV_NotObjectType: 10158 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10159 NeedType = true; 10160 break; 10161 case Expr::MLV_LValueCast: 10162 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10163 break; 10164 case Expr::MLV_Valid: 10165 llvm_unreachable("did not take early return for MLV_Valid"); 10166 case Expr::MLV_InvalidExpression: 10167 case Expr::MLV_MemberFunction: 10168 case Expr::MLV_ClassTemporary: 10169 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10170 break; 10171 case Expr::MLV_IncompleteType: 10172 case Expr::MLV_IncompleteVoidType: 10173 return S.RequireCompleteType(Loc, E->getType(), 10174 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10175 case Expr::MLV_DuplicateVectorComponents: 10176 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10177 break; 10178 case Expr::MLV_NoSetterProperty: 10179 llvm_unreachable("readonly properties should be processed differently"); 10180 case Expr::MLV_InvalidMessageExpression: 10181 DiagID = diag::err_readonly_message_assignment; 10182 break; 10183 case Expr::MLV_SubObjCPropertySetting: 10184 DiagID = diag::err_no_subobject_property_setting; 10185 break; 10186 } 10187 10188 SourceRange Assign; 10189 if (Loc != OrigLoc) 10190 Assign = SourceRange(OrigLoc, OrigLoc); 10191 if (NeedType) 10192 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10193 else 10194 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10195 return true; 10196 } 10197 10198 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10199 SourceLocation Loc, 10200 Sema &Sema) { 10201 // C / C++ fields 10202 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10203 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10204 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10205 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10206 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10207 } 10208 10209 // Objective-C instance variables 10210 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10211 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10212 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10213 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10214 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10215 if (RL && RR && RL->getDecl() == RR->getDecl()) 10216 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10217 } 10218 } 10219 10220 // C99 6.5.16.1 10221 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10222 SourceLocation Loc, 10223 QualType CompoundType) { 10224 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10225 10226 // Verify that LHS is a modifiable lvalue, and emit error if not. 10227 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10228 return QualType(); 10229 10230 QualType LHSType = LHSExpr->getType(); 10231 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10232 CompoundType; 10233 // OpenCL v1.2 s6.1.1.1 p2: 10234 // The half data type can only be used to declare a pointer to a buffer that 10235 // contains half values 10236 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10237 LHSType->isHalfType()) { 10238 Diag(Loc, diag::err_opencl_half_load_store) << 1 10239 << LHSType.getUnqualifiedType(); 10240 return QualType(); 10241 } 10242 10243 AssignConvertType ConvTy; 10244 if (CompoundType.isNull()) { 10245 Expr *RHSCheck = RHS.get(); 10246 10247 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10248 10249 QualType LHSTy(LHSType); 10250 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10251 if (RHS.isInvalid()) 10252 return QualType(); 10253 // Special case of NSObject attributes on c-style pointer types. 10254 if (ConvTy == IncompatiblePointer && 10255 ((Context.isObjCNSObjectType(LHSType) && 10256 RHSType->isObjCObjectPointerType()) || 10257 (Context.isObjCNSObjectType(RHSType) && 10258 LHSType->isObjCObjectPointerType()))) 10259 ConvTy = Compatible; 10260 10261 if (ConvTy == Compatible && 10262 LHSType->isObjCObjectType()) 10263 Diag(Loc, diag::err_objc_object_assignment) 10264 << LHSType; 10265 10266 // If the RHS is a unary plus or minus, check to see if they = and + are 10267 // right next to each other. If so, the user may have typo'd "x =+ 4" 10268 // instead of "x += 4". 10269 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10270 RHSCheck = ICE->getSubExpr(); 10271 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10272 if ((UO->getOpcode() == UO_Plus || 10273 UO->getOpcode() == UO_Minus) && 10274 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10275 // Only if the two operators are exactly adjacent. 10276 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10277 // And there is a space or other character before the subexpr of the 10278 // unary +/-. We don't want to warn on "x=-1". 10279 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10280 UO->getSubExpr()->getLocStart().isFileID()) { 10281 Diag(Loc, diag::warn_not_compound_assign) 10282 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10283 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10284 } 10285 } 10286 10287 if (ConvTy == Compatible) { 10288 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10289 // Warn about retain cycles where a block captures the LHS, but 10290 // not if the LHS is a simple variable into which the block is 10291 // being stored...unless that variable can be captured by reference! 10292 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10293 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10294 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10295 checkRetainCycles(LHSExpr, RHS.get()); 10296 10297 // It is safe to assign a weak reference into a strong variable. 10298 // Although this code can still have problems: 10299 // id x = self.weakProp; 10300 // id y = self.weakProp; 10301 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10302 // paths through the function. This should be revisited if 10303 // -Wrepeated-use-of-weak is made flow-sensitive. 10304 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10305 RHS.get()->getLocStart())) 10306 getCurFunction()->markSafeWeakUse(RHS.get()); 10307 10308 } else if (getLangOpts().ObjCAutoRefCount) { 10309 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10310 } 10311 } 10312 } else { 10313 // Compound assignment "x += y" 10314 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10315 } 10316 10317 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10318 RHS.get(), AA_Assigning)) 10319 return QualType(); 10320 10321 CheckForNullPointerDereference(*this, LHSExpr); 10322 10323 // C99 6.5.16p3: The type of an assignment expression is the type of the 10324 // left operand unless the left operand has qualified type, in which case 10325 // it is the unqualified version of the type of the left operand. 10326 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10327 // is converted to the type of the assignment expression (above). 10328 // C++ 5.17p1: the type of the assignment expression is that of its left 10329 // operand. 10330 return (getLangOpts().CPlusPlus 10331 ? LHSType : LHSType.getUnqualifiedType()); 10332 } 10333 10334 // Only ignore explicit casts to void. 10335 static bool IgnoreCommaOperand(const Expr *E) { 10336 E = E->IgnoreParens(); 10337 10338 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10339 if (CE->getCastKind() == CK_ToVoid) { 10340 return true; 10341 } 10342 } 10343 10344 return false; 10345 } 10346 10347 // Look for instances where it is likely the comma operator is confused with 10348 // another operator. There is a whitelist of acceptable expressions for the 10349 // left hand side of the comma operator, otherwise emit a warning. 10350 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10351 // No warnings in macros 10352 if (Loc.isMacroID()) 10353 return; 10354 10355 // Don't warn in template instantiations. 10356 if (!ActiveTemplateInstantiations.empty()) 10357 return; 10358 10359 // Scope isn't fine-grained enough to whitelist the specific cases, so 10360 // instead, skip more than needed, then call back into here with the 10361 // CommaVisitor in SemaStmt.cpp. 10362 // The whitelisted locations are the initialization and increment portions 10363 // of a for loop. The additional checks are on the condition of 10364 // if statements, do/while loops, and for loops. 10365 const unsigned ForIncrementFlags = 10366 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10367 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10368 const unsigned ScopeFlags = getCurScope()->getFlags(); 10369 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10370 (ScopeFlags & ForInitFlags) == ForInitFlags) 10371 return; 10372 10373 // If there are multiple comma operators used together, get the RHS of the 10374 // of the comma operator as the LHS. 10375 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10376 if (BO->getOpcode() != BO_Comma) 10377 break; 10378 LHS = BO->getRHS(); 10379 } 10380 10381 // Only allow some expressions on LHS to not warn. 10382 if (IgnoreCommaOperand(LHS)) 10383 return; 10384 10385 Diag(Loc, diag::warn_comma_operator); 10386 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10387 << LHS->getSourceRange() 10388 << FixItHint::CreateInsertion(LHS->getLocStart(), 10389 LangOpts.CPlusPlus ? "static_cast<void>(" 10390 : "(void)(") 10391 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10392 ")"); 10393 } 10394 10395 // C99 6.5.17 10396 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10397 SourceLocation Loc) { 10398 LHS = S.CheckPlaceholderExpr(LHS.get()); 10399 RHS = S.CheckPlaceholderExpr(RHS.get()); 10400 if (LHS.isInvalid() || RHS.isInvalid()) 10401 return QualType(); 10402 10403 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10404 // operands, but not unary promotions. 10405 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10406 10407 // So we treat the LHS as a ignored value, and in C++ we allow the 10408 // containing site to determine what should be done with the RHS. 10409 LHS = S.IgnoredValueConversions(LHS.get()); 10410 if (LHS.isInvalid()) 10411 return QualType(); 10412 10413 S.DiagnoseUnusedExprResult(LHS.get()); 10414 10415 if (!S.getLangOpts().CPlusPlus) { 10416 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10417 if (RHS.isInvalid()) 10418 return QualType(); 10419 if (!RHS.get()->getType()->isVoidType()) 10420 S.RequireCompleteType(Loc, RHS.get()->getType(), 10421 diag::err_incomplete_type); 10422 } 10423 10424 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10425 S.DiagnoseCommaOperator(LHS.get(), Loc); 10426 10427 return RHS.get()->getType(); 10428 } 10429 10430 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10431 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10432 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10433 ExprValueKind &VK, 10434 ExprObjectKind &OK, 10435 SourceLocation OpLoc, 10436 bool IsInc, bool IsPrefix) { 10437 if (Op->isTypeDependent()) 10438 return S.Context.DependentTy; 10439 10440 QualType ResType = Op->getType(); 10441 // Atomic types can be used for increment / decrement where the non-atomic 10442 // versions can, so ignore the _Atomic() specifier for the purpose of 10443 // checking. 10444 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10445 ResType = ResAtomicType->getValueType(); 10446 10447 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10448 10449 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10450 // Decrement of bool is not allowed. 10451 if (!IsInc) { 10452 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10453 return QualType(); 10454 } 10455 // Increment of bool sets it to true, but is deprecated. 10456 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10457 : diag::warn_increment_bool) 10458 << Op->getSourceRange(); 10459 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10460 // Error on enum increments and decrements in C++ mode 10461 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10462 return QualType(); 10463 } else if (ResType->isRealType()) { 10464 // OK! 10465 } else if (ResType->isPointerType()) { 10466 // C99 6.5.2.4p2, 6.5.6p2 10467 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10468 return QualType(); 10469 } else if (ResType->isObjCObjectPointerType()) { 10470 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10471 // Otherwise, we just need a complete type. 10472 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10473 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10474 return QualType(); 10475 } else if (ResType->isAnyComplexType()) { 10476 // C99 does not support ++/-- on complex types, we allow as an extension. 10477 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10478 << ResType << Op->getSourceRange(); 10479 } else if (ResType->isPlaceholderType()) { 10480 ExprResult PR = S.CheckPlaceholderExpr(Op); 10481 if (PR.isInvalid()) return QualType(); 10482 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10483 IsInc, IsPrefix); 10484 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10485 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10486 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10487 (ResType->getAs<VectorType>()->getVectorKind() != 10488 VectorType::AltiVecBool)) { 10489 // The z vector extensions allow ++ and -- for non-bool vectors. 10490 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10491 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10492 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10493 } else { 10494 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10495 << ResType << int(IsInc) << Op->getSourceRange(); 10496 return QualType(); 10497 } 10498 // At this point, we know we have a real, complex or pointer type. 10499 // Now make sure the operand is a modifiable lvalue. 10500 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10501 return QualType(); 10502 // In C++, a prefix increment is the same type as the operand. Otherwise 10503 // (in C or with postfix), the increment is the unqualified type of the 10504 // operand. 10505 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10506 VK = VK_LValue; 10507 OK = Op->getObjectKind(); 10508 return ResType; 10509 } else { 10510 VK = VK_RValue; 10511 return ResType.getUnqualifiedType(); 10512 } 10513 } 10514 10515 10516 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10517 /// This routine allows us to typecheck complex/recursive expressions 10518 /// where the declaration is needed for type checking. We only need to 10519 /// handle cases when the expression references a function designator 10520 /// or is an lvalue. Here are some examples: 10521 /// - &(x) => x 10522 /// - &*****f => f for f a function designator. 10523 /// - &s.xx => s 10524 /// - &s.zz[1].yy -> s, if zz is an array 10525 /// - *(x + 1) -> x, if x is an array 10526 /// - &"123"[2] -> 0 10527 /// - & __real__ x -> x 10528 static ValueDecl *getPrimaryDecl(Expr *E) { 10529 switch (E->getStmtClass()) { 10530 case Stmt::DeclRefExprClass: 10531 return cast<DeclRefExpr>(E)->getDecl(); 10532 case Stmt::MemberExprClass: 10533 // If this is an arrow operator, the address is an offset from 10534 // the base's value, so the object the base refers to is 10535 // irrelevant. 10536 if (cast<MemberExpr>(E)->isArrow()) 10537 return nullptr; 10538 // Otherwise, the expression refers to a part of the base 10539 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10540 case Stmt::ArraySubscriptExprClass: { 10541 // FIXME: This code shouldn't be necessary! We should catch the implicit 10542 // promotion of register arrays earlier. 10543 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10544 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10545 if (ICE->getSubExpr()->getType()->isArrayType()) 10546 return getPrimaryDecl(ICE->getSubExpr()); 10547 } 10548 return nullptr; 10549 } 10550 case Stmt::UnaryOperatorClass: { 10551 UnaryOperator *UO = cast<UnaryOperator>(E); 10552 10553 switch(UO->getOpcode()) { 10554 case UO_Real: 10555 case UO_Imag: 10556 case UO_Extension: 10557 return getPrimaryDecl(UO->getSubExpr()); 10558 default: 10559 return nullptr; 10560 } 10561 } 10562 case Stmt::ParenExprClass: 10563 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10564 case Stmt::ImplicitCastExprClass: 10565 // If the result of an implicit cast is an l-value, we care about 10566 // the sub-expression; otherwise, the result here doesn't matter. 10567 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10568 default: 10569 return nullptr; 10570 } 10571 } 10572 10573 namespace { 10574 enum { 10575 AO_Bit_Field = 0, 10576 AO_Vector_Element = 1, 10577 AO_Property_Expansion = 2, 10578 AO_Register_Variable = 3, 10579 AO_No_Error = 4 10580 }; 10581 } 10582 /// \brief Diagnose invalid operand for address of operations. 10583 /// 10584 /// \param Type The type of operand which cannot have its address taken. 10585 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10586 Expr *E, unsigned Type) { 10587 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10588 } 10589 10590 /// CheckAddressOfOperand - The operand of & must be either a function 10591 /// designator or an lvalue designating an object. If it is an lvalue, the 10592 /// object cannot be declared with storage class register or be a bit field. 10593 /// Note: The usual conversions are *not* applied to the operand of the & 10594 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10595 /// In C++, the operand might be an overloaded function name, in which case 10596 /// we allow the '&' but retain the overloaded-function type. 10597 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10598 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10599 if (PTy->getKind() == BuiltinType::Overload) { 10600 Expr *E = OrigOp.get()->IgnoreParens(); 10601 if (!isa<OverloadExpr>(E)) { 10602 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10603 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10604 << OrigOp.get()->getSourceRange(); 10605 return QualType(); 10606 } 10607 10608 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10609 if (isa<UnresolvedMemberExpr>(Ovl)) 10610 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10611 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10612 << OrigOp.get()->getSourceRange(); 10613 return QualType(); 10614 } 10615 10616 return Context.OverloadTy; 10617 } 10618 10619 if (PTy->getKind() == BuiltinType::UnknownAny) 10620 return Context.UnknownAnyTy; 10621 10622 if (PTy->getKind() == BuiltinType::BoundMember) { 10623 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10624 << OrigOp.get()->getSourceRange(); 10625 return QualType(); 10626 } 10627 10628 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10629 if (OrigOp.isInvalid()) return QualType(); 10630 } 10631 10632 if (OrigOp.get()->isTypeDependent()) 10633 return Context.DependentTy; 10634 10635 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10636 10637 // Make sure to ignore parentheses in subsequent checks 10638 Expr *op = OrigOp.get()->IgnoreParens(); 10639 10640 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10641 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10642 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10643 return QualType(); 10644 } 10645 10646 if (getLangOpts().C99) { 10647 // Implement C99-only parts of addressof rules. 10648 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10649 if (uOp->getOpcode() == UO_Deref) 10650 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10651 // (assuming the deref expression is valid). 10652 return uOp->getSubExpr()->getType(); 10653 } 10654 // Technically, there should be a check for array subscript 10655 // expressions here, but the result of one is always an lvalue anyway. 10656 } 10657 ValueDecl *dcl = getPrimaryDecl(op); 10658 10659 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10660 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10661 op->getLocStart())) 10662 return QualType(); 10663 10664 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10665 unsigned AddressOfError = AO_No_Error; 10666 10667 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10668 bool sfinae = (bool)isSFINAEContext(); 10669 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10670 : diag::ext_typecheck_addrof_temporary) 10671 << op->getType() << op->getSourceRange(); 10672 if (sfinae) 10673 return QualType(); 10674 // Materialize the temporary as an lvalue so that we can take its address. 10675 OrigOp = op = 10676 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10677 } else if (isa<ObjCSelectorExpr>(op)) { 10678 return Context.getPointerType(op->getType()); 10679 } else if (lval == Expr::LV_MemberFunction) { 10680 // If it's an instance method, make a member pointer. 10681 // The expression must have exactly the form &A::foo. 10682 10683 // If the underlying expression isn't a decl ref, give up. 10684 if (!isa<DeclRefExpr>(op)) { 10685 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10686 << OrigOp.get()->getSourceRange(); 10687 return QualType(); 10688 } 10689 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10690 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10691 10692 // The id-expression was parenthesized. 10693 if (OrigOp.get() != DRE) { 10694 Diag(OpLoc, diag::err_parens_pointer_member_function) 10695 << OrigOp.get()->getSourceRange(); 10696 10697 // The method was named without a qualifier. 10698 } else if (!DRE->getQualifier()) { 10699 if (MD->getParent()->getName().empty()) 10700 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10701 << op->getSourceRange(); 10702 else { 10703 SmallString<32> Str; 10704 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10705 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10706 << op->getSourceRange() 10707 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10708 } 10709 } 10710 10711 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10712 if (isa<CXXDestructorDecl>(MD)) 10713 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10714 10715 QualType MPTy = Context.getMemberPointerType( 10716 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10717 // Under the MS ABI, lock down the inheritance model now. 10718 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10719 (void)isCompleteType(OpLoc, MPTy); 10720 return MPTy; 10721 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10722 // C99 6.5.3.2p1 10723 // The operand must be either an l-value or a function designator 10724 if (!op->getType()->isFunctionType()) { 10725 // Use a special diagnostic for loads from property references. 10726 if (isa<PseudoObjectExpr>(op)) { 10727 AddressOfError = AO_Property_Expansion; 10728 } else { 10729 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10730 << op->getType() << op->getSourceRange(); 10731 return QualType(); 10732 } 10733 } 10734 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10735 // The operand cannot be a bit-field 10736 AddressOfError = AO_Bit_Field; 10737 } else if (op->getObjectKind() == OK_VectorComponent) { 10738 // The operand cannot be an element of a vector 10739 AddressOfError = AO_Vector_Element; 10740 } else if (dcl) { // C99 6.5.3.2p1 10741 // We have an lvalue with a decl. Make sure the decl is not declared 10742 // with the register storage-class specifier. 10743 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10744 // in C++ it is not error to take address of a register 10745 // variable (c++03 7.1.1P3) 10746 if (vd->getStorageClass() == SC_Register && 10747 !getLangOpts().CPlusPlus) { 10748 AddressOfError = AO_Register_Variable; 10749 } 10750 } else if (isa<MSPropertyDecl>(dcl)) { 10751 AddressOfError = AO_Property_Expansion; 10752 } else if (isa<FunctionTemplateDecl>(dcl)) { 10753 return Context.OverloadTy; 10754 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10755 // Okay: we can take the address of a field. 10756 // Could be a pointer to member, though, if there is an explicit 10757 // scope qualifier for the class. 10758 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10759 DeclContext *Ctx = dcl->getDeclContext(); 10760 if (Ctx && Ctx->isRecord()) { 10761 if (dcl->getType()->isReferenceType()) { 10762 Diag(OpLoc, 10763 diag::err_cannot_form_pointer_to_member_of_reference_type) 10764 << dcl->getDeclName() << dcl->getType(); 10765 return QualType(); 10766 } 10767 10768 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10769 Ctx = Ctx->getParent(); 10770 10771 QualType MPTy = Context.getMemberPointerType( 10772 op->getType(), 10773 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10774 // Under the MS ABI, lock down the inheritance model now. 10775 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10776 (void)isCompleteType(OpLoc, MPTy); 10777 return MPTy; 10778 } 10779 } 10780 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10781 !isa<BindingDecl>(dcl)) 10782 llvm_unreachable("Unknown/unexpected decl type"); 10783 } 10784 10785 if (AddressOfError != AO_No_Error) { 10786 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10787 return QualType(); 10788 } 10789 10790 if (lval == Expr::LV_IncompleteVoidType) { 10791 // Taking the address of a void variable is technically illegal, but we 10792 // allow it in cases which are otherwise valid. 10793 // Example: "extern void x; void* y = &x;". 10794 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10795 } 10796 10797 // If the operand has type "type", the result has type "pointer to type". 10798 if (op->getType()->isObjCObjectType()) 10799 return Context.getObjCObjectPointerType(op->getType()); 10800 10801 CheckAddressOfPackedMember(op); 10802 10803 return Context.getPointerType(op->getType()); 10804 } 10805 10806 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10807 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10808 if (!DRE) 10809 return; 10810 const Decl *D = DRE->getDecl(); 10811 if (!D) 10812 return; 10813 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10814 if (!Param) 10815 return; 10816 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10817 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10818 return; 10819 if (FunctionScopeInfo *FD = S.getCurFunction()) 10820 if (!FD->ModifiedNonNullParams.count(Param)) 10821 FD->ModifiedNonNullParams.insert(Param); 10822 } 10823 10824 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10825 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10826 SourceLocation OpLoc) { 10827 if (Op->isTypeDependent()) 10828 return S.Context.DependentTy; 10829 10830 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10831 if (ConvResult.isInvalid()) 10832 return QualType(); 10833 Op = ConvResult.get(); 10834 QualType OpTy = Op->getType(); 10835 QualType Result; 10836 10837 if (isa<CXXReinterpretCastExpr>(Op)) { 10838 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10839 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10840 Op->getSourceRange()); 10841 } 10842 10843 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10844 { 10845 Result = PT->getPointeeType(); 10846 } 10847 else if (const ObjCObjectPointerType *OPT = 10848 OpTy->getAs<ObjCObjectPointerType>()) 10849 Result = OPT->getPointeeType(); 10850 else { 10851 ExprResult PR = S.CheckPlaceholderExpr(Op); 10852 if (PR.isInvalid()) return QualType(); 10853 if (PR.get() != Op) 10854 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10855 } 10856 10857 if (Result.isNull()) { 10858 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10859 << OpTy << Op->getSourceRange(); 10860 return QualType(); 10861 } 10862 10863 // Note that per both C89 and C99, indirection is always legal, even if Result 10864 // is an incomplete type or void. It would be possible to warn about 10865 // dereferencing a void pointer, but it's completely well-defined, and such a 10866 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10867 // for pointers to 'void' but is fine for any other pointer type: 10868 // 10869 // C++ [expr.unary.op]p1: 10870 // [...] the expression to which [the unary * operator] is applied shall 10871 // be a pointer to an object type, or a pointer to a function type 10872 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10873 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10874 << OpTy << Op->getSourceRange(); 10875 10876 // Dereferences are usually l-values... 10877 VK = VK_LValue; 10878 10879 // ...except that certain expressions are never l-values in C. 10880 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10881 VK = VK_RValue; 10882 10883 return Result; 10884 } 10885 10886 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10887 BinaryOperatorKind Opc; 10888 switch (Kind) { 10889 default: llvm_unreachable("Unknown binop!"); 10890 case tok::periodstar: Opc = BO_PtrMemD; break; 10891 case tok::arrowstar: Opc = BO_PtrMemI; break; 10892 case tok::star: Opc = BO_Mul; break; 10893 case tok::slash: Opc = BO_Div; break; 10894 case tok::percent: Opc = BO_Rem; break; 10895 case tok::plus: Opc = BO_Add; break; 10896 case tok::minus: Opc = BO_Sub; break; 10897 case tok::lessless: Opc = BO_Shl; break; 10898 case tok::greatergreater: Opc = BO_Shr; break; 10899 case tok::lessequal: Opc = BO_LE; break; 10900 case tok::less: Opc = BO_LT; break; 10901 case tok::greaterequal: Opc = BO_GE; break; 10902 case tok::greater: Opc = BO_GT; break; 10903 case tok::exclaimequal: Opc = BO_NE; break; 10904 case tok::equalequal: Opc = BO_EQ; break; 10905 case tok::amp: Opc = BO_And; break; 10906 case tok::caret: Opc = BO_Xor; break; 10907 case tok::pipe: Opc = BO_Or; break; 10908 case tok::ampamp: Opc = BO_LAnd; break; 10909 case tok::pipepipe: Opc = BO_LOr; break; 10910 case tok::equal: Opc = BO_Assign; break; 10911 case tok::starequal: Opc = BO_MulAssign; break; 10912 case tok::slashequal: Opc = BO_DivAssign; break; 10913 case tok::percentequal: Opc = BO_RemAssign; break; 10914 case tok::plusequal: Opc = BO_AddAssign; break; 10915 case tok::minusequal: Opc = BO_SubAssign; break; 10916 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10917 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10918 case tok::ampequal: Opc = BO_AndAssign; break; 10919 case tok::caretequal: Opc = BO_XorAssign; break; 10920 case tok::pipeequal: Opc = BO_OrAssign; break; 10921 case tok::comma: Opc = BO_Comma; break; 10922 } 10923 return Opc; 10924 } 10925 10926 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10927 tok::TokenKind Kind) { 10928 UnaryOperatorKind Opc; 10929 switch (Kind) { 10930 default: llvm_unreachable("Unknown unary op!"); 10931 case tok::plusplus: Opc = UO_PreInc; break; 10932 case tok::minusminus: Opc = UO_PreDec; break; 10933 case tok::amp: Opc = UO_AddrOf; break; 10934 case tok::star: Opc = UO_Deref; break; 10935 case tok::plus: Opc = UO_Plus; break; 10936 case tok::minus: Opc = UO_Minus; break; 10937 case tok::tilde: Opc = UO_Not; break; 10938 case tok::exclaim: Opc = UO_LNot; break; 10939 case tok::kw___real: Opc = UO_Real; break; 10940 case tok::kw___imag: Opc = UO_Imag; break; 10941 case tok::kw___extension__: Opc = UO_Extension; break; 10942 } 10943 return Opc; 10944 } 10945 10946 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10947 /// This warning is only emitted for builtin assignment operations. It is also 10948 /// suppressed in the event of macro expansions. 10949 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10950 SourceLocation OpLoc) { 10951 if (!S.ActiveTemplateInstantiations.empty()) 10952 return; 10953 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10954 return; 10955 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10956 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10957 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10958 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10959 if (!LHSDeclRef || !RHSDeclRef || 10960 LHSDeclRef->getLocation().isMacroID() || 10961 RHSDeclRef->getLocation().isMacroID()) 10962 return; 10963 const ValueDecl *LHSDecl = 10964 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10965 const ValueDecl *RHSDecl = 10966 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10967 if (LHSDecl != RHSDecl) 10968 return; 10969 if (LHSDecl->getType().isVolatileQualified()) 10970 return; 10971 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10972 if (RefTy->getPointeeType().isVolatileQualified()) 10973 return; 10974 10975 S.Diag(OpLoc, diag::warn_self_assignment) 10976 << LHSDeclRef->getType() 10977 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10978 } 10979 10980 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10981 /// is usually indicative of introspection within the Objective-C pointer. 10982 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10983 SourceLocation OpLoc) { 10984 if (!S.getLangOpts().ObjC1) 10985 return; 10986 10987 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10988 const Expr *LHS = L.get(); 10989 const Expr *RHS = R.get(); 10990 10991 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10992 ObjCPointerExpr = LHS; 10993 OtherExpr = RHS; 10994 } 10995 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10996 ObjCPointerExpr = RHS; 10997 OtherExpr = LHS; 10998 } 10999 11000 // This warning is deliberately made very specific to reduce false 11001 // positives with logic that uses '&' for hashing. This logic mainly 11002 // looks for code trying to introspect into tagged pointers, which 11003 // code should generally never do. 11004 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11005 unsigned Diag = diag::warn_objc_pointer_masking; 11006 // Determine if we are introspecting the result of performSelectorXXX. 11007 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11008 // Special case messages to -performSelector and friends, which 11009 // can return non-pointer values boxed in a pointer value. 11010 // Some clients may wish to silence warnings in this subcase. 11011 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11012 Selector S = ME->getSelector(); 11013 StringRef SelArg0 = S.getNameForSlot(0); 11014 if (SelArg0.startswith("performSelector")) 11015 Diag = diag::warn_objc_pointer_masking_performSelector; 11016 } 11017 11018 S.Diag(OpLoc, Diag) 11019 << ObjCPointerExpr->getSourceRange(); 11020 } 11021 } 11022 11023 static NamedDecl *getDeclFromExpr(Expr *E) { 11024 if (!E) 11025 return nullptr; 11026 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11027 return DRE->getDecl(); 11028 if (auto *ME = dyn_cast<MemberExpr>(E)) 11029 return ME->getMemberDecl(); 11030 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11031 return IRE->getDecl(); 11032 return nullptr; 11033 } 11034 11035 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11036 /// operator @p Opc at location @c TokLoc. This routine only supports 11037 /// built-in operations; ActOnBinOp handles overloaded operators. 11038 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11039 BinaryOperatorKind Opc, 11040 Expr *LHSExpr, Expr *RHSExpr) { 11041 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11042 // The syntax only allows initializer lists on the RHS of assignment, 11043 // so we don't need to worry about accepting invalid code for 11044 // non-assignment operators. 11045 // C++11 5.17p9: 11046 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11047 // of x = {} is x = T(). 11048 InitializationKind Kind = 11049 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11050 InitializedEntity Entity = 11051 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11052 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11053 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11054 if (Init.isInvalid()) 11055 return Init; 11056 RHSExpr = Init.get(); 11057 } 11058 11059 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11060 QualType ResultTy; // Result type of the binary operator. 11061 // The following two variables are used for compound assignment operators 11062 QualType CompLHSTy; // Type of LHS after promotions for computation 11063 QualType CompResultTy; // Type of computation result 11064 ExprValueKind VK = VK_RValue; 11065 ExprObjectKind OK = OK_Ordinary; 11066 11067 if (!getLangOpts().CPlusPlus) { 11068 // C cannot handle TypoExpr nodes on either side of a binop because it 11069 // doesn't handle dependent types properly, so make sure any TypoExprs have 11070 // been dealt with before checking the operands. 11071 LHS = CorrectDelayedTyposInExpr(LHSExpr); 11072 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 11073 if (Opc != BO_Assign) 11074 return ExprResult(E); 11075 // Avoid correcting the RHS to the same Expr as the LHS. 11076 Decl *D = getDeclFromExpr(E); 11077 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11078 }); 11079 if (!LHS.isUsable() || !RHS.isUsable()) 11080 return ExprError(); 11081 } 11082 11083 if (getLangOpts().OpenCL) { 11084 QualType LHSTy = LHSExpr->getType(); 11085 QualType RHSTy = RHSExpr->getType(); 11086 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11087 // the ATOMIC_VAR_INIT macro. 11088 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11089 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11090 if (BO_Assign == Opc) 11091 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 11092 else 11093 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11094 return ExprError(); 11095 } 11096 11097 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11098 // only with a builtin functions and therefore should be disallowed here. 11099 if (LHSTy->isImageType() || RHSTy->isImageType() || 11100 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11101 LHSTy->isPipeType() || RHSTy->isPipeType() || 11102 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11103 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11104 return ExprError(); 11105 } 11106 } 11107 11108 switch (Opc) { 11109 case BO_Assign: 11110 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11111 if (getLangOpts().CPlusPlus && 11112 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11113 VK = LHS.get()->getValueKind(); 11114 OK = LHS.get()->getObjectKind(); 11115 } 11116 if (!ResultTy.isNull()) { 11117 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11118 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11119 } 11120 RecordModifiableNonNullParam(*this, LHS.get()); 11121 break; 11122 case BO_PtrMemD: 11123 case BO_PtrMemI: 11124 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11125 Opc == BO_PtrMemI); 11126 break; 11127 case BO_Mul: 11128 case BO_Div: 11129 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11130 Opc == BO_Div); 11131 break; 11132 case BO_Rem: 11133 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11134 break; 11135 case BO_Add: 11136 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11137 break; 11138 case BO_Sub: 11139 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11140 break; 11141 case BO_Shl: 11142 case BO_Shr: 11143 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11144 break; 11145 case BO_LE: 11146 case BO_LT: 11147 case BO_GE: 11148 case BO_GT: 11149 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11150 break; 11151 case BO_EQ: 11152 case BO_NE: 11153 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11154 break; 11155 case BO_And: 11156 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11157 case BO_Xor: 11158 case BO_Or: 11159 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11160 break; 11161 case BO_LAnd: 11162 case BO_LOr: 11163 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11164 break; 11165 case BO_MulAssign: 11166 case BO_DivAssign: 11167 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11168 Opc == BO_DivAssign); 11169 CompLHSTy = CompResultTy; 11170 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11171 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11172 break; 11173 case BO_RemAssign: 11174 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11175 CompLHSTy = CompResultTy; 11176 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11177 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11178 break; 11179 case BO_AddAssign: 11180 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11181 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11182 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11183 break; 11184 case BO_SubAssign: 11185 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11186 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11187 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11188 break; 11189 case BO_ShlAssign: 11190 case BO_ShrAssign: 11191 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11192 CompLHSTy = CompResultTy; 11193 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11194 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11195 break; 11196 case BO_AndAssign: 11197 case BO_OrAssign: // fallthrough 11198 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11199 case BO_XorAssign: 11200 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11201 CompLHSTy = CompResultTy; 11202 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11203 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11204 break; 11205 case BO_Comma: 11206 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11207 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11208 VK = RHS.get()->getValueKind(); 11209 OK = RHS.get()->getObjectKind(); 11210 } 11211 break; 11212 } 11213 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11214 return ExprError(); 11215 11216 // Check for array bounds violations for both sides of the BinaryOperator 11217 CheckArrayAccess(LHS.get()); 11218 CheckArrayAccess(RHS.get()); 11219 11220 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11221 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11222 &Context.Idents.get("object_setClass"), 11223 SourceLocation(), LookupOrdinaryName); 11224 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11225 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11226 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11227 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11228 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11229 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11230 } 11231 else 11232 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11233 } 11234 else if (const ObjCIvarRefExpr *OIRE = 11235 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11236 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11237 11238 if (CompResultTy.isNull()) 11239 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11240 OK, OpLoc, FPFeatures.fp_contract); 11241 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11242 OK_ObjCProperty) { 11243 VK = VK_LValue; 11244 OK = LHS.get()->getObjectKind(); 11245 } 11246 return new (Context) CompoundAssignOperator( 11247 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11248 OpLoc, FPFeatures.fp_contract); 11249 } 11250 11251 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11252 /// operators are mixed in a way that suggests that the programmer forgot that 11253 /// comparison operators have higher precedence. The most typical example of 11254 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11255 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11256 SourceLocation OpLoc, Expr *LHSExpr, 11257 Expr *RHSExpr) { 11258 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11259 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11260 11261 // Check that one of the sides is a comparison operator and the other isn't. 11262 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11263 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11264 if (isLeftComp == isRightComp) 11265 return; 11266 11267 // Bitwise operations are sometimes used as eager logical ops. 11268 // Don't diagnose this. 11269 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11270 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11271 if (isLeftBitwise || isRightBitwise) 11272 return; 11273 11274 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11275 OpLoc) 11276 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11277 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11278 SourceRange ParensRange = isLeftComp ? 11279 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11280 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11281 11282 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11283 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11284 SuggestParentheses(Self, OpLoc, 11285 Self.PDiag(diag::note_precedence_silence) << OpStr, 11286 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11287 SuggestParentheses(Self, OpLoc, 11288 Self.PDiag(diag::note_precedence_bitwise_first) 11289 << BinaryOperator::getOpcodeStr(Opc), 11290 ParensRange); 11291 } 11292 11293 /// \brief It accepts a '&&' expr that is inside a '||' one. 11294 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11295 /// in parentheses. 11296 static void 11297 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11298 BinaryOperator *Bop) { 11299 assert(Bop->getOpcode() == BO_LAnd); 11300 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11301 << Bop->getSourceRange() << OpLoc; 11302 SuggestParentheses(Self, Bop->getOperatorLoc(), 11303 Self.PDiag(diag::note_precedence_silence) 11304 << Bop->getOpcodeStr(), 11305 Bop->getSourceRange()); 11306 } 11307 11308 /// \brief Returns true if the given expression can be evaluated as a constant 11309 /// 'true'. 11310 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11311 bool Res; 11312 return !E->isValueDependent() && 11313 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11314 } 11315 11316 /// \brief Returns true if the given expression can be evaluated as a constant 11317 /// 'false'. 11318 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11319 bool Res; 11320 return !E->isValueDependent() && 11321 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11322 } 11323 11324 /// \brief Look for '&&' in the left hand of a '||' expr. 11325 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11326 Expr *LHSExpr, Expr *RHSExpr) { 11327 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11328 if (Bop->getOpcode() == BO_LAnd) { 11329 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11330 if (EvaluatesAsFalse(S, RHSExpr)) 11331 return; 11332 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11333 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11334 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11335 } else if (Bop->getOpcode() == BO_LOr) { 11336 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11337 // If it's "a || b && 1 || c" we didn't warn earlier for 11338 // "a || b && 1", but warn now. 11339 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11340 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11341 } 11342 } 11343 } 11344 } 11345 11346 /// \brief Look for '&&' in the right hand of a '||' expr. 11347 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11348 Expr *LHSExpr, Expr *RHSExpr) { 11349 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11350 if (Bop->getOpcode() == BO_LAnd) { 11351 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11352 if (EvaluatesAsFalse(S, LHSExpr)) 11353 return; 11354 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11355 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11356 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11357 } 11358 } 11359 } 11360 11361 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11362 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11363 /// the '&' expression in parentheses. 11364 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11365 SourceLocation OpLoc, Expr *SubExpr) { 11366 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11367 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11368 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11369 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11370 << Bop->getSourceRange() << OpLoc; 11371 SuggestParentheses(S, Bop->getOperatorLoc(), 11372 S.PDiag(diag::note_precedence_silence) 11373 << Bop->getOpcodeStr(), 11374 Bop->getSourceRange()); 11375 } 11376 } 11377 } 11378 11379 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11380 Expr *SubExpr, StringRef Shift) { 11381 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11382 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11383 StringRef Op = Bop->getOpcodeStr(); 11384 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11385 << Bop->getSourceRange() << OpLoc << Shift << Op; 11386 SuggestParentheses(S, Bop->getOperatorLoc(), 11387 S.PDiag(diag::note_precedence_silence) << Op, 11388 Bop->getSourceRange()); 11389 } 11390 } 11391 } 11392 11393 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11394 Expr *LHSExpr, Expr *RHSExpr) { 11395 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11396 if (!OCE) 11397 return; 11398 11399 FunctionDecl *FD = OCE->getDirectCallee(); 11400 if (!FD || !FD->isOverloadedOperator()) 11401 return; 11402 11403 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11404 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11405 return; 11406 11407 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11408 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11409 << (Kind == OO_LessLess); 11410 SuggestParentheses(S, OCE->getOperatorLoc(), 11411 S.PDiag(diag::note_precedence_silence) 11412 << (Kind == OO_LessLess ? "<<" : ">>"), 11413 OCE->getSourceRange()); 11414 SuggestParentheses(S, OpLoc, 11415 S.PDiag(diag::note_evaluate_comparison_first), 11416 SourceRange(OCE->getArg(1)->getLocStart(), 11417 RHSExpr->getLocEnd())); 11418 } 11419 11420 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11421 /// precedence. 11422 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11423 SourceLocation OpLoc, Expr *LHSExpr, 11424 Expr *RHSExpr){ 11425 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11426 if (BinaryOperator::isBitwiseOp(Opc)) 11427 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11428 11429 // Diagnose "arg1 & arg2 | arg3" 11430 if ((Opc == BO_Or || Opc == BO_Xor) && 11431 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11432 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11433 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11434 } 11435 11436 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11437 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11438 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11439 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11440 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11441 } 11442 11443 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11444 || Opc == BO_Shr) { 11445 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11446 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11447 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11448 } 11449 11450 // Warn on overloaded shift operators and comparisons, such as: 11451 // cout << 5 == 4; 11452 if (BinaryOperator::isComparisonOp(Opc)) 11453 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11454 } 11455 11456 // Binary Operators. 'Tok' is the token for the operator. 11457 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11458 tok::TokenKind Kind, 11459 Expr *LHSExpr, Expr *RHSExpr) { 11460 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11461 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11462 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11463 11464 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11465 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11466 11467 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11468 } 11469 11470 /// Build an overloaded binary operator expression in the given scope. 11471 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11472 BinaryOperatorKind Opc, 11473 Expr *LHS, Expr *RHS) { 11474 // Find all of the overloaded operators visible from this 11475 // point. We perform both an operator-name lookup from the local 11476 // scope and an argument-dependent lookup based on the types of 11477 // the arguments. 11478 UnresolvedSet<16> Functions; 11479 OverloadedOperatorKind OverOp 11480 = BinaryOperator::getOverloadedOperator(Opc); 11481 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11482 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11483 RHS->getType(), Functions); 11484 11485 // Build the (potentially-overloaded, potentially-dependent) 11486 // binary operation. 11487 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11488 } 11489 11490 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11491 BinaryOperatorKind Opc, 11492 Expr *LHSExpr, Expr *RHSExpr) { 11493 // We want to end up calling one of checkPseudoObjectAssignment 11494 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11495 // both expressions are overloadable or either is type-dependent), 11496 // or CreateBuiltinBinOp (in any other case). We also want to get 11497 // any placeholder types out of the way. 11498 11499 // Handle pseudo-objects in the LHS. 11500 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11501 // Assignments with a pseudo-object l-value need special analysis. 11502 if (pty->getKind() == BuiltinType::PseudoObject && 11503 BinaryOperator::isAssignmentOp(Opc)) 11504 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11505 11506 // Don't resolve overloads if the other type is overloadable. 11507 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 11508 // We can't actually test that if we still have a placeholder, 11509 // though. Fortunately, none of the exceptions we see in that 11510 // code below are valid when the LHS is an overload set. Note 11511 // that an overload set can be dependently-typed, but it never 11512 // instantiates to having an overloadable type. 11513 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11514 if (resolvedRHS.isInvalid()) return ExprError(); 11515 RHSExpr = resolvedRHS.get(); 11516 11517 if (RHSExpr->isTypeDependent() || 11518 RHSExpr->getType()->isOverloadableType()) 11519 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11520 } 11521 11522 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11523 if (LHS.isInvalid()) return ExprError(); 11524 LHSExpr = LHS.get(); 11525 } 11526 11527 // Handle pseudo-objects in the RHS. 11528 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11529 // An overload in the RHS can potentially be resolved by the type 11530 // being assigned to. 11531 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11532 if (getLangOpts().CPlusPlus && 11533 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 11534 LHSExpr->getType()->isOverloadableType())) 11535 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11536 11537 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11538 } 11539 11540 // Don't resolve overloads if the other type is overloadable. 11541 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 11542 LHSExpr->getType()->isOverloadableType()) 11543 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11544 11545 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11546 if (!resolvedRHS.isUsable()) return ExprError(); 11547 RHSExpr = resolvedRHS.get(); 11548 } 11549 11550 if (getLangOpts().CPlusPlus) { 11551 // If either expression is type-dependent, always build an 11552 // overloaded op. 11553 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11554 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11555 11556 // Otherwise, build an overloaded op if either expression has an 11557 // overloadable type. 11558 if (LHSExpr->getType()->isOverloadableType() || 11559 RHSExpr->getType()->isOverloadableType()) 11560 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11561 } 11562 11563 // Build a built-in binary operation. 11564 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11565 } 11566 11567 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11568 UnaryOperatorKind Opc, 11569 Expr *InputExpr) { 11570 ExprResult Input = InputExpr; 11571 ExprValueKind VK = VK_RValue; 11572 ExprObjectKind OK = OK_Ordinary; 11573 QualType resultType; 11574 if (getLangOpts().OpenCL) { 11575 QualType Ty = InputExpr->getType(); 11576 // The only legal unary operation for atomics is '&'. 11577 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11578 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11579 // only with a builtin functions and therefore should be disallowed here. 11580 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11581 || Ty->isBlockPointerType())) { 11582 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11583 << InputExpr->getType() 11584 << Input.get()->getSourceRange()); 11585 } 11586 } 11587 switch (Opc) { 11588 case UO_PreInc: 11589 case UO_PreDec: 11590 case UO_PostInc: 11591 case UO_PostDec: 11592 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11593 OpLoc, 11594 Opc == UO_PreInc || 11595 Opc == UO_PostInc, 11596 Opc == UO_PreInc || 11597 Opc == UO_PreDec); 11598 break; 11599 case UO_AddrOf: 11600 resultType = CheckAddressOfOperand(Input, OpLoc); 11601 RecordModifiableNonNullParam(*this, InputExpr); 11602 break; 11603 case UO_Deref: { 11604 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11605 if (Input.isInvalid()) return ExprError(); 11606 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11607 break; 11608 } 11609 case UO_Plus: 11610 case UO_Minus: 11611 Input = UsualUnaryConversions(Input.get()); 11612 if (Input.isInvalid()) return ExprError(); 11613 resultType = Input.get()->getType(); 11614 if (resultType->isDependentType()) 11615 break; 11616 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11617 break; 11618 else if (resultType->isVectorType() && 11619 // The z vector extensions don't allow + or - with bool vectors. 11620 (!Context.getLangOpts().ZVector || 11621 resultType->getAs<VectorType>()->getVectorKind() != 11622 VectorType::AltiVecBool)) 11623 break; 11624 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11625 Opc == UO_Plus && 11626 resultType->isPointerType()) 11627 break; 11628 11629 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11630 << resultType << Input.get()->getSourceRange()); 11631 11632 case UO_Not: // bitwise complement 11633 Input = UsualUnaryConversions(Input.get()); 11634 if (Input.isInvalid()) 11635 return ExprError(); 11636 resultType = Input.get()->getType(); 11637 if (resultType->isDependentType()) 11638 break; 11639 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11640 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11641 // C99 does not support '~' for complex conjugation. 11642 Diag(OpLoc, diag::ext_integer_complement_complex) 11643 << resultType << Input.get()->getSourceRange(); 11644 else if (resultType->hasIntegerRepresentation()) 11645 break; 11646 else if (resultType->isExtVectorType()) { 11647 if (Context.getLangOpts().OpenCL) { 11648 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11649 // on vector float types. 11650 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11651 if (!T->isIntegerType()) 11652 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11653 << resultType << Input.get()->getSourceRange()); 11654 } 11655 break; 11656 } else { 11657 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11658 << resultType << Input.get()->getSourceRange()); 11659 } 11660 break; 11661 11662 case UO_LNot: // logical negation 11663 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11664 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11665 if (Input.isInvalid()) return ExprError(); 11666 resultType = Input.get()->getType(); 11667 11668 // Though we still have to promote half FP to float... 11669 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11670 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11671 resultType = Context.FloatTy; 11672 } 11673 11674 if (resultType->isDependentType()) 11675 break; 11676 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11677 // C99 6.5.3.3p1: ok, fallthrough; 11678 if (Context.getLangOpts().CPlusPlus) { 11679 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11680 // operand contextually converted to bool. 11681 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11682 ScalarTypeToBooleanCastKind(resultType)); 11683 } else if (Context.getLangOpts().OpenCL && 11684 Context.getLangOpts().OpenCLVersion < 120) { 11685 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11686 // operate on scalar float types. 11687 if (!resultType->isIntegerType() && !resultType->isPointerType()) 11688 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11689 << resultType << Input.get()->getSourceRange()); 11690 } 11691 } else if (resultType->isExtVectorType()) { 11692 if (Context.getLangOpts().OpenCL && 11693 Context.getLangOpts().OpenCLVersion < 120) { 11694 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11695 // operate on vector float types. 11696 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11697 if (!T->isIntegerType()) 11698 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11699 << resultType << Input.get()->getSourceRange()); 11700 } 11701 // Vector logical not returns the signed variant of the operand type. 11702 resultType = GetSignedVectorType(resultType); 11703 break; 11704 } else { 11705 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11706 << resultType << Input.get()->getSourceRange()); 11707 } 11708 11709 // LNot always has type int. C99 6.5.3.3p5. 11710 // In C++, it's bool. C++ 5.3.1p8 11711 resultType = Context.getLogicalOperationType(); 11712 break; 11713 case UO_Real: 11714 case UO_Imag: 11715 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11716 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11717 // complex l-values to ordinary l-values and all other values to r-values. 11718 if (Input.isInvalid()) return ExprError(); 11719 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11720 if (Input.get()->getValueKind() != VK_RValue && 11721 Input.get()->getObjectKind() == OK_Ordinary) 11722 VK = Input.get()->getValueKind(); 11723 } else if (!getLangOpts().CPlusPlus) { 11724 // In C, a volatile scalar is read by __imag. In C++, it is not. 11725 Input = DefaultLvalueConversion(Input.get()); 11726 } 11727 break; 11728 case UO_Extension: 11729 case UO_Coawait: 11730 resultType = Input.get()->getType(); 11731 VK = Input.get()->getValueKind(); 11732 OK = Input.get()->getObjectKind(); 11733 break; 11734 } 11735 if (resultType.isNull() || Input.isInvalid()) 11736 return ExprError(); 11737 11738 // Check for array bounds violations in the operand of the UnaryOperator, 11739 // except for the '*' and '&' operators that have to be handled specially 11740 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11741 // that are explicitly defined as valid by the standard). 11742 if (Opc != UO_AddrOf && Opc != UO_Deref) 11743 CheckArrayAccess(Input.get()); 11744 11745 return new (Context) 11746 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11747 } 11748 11749 /// \brief Determine whether the given expression is a qualified member 11750 /// access expression, of a form that could be turned into a pointer to member 11751 /// with the address-of operator. 11752 static bool isQualifiedMemberAccess(Expr *E) { 11753 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11754 if (!DRE->getQualifier()) 11755 return false; 11756 11757 ValueDecl *VD = DRE->getDecl(); 11758 if (!VD->isCXXClassMember()) 11759 return false; 11760 11761 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11762 return true; 11763 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11764 return Method->isInstance(); 11765 11766 return false; 11767 } 11768 11769 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11770 if (!ULE->getQualifier()) 11771 return false; 11772 11773 for (NamedDecl *D : ULE->decls()) { 11774 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11775 if (Method->isInstance()) 11776 return true; 11777 } else { 11778 // Overload set does not contain methods. 11779 break; 11780 } 11781 } 11782 11783 return false; 11784 } 11785 11786 return false; 11787 } 11788 11789 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11790 UnaryOperatorKind Opc, Expr *Input) { 11791 // First things first: handle placeholders so that the 11792 // overloaded-operator check considers the right type. 11793 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11794 // Increment and decrement of pseudo-object references. 11795 if (pty->getKind() == BuiltinType::PseudoObject && 11796 UnaryOperator::isIncrementDecrementOp(Opc)) 11797 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11798 11799 // extension is always a builtin operator. 11800 if (Opc == UO_Extension) 11801 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11802 11803 // & gets special logic for several kinds of placeholder. 11804 // The builtin code knows what to do. 11805 if (Opc == UO_AddrOf && 11806 (pty->getKind() == BuiltinType::Overload || 11807 pty->getKind() == BuiltinType::UnknownAny || 11808 pty->getKind() == BuiltinType::BoundMember)) 11809 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11810 11811 // Anything else needs to be handled now. 11812 ExprResult Result = CheckPlaceholderExpr(Input); 11813 if (Result.isInvalid()) return ExprError(); 11814 Input = Result.get(); 11815 } 11816 11817 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11818 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11819 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11820 // Find all of the overloaded operators visible from this 11821 // point. We perform both an operator-name lookup from the local 11822 // scope and an argument-dependent lookup based on the types of 11823 // the arguments. 11824 UnresolvedSet<16> Functions; 11825 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11826 if (S && OverOp != OO_None) 11827 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11828 Functions); 11829 11830 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11831 } 11832 11833 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11834 } 11835 11836 // Unary Operators. 'Tok' is the token for the operator. 11837 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11838 tok::TokenKind Op, Expr *Input) { 11839 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11840 } 11841 11842 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11843 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11844 LabelDecl *TheDecl) { 11845 TheDecl->markUsed(Context); 11846 // Create the AST node. The address of a label always has type 'void*'. 11847 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11848 Context.getPointerType(Context.VoidTy)); 11849 } 11850 11851 /// Given the last statement in a statement-expression, check whether 11852 /// the result is a producing expression (like a call to an 11853 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11854 /// release out of the full-expression. Otherwise, return null. 11855 /// Cannot fail. 11856 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11857 // Should always be wrapped with one of these. 11858 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11859 if (!cleanups) return nullptr; 11860 11861 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11862 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11863 return nullptr; 11864 11865 // Splice out the cast. This shouldn't modify any interesting 11866 // features of the statement. 11867 Expr *producer = cast->getSubExpr(); 11868 assert(producer->getType() == cast->getType()); 11869 assert(producer->getValueKind() == cast->getValueKind()); 11870 cleanups->setSubExpr(producer); 11871 return cleanups; 11872 } 11873 11874 void Sema::ActOnStartStmtExpr() { 11875 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11876 } 11877 11878 void Sema::ActOnStmtExprError() { 11879 // Note that function is also called by TreeTransform when leaving a 11880 // StmtExpr scope without rebuilding anything. 11881 11882 DiscardCleanupsInEvaluationContext(); 11883 PopExpressionEvaluationContext(); 11884 } 11885 11886 ExprResult 11887 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11888 SourceLocation RPLoc) { // "({..})" 11889 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11890 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11891 11892 if (hasAnyUnrecoverableErrorsInThisFunction()) 11893 DiscardCleanupsInEvaluationContext(); 11894 assert(!Cleanup.exprNeedsCleanups() && 11895 "cleanups within StmtExpr not correctly bound!"); 11896 PopExpressionEvaluationContext(); 11897 11898 // FIXME: there are a variety of strange constraints to enforce here, for 11899 // example, it is not possible to goto into a stmt expression apparently. 11900 // More semantic analysis is needed. 11901 11902 // If there are sub-stmts in the compound stmt, take the type of the last one 11903 // as the type of the stmtexpr. 11904 QualType Ty = Context.VoidTy; 11905 bool StmtExprMayBindToTemp = false; 11906 if (!Compound->body_empty()) { 11907 Stmt *LastStmt = Compound->body_back(); 11908 LabelStmt *LastLabelStmt = nullptr; 11909 // If LastStmt is a label, skip down through into the body. 11910 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11911 LastLabelStmt = Label; 11912 LastStmt = Label->getSubStmt(); 11913 } 11914 11915 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11916 // Do function/array conversion on the last expression, but not 11917 // lvalue-to-rvalue. However, initialize an unqualified type. 11918 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11919 if (LastExpr.isInvalid()) 11920 return ExprError(); 11921 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11922 11923 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11924 // In ARC, if the final expression ends in a consume, splice 11925 // the consume out and bind it later. In the alternate case 11926 // (when dealing with a retainable type), the result 11927 // initialization will create a produce. In both cases the 11928 // result will be +1, and we'll need to balance that out with 11929 // a bind. 11930 if (Expr *rebuiltLastStmt 11931 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11932 LastExpr = rebuiltLastStmt; 11933 } else { 11934 LastExpr = PerformCopyInitialization( 11935 InitializedEntity::InitializeResult(LPLoc, 11936 Ty, 11937 false), 11938 SourceLocation(), 11939 LastExpr); 11940 } 11941 11942 if (LastExpr.isInvalid()) 11943 return ExprError(); 11944 if (LastExpr.get() != nullptr) { 11945 if (!LastLabelStmt) 11946 Compound->setLastStmt(LastExpr.get()); 11947 else 11948 LastLabelStmt->setSubStmt(LastExpr.get()); 11949 StmtExprMayBindToTemp = true; 11950 } 11951 } 11952 } 11953 } 11954 11955 // FIXME: Check that expression type is complete/non-abstract; statement 11956 // expressions are not lvalues. 11957 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11958 if (StmtExprMayBindToTemp) 11959 return MaybeBindToTemporary(ResStmtExpr); 11960 return ResStmtExpr; 11961 } 11962 11963 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11964 TypeSourceInfo *TInfo, 11965 ArrayRef<OffsetOfComponent> Components, 11966 SourceLocation RParenLoc) { 11967 QualType ArgTy = TInfo->getType(); 11968 bool Dependent = ArgTy->isDependentType(); 11969 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11970 11971 // We must have at least one component that refers to the type, and the first 11972 // one is known to be a field designator. Verify that the ArgTy represents 11973 // a struct/union/class. 11974 if (!Dependent && !ArgTy->isRecordType()) 11975 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11976 << ArgTy << TypeRange); 11977 11978 // Type must be complete per C99 7.17p3 because a declaring a variable 11979 // with an incomplete type would be ill-formed. 11980 if (!Dependent 11981 && RequireCompleteType(BuiltinLoc, ArgTy, 11982 diag::err_offsetof_incomplete_type, TypeRange)) 11983 return ExprError(); 11984 11985 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11986 // GCC extension, diagnose them. 11987 // FIXME: This diagnostic isn't actually visible because the location is in 11988 // a system header! 11989 if (Components.size() != 1) 11990 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11991 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11992 11993 bool DidWarnAboutNonPOD = false; 11994 QualType CurrentType = ArgTy; 11995 SmallVector<OffsetOfNode, 4> Comps; 11996 SmallVector<Expr*, 4> Exprs; 11997 for (const OffsetOfComponent &OC : Components) { 11998 if (OC.isBrackets) { 11999 // Offset of an array sub-field. TODO: Should we allow vector elements? 12000 if (!CurrentType->isDependentType()) { 12001 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12002 if(!AT) 12003 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12004 << CurrentType); 12005 CurrentType = AT->getElementType(); 12006 } else 12007 CurrentType = Context.DependentTy; 12008 12009 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12010 if (IdxRval.isInvalid()) 12011 return ExprError(); 12012 Expr *Idx = IdxRval.get(); 12013 12014 // The expression must be an integral expression. 12015 // FIXME: An integral constant expression? 12016 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12017 !Idx->getType()->isIntegerType()) 12018 return ExprError(Diag(Idx->getLocStart(), 12019 diag::err_typecheck_subscript_not_integer) 12020 << Idx->getSourceRange()); 12021 12022 // Record this array index. 12023 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12024 Exprs.push_back(Idx); 12025 continue; 12026 } 12027 12028 // Offset of a field. 12029 if (CurrentType->isDependentType()) { 12030 // We have the offset of a field, but we can't look into the dependent 12031 // type. Just record the identifier of the field. 12032 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12033 CurrentType = Context.DependentTy; 12034 continue; 12035 } 12036 12037 // We need to have a complete type to look into. 12038 if (RequireCompleteType(OC.LocStart, CurrentType, 12039 diag::err_offsetof_incomplete_type)) 12040 return ExprError(); 12041 12042 // Look for the designated field. 12043 const RecordType *RC = CurrentType->getAs<RecordType>(); 12044 if (!RC) 12045 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12046 << CurrentType); 12047 RecordDecl *RD = RC->getDecl(); 12048 12049 // C++ [lib.support.types]p5: 12050 // The macro offsetof accepts a restricted set of type arguments in this 12051 // International Standard. type shall be a POD structure or a POD union 12052 // (clause 9). 12053 // C++11 [support.types]p4: 12054 // If type is not a standard-layout class (Clause 9), the results are 12055 // undefined. 12056 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12057 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12058 unsigned DiagID = 12059 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12060 : diag::ext_offsetof_non_pod_type; 12061 12062 if (!IsSafe && !DidWarnAboutNonPOD && 12063 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12064 PDiag(DiagID) 12065 << SourceRange(Components[0].LocStart, OC.LocEnd) 12066 << CurrentType)) 12067 DidWarnAboutNonPOD = true; 12068 } 12069 12070 // Look for the field. 12071 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12072 LookupQualifiedName(R, RD); 12073 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12074 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12075 if (!MemberDecl) { 12076 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12077 MemberDecl = IndirectMemberDecl->getAnonField(); 12078 } 12079 12080 if (!MemberDecl) 12081 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12082 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12083 OC.LocEnd)); 12084 12085 // C99 7.17p3: 12086 // (If the specified member is a bit-field, the behavior is undefined.) 12087 // 12088 // We diagnose this as an error. 12089 if (MemberDecl->isBitField()) { 12090 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12091 << MemberDecl->getDeclName() 12092 << SourceRange(BuiltinLoc, RParenLoc); 12093 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12094 return ExprError(); 12095 } 12096 12097 RecordDecl *Parent = MemberDecl->getParent(); 12098 if (IndirectMemberDecl) 12099 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12100 12101 // If the member was found in a base class, introduce OffsetOfNodes for 12102 // the base class indirections. 12103 CXXBasePaths Paths; 12104 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12105 Paths)) { 12106 if (Paths.getDetectedVirtual()) { 12107 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12108 << MemberDecl->getDeclName() 12109 << SourceRange(BuiltinLoc, RParenLoc); 12110 return ExprError(); 12111 } 12112 12113 CXXBasePath &Path = Paths.front(); 12114 for (const CXXBasePathElement &B : Path) 12115 Comps.push_back(OffsetOfNode(B.Base)); 12116 } 12117 12118 if (IndirectMemberDecl) { 12119 for (auto *FI : IndirectMemberDecl->chain()) { 12120 assert(isa<FieldDecl>(FI)); 12121 Comps.push_back(OffsetOfNode(OC.LocStart, 12122 cast<FieldDecl>(FI), OC.LocEnd)); 12123 } 12124 } else 12125 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12126 12127 CurrentType = MemberDecl->getType().getNonReferenceType(); 12128 } 12129 12130 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12131 Comps, Exprs, RParenLoc); 12132 } 12133 12134 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12135 SourceLocation BuiltinLoc, 12136 SourceLocation TypeLoc, 12137 ParsedType ParsedArgTy, 12138 ArrayRef<OffsetOfComponent> Components, 12139 SourceLocation RParenLoc) { 12140 12141 TypeSourceInfo *ArgTInfo; 12142 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12143 if (ArgTy.isNull()) 12144 return ExprError(); 12145 12146 if (!ArgTInfo) 12147 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12148 12149 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12150 } 12151 12152 12153 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12154 Expr *CondExpr, 12155 Expr *LHSExpr, Expr *RHSExpr, 12156 SourceLocation RPLoc) { 12157 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12158 12159 ExprValueKind VK = VK_RValue; 12160 ExprObjectKind OK = OK_Ordinary; 12161 QualType resType; 12162 bool ValueDependent = false; 12163 bool CondIsTrue = false; 12164 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12165 resType = Context.DependentTy; 12166 ValueDependent = true; 12167 } else { 12168 // The conditional expression is required to be a constant expression. 12169 llvm::APSInt condEval(32); 12170 ExprResult CondICE 12171 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12172 diag::err_typecheck_choose_expr_requires_constant, false); 12173 if (CondICE.isInvalid()) 12174 return ExprError(); 12175 CondExpr = CondICE.get(); 12176 CondIsTrue = condEval.getZExtValue(); 12177 12178 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12179 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12180 12181 resType = ActiveExpr->getType(); 12182 ValueDependent = ActiveExpr->isValueDependent(); 12183 VK = ActiveExpr->getValueKind(); 12184 OK = ActiveExpr->getObjectKind(); 12185 } 12186 12187 return new (Context) 12188 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12189 CondIsTrue, resType->isDependentType(), ValueDependent); 12190 } 12191 12192 //===----------------------------------------------------------------------===// 12193 // Clang Extensions. 12194 //===----------------------------------------------------------------------===// 12195 12196 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12197 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12198 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12199 12200 if (LangOpts.CPlusPlus) { 12201 Decl *ManglingContextDecl; 12202 if (MangleNumberingContext *MCtx = 12203 getCurrentMangleNumberContext(Block->getDeclContext(), 12204 ManglingContextDecl)) { 12205 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12206 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12207 } 12208 } 12209 12210 PushBlockScope(CurScope, Block); 12211 CurContext->addDecl(Block); 12212 if (CurScope) 12213 PushDeclContext(CurScope, Block); 12214 else 12215 CurContext = Block; 12216 12217 getCurBlock()->HasImplicitReturnType = true; 12218 12219 // Enter a new evaluation context to insulate the block from any 12220 // cleanups from the enclosing full-expression. 12221 PushExpressionEvaluationContext(PotentiallyEvaluated); 12222 } 12223 12224 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12225 Scope *CurScope) { 12226 assert(ParamInfo.getIdentifier() == nullptr && 12227 "block-id should have no identifier!"); 12228 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12229 BlockScopeInfo *CurBlock = getCurBlock(); 12230 12231 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12232 QualType T = Sig->getType(); 12233 12234 // FIXME: We should allow unexpanded parameter packs here, but that would, 12235 // in turn, make the block expression contain unexpanded parameter packs. 12236 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12237 // Drop the parameters. 12238 FunctionProtoType::ExtProtoInfo EPI; 12239 EPI.HasTrailingReturn = false; 12240 EPI.TypeQuals |= DeclSpec::TQ_const; 12241 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12242 Sig = Context.getTrivialTypeSourceInfo(T); 12243 } 12244 12245 // GetTypeForDeclarator always produces a function type for a block 12246 // literal signature. Furthermore, it is always a FunctionProtoType 12247 // unless the function was written with a typedef. 12248 assert(T->isFunctionType() && 12249 "GetTypeForDeclarator made a non-function block signature"); 12250 12251 // Look for an explicit signature in that function type. 12252 FunctionProtoTypeLoc ExplicitSignature; 12253 12254 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12255 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12256 12257 // Check whether that explicit signature was synthesized by 12258 // GetTypeForDeclarator. If so, don't save that as part of the 12259 // written signature. 12260 if (ExplicitSignature.getLocalRangeBegin() == 12261 ExplicitSignature.getLocalRangeEnd()) { 12262 // This would be much cheaper if we stored TypeLocs instead of 12263 // TypeSourceInfos. 12264 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12265 unsigned Size = Result.getFullDataSize(); 12266 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12267 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12268 12269 ExplicitSignature = FunctionProtoTypeLoc(); 12270 } 12271 } 12272 12273 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12274 CurBlock->FunctionType = T; 12275 12276 const FunctionType *Fn = T->getAs<FunctionType>(); 12277 QualType RetTy = Fn->getReturnType(); 12278 bool isVariadic = 12279 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12280 12281 CurBlock->TheDecl->setIsVariadic(isVariadic); 12282 12283 // Context.DependentTy is used as a placeholder for a missing block 12284 // return type. TODO: what should we do with declarators like: 12285 // ^ * { ... } 12286 // If the answer is "apply template argument deduction".... 12287 if (RetTy != Context.DependentTy) { 12288 CurBlock->ReturnType = RetTy; 12289 CurBlock->TheDecl->setBlockMissingReturnType(false); 12290 CurBlock->HasImplicitReturnType = false; 12291 } 12292 12293 // Push block parameters from the declarator if we had them. 12294 SmallVector<ParmVarDecl*, 8> Params; 12295 if (ExplicitSignature) { 12296 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12297 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12298 if (Param->getIdentifier() == nullptr && 12299 !Param->isImplicit() && 12300 !Param->isInvalidDecl() && 12301 !getLangOpts().CPlusPlus) 12302 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12303 Params.push_back(Param); 12304 } 12305 12306 // Fake up parameter variables if we have a typedef, like 12307 // ^ fntype { ... } 12308 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12309 for (const auto &I : Fn->param_types()) { 12310 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12311 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12312 Params.push_back(Param); 12313 } 12314 } 12315 12316 // Set the parameters on the block decl. 12317 if (!Params.empty()) { 12318 CurBlock->TheDecl->setParams(Params); 12319 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12320 /*CheckParameterNames=*/false); 12321 } 12322 12323 // Finally we can process decl attributes. 12324 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12325 12326 // Put the parameter variables in scope. 12327 for (auto AI : CurBlock->TheDecl->parameters()) { 12328 AI->setOwningFunction(CurBlock->TheDecl); 12329 12330 // If this has an identifier, add it to the scope stack. 12331 if (AI->getIdentifier()) { 12332 CheckShadow(CurBlock->TheScope, AI); 12333 12334 PushOnScopeChains(AI, CurBlock->TheScope); 12335 } 12336 } 12337 } 12338 12339 /// ActOnBlockError - If there is an error parsing a block, this callback 12340 /// is invoked to pop the information about the block from the action impl. 12341 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12342 // Leave the expression-evaluation context. 12343 DiscardCleanupsInEvaluationContext(); 12344 PopExpressionEvaluationContext(); 12345 12346 // Pop off CurBlock, handle nested blocks. 12347 PopDeclContext(); 12348 PopFunctionScopeInfo(); 12349 } 12350 12351 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12352 /// literal was successfully completed. ^(int x){...} 12353 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12354 Stmt *Body, Scope *CurScope) { 12355 // If blocks are disabled, emit an error. 12356 if (!LangOpts.Blocks) 12357 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12358 12359 // Leave the expression-evaluation context. 12360 if (hasAnyUnrecoverableErrorsInThisFunction()) 12361 DiscardCleanupsInEvaluationContext(); 12362 assert(!Cleanup.exprNeedsCleanups() && 12363 "cleanups within block not correctly bound!"); 12364 PopExpressionEvaluationContext(); 12365 12366 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12367 12368 if (BSI->HasImplicitReturnType) 12369 deduceClosureReturnType(*BSI); 12370 12371 PopDeclContext(); 12372 12373 QualType RetTy = Context.VoidTy; 12374 if (!BSI->ReturnType.isNull()) 12375 RetTy = BSI->ReturnType; 12376 12377 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12378 QualType BlockTy; 12379 12380 // Set the captured variables on the block. 12381 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12382 SmallVector<BlockDecl::Capture, 4> Captures; 12383 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12384 if (Cap.isThisCapture()) 12385 continue; 12386 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12387 Cap.isNested(), Cap.getInitExpr()); 12388 Captures.push_back(NewCap); 12389 } 12390 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12391 12392 // If the user wrote a function type in some form, try to use that. 12393 if (!BSI->FunctionType.isNull()) { 12394 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12395 12396 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12397 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12398 12399 // Turn protoless block types into nullary block types. 12400 if (isa<FunctionNoProtoType>(FTy)) { 12401 FunctionProtoType::ExtProtoInfo EPI; 12402 EPI.ExtInfo = Ext; 12403 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12404 12405 // Otherwise, if we don't need to change anything about the function type, 12406 // preserve its sugar structure. 12407 } else if (FTy->getReturnType() == RetTy && 12408 (!NoReturn || FTy->getNoReturnAttr())) { 12409 BlockTy = BSI->FunctionType; 12410 12411 // Otherwise, make the minimal modifications to the function type. 12412 } else { 12413 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12414 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12415 EPI.TypeQuals = 0; // FIXME: silently? 12416 EPI.ExtInfo = Ext; 12417 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12418 } 12419 12420 // If we don't have a function type, just build one from nothing. 12421 } else { 12422 FunctionProtoType::ExtProtoInfo EPI; 12423 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12424 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12425 } 12426 12427 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12428 BlockTy = Context.getBlockPointerType(BlockTy); 12429 12430 // If needed, diagnose invalid gotos and switches in the block. 12431 if (getCurFunction()->NeedsScopeChecking() && 12432 !PP.isCodeCompletionEnabled()) 12433 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12434 12435 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12436 12437 // Try to apply the named return value optimization. We have to check again 12438 // if we can do this, though, because blocks keep return statements around 12439 // to deduce an implicit return type. 12440 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12441 !BSI->TheDecl->isDependentContext()) 12442 computeNRVO(Body, BSI); 12443 12444 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12445 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12446 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12447 12448 // If the block isn't obviously global, i.e. it captures anything at 12449 // all, then we need to do a few things in the surrounding context: 12450 if (Result->getBlockDecl()->hasCaptures()) { 12451 // First, this expression has a new cleanup object. 12452 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12453 Cleanup.setExprNeedsCleanups(true); 12454 12455 // It also gets a branch-protected scope if any of the captured 12456 // variables needs destruction. 12457 for (const auto &CI : Result->getBlockDecl()->captures()) { 12458 const VarDecl *var = CI.getVariable(); 12459 if (var->getType().isDestructedType() != QualType::DK_none) { 12460 getCurFunction()->setHasBranchProtectedScope(); 12461 break; 12462 } 12463 } 12464 } 12465 12466 return Result; 12467 } 12468 12469 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12470 SourceLocation RPLoc) { 12471 TypeSourceInfo *TInfo; 12472 GetTypeFromParser(Ty, &TInfo); 12473 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12474 } 12475 12476 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12477 Expr *E, TypeSourceInfo *TInfo, 12478 SourceLocation RPLoc) { 12479 Expr *OrigExpr = E; 12480 bool IsMS = false; 12481 12482 // CUDA device code does not support varargs. 12483 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12484 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12485 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12486 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12487 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12488 } 12489 } 12490 12491 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12492 // as Microsoft ABI on an actual Microsoft platform, where 12493 // __builtin_ms_va_list and __builtin_va_list are the same.) 12494 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12495 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12496 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12497 if (Context.hasSameType(MSVaListType, E->getType())) { 12498 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12499 return ExprError(); 12500 IsMS = true; 12501 } 12502 } 12503 12504 // Get the va_list type 12505 QualType VaListType = Context.getBuiltinVaListType(); 12506 if (!IsMS) { 12507 if (VaListType->isArrayType()) { 12508 // Deal with implicit array decay; for example, on x86-64, 12509 // va_list is an array, but it's supposed to decay to 12510 // a pointer for va_arg. 12511 VaListType = Context.getArrayDecayedType(VaListType); 12512 // Make sure the input expression also decays appropriately. 12513 ExprResult Result = UsualUnaryConversions(E); 12514 if (Result.isInvalid()) 12515 return ExprError(); 12516 E = Result.get(); 12517 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12518 // If va_list is a record type and we are compiling in C++ mode, 12519 // check the argument using reference binding. 12520 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12521 Context, Context.getLValueReferenceType(VaListType), false); 12522 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12523 if (Init.isInvalid()) 12524 return ExprError(); 12525 E = Init.getAs<Expr>(); 12526 } else { 12527 // Otherwise, the va_list argument must be an l-value because 12528 // it is modified by va_arg. 12529 if (!E->isTypeDependent() && 12530 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12531 return ExprError(); 12532 } 12533 } 12534 12535 if (!IsMS && !E->isTypeDependent() && 12536 !Context.hasSameType(VaListType, E->getType())) 12537 return ExprError(Diag(E->getLocStart(), 12538 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12539 << OrigExpr->getType() << E->getSourceRange()); 12540 12541 if (!TInfo->getType()->isDependentType()) { 12542 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12543 diag::err_second_parameter_to_va_arg_incomplete, 12544 TInfo->getTypeLoc())) 12545 return ExprError(); 12546 12547 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12548 TInfo->getType(), 12549 diag::err_second_parameter_to_va_arg_abstract, 12550 TInfo->getTypeLoc())) 12551 return ExprError(); 12552 12553 if (!TInfo->getType().isPODType(Context)) { 12554 Diag(TInfo->getTypeLoc().getBeginLoc(), 12555 TInfo->getType()->isObjCLifetimeType() 12556 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12557 : diag::warn_second_parameter_to_va_arg_not_pod) 12558 << TInfo->getType() 12559 << TInfo->getTypeLoc().getSourceRange(); 12560 } 12561 12562 // Check for va_arg where arguments of the given type will be promoted 12563 // (i.e. this va_arg is guaranteed to have undefined behavior). 12564 QualType PromoteType; 12565 if (TInfo->getType()->isPromotableIntegerType()) { 12566 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12567 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12568 PromoteType = QualType(); 12569 } 12570 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12571 PromoteType = Context.DoubleTy; 12572 if (!PromoteType.isNull()) 12573 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12574 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12575 << TInfo->getType() 12576 << PromoteType 12577 << TInfo->getTypeLoc().getSourceRange()); 12578 } 12579 12580 QualType T = TInfo->getType().getNonLValueExprType(Context); 12581 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12582 } 12583 12584 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12585 // The type of __null will be int or long, depending on the size of 12586 // pointers on the target. 12587 QualType Ty; 12588 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12589 if (pw == Context.getTargetInfo().getIntWidth()) 12590 Ty = Context.IntTy; 12591 else if (pw == Context.getTargetInfo().getLongWidth()) 12592 Ty = Context.LongTy; 12593 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12594 Ty = Context.LongLongTy; 12595 else { 12596 llvm_unreachable("I don't know size of pointer!"); 12597 } 12598 12599 return new (Context) GNUNullExpr(Ty, TokenLoc); 12600 } 12601 12602 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12603 bool Diagnose) { 12604 if (!getLangOpts().ObjC1) 12605 return false; 12606 12607 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12608 if (!PT) 12609 return false; 12610 12611 if (!PT->isObjCIdType()) { 12612 // Check if the destination is the 'NSString' interface. 12613 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12614 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12615 return false; 12616 } 12617 12618 // Ignore any parens, implicit casts (should only be 12619 // array-to-pointer decays), and not-so-opaque values. The last is 12620 // important for making this trigger for property assignments. 12621 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12622 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12623 if (OV->getSourceExpr()) 12624 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12625 12626 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12627 if (!SL || !SL->isAscii()) 12628 return false; 12629 if (Diagnose) { 12630 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12631 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12632 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12633 } 12634 return true; 12635 } 12636 12637 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12638 const Expr *SrcExpr) { 12639 if (!DstType->isFunctionPointerType() || 12640 !SrcExpr->getType()->isFunctionType()) 12641 return false; 12642 12643 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12644 if (!DRE) 12645 return false; 12646 12647 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12648 if (!FD) 12649 return false; 12650 12651 return !S.checkAddressOfFunctionIsAvailable(FD, 12652 /*Complain=*/true, 12653 SrcExpr->getLocStart()); 12654 } 12655 12656 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12657 SourceLocation Loc, 12658 QualType DstType, QualType SrcType, 12659 Expr *SrcExpr, AssignmentAction Action, 12660 bool *Complained) { 12661 if (Complained) 12662 *Complained = false; 12663 12664 // Decode the result (notice that AST's are still created for extensions). 12665 bool CheckInferredResultType = false; 12666 bool isInvalid = false; 12667 unsigned DiagKind = 0; 12668 FixItHint Hint; 12669 ConversionFixItGenerator ConvHints; 12670 bool MayHaveConvFixit = false; 12671 bool MayHaveFunctionDiff = false; 12672 const ObjCInterfaceDecl *IFace = nullptr; 12673 const ObjCProtocolDecl *PDecl = nullptr; 12674 12675 switch (ConvTy) { 12676 case Compatible: 12677 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12678 return false; 12679 12680 case PointerToInt: 12681 DiagKind = diag::ext_typecheck_convert_pointer_int; 12682 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12683 MayHaveConvFixit = true; 12684 break; 12685 case IntToPointer: 12686 DiagKind = diag::ext_typecheck_convert_int_pointer; 12687 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12688 MayHaveConvFixit = true; 12689 break; 12690 case IncompatiblePointer: 12691 if (Action == AA_Passing_CFAudited) 12692 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12693 else if (SrcType->isFunctionPointerType() && 12694 DstType->isFunctionPointerType()) 12695 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12696 else 12697 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12698 12699 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12700 SrcType->isObjCObjectPointerType(); 12701 if (Hint.isNull() && !CheckInferredResultType) { 12702 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12703 } 12704 else if (CheckInferredResultType) { 12705 SrcType = SrcType.getUnqualifiedType(); 12706 DstType = DstType.getUnqualifiedType(); 12707 } 12708 MayHaveConvFixit = true; 12709 break; 12710 case IncompatiblePointerSign: 12711 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12712 break; 12713 case FunctionVoidPointer: 12714 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12715 break; 12716 case IncompatiblePointerDiscardsQualifiers: { 12717 // Perform array-to-pointer decay if necessary. 12718 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12719 12720 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12721 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12722 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12723 DiagKind = diag::err_typecheck_incompatible_address_space; 12724 break; 12725 12726 12727 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12728 DiagKind = diag::err_typecheck_incompatible_ownership; 12729 break; 12730 } 12731 12732 llvm_unreachable("unknown error case for discarding qualifiers!"); 12733 // fallthrough 12734 } 12735 case CompatiblePointerDiscardsQualifiers: 12736 // If the qualifiers lost were because we were applying the 12737 // (deprecated) C++ conversion from a string literal to a char* 12738 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12739 // Ideally, this check would be performed in 12740 // checkPointerTypesForAssignment. However, that would require a 12741 // bit of refactoring (so that the second argument is an 12742 // expression, rather than a type), which should be done as part 12743 // of a larger effort to fix checkPointerTypesForAssignment for 12744 // C++ semantics. 12745 if (getLangOpts().CPlusPlus && 12746 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12747 return false; 12748 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12749 break; 12750 case IncompatibleNestedPointerQualifiers: 12751 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12752 break; 12753 case IntToBlockPointer: 12754 DiagKind = diag::err_int_to_block_pointer; 12755 break; 12756 case IncompatibleBlockPointer: 12757 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12758 break; 12759 case IncompatibleObjCQualifiedId: { 12760 if (SrcType->isObjCQualifiedIdType()) { 12761 const ObjCObjectPointerType *srcOPT = 12762 SrcType->getAs<ObjCObjectPointerType>(); 12763 for (auto *srcProto : srcOPT->quals()) { 12764 PDecl = srcProto; 12765 break; 12766 } 12767 if (const ObjCInterfaceType *IFaceT = 12768 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12769 IFace = IFaceT->getDecl(); 12770 } 12771 else if (DstType->isObjCQualifiedIdType()) { 12772 const ObjCObjectPointerType *dstOPT = 12773 DstType->getAs<ObjCObjectPointerType>(); 12774 for (auto *dstProto : dstOPT->quals()) { 12775 PDecl = dstProto; 12776 break; 12777 } 12778 if (const ObjCInterfaceType *IFaceT = 12779 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12780 IFace = IFaceT->getDecl(); 12781 } 12782 DiagKind = diag::warn_incompatible_qualified_id; 12783 break; 12784 } 12785 case IncompatibleVectors: 12786 DiagKind = diag::warn_incompatible_vectors; 12787 break; 12788 case IncompatibleObjCWeakRef: 12789 DiagKind = diag::err_arc_weak_unavailable_assign; 12790 break; 12791 case Incompatible: 12792 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12793 if (Complained) 12794 *Complained = true; 12795 return true; 12796 } 12797 12798 DiagKind = diag::err_typecheck_convert_incompatible; 12799 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12800 MayHaveConvFixit = true; 12801 isInvalid = true; 12802 MayHaveFunctionDiff = true; 12803 break; 12804 } 12805 12806 QualType FirstType, SecondType; 12807 switch (Action) { 12808 case AA_Assigning: 12809 case AA_Initializing: 12810 // The destination type comes first. 12811 FirstType = DstType; 12812 SecondType = SrcType; 12813 break; 12814 12815 case AA_Returning: 12816 case AA_Passing: 12817 case AA_Passing_CFAudited: 12818 case AA_Converting: 12819 case AA_Sending: 12820 case AA_Casting: 12821 // The source type comes first. 12822 FirstType = SrcType; 12823 SecondType = DstType; 12824 break; 12825 } 12826 12827 PartialDiagnostic FDiag = PDiag(DiagKind); 12828 if (Action == AA_Passing_CFAudited) 12829 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12830 else 12831 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12832 12833 // If we can fix the conversion, suggest the FixIts. 12834 assert(ConvHints.isNull() || Hint.isNull()); 12835 if (!ConvHints.isNull()) { 12836 for (FixItHint &H : ConvHints.Hints) 12837 FDiag << H; 12838 } else { 12839 FDiag << Hint; 12840 } 12841 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12842 12843 if (MayHaveFunctionDiff) 12844 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12845 12846 Diag(Loc, FDiag); 12847 if (DiagKind == diag::warn_incompatible_qualified_id && 12848 PDecl && IFace && !IFace->hasDefinition()) 12849 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 12850 << IFace->getName() << PDecl->getName(); 12851 12852 if (SecondType == Context.OverloadTy) 12853 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12854 FirstType, /*TakingAddress=*/true); 12855 12856 if (CheckInferredResultType) 12857 EmitRelatedResultTypeNote(SrcExpr); 12858 12859 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12860 EmitRelatedResultTypeNoteForReturn(DstType); 12861 12862 if (Complained) 12863 *Complained = true; 12864 return isInvalid; 12865 } 12866 12867 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12868 llvm::APSInt *Result) { 12869 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12870 public: 12871 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12872 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12873 } 12874 } Diagnoser; 12875 12876 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12877 } 12878 12879 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12880 llvm::APSInt *Result, 12881 unsigned DiagID, 12882 bool AllowFold) { 12883 class IDDiagnoser : public VerifyICEDiagnoser { 12884 unsigned DiagID; 12885 12886 public: 12887 IDDiagnoser(unsigned DiagID) 12888 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12889 12890 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12891 S.Diag(Loc, DiagID) << SR; 12892 } 12893 } Diagnoser(DiagID); 12894 12895 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12896 } 12897 12898 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12899 SourceRange SR) { 12900 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12901 } 12902 12903 ExprResult 12904 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12905 VerifyICEDiagnoser &Diagnoser, 12906 bool AllowFold) { 12907 SourceLocation DiagLoc = E->getLocStart(); 12908 12909 if (getLangOpts().CPlusPlus11) { 12910 // C++11 [expr.const]p5: 12911 // If an expression of literal class type is used in a context where an 12912 // integral constant expression is required, then that class type shall 12913 // have a single non-explicit conversion function to an integral or 12914 // unscoped enumeration type 12915 ExprResult Converted; 12916 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12917 public: 12918 CXX11ConvertDiagnoser(bool Silent) 12919 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12920 Silent, true) {} 12921 12922 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12923 QualType T) override { 12924 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12925 } 12926 12927 SemaDiagnosticBuilder diagnoseIncomplete( 12928 Sema &S, SourceLocation Loc, QualType T) override { 12929 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12930 } 12931 12932 SemaDiagnosticBuilder diagnoseExplicitConv( 12933 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12934 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12935 } 12936 12937 SemaDiagnosticBuilder noteExplicitConv( 12938 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12939 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12940 << ConvTy->isEnumeralType() << ConvTy; 12941 } 12942 12943 SemaDiagnosticBuilder diagnoseAmbiguous( 12944 Sema &S, SourceLocation Loc, QualType T) override { 12945 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12946 } 12947 12948 SemaDiagnosticBuilder noteAmbiguous( 12949 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12950 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12951 << ConvTy->isEnumeralType() << ConvTy; 12952 } 12953 12954 SemaDiagnosticBuilder diagnoseConversion( 12955 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12956 llvm_unreachable("conversion functions are permitted"); 12957 } 12958 } ConvertDiagnoser(Diagnoser.Suppress); 12959 12960 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12961 ConvertDiagnoser); 12962 if (Converted.isInvalid()) 12963 return Converted; 12964 E = Converted.get(); 12965 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12966 return ExprError(); 12967 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12968 // An ICE must be of integral or unscoped enumeration type. 12969 if (!Diagnoser.Suppress) 12970 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12971 return ExprError(); 12972 } 12973 12974 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12975 // in the non-ICE case. 12976 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12977 if (Result) 12978 *Result = E->EvaluateKnownConstInt(Context); 12979 return E; 12980 } 12981 12982 Expr::EvalResult EvalResult; 12983 SmallVector<PartialDiagnosticAt, 8> Notes; 12984 EvalResult.Diag = &Notes; 12985 12986 // Try to evaluate the expression, and produce diagnostics explaining why it's 12987 // not a constant expression as a side-effect. 12988 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12989 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12990 12991 // In C++11, we can rely on diagnostics being produced for any expression 12992 // which is not a constant expression. If no diagnostics were produced, then 12993 // this is a constant expression. 12994 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12995 if (Result) 12996 *Result = EvalResult.Val.getInt(); 12997 return E; 12998 } 12999 13000 // If our only note is the usual "invalid subexpression" note, just point 13001 // the caret at its location rather than producing an essentially 13002 // redundant note. 13003 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13004 diag::note_invalid_subexpr_in_const_expr) { 13005 DiagLoc = Notes[0].first; 13006 Notes.clear(); 13007 } 13008 13009 if (!Folded || !AllowFold) { 13010 if (!Diagnoser.Suppress) { 13011 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13012 for (const PartialDiagnosticAt &Note : Notes) 13013 Diag(Note.first, Note.second); 13014 } 13015 13016 return ExprError(); 13017 } 13018 13019 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13020 for (const PartialDiagnosticAt &Note : Notes) 13021 Diag(Note.first, Note.second); 13022 13023 if (Result) 13024 *Result = EvalResult.Val.getInt(); 13025 return E; 13026 } 13027 13028 namespace { 13029 // Handle the case where we conclude a expression which we speculatively 13030 // considered to be unevaluated is actually evaluated. 13031 class TransformToPE : public TreeTransform<TransformToPE> { 13032 typedef TreeTransform<TransformToPE> BaseTransform; 13033 13034 public: 13035 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13036 13037 // Make sure we redo semantic analysis 13038 bool AlwaysRebuild() { return true; } 13039 13040 // Make sure we handle LabelStmts correctly. 13041 // FIXME: This does the right thing, but maybe we need a more general 13042 // fix to TreeTransform? 13043 StmtResult TransformLabelStmt(LabelStmt *S) { 13044 S->getDecl()->setStmt(nullptr); 13045 return BaseTransform::TransformLabelStmt(S); 13046 } 13047 13048 // We need to special-case DeclRefExprs referring to FieldDecls which 13049 // are not part of a member pointer formation; normal TreeTransforming 13050 // doesn't catch this case because of the way we represent them in the AST. 13051 // FIXME: This is a bit ugly; is it really the best way to handle this 13052 // case? 13053 // 13054 // Error on DeclRefExprs referring to FieldDecls. 13055 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13056 if (isa<FieldDecl>(E->getDecl()) && 13057 !SemaRef.isUnevaluatedContext()) 13058 return SemaRef.Diag(E->getLocation(), 13059 diag::err_invalid_non_static_member_use) 13060 << E->getDecl() << E->getSourceRange(); 13061 13062 return BaseTransform::TransformDeclRefExpr(E); 13063 } 13064 13065 // Exception: filter out member pointer formation 13066 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13067 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13068 return E; 13069 13070 return BaseTransform::TransformUnaryOperator(E); 13071 } 13072 13073 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13074 // Lambdas never need to be transformed. 13075 return E; 13076 } 13077 }; 13078 } 13079 13080 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13081 assert(isUnevaluatedContext() && 13082 "Should only transform unevaluated expressions"); 13083 ExprEvalContexts.back().Context = 13084 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13085 if (isUnevaluatedContext()) 13086 return E; 13087 return TransformToPE(*this).TransformExpr(E); 13088 } 13089 13090 void 13091 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13092 Decl *LambdaContextDecl, 13093 bool IsDecltype) { 13094 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13095 LambdaContextDecl, IsDecltype); 13096 Cleanup.reset(); 13097 if (!MaybeODRUseExprs.empty()) 13098 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13099 } 13100 13101 void 13102 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13103 ReuseLambdaContextDecl_t, 13104 bool IsDecltype) { 13105 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13106 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13107 } 13108 13109 void Sema::PopExpressionEvaluationContext() { 13110 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13111 unsigned NumTypos = Rec.NumTypos; 13112 13113 if (!Rec.Lambdas.empty()) { 13114 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13115 unsigned D; 13116 if (Rec.isUnevaluated()) { 13117 // C++11 [expr.prim.lambda]p2: 13118 // A lambda-expression shall not appear in an unevaluated operand 13119 // (Clause 5). 13120 D = diag::err_lambda_unevaluated_operand; 13121 } else { 13122 // C++1y [expr.const]p2: 13123 // A conditional-expression e is a core constant expression unless the 13124 // evaluation of e, following the rules of the abstract machine, would 13125 // evaluate [...] a lambda-expression. 13126 D = diag::err_lambda_in_constant_expression; 13127 } 13128 13129 // C++1z allows lambda expressions as core constant expressions. 13130 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13131 // 1607) from appearing within template-arguments and array-bounds that 13132 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13133 // unevaluated contexts) might lift some of these restrictions in a 13134 // future version. 13135 if (Rec.Context != ConstantEvaluated || !getLangOpts().CPlusPlus1z) 13136 for (const auto *L : Rec.Lambdas) 13137 Diag(L->getLocStart(), D); 13138 } else { 13139 // Mark the capture expressions odr-used. This was deferred 13140 // during lambda expression creation. 13141 for (auto *Lambda : Rec.Lambdas) { 13142 for (auto *C : Lambda->capture_inits()) 13143 MarkDeclarationsReferencedInExpr(C); 13144 } 13145 } 13146 } 13147 13148 // When are coming out of an unevaluated context, clear out any 13149 // temporaries that we may have created as part of the evaluation of 13150 // the expression in that context: they aren't relevant because they 13151 // will never be constructed. 13152 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13153 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13154 ExprCleanupObjects.end()); 13155 Cleanup = Rec.ParentCleanup; 13156 CleanupVarDeclMarking(); 13157 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13158 // Otherwise, merge the contexts together. 13159 } else { 13160 Cleanup.mergeFrom(Rec.ParentCleanup); 13161 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13162 Rec.SavedMaybeODRUseExprs.end()); 13163 } 13164 13165 // Pop the current expression evaluation context off the stack. 13166 ExprEvalContexts.pop_back(); 13167 13168 if (!ExprEvalContexts.empty()) 13169 ExprEvalContexts.back().NumTypos += NumTypos; 13170 else 13171 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13172 "last ExpressionEvaluationContextRecord"); 13173 } 13174 13175 void Sema::DiscardCleanupsInEvaluationContext() { 13176 ExprCleanupObjects.erase( 13177 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13178 ExprCleanupObjects.end()); 13179 Cleanup.reset(); 13180 MaybeODRUseExprs.clear(); 13181 } 13182 13183 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13184 if (!E->getType()->isVariablyModifiedType()) 13185 return E; 13186 return TransformToPotentiallyEvaluated(E); 13187 } 13188 13189 /// Are we within a context in which some evaluation could be performed (be it 13190 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13191 /// captured by C++'s idea of an "unevaluated context". 13192 static bool isEvaluatableContext(Sema &SemaRef) { 13193 switch (SemaRef.ExprEvalContexts.back().Context) { 13194 case Sema::Unevaluated: 13195 case Sema::UnevaluatedAbstract: 13196 case Sema::DiscardedStatement: 13197 // Expressions in this context are never evaluated. 13198 return false; 13199 13200 case Sema::UnevaluatedList: 13201 case Sema::ConstantEvaluated: 13202 case Sema::PotentiallyEvaluated: 13203 // Expressions in this context could be evaluated. 13204 return true; 13205 13206 case Sema::PotentiallyEvaluatedIfUsed: 13207 // Referenced declarations will only be used if the construct in the 13208 // containing expression is used, at which point we'll be given another 13209 // turn to mark them. 13210 return false; 13211 } 13212 llvm_unreachable("Invalid context"); 13213 } 13214 13215 /// Are we within a context in which references to resolved functions or to 13216 /// variables result in odr-use? 13217 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13218 // An expression in a template is not really an expression until it's been 13219 // instantiated, so it doesn't trigger odr-use. 13220 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13221 return false; 13222 13223 switch (SemaRef.ExprEvalContexts.back().Context) { 13224 case Sema::Unevaluated: 13225 case Sema::UnevaluatedList: 13226 case Sema::UnevaluatedAbstract: 13227 case Sema::DiscardedStatement: 13228 return false; 13229 13230 case Sema::ConstantEvaluated: 13231 case Sema::PotentiallyEvaluated: 13232 return true; 13233 13234 case Sema::PotentiallyEvaluatedIfUsed: 13235 return false; 13236 } 13237 llvm_unreachable("Invalid context"); 13238 } 13239 13240 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13241 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13242 return Func->isConstexpr() && 13243 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13244 } 13245 13246 /// \brief Mark a function referenced, and check whether it is odr-used 13247 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13248 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13249 bool MightBeOdrUse) { 13250 assert(Func && "No function?"); 13251 13252 Func->setReferenced(); 13253 13254 // C++11 [basic.def.odr]p3: 13255 // A function whose name appears as a potentially-evaluated expression is 13256 // odr-used if it is the unique lookup result or the selected member of a 13257 // set of overloaded functions [...]. 13258 // 13259 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13260 // can just check that here. 13261 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13262 13263 // Determine whether we require a function definition to exist, per 13264 // C++11 [temp.inst]p3: 13265 // Unless a function template specialization has been explicitly 13266 // instantiated or explicitly specialized, the function template 13267 // specialization is implicitly instantiated when the specialization is 13268 // referenced in a context that requires a function definition to exist. 13269 // 13270 // That is either when this is an odr-use, or when a usage of a constexpr 13271 // function occurs within an evaluatable context. 13272 bool NeedDefinition = 13273 OdrUse || (isEvaluatableContext(*this) && 13274 isImplicitlyDefinableConstexprFunction(Func)); 13275 13276 // C++14 [temp.expl.spec]p6: 13277 // If a template [...] is explicitly specialized then that specialization 13278 // shall be declared before the first use of that specialization that would 13279 // cause an implicit instantiation to take place, in every translation unit 13280 // in which such a use occurs 13281 if (NeedDefinition && 13282 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13283 Func->getMemberSpecializationInfo())) 13284 checkSpecializationVisibility(Loc, Func); 13285 13286 // C++14 [except.spec]p17: 13287 // An exception-specification is considered to be needed when: 13288 // - the function is odr-used or, if it appears in an unevaluated operand, 13289 // would be odr-used if the expression were potentially-evaluated; 13290 // 13291 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13292 // function is a pure virtual function we're calling, and in that case the 13293 // function was selected by overload resolution and we need to resolve its 13294 // exception specification for a different reason. 13295 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13296 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13297 ResolveExceptionSpec(Loc, FPT); 13298 13299 // If we don't need to mark the function as used, and we don't need to 13300 // try to provide a definition, there's nothing more to do. 13301 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13302 (!NeedDefinition || Func->getBody())) 13303 return; 13304 13305 // Note that this declaration has been used. 13306 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13307 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13308 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13309 if (Constructor->isDefaultConstructor()) { 13310 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13311 return; 13312 DefineImplicitDefaultConstructor(Loc, Constructor); 13313 } else if (Constructor->isCopyConstructor()) { 13314 DefineImplicitCopyConstructor(Loc, Constructor); 13315 } else if (Constructor->isMoveConstructor()) { 13316 DefineImplicitMoveConstructor(Loc, Constructor); 13317 } 13318 } else if (Constructor->getInheritedConstructor()) { 13319 DefineInheritingConstructor(Loc, Constructor); 13320 } 13321 } else if (CXXDestructorDecl *Destructor = 13322 dyn_cast<CXXDestructorDecl>(Func)) { 13323 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13324 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13325 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13326 return; 13327 DefineImplicitDestructor(Loc, Destructor); 13328 } 13329 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13330 MarkVTableUsed(Loc, Destructor->getParent()); 13331 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13332 if (MethodDecl->isOverloadedOperator() && 13333 MethodDecl->getOverloadedOperator() == OO_Equal) { 13334 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13335 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13336 if (MethodDecl->isCopyAssignmentOperator()) 13337 DefineImplicitCopyAssignment(Loc, MethodDecl); 13338 else if (MethodDecl->isMoveAssignmentOperator()) 13339 DefineImplicitMoveAssignment(Loc, MethodDecl); 13340 } 13341 } else if (isa<CXXConversionDecl>(MethodDecl) && 13342 MethodDecl->getParent()->isLambda()) { 13343 CXXConversionDecl *Conversion = 13344 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13345 if (Conversion->isLambdaToBlockPointerConversion()) 13346 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13347 else 13348 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13349 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13350 MarkVTableUsed(Loc, MethodDecl->getParent()); 13351 } 13352 13353 // Recursive functions should be marked when used from another function. 13354 // FIXME: Is this really right? 13355 if (CurContext == Func) return; 13356 13357 // Implicit instantiation of function templates and member functions of 13358 // class templates. 13359 if (Func->isImplicitlyInstantiable()) { 13360 bool AlreadyInstantiated = false; 13361 SourceLocation PointOfInstantiation = Loc; 13362 if (FunctionTemplateSpecializationInfo *SpecInfo 13363 = Func->getTemplateSpecializationInfo()) { 13364 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13365 SpecInfo->setPointOfInstantiation(Loc); 13366 else if (SpecInfo->getTemplateSpecializationKind() 13367 == TSK_ImplicitInstantiation) { 13368 AlreadyInstantiated = true; 13369 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13370 } 13371 } else if (MemberSpecializationInfo *MSInfo 13372 = Func->getMemberSpecializationInfo()) { 13373 if (MSInfo->getPointOfInstantiation().isInvalid()) 13374 MSInfo->setPointOfInstantiation(Loc); 13375 else if (MSInfo->getTemplateSpecializationKind() 13376 == TSK_ImplicitInstantiation) { 13377 AlreadyInstantiated = true; 13378 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13379 } 13380 } 13381 13382 if (!AlreadyInstantiated || Func->isConstexpr()) { 13383 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13384 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13385 ActiveTemplateInstantiations.size()) 13386 PendingLocalImplicitInstantiations.push_back( 13387 std::make_pair(Func, PointOfInstantiation)); 13388 else if (Func->isConstexpr()) 13389 // Do not defer instantiations of constexpr functions, to avoid the 13390 // expression evaluator needing to call back into Sema if it sees a 13391 // call to such a function. 13392 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13393 else { 13394 PendingInstantiations.push_back(std::make_pair(Func, 13395 PointOfInstantiation)); 13396 // Notify the consumer that a function was implicitly instantiated. 13397 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13398 } 13399 } 13400 } else { 13401 // Walk redefinitions, as some of them may be instantiable. 13402 for (auto i : Func->redecls()) { 13403 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13404 MarkFunctionReferenced(Loc, i, OdrUse); 13405 } 13406 } 13407 13408 if (!OdrUse) return; 13409 13410 // Keep track of used but undefined functions. 13411 if (!Func->isDefined()) { 13412 if (mightHaveNonExternalLinkage(Func)) 13413 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13414 else if (Func->getMostRecentDecl()->isInlined() && 13415 !LangOpts.GNUInline && 13416 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13417 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13418 } 13419 13420 Func->markUsed(Context); 13421 } 13422 13423 static void 13424 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13425 ValueDecl *var, DeclContext *DC) { 13426 DeclContext *VarDC = var->getDeclContext(); 13427 13428 // If the parameter still belongs to the translation unit, then 13429 // we're actually just using one parameter in the declaration of 13430 // the next. 13431 if (isa<ParmVarDecl>(var) && 13432 isa<TranslationUnitDecl>(VarDC)) 13433 return; 13434 13435 // For C code, don't diagnose about capture if we're not actually in code 13436 // right now; it's impossible to write a non-constant expression outside of 13437 // function context, so we'll get other (more useful) diagnostics later. 13438 // 13439 // For C++, things get a bit more nasty... it would be nice to suppress this 13440 // diagnostic for certain cases like using a local variable in an array bound 13441 // for a member of a local class, but the correct predicate is not obvious. 13442 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13443 return; 13444 13445 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13446 unsigned ContextKind = 3; // unknown 13447 if (isa<CXXMethodDecl>(VarDC) && 13448 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13449 ContextKind = 2; 13450 } else if (isa<FunctionDecl>(VarDC)) { 13451 ContextKind = 0; 13452 } else if (isa<BlockDecl>(VarDC)) { 13453 ContextKind = 1; 13454 } 13455 13456 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13457 << var << ValueKind << ContextKind << VarDC; 13458 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13459 << var; 13460 13461 // FIXME: Add additional diagnostic info about class etc. which prevents 13462 // capture. 13463 } 13464 13465 13466 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13467 bool &SubCapturesAreNested, 13468 QualType &CaptureType, 13469 QualType &DeclRefType) { 13470 // Check whether we've already captured it. 13471 if (CSI->CaptureMap.count(Var)) { 13472 // If we found a capture, any subcaptures are nested. 13473 SubCapturesAreNested = true; 13474 13475 // Retrieve the capture type for this variable. 13476 CaptureType = CSI->getCapture(Var).getCaptureType(); 13477 13478 // Compute the type of an expression that refers to this variable. 13479 DeclRefType = CaptureType.getNonReferenceType(); 13480 13481 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13482 // are mutable in the sense that user can change their value - they are 13483 // private instances of the captured declarations. 13484 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13485 if (Cap.isCopyCapture() && 13486 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13487 !(isa<CapturedRegionScopeInfo>(CSI) && 13488 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13489 DeclRefType.addConst(); 13490 return true; 13491 } 13492 return false; 13493 } 13494 13495 // Only block literals, captured statements, and lambda expressions can 13496 // capture; other scopes don't work. 13497 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13498 SourceLocation Loc, 13499 const bool Diagnose, Sema &S) { 13500 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13501 return getLambdaAwareParentOfDeclContext(DC); 13502 else if (Var->hasLocalStorage()) { 13503 if (Diagnose) 13504 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13505 } 13506 return nullptr; 13507 } 13508 13509 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13510 // certain types of variables (unnamed, variably modified types etc.) 13511 // so check for eligibility. 13512 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13513 SourceLocation Loc, 13514 const bool Diagnose, Sema &S) { 13515 13516 bool IsBlock = isa<BlockScopeInfo>(CSI); 13517 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13518 13519 // Lambdas are not allowed to capture unnamed variables 13520 // (e.g. anonymous unions). 13521 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13522 // assuming that's the intent. 13523 if (IsLambda && !Var->getDeclName()) { 13524 if (Diagnose) { 13525 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13526 S.Diag(Var->getLocation(), diag::note_declared_at); 13527 } 13528 return false; 13529 } 13530 13531 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13532 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13533 if (Diagnose) { 13534 S.Diag(Loc, diag::err_ref_vm_type); 13535 S.Diag(Var->getLocation(), diag::note_previous_decl) 13536 << Var->getDeclName(); 13537 } 13538 return false; 13539 } 13540 // Prohibit structs with flexible array members too. 13541 // We cannot capture what is in the tail end of the struct. 13542 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13543 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13544 if (Diagnose) { 13545 if (IsBlock) 13546 S.Diag(Loc, diag::err_ref_flexarray_type); 13547 else 13548 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13549 << Var->getDeclName(); 13550 S.Diag(Var->getLocation(), diag::note_previous_decl) 13551 << Var->getDeclName(); 13552 } 13553 return false; 13554 } 13555 } 13556 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13557 // Lambdas and captured statements are not allowed to capture __block 13558 // variables; they don't support the expected semantics. 13559 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13560 if (Diagnose) { 13561 S.Diag(Loc, diag::err_capture_block_variable) 13562 << Var->getDeclName() << !IsLambda; 13563 S.Diag(Var->getLocation(), diag::note_previous_decl) 13564 << Var->getDeclName(); 13565 } 13566 return false; 13567 } 13568 13569 return true; 13570 } 13571 13572 // Returns true if the capture by block was successful. 13573 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13574 SourceLocation Loc, 13575 const bool BuildAndDiagnose, 13576 QualType &CaptureType, 13577 QualType &DeclRefType, 13578 const bool Nested, 13579 Sema &S) { 13580 Expr *CopyExpr = nullptr; 13581 bool ByRef = false; 13582 13583 // Blocks are not allowed to capture arrays. 13584 if (CaptureType->isArrayType()) { 13585 if (BuildAndDiagnose) { 13586 S.Diag(Loc, diag::err_ref_array_type); 13587 S.Diag(Var->getLocation(), diag::note_previous_decl) 13588 << Var->getDeclName(); 13589 } 13590 return false; 13591 } 13592 13593 // Forbid the block-capture of autoreleasing variables. 13594 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13595 if (BuildAndDiagnose) { 13596 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13597 << /*block*/ 0; 13598 S.Diag(Var->getLocation(), diag::note_previous_decl) 13599 << Var->getDeclName(); 13600 } 13601 return false; 13602 } 13603 13604 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13605 if (const auto *PT = CaptureType->getAs<PointerType>()) { 13606 // This function finds out whether there is an AttributedType of kind 13607 // attr_objc_ownership in Ty. The existence of AttributedType of kind 13608 // attr_objc_ownership implies __autoreleasing was explicitly specified 13609 // rather than being added implicitly by the compiler. 13610 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 13611 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 13612 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 13613 return true; 13614 13615 // Peel off AttributedTypes that are not of kind objc_ownership. 13616 Ty = AttrTy->getModifiedType(); 13617 } 13618 13619 return false; 13620 }; 13621 13622 QualType PointeeTy = PT->getPointeeType(); 13623 13624 if (PointeeTy->getAs<ObjCObjectPointerType>() && 13625 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13626 !IsObjCOwnershipAttributedType(PointeeTy)) { 13627 if (BuildAndDiagnose) { 13628 SourceLocation VarLoc = Var->getLocation(); 13629 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13630 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) << 13631 FixItHint::CreateInsertion(VarLoc, "__autoreleasing"); 13632 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13633 } 13634 } 13635 } 13636 13637 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13638 if (HasBlocksAttr || CaptureType->isReferenceType() || 13639 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13640 // Block capture by reference does not change the capture or 13641 // declaration reference types. 13642 ByRef = true; 13643 } else { 13644 // Block capture by copy introduces 'const'. 13645 CaptureType = CaptureType.getNonReferenceType().withConst(); 13646 DeclRefType = CaptureType; 13647 13648 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13649 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13650 // The capture logic needs the destructor, so make sure we mark it. 13651 // Usually this is unnecessary because most local variables have 13652 // their destructors marked at declaration time, but parameters are 13653 // an exception because it's technically only the call site that 13654 // actually requires the destructor. 13655 if (isa<ParmVarDecl>(Var)) 13656 S.FinalizeVarWithDestructor(Var, Record); 13657 13658 // Enter a new evaluation context to insulate the copy 13659 // full-expression. 13660 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13661 13662 // According to the blocks spec, the capture of a variable from 13663 // the stack requires a const copy constructor. This is not true 13664 // of the copy/move done to move a __block variable to the heap. 13665 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13666 DeclRefType.withConst(), 13667 VK_LValue, Loc); 13668 13669 ExprResult Result 13670 = S.PerformCopyInitialization( 13671 InitializedEntity::InitializeBlock(Var->getLocation(), 13672 CaptureType, false), 13673 Loc, DeclRef); 13674 13675 // Build a full-expression copy expression if initialization 13676 // succeeded and used a non-trivial constructor. Recover from 13677 // errors by pretending that the copy isn't necessary. 13678 if (!Result.isInvalid() && 13679 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13680 ->isTrivial()) { 13681 Result = S.MaybeCreateExprWithCleanups(Result); 13682 CopyExpr = Result.get(); 13683 } 13684 } 13685 } 13686 } 13687 13688 // Actually capture the variable. 13689 if (BuildAndDiagnose) 13690 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13691 SourceLocation(), CaptureType, CopyExpr); 13692 13693 return true; 13694 13695 } 13696 13697 13698 /// \brief Capture the given variable in the captured region. 13699 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13700 VarDecl *Var, 13701 SourceLocation Loc, 13702 const bool BuildAndDiagnose, 13703 QualType &CaptureType, 13704 QualType &DeclRefType, 13705 const bool RefersToCapturedVariable, 13706 Sema &S) { 13707 // By default, capture variables by reference. 13708 bool ByRef = true; 13709 // Using an LValue reference type is consistent with Lambdas (see below). 13710 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13711 if (S.IsOpenMPCapturedDecl(Var)) 13712 DeclRefType = DeclRefType.getUnqualifiedType(); 13713 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13714 } 13715 13716 if (ByRef) 13717 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13718 else 13719 CaptureType = DeclRefType; 13720 13721 Expr *CopyExpr = nullptr; 13722 if (BuildAndDiagnose) { 13723 // The current implementation assumes that all variables are captured 13724 // by references. Since there is no capture by copy, no expression 13725 // evaluation will be needed. 13726 RecordDecl *RD = RSI->TheRecordDecl; 13727 13728 FieldDecl *Field 13729 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13730 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13731 nullptr, false, ICIS_NoInit); 13732 Field->setImplicit(true); 13733 Field->setAccess(AS_private); 13734 RD->addDecl(Field); 13735 13736 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13737 DeclRefType, VK_LValue, Loc); 13738 Var->setReferenced(true); 13739 Var->markUsed(S.Context); 13740 } 13741 13742 // Actually capture the variable. 13743 if (BuildAndDiagnose) 13744 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13745 SourceLocation(), CaptureType, CopyExpr); 13746 13747 13748 return true; 13749 } 13750 13751 /// \brief Create a field within the lambda class for the variable 13752 /// being captured. 13753 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13754 QualType FieldType, QualType DeclRefType, 13755 SourceLocation Loc, 13756 bool RefersToCapturedVariable) { 13757 CXXRecordDecl *Lambda = LSI->Lambda; 13758 13759 // Build the non-static data member. 13760 FieldDecl *Field 13761 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13762 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13763 nullptr, false, ICIS_NoInit); 13764 Field->setImplicit(true); 13765 Field->setAccess(AS_private); 13766 Lambda->addDecl(Field); 13767 } 13768 13769 /// \brief Capture the given variable in the lambda. 13770 static bool captureInLambda(LambdaScopeInfo *LSI, 13771 VarDecl *Var, 13772 SourceLocation Loc, 13773 const bool BuildAndDiagnose, 13774 QualType &CaptureType, 13775 QualType &DeclRefType, 13776 const bool RefersToCapturedVariable, 13777 const Sema::TryCaptureKind Kind, 13778 SourceLocation EllipsisLoc, 13779 const bool IsTopScope, 13780 Sema &S) { 13781 13782 // Determine whether we are capturing by reference or by value. 13783 bool ByRef = false; 13784 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13785 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13786 } else { 13787 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13788 } 13789 13790 // Compute the type of the field that will capture this variable. 13791 if (ByRef) { 13792 // C++11 [expr.prim.lambda]p15: 13793 // An entity is captured by reference if it is implicitly or 13794 // explicitly captured but not captured by copy. It is 13795 // unspecified whether additional unnamed non-static data 13796 // members are declared in the closure type for entities 13797 // captured by reference. 13798 // 13799 // FIXME: It is not clear whether we want to build an lvalue reference 13800 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13801 // to do the former, while EDG does the latter. Core issue 1249 will 13802 // clarify, but for now we follow GCC because it's a more permissive and 13803 // easily defensible position. 13804 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13805 } else { 13806 // C++11 [expr.prim.lambda]p14: 13807 // For each entity captured by copy, an unnamed non-static 13808 // data member is declared in the closure type. The 13809 // declaration order of these members is unspecified. The type 13810 // of such a data member is the type of the corresponding 13811 // captured entity if the entity is not a reference to an 13812 // object, or the referenced type otherwise. [Note: If the 13813 // captured entity is a reference to a function, the 13814 // corresponding data member is also a reference to a 13815 // function. - end note ] 13816 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13817 if (!RefType->getPointeeType()->isFunctionType()) 13818 CaptureType = RefType->getPointeeType(); 13819 } 13820 13821 // Forbid the lambda copy-capture of autoreleasing variables. 13822 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13823 if (BuildAndDiagnose) { 13824 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13825 S.Diag(Var->getLocation(), diag::note_previous_decl) 13826 << Var->getDeclName(); 13827 } 13828 return false; 13829 } 13830 13831 // Make sure that by-copy captures are of a complete and non-abstract type. 13832 if (BuildAndDiagnose) { 13833 if (!CaptureType->isDependentType() && 13834 S.RequireCompleteType(Loc, CaptureType, 13835 diag::err_capture_of_incomplete_type, 13836 Var->getDeclName())) 13837 return false; 13838 13839 if (S.RequireNonAbstractType(Loc, CaptureType, 13840 diag::err_capture_of_abstract_type)) 13841 return false; 13842 } 13843 } 13844 13845 // Capture this variable in the lambda. 13846 if (BuildAndDiagnose) 13847 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13848 RefersToCapturedVariable); 13849 13850 // Compute the type of a reference to this captured variable. 13851 if (ByRef) 13852 DeclRefType = CaptureType.getNonReferenceType(); 13853 else { 13854 // C++ [expr.prim.lambda]p5: 13855 // The closure type for a lambda-expression has a public inline 13856 // function call operator [...]. This function call operator is 13857 // declared const (9.3.1) if and only if the lambda-expression's 13858 // parameter-declaration-clause is not followed by mutable. 13859 DeclRefType = CaptureType.getNonReferenceType(); 13860 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13861 DeclRefType.addConst(); 13862 } 13863 13864 // Add the capture. 13865 if (BuildAndDiagnose) 13866 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13867 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13868 13869 return true; 13870 } 13871 13872 bool Sema::tryCaptureVariable( 13873 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13874 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13875 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13876 // An init-capture is notionally from the context surrounding its 13877 // declaration, but its parent DC is the lambda class. 13878 DeclContext *VarDC = Var->getDeclContext(); 13879 if (Var->isInitCapture()) 13880 VarDC = VarDC->getParent(); 13881 13882 DeclContext *DC = CurContext; 13883 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13884 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13885 // We need to sync up the Declaration Context with the 13886 // FunctionScopeIndexToStopAt 13887 if (FunctionScopeIndexToStopAt) { 13888 unsigned FSIndex = FunctionScopes.size() - 1; 13889 while (FSIndex != MaxFunctionScopesIndex) { 13890 DC = getLambdaAwareParentOfDeclContext(DC); 13891 --FSIndex; 13892 } 13893 } 13894 13895 13896 // If the variable is declared in the current context, there is no need to 13897 // capture it. 13898 if (VarDC == DC) return true; 13899 13900 // Capture global variables if it is required to use private copy of this 13901 // variable. 13902 bool IsGlobal = !Var->hasLocalStorage(); 13903 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13904 return true; 13905 13906 // Walk up the stack to determine whether we can capture the variable, 13907 // performing the "simple" checks that don't depend on type. We stop when 13908 // we've either hit the declared scope of the variable or find an existing 13909 // capture of that variable. We start from the innermost capturing-entity 13910 // (the DC) and ensure that all intervening capturing-entities 13911 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13912 // declcontext can either capture the variable or have already captured 13913 // the variable. 13914 CaptureType = Var->getType(); 13915 DeclRefType = CaptureType.getNonReferenceType(); 13916 bool Nested = false; 13917 bool Explicit = (Kind != TryCapture_Implicit); 13918 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13919 do { 13920 // Only block literals, captured statements, and lambda expressions can 13921 // capture; other scopes don't work. 13922 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13923 ExprLoc, 13924 BuildAndDiagnose, 13925 *this); 13926 // We need to check for the parent *first* because, if we *have* 13927 // private-captured a global variable, we need to recursively capture it in 13928 // intermediate blocks, lambdas, etc. 13929 if (!ParentDC) { 13930 if (IsGlobal) { 13931 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13932 break; 13933 } 13934 return true; 13935 } 13936 13937 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13938 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13939 13940 13941 // Check whether we've already captured it. 13942 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13943 DeclRefType)) { 13944 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 13945 break; 13946 } 13947 // If we are instantiating a generic lambda call operator body, 13948 // we do not want to capture new variables. What was captured 13949 // during either a lambdas transformation or initial parsing 13950 // should be used. 13951 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13952 if (BuildAndDiagnose) { 13953 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13954 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13955 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13956 Diag(Var->getLocation(), diag::note_previous_decl) 13957 << Var->getDeclName(); 13958 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13959 } else 13960 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13961 } 13962 return true; 13963 } 13964 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13965 // certain types of variables (unnamed, variably modified types etc.) 13966 // so check for eligibility. 13967 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13968 return true; 13969 13970 // Try to capture variable-length arrays types. 13971 if (Var->getType()->isVariablyModifiedType()) { 13972 // We're going to walk down into the type and look for VLA 13973 // expressions. 13974 QualType QTy = Var->getType(); 13975 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13976 QTy = PVD->getOriginalType(); 13977 captureVariablyModifiedType(Context, QTy, CSI); 13978 } 13979 13980 if (getLangOpts().OpenMP) { 13981 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13982 // OpenMP private variables should not be captured in outer scope, so 13983 // just break here. Similarly, global variables that are captured in a 13984 // target region should not be captured outside the scope of the region. 13985 if (RSI->CapRegionKind == CR_OpenMP) { 13986 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13987 // When we detect target captures we are looking from inside the 13988 // target region, therefore we need to propagate the capture from the 13989 // enclosing region. Therefore, the capture is not initially nested. 13990 if (IsTargetCap) 13991 FunctionScopesIndex--; 13992 13993 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13994 Nested = !IsTargetCap; 13995 DeclRefType = DeclRefType.getUnqualifiedType(); 13996 CaptureType = Context.getLValueReferenceType(DeclRefType); 13997 break; 13998 } 13999 } 14000 } 14001 } 14002 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14003 // No capture-default, and this is not an explicit capture 14004 // so cannot capture this variable. 14005 if (BuildAndDiagnose) { 14006 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14007 Diag(Var->getLocation(), diag::note_previous_decl) 14008 << Var->getDeclName(); 14009 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14010 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14011 diag::note_lambda_decl); 14012 // FIXME: If we error out because an outer lambda can not implicitly 14013 // capture a variable that an inner lambda explicitly captures, we 14014 // should have the inner lambda do the explicit capture - because 14015 // it makes for cleaner diagnostics later. This would purely be done 14016 // so that the diagnostic does not misleadingly claim that a variable 14017 // can not be captured by a lambda implicitly even though it is captured 14018 // explicitly. Suggestion: 14019 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14020 // at the function head 14021 // - cache the StartingDeclContext - this must be a lambda 14022 // - captureInLambda in the innermost lambda the variable. 14023 } 14024 return true; 14025 } 14026 14027 FunctionScopesIndex--; 14028 DC = ParentDC; 14029 Explicit = false; 14030 } while (!VarDC->Equals(DC)); 14031 14032 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14033 // computing the type of the capture at each step, checking type-specific 14034 // requirements, and adding captures if requested. 14035 // If the variable had already been captured previously, we start capturing 14036 // at the lambda nested within that one. 14037 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14038 ++I) { 14039 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14040 14041 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14042 if (!captureInBlock(BSI, Var, ExprLoc, 14043 BuildAndDiagnose, CaptureType, 14044 DeclRefType, Nested, *this)) 14045 return true; 14046 Nested = true; 14047 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14048 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14049 BuildAndDiagnose, CaptureType, 14050 DeclRefType, Nested, *this)) 14051 return true; 14052 Nested = true; 14053 } else { 14054 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14055 if (!captureInLambda(LSI, Var, ExprLoc, 14056 BuildAndDiagnose, CaptureType, 14057 DeclRefType, Nested, Kind, EllipsisLoc, 14058 /*IsTopScope*/I == N - 1, *this)) 14059 return true; 14060 Nested = true; 14061 } 14062 } 14063 return false; 14064 } 14065 14066 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14067 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14068 QualType CaptureType; 14069 QualType DeclRefType; 14070 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14071 /*BuildAndDiagnose=*/true, CaptureType, 14072 DeclRefType, nullptr); 14073 } 14074 14075 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14076 QualType CaptureType; 14077 QualType DeclRefType; 14078 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14079 /*BuildAndDiagnose=*/false, CaptureType, 14080 DeclRefType, nullptr); 14081 } 14082 14083 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14084 QualType CaptureType; 14085 QualType DeclRefType; 14086 14087 // Determine whether we can capture this variable. 14088 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14089 /*BuildAndDiagnose=*/false, CaptureType, 14090 DeclRefType, nullptr)) 14091 return QualType(); 14092 14093 return DeclRefType; 14094 } 14095 14096 14097 14098 // If either the type of the variable or the initializer is dependent, 14099 // return false. Otherwise, determine whether the variable is a constant 14100 // expression. Use this if you need to know if a variable that might or 14101 // might not be dependent is truly a constant expression. 14102 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14103 ASTContext &Context) { 14104 14105 if (Var->getType()->isDependentType()) 14106 return false; 14107 const VarDecl *DefVD = nullptr; 14108 Var->getAnyInitializer(DefVD); 14109 if (!DefVD) 14110 return false; 14111 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14112 Expr *Init = cast<Expr>(Eval->Value); 14113 if (Init->isValueDependent()) 14114 return false; 14115 return IsVariableAConstantExpression(Var, Context); 14116 } 14117 14118 14119 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14120 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14121 // an object that satisfies the requirements for appearing in a 14122 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14123 // is immediately applied." This function handles the lvalue-to-rvalue 14124 // conversion part. 14125 MaybeODRUseExprs.erase(E->IgnoreParens()); 14126 14127 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14128 // to a variable that is a constant expression, and if so, identify it as 14129 // a reference to a variable that does not involve an odr-use of that 14130 // variable. 14131 if (LambdaScopeInfo *LSI = getCurLambda()) { 14132 Expr *SansParensExpr = E->IgnoreParens(); 14133 VarDecl *Var = nullptr; 14134 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14135 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14136 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14137 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14138 14139 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14140 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14141 } 14142 } 14143 14144 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14145 Res = CorrectDelayedTyposInExpr(Res); 14146 14147 if (!Res.isUsable()) 14148 return Res; 14149 14150 // If a constant-expression is a reference to a variable where we delay 14151 // deciding whether it is an odr-use, just assume we will apply the 14152 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14153 // (a non-type template argument), we have special handling anyway. 14154 UpdateMarkingForLValueToRValue(Res.get()); 14155 return Res; 14156 } 14157 14158 void Sema::CleanupVarDeclMarking() { 14159 for (Expr *E : MaybeODRUseExprs) { 14160 VarDecl *Var; 14161 SourceLocation Loc; 14162 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14163 Var = cast<VarDecl>(DRE->getDecl()); 14164 Loc = DRE->getLocation(); 14165 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14166 Var = cast<VarDecl>(ME->getMemberDecl()); 14167 Loc = ME->getMemberLoc(); 14168 } else { 14169 llvm_unreachable("Unexpected expression"); 14170 } 14171 14172 MarkVarDeclODRUsed(Var, Loc, *this, 14173 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14174 } 14175 14176 MaybeODRUseExprs.clear(); 14177 } 14178 14179 14180 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14181 VarDecl *Var, Expr *E) { 14182 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14183 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14184 Var->setReferenced(); 14185 14186 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14187 14188 bool OdrUseContext = isOdrUseContext(SemaRef); 14189 bool NeedDefinition = 14190 OdrUseContext || (isEvaluatableContext(SemaRef) && 14191 Var->isUsableInConstantExpressions(SemaRef.Context)); 14192 14193 VarTemplateSpecializationDecl *VarSpec = 14194 dyn_cast<VarTemplateSpecializationDecl>(Var); 14195 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14196 "Can't instantiate a partial template specialization."); 14197 14198 // If this might be a member specialization of a static data member, check 14199 // the specialization is visible. We already did the checks for variable 14200 // template specializations when we created them. 14201 if (NeedDefinition && TSK != TSK_Undeclared && 14202 !isa<VarTemplateSpecializationDecl>(Var)) 14203 SemaRef.checkSpecializationVisibility(Loc, Var); 14204 14205 // Perform implicit instantiation of static data members, static data member 14206 // templates of class templates, and variable template specializations. Delay 14207 // instantiations of variable templates, except for those that could be used 14208 // in a constant expression. 14209 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14210 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14211 14212 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14213 if (Var->getPointOfInstantiation().isInvalid()) { 14214 // This is a modification of an existing AST node. Notify listeners. 14215 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14216 L->StaticDataMemberInstantiated(Var); 14217 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14218 // Don't bother trying to instantiate it again, unless we might need 14219 // its initializer before we get to the end of the TU. 14220 TryInstantiating = false; 14221 } 14222 14223 if (Var->getPointOfInstantiation().isInvalid()) 14224 Var->setTemplateSpecializationKind(TSK, Loc); 14225 14226 if (TryInstantiating) { 14227 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14228 bool InstantiationDependent = false; 14229 bool IsNonDependent = 14230 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14231 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14232 : true; 14233 14234 // Do not instantiate specializations that are still type-dependent. 14235 if (IsNonDependent) { 14236 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14237 // Do not defer instantiations of variables which could be used in a 14238 // constant expression. 14239 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14240 } else { 14241 SemaRef.PendingInstantiations 14242 .push_back(std::make_pair(Var, PointOfInstantiation)); 14243 } 14244 } 14245 } 14246 } 14247 14248 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14249 // the requirements for appearing in a constant expression (5.19) and, if 14250 // it is an object, the lvalue-to-rvalue conversion (4.1) 14251 // is immediately applied." We check the first part here, and 14252 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14253 // Note that we use the C++11 definition everywhere because nothing in 14254 // C++03 depends on whether we get the C++03 version correct. The second 14255 // part does not apply to references, since they are not objects. 14256 if (OdrUseContext && E && 14257 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14258 // A reference initialized by a constant expression can never be 14259 // odr-used, so simply ignore it. 14260 if (!Var->getType()->isReferenceType()) 14261 SemaRef.MaybeODRUseExprs.insert(E); 14262 } else if (OdrUseContext) { 14263 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14264 /*MaxFunctionScopeIndex ptr*/ nullptr); 14265 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14266 // If this is a dependent context, we don't need to mark variables as 14267 // odr-used, but we may still need to track them for lambda capture. 14268 // FIXME: Do we also need to do this inside dependent typeid expressions 14269 // (which are modeled as unevaluated at this point)? 14270 const bool RefersToEnclosingScope = 14271 (SemaRef.CurContext != Var->getDeclContext() && 14272 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14273 if (RefersToEnclosingScope) { 14274 if (LambdaScopeInfo *const LSI = 14275 SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) { 14276 // If a variable could potentially be odr-used, defer marking it so 14277 // until we finish analyzing the full expression for any 14278 // lvalue-to-rvalue 14279 // or discarded value conversions that would obviate odr-use. 14280 // Add it to the list of potential captures that will be analyzed 14281 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14282 // unless the variable is a reference that was initialized by a constant 14283 // expression (this will never need to be captured or odr-used). 14284 assert(E && "Capture variable should be used in an expression."); 14285 if (!Var->getType()->isReferenceType() || 14286 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14287 LSI->addPotentialCapture(E->IgnoreParens()); 14288 } 14289 } 14290 } 14291 } 14292 14293 /// \brief Mark a variable referenced, and check whether it is odr-used 14294 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14295 /// used directly for normal expressions referring to VarDecl. 14296 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14297 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14298 } 14299 14300 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14301 Decl *D, Expr *E, bool MightBeOdrUse) { 14302 if (SemaRef.isInOpenMPDeclareTargetContext()) 14303 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14304 14305 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14306 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14307 return; 14308 } 14309 14310 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14311 14312 // If this is a call to a method via a cast, also mark the method in the 14313 // derived class used in case codegen can devirtualize the call. 14314 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14315 if (!ME) 14316 return; 14317 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14318 if (!MD) 14319 return; 14320 // Only attempt to devirtualize if this is truly a virtual call. 14321 bool IsVirtualCall = MD->isVirtual() && 14322 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14323 if (!IsVirtualCall) 14324 return; 14325 const Expr *Base = ME->getBase(); 14326 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14327 if (!MostDerivedClassDecl) 14328 return; 14329 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14330 if (!DM || DM->isPure()) 14331 return; 14332 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14333 } 14334 14335 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14336 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14337 // TODO: update this with DR# once a defect report is filed. 14338 // C++11 defect. The address of a pure member should not be an ODR use, even 14339 // if it's a qualified reference. 14340 bool OdrUse = true; 14341 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14342 if (Method->isVirtual()) 14343 OdrUse = false; 14344 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14345 } 14346 14347 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14348 void Sema::MarkMemberReferenced(MemberExpr *E) { 14349 // C++11 [basic.def.odr]p2: 14350 // A non-overloaded function whose name appears as a potentially-evaluated 14351 // expression or a member of a set of candidate functions, if selected by 14352 // overload resolution when referred to from a potentially-evaluated 14353 // expression, is odr-used, unless it is a pure virtual function and its 14354 // name is not explicitly qualified. 14355 bool MightBeOdrUse = true; 14356 if (E->performsVirtualDispatch(getLangOpts())) { 14357 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14358 if (Method->isPure()) 14359 MightBeOdrUse = false; 14360 } 14361 SourceLocation Loc = E->getMemberLoc().isValid() ? 14362 E->getMemberLoc() : E->getLocStart(); 14363 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14364 } 14365 14366 /// \brief Perform marking for a reference to an arbitrary declaration. It 14367 /// marks the declaration referenced, and performs odr-use checking for 14368 /// functions and variables. This method should not be used when building a 14369 /// normal expression which refers to a variable. 14370 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14371 bool MightBeOdrUse) { 14372 if (MightBeOdrUse) { 14373 if (auto *VD = dyn_cast<VarDecl>(D)) { 14374 MarkVariableReferenced(Loc, VD); 14375 return; 14376 } 14377 } 14378 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14379 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14380 return; 14381 } 14382 D->setReferenced(); 14383 } 14384 14385 namespace { 14386 // Mark all of the declarations used by a type as referenced. 14387 // FIXME: Not fully implemented yet! We need to have a better understanding 14388 // of when we're entering a context we should not recurse into. 14389 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 14390 // TreeTransforms rebuilding the type in a new context. Rather than 14391 // duplicating the TreeTransform logic, we should consider reusing it here. 14392 // Currently that causes problems when rebuilding LambdaExprs. 14393 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14394 Sema &S; 14395 SourceLocation Loc; 14396 14397 public: 14398 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14399 14400 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14401 14402 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14403 }; 14404 } 14405 14406 bool MarkReferencedDecls::TraverseTemplateArgument( 14407 const TemplateArgument &Arg) { 14408 { 14409 // A non-type template argument is a constant-evaluated context. 14410 EnterExpressionEvaluationContext Evaluated(S, Sema::ConstantEvaluated); 14411 if (Arg.getKind() == TemplateArgument::Declaration) { 14412 if (Decl *D = Arg.getAsDecl()) 14413 S.MarkAnyDeclReferenced(Loc, D, true); 14414 } else if (Arg.getKind() == TemplateArgument::Expression) { 14415 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 14416 } 14417 } 14418 14419 return Inherited::TraverseTemplateArgument(Arg); 14420 } 14421 14422 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14423 MarkReferencedDecls Marker(*this, Loc); 14424 Marker.TraverseType(T); 14425 } 14426 14427 namespace { 14428 /// \brief Helper class that marks all of the declarations referenced by 14429 /// potentially-evaluated subexpressions as "referenced". 14430 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14431 Sema &S; 14432 bool SkipLocalVariables; 14433 14434 public: 14435 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14436 14437 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14438 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14439 14440 void VisitDeclRefExpr(DeclRefExpr *E) { 14441 // If we were asked not to visit local variables, don't. 14442 if (SkipLocalVariables) { 14443 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14444 if (VD->hasLocalStorage()) 14445 return; 14446 } 14447 14448 S.MarkDeclRefReferenced(E); 14449 } 14450 14451 void VisitMemberExpr(MemberExpr *E) { 14452 S.MarkMemberReferenced(E); 14453 Inherited::VisitMemberExpr(E); 14454 } 14455 14456 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14457 S.MarkFunctionReferenced(E->getLocStart(), 14458 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14459 Visit(E->getSubExpr()); 14460 } 14461 14462 void VisitCXXNewExpr(CXXNewExpr *E) { 14463 if (E->getOperatorNew()) 14464 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14465 if (E->getOperatorDelete()) 14466 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14467 Inherited::VisitCXXNewExpr(E); 14468 } 14469 14470 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14471 if (E->getOperatorDelete()) 14472 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14473 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14474 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14475 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14476 S.MarkFunctionReferenced(E->getLocStart(), 14477 S.LookupDestructor(Record)); 14478 } 14479 14480 Inherited::VisitCXXDeleteExpr(E); 14481 } 14482 14483 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14484 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14485 Inherited::VisitCXXConstructExpr(E); 14486 } 14487 14488 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14489 Visit(E->getExpr()); 14490 } 14491 14492 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14493 Inherited::VisitImplicitCastExpr(E); 14494 14495 if (E->getCastKind() == CK_LValueToRValue) 14496 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14497 } 14498 }; 14499 } 14500 14501 /// \brief Mark any declarations that appear within this expression or any 14502 /// potentially-evaluated subexpressions as "referenced". 14503 /// 14504 /// \param SkipLocalVariables If true, don't mark local variables as 14505 /// 'referenced'. 14506 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14507 bool SkipLocalVariables) { 14508 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14509 } 14510 14511 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14512 /// of the program being compiled. 14513 /// 14514 /// This routine emits the given diagnostic when the code currently being 14515 /// type-checked is "potentially evaluated", meaning that there is a 14516 /// possibility that the code will actually be executable. Code in sizeof() 14517 /// expressions, code used only during overload resolution, etc., are not 14518 /// potentially evaluated. This routine will suppress such diagnostics or, 14519 /// in the absolutely nutty case of potentially potentially evaluated 14520 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14521 /// later. 14522 /// 14523 /// This routine should be used for all diagnostics that describe the run-time 14524 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14525 /// Failure to do so will likely result in spurious diagnostics or failures 14526 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14527 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14528 const PartialDiagnostic &PD) { 14529 switch (ExprEvalContexts.back().Context) { 14530 case Unevaluated: 14531 case UnevaluatedList: 14532 case UnevaluatedAbstract: 14533 case DiscardedStatement: 14534 // The argument will never be evaluated, so don't complain. 14535 break; 14536 14537 case ConstantEvaluated: 14538 // Relevant diagnostics should be produced by constant evaluation. 14539 break; 14540 14541 case PotentiallyEvaluated: 14542 case PotentiallyEvaluatedIfUsed: 14543 if (Statement && getCurFunctionOrMethodDecl()) { 14544 FunctionScopes.back()->PossiblyUnreachableDiags. 14545 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14546 } 14547 else 14548 Diag(Loc, PD); 14549 14550 return true; 14551 } 14552 14553 return false; 14554 } 14555 14556 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14557 CallExpr *CE, FunctionDecl *FD) { 14558 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14559 return false; 14560 14561 // If we're inside a decltype's expression, don't check for a valid return 14562 // type or construct temporaries until we know whether this is the last call. 14563 if (ExprEvalContexts.back().IsDecltype) { 14564 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14565 return false; 14566 } 14567 14568 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14569 FunctionDecl *FD; 14570 CallExpr *CE; 14571 14572 public: 14573 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14574 : FD(FD), CE(CE) { } 14575 14576 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14577 if (!FD) { 14578 S.Diag(Loc, diag::err_call_incomplete_return) 14579 << T << CE->getSourceRange(); 14580 return; 14581 } 14582 14583 S.Diag(Loc, diag::err_call_function_incomplete_return) 14584 << CE->getSourceRange() << FD->getDeclName() << T; 14585 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14586 << FD->getDeclName(); 14587 } 14588 } Diagnoser(FD, CE); 14589 14590 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14591 return true; 14592 14593 return false; 14594 } 14595 14596 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14597 // will prevent this condition from triggering, which is what we want. 14598 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14599 SourceLocation Loc; 14600 14601 unsigned diagnostic = diag::warn_condition_is_assignment; 14602 bool IsOrAssign = false; 14603 14604 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14605 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14606 return; 14607 14608 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14609 14610 // Greylist some idioms by putting them into a warning subcategory. 14611 if (ObjCMessageExpr *ME 14612 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14613 Selector Sel = ME->getSelector(); 14614 14615 // self = [<foo> init...] 14616 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14617 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14618 14619 // <foo> = [<bar> nextObject] 14620 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14621 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14622 } 14623 14624 Loc = Op->getOperatorLoc(); 14625 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14626 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14627 return; 14628 14629 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14630 Loc = Op->getOperatorLoc(); 14631 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14632 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14633 else { 14634 // Not an assignment. 14635 return; 14636 } 14637 14638 Diag(Loc, diagnostic) << E->getSourceRange(); 14639 14640 SourceLocation Open = E->getLocStart(); 14641 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14642 Diag(Loc, diag::note_condition_assign_silence) 14643 << FixItHint::CreateInsertion(Open, "(") 14644 << FixItHint::CreateInsertion(Close, ")"); 14645 14646 if (IsOrAssign) 14647 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14648 << FixItHint::CreateReplacement(Loc, "!="); 14649 else 14650 Diag(Loc, diag::note_condition_assign_to_comparison) 14651 << FixItHint::CreateReplacement(Loc, "=="); 14652 } 14653 14654 /// \brief Redundant parentheses over an equality comparison can indicate 14655 /// that the user intended an assignment used as condition. 14656 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14657 // Don't warn if the parens came from a macro. 14658 SourceLocation parenLoc = ParenE->getLocStart(); 14659 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14660 return; 14661 // Don't warn for dependent expressions. 14662 if (ParenE->isTypeDependent()) 14663 return; 14664 14665 Expr *E = ParenE->IgnoreParens(); 14666 14667 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14668 if (opE->getOpcode() == BO_EQ && 14669 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14670 == Expr::MLV_Valid) { 14671 SourceLocation Loc = opE->getOperatorLoc(); 14672 14673 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14674 SourceRange ParenERange = ParenE->getSourceRange(); 14675 Diag(Loc, diag::note_equality_comparison_silence) 14676 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14677 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14678 Diag(Loc, diag::note_equality_comparison_to_assign) 14679 << FixItHint::CreateReplacement(Loc, "="); 14680 } 14681 } 14682 14683 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14684 bool IsConstexpr) { 14685 DiagnoseAssignmentAsCondition(E); 14686 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14687 DiagnoseEqualityWithExtraParens(parenE); 14688 14689 ExprResult result = CheckPlaceholderExpr(E); 14690 if (result.isInvalid()) return ExprError(); 14691 E = result.get(); 14692 14693 if (!E->isTypeDependent()) { 14694 if (getLangOpts().CPlusPlus) 14695 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14696 14697 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14698 if (ERes.isInvalid()) 14699 return ExprError(); 14700 E = ERes.get(); 14701 14702 QualType T = E->getType(); 14703 if (!T->isScalarType()) { // C99 6.8.4.1p1 14704 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14705 << T << E->getSourceRange(); 14706 return ExprError(); 14707 } 14708 CheckBoolLikeConversion(E, Loc); 14709 } 14710 14711 return E; 14712 } 14713 14714 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14715 Expr *SubExpr, ConditionKind CK) { 14716 // Empty conditions are valid in for-statements. 14717 if (!SubExpr) 14718 return ConditionResult(); 14719 14720 ExprResult Cond; 14721 switch (CK) { 14722 case ConditionKind::Boolean: 14723 Cond = CheckBooleanCondition(Loc, SubExpr); 14724 break; 14725 14726 case ConditionKind::ConstexprIf: 14727 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14728 break; 14729 14730 case ConditionKind::Switch: 14731 Cond = CheckSwitchCondition(Loc, SubExpr); 14732 break; 14733 } 14734 if (Cond.isInvalid()) 14735 return ConditionError(); 14736 14737 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14738 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14739 if (!FullExpr.get()) 14740 return ConditionError(); 14741 14742 return ConditionResult(*this, nullptr, FullExpr, 14743 CK == ConditionKind::ConstexprIf); 14744 } 14745 14746 namespace { 14747 /// A visitor for rebuilding a call to an __unknown_any expression 14748 /// to have an appropriate type. 14749 struct RebuildUnknownAnyFunction 14750 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14751 14752 Sema &S; 14753 14754 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14755 14756 ExprResult VisitStmt(Stmt *S) { 14757 llvm_unreachable("unexpected statement!"); 14758 } 14759 14760 ExprResult VisitExpr(Expr *E) { 14761 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14762 << E->getSourceRange(); 14763 return ExprError(); 14764 } 14765 14766 /// Rebuild an expression which simply semantically wraps another 14767 /// expression which it shares the type and value kind of. 14768 template <class T> ExprResult rebuildSugarExpr(T *E) { 14769 ExprResult SubResult = Visit(E->getSubExpr()); 14770 if (SubResult.isInvalid()) return ExprError(); 14771 14772 Expr *SubExpr = SubResult.get(); 14773 E->setSubExpr(SubExpr); 14774 E->setType(SubExpr->getType()); 14775 E->setValueKind(SubExpr->getValueKind()); 14776 assert(E->getObjectKind() == OK_Ordinary); 14777 return E; 14778 } 14779 14780 ExprResult VisitParenExpr(ParenExpr *E) { 14781 return rebuildSugarExpr(E); 14782 } 14783 14784 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14785 return rebuildSugarExpr(E); 14786 } 14787 14788 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14789 ExprResult SubResult = Visit(E->getSubExpr()); 14790 if (SubResult.isInvalid()) return ExprError(); 14791 14792 Expr *SubExpr = SubResult.get(); 14793 E->setSubExpr(SubExpr); 14794 E->setType(S.Context.getPointerType(SubExpr->getType())); 14795 assert(E->getValueKind() == VK_RValue); 14796 assert(E->getObjectKind() == OK_Ordinary); 14797 return E; 14798 } 14799 14800 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14801 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14802 14803 E->setType(VD->getType()); 14804 14805 assert(E->getValueKind() == VK_RValue); 14806 if (S.getLangOpts().CPlusPlus && 14807 !(isa<CXXMethodDecl>(VD) && 14808 cast<CXXMethodDecl>(VD)->isInstance())) 14809 E->setValueKind(VK_LValue); 14810 14811 return E; 14812 } 14813 14814 ExprResult VisitMemberExpr(MemberExpr *E) { 14815 return resolveDecl(E, E->getMemberDecl()); 14816 } 14817 14818 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14819 return resolveDecl(E, E->getDecl()); 14820 } 14821 }; 14822 } 14823 14824 /// Given a function expression of unknown-any type, try to rebuild it 14825 /// to have a function type. 14826 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14827 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14828 if (Result.isInvalid()) return ExprError(); 14829 return S.DefaultFunctionArrayConversion(Result.get()); 14830 } 14831 14832 namespace { 14833 /// A visitor for rebuilding an expression of type __unknown_anytype 14834 /// into one which resolves the type directly on the referring 14835 /// expression. Strict preservation of the original source 14836 /// structure is not a goal. 14837 struct RebuildUnknownAnyExpr 14838 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14839 14840 Sema &S; 14841 14842 /// The current destination type. 14843 QualType DestType; 14844 14845 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14846 : S(S), DestType(CastType) {} 14847 14848 ExprResult VisitStmt(Stmt *S) { 14849 llvm_unreachable("unexpected statement!"); 14850 } 14851 14852 ExprResult VisitExpr(Expr *E) { 14853 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14854 << E->getSourceRange(); 14855 return ExprError(); 14856 } 14857 14858 ExprResult VisitCallExpr(CallExpr *E); 14859 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14860 14861 /// Rebuild an expression which simply semantically wraps another 14862 /// expression which it shares the type and value kind of. 14863 template <class T> ExprResult rebuildSugarExpr(T *E) { 14864 ExprResult SubResult = Visit(E->getSubExpr()); 14865 if (SubResult.isInvalid()) return ExprError(); 14866 Expr *SubExpr = SubResult.get(); 14867 E->setSubExpr(SubExpr); 14868 E->setType(SubExpr->getType()); 14869 E->setValueKind(SubExpr->getValueKind()); 14870 assert(E->getObjectKind() == OK_Ordinary); 14871 return E; 14872 } 14873 14874 ExprResult VisitParenExpr(ParenExpr *E) { 14875 return rebuildSugarExpr(E); 14876 } 14877 14878 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14879 return rebuildSugarExpr(E); 14880 } 14881 14882 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14883 const PointerType *Ptr = DestType->getAs<PointerType>(); 14884 if (!Ptr) { 14885 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14886 << E->getSourceRange(); 14887 return ExprError(); 14888 } 14889 14890 if (isa<CallExpr>(E->getSubExpr())) { 14891 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 14892 << E->getSourceRange(); 14893 return ExprError(); 14894 } 14895 14896 assert(E->getValueKind() == VK_RValue); 14897 assert(E->getObjectKind() == OK_Ordinary); 14898 E->setType(DestType); 14899 14900 // Build the sub-expression as if it were an object of the pointee type. 14901 DestType = Ptr->getPointeeType(); 14902 ExprResult SubResult = Visit(E->getSubExpr()); 14903 if (SubResult.isInvalid()) return ExprError(); 14904 E->setSubExpr(SubResult.get()); 14905 return E; 14906 } 14907 14908 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14909 14910 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14911 14912 ExprResult VisitMemberExpr(MemberExpr *E) { 14913 return resolveDecl(E, E->getMemberDecl()); 14914 } 14915 14916 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14917 return resolveDecl(E, E->getDecl()); 14918 } 14919 }; 14920 } 14921 14922 /// Rebuilds a call expression which yielded __unknown_anytype. 14923 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14924 Expr *CalleeExpr = E->getCallee(); 14925 14926 enum FnKind { 14927 FK_MemberFunction, 14928 FK_FunctionPointer, 14929 FK_BlockPointer 14930 }; 14931 14932 FnKind Kind; 14933 QualType CalleeType = CalleeExpr->getType(); 14934 if (CalleeType == S.Context.BoundMemberTy) { 14935 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14936 Kind = FK_MemberFunction; 14937 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14938 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14939 CalleeType = Ptr->getPointeeType(); 14940 Kind = FK_FunctionPointer; 14941 } else { 14942 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14943 Kind = FK_BlockPointer; 14944 } 14945 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14946 14947 // Verify that this is a legal result type of a function. 14948 if (DestType->isArrayType() || DestType->isFunctionType()) { 14949 unsigned diagID = diag::err_func_returning_array_function; 14950 if (Kind == FK_BlockPointer) 14951 diagID = diag::err_block_returning_array_function; 14952 14953 S.Diag(E->getExprLoc(), diagID) 14954 << DestType->isFunctionType() << DestType; 14955 return ExprError(); 14956 } 14957 14958 // Otherwise, go ahead and set DestType as the call's result. 14959 E->setType(DestType.getNonLValueExprType(S.Context)); 14960 E->setValueKind(Expr::getValueKindForType(DestType)); 14961 assert(E->getObjectKind() == OK_Ordinary); 14962 14963 // Rebuild the function type, replacing the result type with DestType. 14964 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14965 if (Proto) { 14966 // __unknown_anytype(...) is a special case used by the debugger when 14967 // it has no idea what a function's signature is. 14968 // 14969 // We want to build this call essentially under the K&R 14970 // unprototyped rules, but making a FunctionNoProtoType in C++ 14971 // would foul up all sorts of assumptions. However, we cannot 14972 // simply pass all arguments as variadic arguments, nor can we 14973 // portably just call the function under a non-variadic type; see 14974 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14975 // However, it turns out that in practice it is generally safe to 14976 // call a function declared as "A foo(B,C,D);" under the prototype 14977 // "A foo(B,C,D,...);". The only known exception is with the 14978 // Windows ABI, where any variadic function is implicitly cdecl 14979 // regardless of its normal CC. Therefore we change the parameter 14980 // types to match the types of the arguments. 14981 // 14982 // This is a hack, but it is far superior to moving the 14983 // corresponding target-specific code from IR-gen to Sema/AST. 14984 14985 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14986 SmallVector<QualType, 8> ArgTypes; 14987 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14988 ArgTypes.reserve(E->getNumArgs()); 14989 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14990 Expr *Arg = E->getArg(i); 14991 QualType ArgType = Arg->getType(); 14992 if (E->isLValue()) { 14993 ArgType = S.Context.getLValueReferenceType(ArgType); 14994 } else if (E->isXValue()) { 14995 ArgType = S.Context.getRValueReferenceType(ArgType); 14996 } 14997 ArgTypes.push_back(ArgType); 14998 } 14999 ParamTypes = ArgTypes; 15000 } 15001 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15002 Proto->getExtProtoInfo()); 15003 } else { 15004 DestType = S.Context.getFunctionNoProtoType(DestType, 15005 FnType->getExtInfo()); 15006 } 15007 15008 // Rebuild the appropriate pointer-to-function type. 15009 switch (Kind) { 15010 case FK_MemberFunction: 15011 // Nothing to do. 15012 break; 15013 15014 case FK_FunctionPointer: 15015 DestType = S.Context.getPointerType(DestType); 15016 break; 15017 15018 case FK_BlockPointer: 15019 DestType = S.Context.getBlockPointerType(DestType); 15020 break; 15021 } 15022 15023 // Finally, we can recurse. 15024 ExprResult CalleeResult = Visit(CalleeExpr); 15025 if (!CalleeResult.isUsable()) return ExprError(); 15026 E->setCallee(CalleeResult.get()); 15027 15028 // Bind a temporary if necessary. 15029 return S.MaybeBindToTemporary(E); 15030 } 15031 15032 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15033 // Verify that this is a legal result type of a call. 15034 if (DestType->isArrayType() || DestType->isFunctionType()) { 15035 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15036 << DestType->isFunctionType() << DestType; 15037 return ExprError(); 15038 } 15039 15040 // Rewrite the method result type if available. 15041 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15042 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15043 Method->setReturnType(DestType); 15044 } 15045 15046 // Change the type of the message. 15047 E->setType(DestType.getNonReferenceType()); 15048 E->setValueKind(Expr::getValueKindForType(DestType)); 15049 15050 return S.MaybeBindToTemporary(E); 15051 } 15052 15053 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15054 // The only case we should ever see here is a function-to-pointer decay. 15055 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15056 assert(E->getValueKind() == VK_RValue); 15057 assert(E->getObjectKind() == OK_Ordinary); 15058 15059 E->setType(DestType); 15060 15061 // Rebuild the sub-expression as the pointee (function) type. 15062 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15063 15064 ExprResult Result = Visit(E->getSubExpr()); 15065 if (!Result.isUsable()) return ExprError(); 15066 15067 E->setSubExpr(Result.get()); 15068 return E; 15069 } else if (E->getCastKind() == CK_LValueToRValue) { 15070 assert(E->getValueKind() == VK_RValue); 15071 assert(E->getObjectKind() == OK_Ordinary); 15072 15073 assert(isa<BlockPointerType>(E->getType())); 15074 15075 E->setType(DestType); 15076 15077 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15078 DestType = S.Context.getLValueReferenceType(DestType); 15079 15080 ExprResult Result = Visit(E->getSubExpr()); 15081 if (!Result.isUsable()) return ExprError(); 15082 15083 E->setSubExpr(Result.get()); 15084 return E; 15085 } else { 15086 llvm_unreachable("Unhandled cast type!"); 15087 } 15088 } 15089 15090 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15091 ExprValueKind ValueKind = VK_LValue; 15092 QualType Type = DestType; 15093 15094 // We know how to make this work for certain kinds of decls: 15095 15096 // - functions 15097 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15098 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15099 DestType = Ptr->getPointeeType(); 15100 ExprResult Result = resolveDecl(E, VD); 15101 if (Result.isInvalid()) return ExprError(); 15102 return S.ImpCastExprToType(Result.get(), Type, 15103 CK_FunctionToPointerDecay, VK_RValue); 15104 } 15105 15106 if (!Type->isFunctionType()) { 15107 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15108 << VD << E->getSourceRange(); 15109 return ExprError(); 15110 } 15111 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15112 // We must match the FunctionDecl's type to the hack introduced in 15113 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15114 // type. See the lengthy commentary in that routine. 15115 QualType FDT = FD->getType(); 15116 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15117 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15118 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15119 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15120 SourceLocation Loc = FD->getLocation(); 15121 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15122 FD->getDeclContext(), 15123 Loc, Loc, FD->getNameInfo().getName(), 15124 DestType, FD->getTypeSourceInfo(), 15125 SC_None, false/*isInlineSpecified*/, 15126 FD->hasPrototype(), 15127 false/*isConstexprSpecified*/); 15128 15129 if (FD->getQualifier()) 15130 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15131 15132 SmallVector<ParmVarDecl*, 16> Params; 15133 for (const auto &AI : FT->param_types()) { 15134 ParmVarDecl *Param = 15135 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15136 Param->setScopeInfo(0, Params.size()); 15137 Params.push_back(Param); 15138 } 15139 NewFD->setParams(Params); 15140 DRE->setDecl(NewFD); 15141 VD = DRE->getDecl(); 15142 } 15143 } 15144 15145 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15146 if (MD->isInstance()) { 15147 ValueKind = VK_RValue; 15148 Type = S.Context.BoundMemberTy; 15149 } 15150 15151 // Function references aren't l-values in C. 15152 if (!S.getLangOpts().CPlusPlus) 15153 ValueKind = VK_RValue; 15154 15155 // - variables 15156 } else if (isa<VarDecl>(VD)) { 15157 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15158 Type = RefTy->getPointeeType(); 15159 } else if (Type->isFunctionType()) { 15160 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15161 << VD << E->getSourceRange(); 15162 return ExprError(); 15163 } 15164 15165 // - nothing else 15166 } else { 15167 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15168 << VD << E->getSourceRange(); 15169 return ExprError(); 15170 } 15171 15172 // Modifying the declaration like this is friendly to IR-gen but 15173 // also really dangerous. 15174 VD->setType(DestType); 15175 E->setType(Type); 15176 E->setValueKind(ValueKind); 15177 return E; 15178 } 15179 15180 /// Check a cast of an unknown-any type. We intentionally only 15181 /// trigger this for C-style casts. 15182 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15183 Expr *CastExpr, CastKind &CastKind, 15184 ExprValueKind &VK, CXXCastPath &Path) { 15185 // The type we're casting to must be either void or complete. 15186 if (!CastType->isVoidType() && 15187 RequireCompleteType(TypeRange.getBegin(), CastType, 15188 diag::err_typecheck_cast_to_incomplete)) 15189 return ExprError(); 15190 15191 // Rewrite the casted expression from scratch. 15192 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15193 if (!result.isUsable()) return ExprError(); 15194 15195 CastExpr = result.get(); 15196 VK = CastExpr->getValueKind(); 15197 CastKind = CK_NoOp; 15198 15199 return CastExpr; 15200 } 15201 15202 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15203 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15204 } 15205 15206 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15207 Expr *arg, QualType ¶mType) { 15208 // If the syntactic form of the argument is not an explicit cast of 15209 // any sort, just do default argument promotion. 15210 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15211 if (!castArg) { 15212 ExprResult result = DefaultArgumentPromotion(arg); 15213 if (result.isInvalid()) return ExprError(); 15214 paramType = result.get()->getType(); 15215 return result; 15216 } 15217 15218 // Otherwise, use the type that was written in the explicit cast. 15219 assert(!arg->hasPlaceholderType()); 15220 paramType = castArg->getTypeAsWritten(); 15221 15222 // Copy-initialize a parameter of that type. 15223 InitializedEntity entity = 15224 InitializedEntity::InitializeParameter(Context, paramType, 15225 /*consumed*/ false); 15226 return PerformCopyInitialization(entity, callLoc, arg); 15227 } 15228 15229 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15230 Expr *orig = E; 15231 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15232 while (true) { 15233 E = E->IgnoreParenImpCasts(); 15234 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15235 E = call->getCallee(); 15236 diagID = diag::err_uncasted_call_of_unknown_any; 15237 } else { 15238 break; 15239 } 15240 } 15241 15242 SourceLocation loc; 15243 NamedDecl *d; 15244 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15245 loc = ref->getLocation(); 15246 d = ref->getDecl(); 15247 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15248 loc = mem->getMemberLoc(); 15249 d = mem->getMemberDecl(); 15250 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15251 diagID = diag::err_uncasted_call_of_unknown_any; 15252 loc = msg->getSelectorStartLoc(); 15253 d = msg->getMethodDecl(); 15254 if (!d) { 15255 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15256 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15257 << orig->getSourceRange(); 15258 return ExprError(); 15259 } 15260 } else { 15261 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15262 << E->getSourceRange(); 15263 return ExprError(); 15264 } 15265 15266 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15267 15268 // Never recoverable. 15269 return ExprError(); 15270 } 15271 15272 /// Check for operands with placeholder types and complain if found. 15273 /// Returns true if there was an error and no recovery was possible. 15274 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15275 if (!getLangOpts().CPlusPlus) { 15276 // C cannot handle TypoExpr nodes on either side of a binop because it 15277 // doesn't handle dependent types properly, so make sure any TypoExprs have 15278 // been dealt with before checking the operands. 15279 ExprResult Result = CorrectDelayedTyposInExpr(E); 15280 if (!Result.isUsable()) return ExprError(); 15281 E = Result.get(); 15282 } 15283 15284 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15285 if (!placeholderType) return E; 15286 15287 switch (placeholderType->getKind()) { 15288 15289 // Overloaded expressions. 15290 case BuiltinType::Overload: { 15291 // Try to resolve a single function template specialization. 15292 // This is obligatory. 15293 ExprResult Result = E; 15294 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15295 return Result; 15296 15297 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15298 // leaves Result unchanged on failure. 15299 Result = E; 15300 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15301 return Result; 15302 15303 // If that failed, try to recover with a call. 15304 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15305 /*complain*/ true); 15306 return Result; 15307 } 15308 15309 // Bound member functions. 15310 case BuiltinType::BoundMember: { 15311 ExprResult result = E; 15312 const Expr *BME = E->IgnoreParens(); 15313 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15314 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15315 if (isa<CXXPseudoDestructorExpr>(BME)) { 15316 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15317 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15318 if (ME->getMemberNameInfo().getName().getNameKind() == 15319 DeclarationName::CXXDestructorName) 15320 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15321 } 15322 tryToRecoverWithCall(result, PD, 15323 /*complain*/ true); 15324 return result; 15325 } 15326 15327 // ARC unbridged casts. 15328 case BuiltinType::ARCUnbridgedCast: { 15329 Expr *realCast = stripARCUnbridgedCast(E); 15330 diagnoseARCUnbridgedCast(realCast); 15331 return realCast; 15332 } 15333 15334 // Expressions of unknown type. 15335 case BuiltinType::UnknownAny: 15336 return diagnoseUnknownAnyExpr(*this, E); 15337 15338 // Pseudo-objects. 15339 case BuiltinType::PseudoObject: 15340 return checkPseudoObjectRValue(E); 15341 15342 case BuiltinType::BuiltinFn: { 15343 // Accept __noop without parens by implicitly converting it to a call expr. 15344 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15345 if (DRE) { 15346 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15347 if (FD->getBuiltinID() == Builtin::BI__noop) { 15348 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15349 CK_BuiltinFnToFnPtr).get(); 15350 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15351 VK_RValue, SourceLocation()); 15352 } 15353 } 15354 15355 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15356 return ExprError(); 15357 } 15358 15359 // Expressions of unknown type. 15360 case BuiltinType::OMPArraySection: 15361 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15362 return ExprError(); 15363 15364 // Everything else should be impossible. 15365 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15366 case BuiltinType::Id: 15367 #include "clang/Basic/OpenCLImageTypes.def" 15368 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15369 #define PLACEHOLDER_TYPE(Id, SingletonId) 15370 #include "clang/AST/BuiltinTypes.def" 15371 break; 15372 } 15373 15374 llvm_unreachable("invalid placeholder type!"); 15375 } 15376 15377 bool Sema::CheckCaseExpression(Expr *E) { 15378 if (E->isTypeDependent()) 15379 return true; 15380 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15381 return E->getType()->isIntegralOrEnumerationType(); 15382 return false; 15383 } 15384 15385 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15386 ExprResult 15387 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15388 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15389 "Unknown Objective-C Boolean value!"); 15390 QualType BoolT = Context.ObjCBuiltinBoolTy; 15391 if (!Context.getBOOLDecl()) { 15392 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15393 Sema::LookupOrdinaryName); 15394 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15395 NamedDecl *ND = Result.getFoundDecl(); 15396 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15397 Context.setBOOLDecl(TD); 15398 } 15399 } 15400 if (Context.getBOOLDecl()) 15401 BoolT = Context.getBOOLType(); 15402 return new (Context) 15403 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15404 } 15405 15406 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15407 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15408 SourceLocation RParen) { 15409 15410 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15411 15412 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15413 [&](const AvailabilitySpec &Spec) { 15414 return Spec.getPlatform() == Platform; 15415 }); 15416 15417 VersionTuple Version; 15418 if (Spec != AvailSpecs.end()) 15419 Version = Spec->getVersion(); 15420 15421 return new (Context) 15422 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15423 } 15424