1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) { 83 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 84 if (DC && !DC->hasAttr<UnusedAttr>()) 85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 86 } 87 } 88 } 89 90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 92 if (!OMD) 93 return false; 94 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 95 if (!OID) 96 return false; 97 98 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 99 if (ObjCMethodDecl *CatMeth = 100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 101 if (!CatMeth->hasAttr<AvailabilityAttr>()) 102 return true; 103 return false; 104 } 105 106 AvailabilityResult Sema::ShouldDiagnoseAvailabilityOfDecl( 107 NamedDecl *&D, VersionTuple ContextVersion, std::string *Message) { 108 AvailabilityResult Result = D->getAvailability(Message, ContextVersion); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(Message, ContextVersion); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(Message, ContextVersion); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(Message, ContextVersion); 136 } 137 138 switch (Result) { 139 case AR_Available: 140 return Result; 141 142 case AR_Unavailable: 143 case AR_Deprecated: 144 return getCurContextAvailability() != Result ? Result : AR_Available; 145 146 case AR_NotYetIntroduced: { 147 // Don't do this for enums, they can't be redeclared. 148 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 149 return AR_Available; 150 151 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 152 // Objective-C method declarations in categories are not modelled as 153 // redeclarations, so manually look for a redeclaration in a category 154 // if necessary. 155 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 156 Warn = false; 157 // In general, D will point to the most recent redeclaration. However, 158 // for `@class A;` decls, this isn't true -- manually go through the 159 // redecl chain in that case. 160 if (Warn && isa<ObjCInterfaceDecl>(D)) 161 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 162 Redecl = Redecl->getPreviousDecl()) 163 if (!Redecl->hasAttr<AvailabilityAttr>() || 164 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 165 Warn = false; 166 167 return Warn ? AR_NotYetIntroduced : AR_Available; 168 } 169 } 170 llvm_unreachable("Unknown availability result!"); 171 } 172 173 static void 174 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 175 const ObjCInterfaceDecl *UnknownObjCClass, 176 bool ObjCPropertyAccess) { 177 VersionTuple ContextVersion; 178 if (const DeclContext *DC = S.getCurObjCLexicalContext()) 179 ContextVersion = S.getVersionForDecl(cast<Decl>(DC)); 180 181 std::string Message; 182 // See if this declaration is unavailable, deprecated, or partial in the 183 // current context. 184 if (AvailabilityResult Result = 185 S.ShouldDiagnoseAvailabilityOfDecl(D, ContextVersion, &Message)) { 186 187 if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) { 188 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 189 return; 190 } 191 192 const ObjCPropertyDecl *ObjCPDecl = nullptr; 193 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 194 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 195 AvailabilityResult PDeclResult = 196 PD->getAvailability(nullptr, ContextVersion); 197 if (PDeclResult == Result) 198 ObjCPDecl = PD; 199 } 200 } 201 202 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 203 ObjCPDecl, ObjCPropertyAccess); 204 } 205 } 206 207 /// \brief Emit a note explaining that this function is deleted. 208 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 209 assert(Decl->isDeleted()); 210 211 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 212 213 if (Method && Method->isDeleted() && Method->isDefaulted()) { 214 // If the method was explicitly defaulted, point at that declaration. 215 if (!Method->isImplicit()) 216 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 217 218 // Try to diagnose why this special member function was implicitly 219 // deleted. This might fail, if that reason no longer applies. 220 CXXSpecialMember CSM = getSpecialMember(Method); 221 if (CSM != CXXInvalid) 222 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 223 224 return; 225 } 226 227 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 228 if (Ctor && Ctor->isInheritingConstructor()) 229 return NoteDeletedInheritingConstructor(Ctor); 230 231 Diag(Decl->getLocation(), diag::note_availability_specified_here) 232 << Decl << true; 233 } 234 235 /// \brief Determine whether a FunctionDecl was ever declared with an 236 /// explicit storage class. 237 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 238 for (auto I : D->redecls()) { 239 if (I->getStorageClass() != SC_None) 240 return true; 241 } 242 return false; 243 } 244 245 /// \brief Check whether we're in an extern inline function and referring to a 246 /// variable or function with internal linkage (C11 6.7.4p3). 247 /// 248 /// This is only a warning because we used to silently accept this code, but 249 /// in many cases it will not behave correctly. This is not enabled in C++ mode 250 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 251 /// and so while there may still be user mistakes, most of the time we can't 252 /// prove that there are errors. 253 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 254 const NamedDecl *D, 255 SourceLocation Loc) { 256 // This is disabled under C++; there are too many ways for this to fire in 257 // contexts where the warning is a false positive, or where it is technically 258 // correct but benign. 259 if (S.getLangOpts().CPlusPlus) 260 return; 261 262 // Check if this is an inlined function or method. 263 FunctionDecl *Current = S.getCurFunctionDecl(); 264 if (!Current) 265 return; 266 if (!Current->isInlined()) 267 return; 268 if (!Current->isExternallyVisible()) 269 return; 270 271 // Check if the decl has internal linkage. 272 if (D->getFormalLinkage() != InternalLinkage) 273 return; 274 275 // Downgrade from ExtWarn to Extension if 276 // (1) the supposedly external inline function is in the main file, 277 // and probably won't be included anywhere else. 278 // (2) the thing we're referencing is a pure function. 279 // (3) the thing we're referencing is another inline function. 280 // This last can give us false negatives, but it's better than warning on 281 // wrappers for simple C library functions. 282 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 283 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 284 if (!DowngradeWarning && UsedFn) 285 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 286 287 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 288 : diag::ext_internal_in_extern_inline) 289 << /*IsVar=*/!UsedFn << D; 290 291 S.MaybeSuggestAddingStaticToDecl(Current); 292 293 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 294 << D; 295 } 296 297 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 298 const FunctionDecl *First = Cur->getFirstDecl(); 299 300 // Suggest "static" on the function, if possible. 301 if (!hasAnyExplicitStorageClass(First)) { 302 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 303 Diag(DeclBegin, diag::note_convert_inline_to_static) 304 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 305 } 306 } 307 308 /// \brief Determine whether the use of this declaration is valid, and 309 /// emit any corresponding diagnostics. 310 /// 311 /// This routine diagnoses various problems with referencing 312 /// declarations that can occur when using a declaration. For example, 313 /// it might warn if a deprecated or unavailable declaration is being 314 /// used, or produce an error (and return true) if a C++0x deleted 315 /// function is being used. 316 /// 317 /// \returns true if there was an error (this declaration cannot be 318 /// referenced), false otherwise. 319 /// 320 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 321 const ObjCInterfaceDecl *UnknownObjCClass, 322 bool ObjCPropertyAccess) { 323 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 324 // If there were any diagnostics suppressed by template argument deduction, 325 // emit them now. 326 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 327 if (Pos != SuppressedDiagnostics.end()) { 328 for (const PartialDiagnosticAt &Suppressed : Pos->second) 329 Diag(Suppressed.first, Suppressed.second); 330 331 // Clear out the list of suppressed diagnostics, so that we don't emit 332 // them again for this specialization. However, we don't obsolete this 333 // entry from the table, because we want to avoid ever emitting these 334 // diagnostics again. 335 Pos->second.clear(); 336 } 337 338 // C++ [basic.start.main]p3: 339 // The function 'main' shall not be used within a program. 340 if (cast<FunctionDecl>(D)->isMain()) 341 Diag(Loc, diag::ext_main_used); 342 } 343 344 // See if this is an auto-typed variable whose initializer we are parsing. 345 if (ParsingInitForAutoVars.count(D)) { 346 if (isa<BindingDecl>(D)) { 347 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 348 << D->getDeclName(); 349 } else { 350 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 351 352 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName() << (unsigned)AT->getKeyword(); 354 } 355 return true; 356 } 357 358 // See if this is a deleted function. 359 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 360 if (FD->isDeleted()) { 361 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 362 if (Ctor && Ctor->isInheritingConstructor()) 363 Diag(Loc, diag::err_deleted_inherited_ctor_use) 364 << Ctor->getParent() 365 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 366 else 367 Diag(Loc, diag::err_deleted_function_use); 368 NoteDeletedFunction(FD); 369 return true; 370 } 371 372 // If the function has a deduced return type, and we can't deduce it, 373 // then we can't use it either. 374 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 375 DeduceReturnType(FD, Loc)) 376 return true; 377 } 378 379 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 380 // Only the variables omp_in and omp_out are allowed in the combiner. 381 // Only the variables omp_priv and omp_orig are allowed in the 382 // initializer-clause. 383 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 384 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 385 isa<VarDecl>(D)) { 386 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 387 << getCurFunction()->HasOMPDeclareReductionCombiner; 388 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 389 return true; 390 } 391 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 392 ObjCPropertyAccess); 393 394 DiagnoseUnusedOfDecl(*this, D, Loc); 395 396 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 397 398 return false; 399 } 400 401 /// \brief Retrieve the message suffix that should be added to a 402 /// diagnostic complaining about the given function being deleted or 403 /// unavailable. 404 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 405 std::string Message; 406 if (FD->getAvailability(&Message)) 407 return ": " + Message; 408 409 return std::string(); 410 } 411 412 /// DiagnoseSentinelCalls - This routine checks whether a call or 413 /// message-send is to a declaration with the sentinel attribute, and 414 /// if so, it checks that the requirements of the sentinel are 415 /// satisfied. 416 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 417 ArrayRef<Expr *> Args) { 418 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 419 if (!attr) 420 return; 421 422 // The number of formal parameters of the declaration. 423 unsigned numFormalParams; 424 425 // The kind of declaration. This is also an index into a %select in 426 // the diagnostic. 427 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 428 429 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 430 numFormalParams = MD->param_size(); 431 calleeType = CT_Method; 432 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 433 numFormalParams = FD->param_size(); 434 calleeType = CT_Function; 435 } else if (isa<VarDecl>(D)) { 436 QualType type = cast<ValueDecl>(D)->getType(); 437 const FunctionType *fn = nullptr; 438 if (const PointerType *ptr = type->getAs<PointerType>()) { 439 fn = ptr->getPointeeType()->getAs<FunctionType>(); 440 if (!fn) return; 441 calleeType = CT_Function; 442 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 443 fn = ptr->getPointeeType()->castAs<FunctionType>(); 444 calleeType = CT_Block; 445 } else { 446 return; 447 } 448 449 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 450 numFormalParams = proto->getNumParams(); 451 } else { 452 numFormalParams = 0; 453 } 454 } else { 455 return; 456 } 457 458 // "nullPos" is the number of formal parameters at the end which 459 // effectively count as part of the variadic arguments. This is 460 // useful if you would prefer to not have *any* formal parameters, 461 // but the language forces you to have at least one. 462 unsigned nullPos = attr->getNullPos(); 463 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 464 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 465 466 // The number of arguments which should follow the sentinel. 467 unsigned numArgsAfterSentinel = attr->getSentinel(); 468 469 // If there aren't enough arguments for all the formal parameters, 470 // the sentinel, and the args after the sentinel, complain. 471 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 472 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 473 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 474 return; 475 } 476 477 // Otherwise, find the sentinel expression. 478 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 479 if (!sentinelExpr) return; 480 if (sentinelExpr->isValueDependent()) return; 481 if (Context.isSentinelNullExpr(sentinelExpr)) return; 482 483 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 484 // or 'NULL' if those are actually defined in the context. Only use 485 // 'nil' for ObjC methods, where it's much more likely that the 486 // variadic arguments form a list of object pointers. 487 SourceLocation MissingNilLoc 488 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 489 std::string NullValue; 490 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 491 NullValue = "nil"; 492 else if (getLangOpts().CPlusPlus11) 493 NullValue = "nullptr"; 494 else if (PP.isMacroDefined("NULL")) 495 NullValue = "NULL"; 496 else 497 NullValue = "(void*) 0"; 498 499 if (MissingNilLoc.isInvalid()) 500 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 501 else 502 Diag(MissingNilLoc, diag::warn_missing_sentinel) 503 << int(calleeType) 504 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 505 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 506 } 507 508 SourceRange Sema::getExprRange(Expr *E) const { 509 return E ? E->getSourceRange() : SourceRange(); 510 } 511 512 //===----------------------------------------------------------------------===// 513 // Standard Promotions and Conversions 514 //===----------------------------------------------------------------------===// 515 516 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 517 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 518 // Handle any placeholder expressions which made it here. 519 if (E->getType()->isPlaceholderType()) { 520 ExprResult result = CheckPlaceholderExpr(E); 521 if (result.isInvalid()) return ExprError(); 522 E = result.get(); 523 } 524 525 QualType Ty = E->getType(); 526 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 527 528 if (Ty->isFunctionType()) { 529 // If we are here, we are not calling a function but taking 530 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 531 if (getLangOpts().OpenCL) { 532 if (Diagnose) 533 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 534 return ExprError(); 535 } 536 537 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 538 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 539 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 540 return ExprError(); 541 542 E = ImpCastExprToType(E, Context.getPointerType(Ty), 543 CK_FunctionToPointerDecay).get(); 544 } else if (Ty->isArrayType()) { 545 // In C90 mode, arrays only promote to pointers if the array expression is 546 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 547 // type 'array of type' is converted to an expression that has type 'pointer 548 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 549 // that has type 'array of type' ...". The relevant change is "an lvalue" 550 // (C90) to "an expression" (C99). 551 // 552 // C++ 4.2p1: 553 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 554 // T" can be converted to an rvalue of type "pointer to T". 555 // 556 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 557 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 558 CK_ArrayToPointerDecay).get(); 559 } 560 return E; 561 } 562 563 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 564 // Check to see if we are dereferencing a null pointer. If so, 565 // and if not volatile-qualified, this is undefined behavior that the 566 // optimizer will delete, so warn about it. People sometimes try to use this 567 // to get a deterministic trap and are surprised by clang's behavior. This 568 // only handles the pattern "*null", which is a very syntactic check. 569 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 570 if (UO->getOpcode() == UO_Deref && 571 UO->getSubExpr()->IgnoreParenCasts()-> 572 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 573 !UO->getType().isVolatileQualified()) { 574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 575 S.PDiag(diag::warn_indirection_through_null) 576 << UO->getSubExpr()->getSourceRange()); 577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 578 S.PDiag(diag::note_indirection_through_null)); 579 } 580 } 581 582 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 583 SourceLocation AssignLoc, 584 const Expr* RHS) { 585 const ObjCIvarDecl *IV = OIRE->getDecl(); 586 if (!IV) 587 return; 588 589 DeclarationName MemberName = IV->getDeclName(); 590 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 591 if (!Member || !Member->isStr("isa")) 592 return; 593 594 const Expr *Base = OIRE->getBase(); 595 QualType BaseType = Base->getType(); 596 if (OIRE->isArrow()) 597 BaseType = BaseType->getPointeeType(); 598 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 599 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 600 ObjCInterfaceDecl *ClassDeclared = nullptr; 601 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 602 if (!ClassDeclared->getSuperClass() 603 && (*ClassDeclared->ivar_begin()) == IV) { 604 if (RHS) { 605 NamedDecl *ObjectSetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_setClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectSetClass) { 610 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 611 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 612 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 613 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 614 AssignLoc), ",") << 615 FixItHint::CreateInsertion(RHSLocEnd, ")"); 616 } 617 else 618 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 619 } else { 620 NamedDecl *ObjectGetClass = 621 S.LookupSingleName(S.TUScope, 622 &S.Context.Idents.get("object_getClass"), 623 SourceLocation(), S.LookupOrdinaryName); 624 if (ObjectGetClass) 625 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 626 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 627 FixItHint::CreateReplacement( 628 SourceRange(OIRE->getOpLoc(), 629 OIRE->getLocEnd()), ")"); 630 else 631 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 632 } 633 S.Diag(IV->getLocation(), diag::note_ivar_decl); 634 } 635 } 636 } 637 638 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 639 // Handle any placeholder expressions which made it here. 640 if (E->getType()->isPlaceholderType()) { 641 ExprResult result = CheckPlaceholderExpr(E); 642 if (result.isInvalid()) return ExprError(); 643 E = result.get(); 644 } 645 646 // C++ [conv.lval]p1: 647 // A glvalue of a non-function, non-array type T can be 648 // converted to a prvalue. 649 if (!E->isGLValue()) return E; 650 651 QualType T = E->getType(); 652 assert(!T.isNull() && "r-value conversion on typeless expression?"); 653 654 // We don't want to throw lvalue-to-rvalue casts on top of 655 // expressions of certain types in C++. 656 if (getLangOpts().CPlusPlus && 657 (E->getType() == Context.OverloadTy || 658 T->isDependentType() || 659 T->isRecordType())) 660 return E; 661 662 // The C standard is actually really unclear on this point, and 663 // DR106 tells us what the result should be but not why. It's 664 // generally best to say that void types just doesn't undergo 665 // lvalue-to-rvalue at all. Note that expressions of unqualified 666 // 'void' type are never l-values, but qualified void can be. 667 if (T->isVoidType()) 668 return E; 669 670 // OpenCL usually rejects direct accesses to values of 'half' type. 671 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 672 T->isHalfType()) { 673 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 674 << 0 << T; 675 return ExprError(); 676 } 677 678 CheckForNullPointerDereference(*this, E); 679 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 680 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 681 &Context.Idents.get("object_getClass"), 682 SourceLocation(), LookupOrdinaryName); 683 if (ObjectGetClass) 684 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 685 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 686 FixItHint::CreateReplacement( 687 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 688 else 689 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 690 } 691 else if (const ObjCIvarRefExpr *OIRE = 692 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 693 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 694 695 // C++ [conv.lval]p1: 696 // [...] If T is a non-class type, the type of the prvalue is the 697 // cv-unqualified version of T. Otherwise, the type of the 698 // rvalue is T. 699 // 700 // C99 6.3.2.1p2: 701 // If the lvalue has qualified type, the value has the unqualified 702 // version of the type of the lvalue; otherwise, the value has the 703 // type of the lvalue. 704 if (T.hasQualifiers()) 705 T = T.getUnqualifiedType(); 706 707 // Under the MS ABI, lock down the inheritance model now. 708 if (T->isMemberPointerType() && 709 Context.getTargetInfo().getCXXABI().isMicrosoft()) 710 (void)isCompleteType(E->getExprLoc(), T); 711 712 UpdateMarkingForLValueToRValue(E); 713 714 // Loading a __weak object implicitly retains the value, so we need a cleanup to 715 // balance that. 716 if (getLangOpts().ObjCAutoRefCount && 717 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 718 Cleanup.setExprNeedsCleanups(true); 719 720 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 721 nullptr, VK_RValue); 722 723 // C11 6.3.2.1p2: 724 // ... if the lvalue has atomic type, the value has the non-atomic version 725 // of the type of the lvalue ... 726 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 727 T = Atomic->getValueType().getUnqualifiedType(); 728 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 729 nullptr, VK_RValue); 730 } 731 732 return Res; 733 } 734 735 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 736 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 737 if (Res.isInvalid()) 738 return ExprError(); 739 Res = DefaultLvalueConversion(Res.get()); 740 if (Res.isInvalid()) 741 return ExprError(); 742 return Res; 743 } 744 745 /// CallExprUnaryConversions - a special case of an unary conversion 746 /// performed on a function designator of a call expression. 747 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 748 QualType Ty = E->getType(); 749 ExprResult Res = E; 750 // Only do implicit cast for a function type, but not for a pointer 751 // to function type. 752 if (Ty->isFunctionType()) { 753 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 754 CK_FunctionToPointerDecay).get(); 755 if (Res.isInvalid()) 756 return ExprError(); 757 } 758 Res = DefaultLvalueConversion(Res.get()); 759 if (Res.isInvalid()) 760 return ExprError(); 761 return Res.get(); 762 } 763 764 /// UsualUnaryConversions - Performs various conversions that are common to most 765 /// operators (C99 6.3). The conversions of array and function types are 766 /// sometimes suppressed. For example, the array->pointer conversion doesn't 767 /// apply if the array is an argument to the sizeof or address (&) operators. 768 /// In these instances, this routine should *not* be called. 769 ExprResult Sema::UsualUnaryConversions(Expr *E) { 770 // First, convert to an r-value. 771 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 772 if (Res.isInvalid()) 773 return ExprError(); 774 E = Res.get(); 775 776 QualType Ty = E->getType(); 777 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 778 779 // Half FP have to be promoted to float unless it is natively supported 780 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 781 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 782 783 // Try to perform integral promotions if the object has a theoretically 784 // promotable type. 785 if (Ty->isIntegralOrUnscopedEnumerationType()) { 786 // C99 6.3.1.1p2: 787 // 788 // The following may be used in an expression wherever an int or 789 // unsigned int may be used: 790 // - an object or expression with an integer type whose integer 791 // conversion rank is less than or equal to the rank of int 792 // and unsigned int. 793 // - A bit-field of type _Bool, int, signed int, or unsigned int. 794 // 795 // If an int can represent all values of the original type, the 796 // value is converted to an int; otherwise, it is converted to an 797 // unsigned int. These are called the integer promotions. All 798 // other types are unchanged by the integer promotions. 799 800 QualType PTy = Context.isPromotableBitField(E); 801 if (!PTy.isNull()) { 802 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 803 return E; 804 } 805 if (Ty->isPromotableIntegerType()) { 806 QualType PT = Context.getPromotedIntegerType(Ty); 807 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 808 return E; 809 } 810 } 811 return E; 812 } 813 814 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 815 /// do not have a prototype. Arguments that have type float or __fp16 816 /// are promoted to double. All other argument types are converted by 817 /// UsualUnaryConversions(). 818 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 819 QualType Ty = E->getType(); 820 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 821 822 ExprResult Res = UsualUnaryConversions(E); 823 if (Res.isInvalid()) 824 return ExprError(); 825 E = Res.get(); 826 827 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 828 // double. 829 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 830 if (BTy && (BTy->getKind() == BuiltinType::Half || 831 BTy->getKind() == BuiltinType::Float)) 832 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 833 834 // C++ performs lvalue-to-rvalue conversion as a default argument 835 // promotion, even on class types, but note: 836 // C++11 [conv.lval]p2: 837 // When an lvalue-to-rvalue conversion occurs in an unevaluated 838 // operand or a subexpression thereof the value contained in the 839 // referenced object is not accessed. Otherwise, if the glvalue 840 // has a class type, the conversion copy-initializes a temporary 841 // of type T from the glvalue and the result of the conversion 842 // is a prvalue for the temporary. 843 // FIXME: add some way to gate this entire thing for correctness in 844 // potentially potentially evaluated contexts. 845 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 846 ExprResult Temp = PerformCopyInitialization( 847 InitializedEntity::InitializeTemporary(E->getType()), 848 E->getExprLoc(), E); 849 if (Temp.isInvalid()) 850 return ExprError(); 851 E = Temp.get(); 852 } 853 854 return E; 855 } 856 857 /// Determine the degree of POD-ness for an expression. 858 /// Incomplete types are considered POD, since this check can be performed 859 /// when we're in an unevaluated context. 860 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 861 if (Ty->isIncompleteType()) { 862 // C++11 [expr.call]p7: 863 // After these conversions, if the argument does not have arithmetic, 864 // enumeration, pointer, pointer to member, or class type, the program 865 // is ill-formed. 866 // 867 // Since we've already performed array-to-pointer and function-to-pointer 868 // decay, the only such type in C++ is cv void. This also handles 869 // initializer lists as variadic arguments. 870 if (Ty->isVoidType()) 871 return VAK_Invalid; 872 873 if (Ty->isObjCObjectType()) 874 return VAK_Invalid; 875 return VAK_Valid; 876 } 877 878 if (Ty.isCXX98PODType(Context)) 879 return VAK_Valid; 880 881 // C++11 [expr.call]p7: 882 // Passing a potentially-evaluated argument of class type (Clause 9) 883 // having a non-trivial copy constructor, a non-trivial move constructor, 884 // or a non-trivial destructor, with no corresponding parameter, 885 // is conditionally-supported with implementation-defined semantics. 886 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 887 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 888 if (!Record->hasNonTrivialCopyConstructor() && 889 !Record->hasNonTrivialMoveConstructor() && 890 !Record->hasNonTrivialDestructor()) 891 return VAK_ValidInCXX11; 892 893 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 894 return VAK_Valid; 895 896 if (Ty->isObjCObjectType()) 897 return VAK_Invalid; 898 899 if (getLangOpts().MSVCCompat) 900 return VAK_MSVCUndefined; 901 902 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 903 // permitted to reject them. We should consider doing so. 904 return VAK_Undefined; 905 } 906 907 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 908 // Don't allow one to pass an Objective-C interface to a vararg. 909 const QualType &Ty = E->getType(); 910 VarArgKind VAK = isValidVarArgType(Ty); 911 912 // Complain about passing non-POD types through varargs. 913 switch (VAK) { 914 case VAK_ValidInCXX11: 915 DiagRuntimeBehavior( 916 E->getLocStart(), nullptr, 917 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 918 << Ty << CT); 919 // Fall through. 920 case VAK_Valid: 921 if (Ty->isRecordType()) { 922 // This is unlikely to be what the user intended. If the class has a 923 // 'c_str' member function, the user probably meant to call that. 924 DiagRuntimeBehavior(E->getLocStart(), nullptr, 925 PDiag(diag::warn_pass_class_arg_to_vararg) 926 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 927 } 928 break; 929 930 case VAK_Undefined: 931 case VAK_MSVCUndefined: 932 DiagRuntimeBehavior( 933 E->getLocStart(), nullptr, 934 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 935 << getLangOpts().CPlusPlus11 << Ty << CT); 936 break; 937 938 case VAK_Invalid: 939 if (Ty->isObjCObjectType()) 940 DiagRuntimeBehavior( 941 E->getLocStart(), nullptr, 942 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 943 << Ty << CT); 944 else 945 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 946 << isa<InitListExpr>(E) << Ty << CT; 947 break; 948 } 949 } 950 951 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 952 /// will create a trap if the resulting type is not a POD type. 953 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 954 FunctionDecl *FDecl) { 955 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 956 // Strip the unbridged-cast placeholder expression off, if applicable. 957 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 958 (CT == VariadicMethod || 959 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 960 E = stripARCUnbridgedCast(E); 961 962 // Otherwise, do normal placeholder checking. 963 } else { 964 ExprResult ExprRes = CheckPlaceholderExpr(E); 965 if (ExprRes.isInvalid()) 966 return ExprError(); 967 E = ExprRes.get(); 968 } 969 } 970 971 ExprResult ExprRes = DefaultArgumentPromotion(E); 972 if (ExprRes.isInvalid()) 973 return ExprError(); 974 E = ExprRes.get(); 975 976 // Diagnostics regarding non-POD argument types are 977 // emitted along with format string checking in Sema::CheckFunctionCall(). 978 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 979 // Turn this into a trap. 980 CXXScopeSpec SS; 981 SourceLocation TemplateKWLoc; 982 UnqualifiedId Name; 983 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 984 E->getLocStart()); 985 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 986 Name, true, false); 987 if (TrapFn.isInvalid()) 988 return ExprError(); 989 990 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 991 E->getLocStart(), None, 992 E->getLocEnd()); 993 if (Call.isInvalid()) 994 return ExprError(); 995 996 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 997 Call.get(), E); 998 if (Comma.isInvalid()) 999 return ExprError(); 1000 return Comma.get(); 1001 } 1002 1003 if (!getLangOpts().CPlusPlus && 1004 RequireCompleteType(E->getExprLoc(), E->getType(), 1005 diag::err_call_incomplete_argument)) 1006 return ExprError(); 1007 1008 return E; 1009 } 1010 1011 /// \brief Converts an integer to complex float type. Helper function of 1012 /// UsualArithmeticConversions() 1013 /// 1014 /// \return false if the integer expression is an integer type and is 1015 /// successfully converted to the complex type. 1016 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1017 ExprResult &ComplexExpr, 1018 QualType IntTy, 1019 QualType ComplexTy, 1020 bool SkipCast) { 1021 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1022 if (SkipCast) return false; 1023 if (IntTy->isIntegerType()) { 1024 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1025 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1026 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1027 CK_FloatingRealToComplex); 1028 } else { 1029 assert(IntTy->isComplexIntegerType()); 1030 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1031 CK_IntegralComplexToFloatingComplex); 1032 } 1033 return false; 1034 } 1035 1036 /// \brief Handle arithmetic conversion with complex types. Helper function of 1037 /// UsualArithmeticConversions() 1038 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1039 ExprResult &RHS, QualType LHSType, 1040 QualType RHSType, 1041 bool IsCompAssign) { 1042 // if we have an integer operand, the result is the complex type. 1043 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1044 /*skipCast*/false)) 1045 return LHSType; 1046 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1047 /*skipCast*/IsCompAssign)) 1048 return RHSType; 1049 1050 // This handles complex/complex, complex/float, or float/complex. 1051 // When both operands are complex, the shorter operand is converted to the 1052 // type of the longer, and that is the type of the result. This corresponds 1053 // to what is done when combining two real floating-point operands. 1054 // The fun begins when size promotion occur across type domains. 1055 // From H&S 6.3.4: When one operand is complex and the other is a real 1056 // floating-point type, the less precise type is converted, within it's 1057 // real or complex domain, to the precision of the other type. For example, 1058 // when combining a "long double" with a "double _Complex", the 1059 // "double _Complex" is promoted to "long double _Complex". 1060 1061 // Compute the rank of the two types, regardless of whether they are complex. 1062 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1063 1064 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1065 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1066 QualType LHSElementType = 1067 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1068 QualType RHSElementType = 1069 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1070 1071 QualType ResultType = S.Context.getComplexType(LHSElementType); 1072 if (Order < 0) { 1073 // Promote the precision of the LHS if not an assignment. 1074 ResultType = S.Context.getComplexType(RHSElementType); 1075 if (!IsCompAssign) { 1076 if (LHSComplexType) 1077 LHS = 1078 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1079 else 1080 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1081 } 1082 } else if (Order > 0) { 1083 // Promote the precision of the RHS. 1084 if (RHSComplexType) 1085 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1086 else 1087 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1088 } 1089 return ResultType; 1090 } 1091 1092 /// \brief Hande arithmetic conversion from integer to float. Helper function 1093 /// of UsualArithmeticConversions() 1094 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1095 ExprResult &IntExpr, 1096 QualType FloatTy, QualType IntTy, 1097 bool ConvertFloat, bool ConvertInt) { 1098 if (IntTy->isIntegerType()) { 1099 if (ConvertInt) 1100 // Convert intExpr to the lhs floating point type. 1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1102 CK_IntegralToFloating); 1103 return FloatTy; 1104 } 1105 1106 // Convert both sides to the appropriate complex float. 1107 assert(IntTy->isComplexIntegerType()); 1108 QualType result = S.Context.getComplexType(FloatTy); 1109 1110 // _Complex int -> _Complex float 1111 if (ConvertInt) 1112 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1113 CK_IntegralComplexToFloatingComplex); 1114 1115 // float -> _Complex float 1116 if (ConvertFloat) 1117 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1118 CK_FloatingRealToComplex); 1119 1120 return result; 1121 } 1122 1123 /// \brief Handle arithmethic conversion with floating point types. Helper 1124 /// function of UsualArithmeticConversions() 1125 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1126 ExprResult &RHS, QualType LHSType, 1127 QualType RHSType, bool IsCompAssign) { 1128 bool LHSFloat = LHSType->isRealFloatingType(); 1129 bool RHSFloat = RHSType->isRealFloatingType(); 1130 1131 // If we have two real floating types, convert the smaller operand 1132 // to the bigger result. 1133 if (LHSFloat && RHSFloat) { 1134 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1135 if (order > 0) { 1136 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1137 return LHSType; 1138 } 1139 1140 assert(order < 0 && "illegal float comparison"); 1141 if (!IsCompAssign) 1142 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1143 return RHSType; 1144 } 1145 1146 if (LHSFloat) { 1147 // Half FP has to be promoted to float unless it is natively supported 1148 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1149 LHSType = S.Context.FloatTy; 1150 1151 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1152 /*convertFloat=*/!IsCompAssign, 1153 /*convertInt=*/ true); 1154 } 1155 assert(RHSFloat); 1156 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1157 /*convertInt=*/ true, 1158 /*convertFloat=*/!IsCompAssign); 1159 } 1160 1161 /// \brief Diagnose attempts to convert between __float128 and long double if 1162 /// there is no support for such conversion. Helper function of 1163 /// UsualArithmeticConversions(). 1164 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1165 QualType RHSType) { 1166 /* No issue converting if at least one of the types is not a floating point 1167 type or the two types have the same rank. 1168 */ 1169 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1170 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1171 return false; 1172 1173 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1174 "The remaining types must be floating point types."); 1175 1176 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1177 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1178 1179 QualType LHSElemType = LHSComplex ? 1180 LHSComplex->getElementType() : LHSType; 1181 QualType RHSElemType = RHSComplex ? 1182 RHSComplex->getElementType() : RHSType; 1183 1184 // No issue if the two types have the same representation 1185 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1186 &S.Context.getFloatTypeSemantics(RHSElemType)) 1187 return false; 1188 1189 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1190 RHSElemType == S.Context.LongDoubleTy); 1191 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1192 RHSElemType == S.Context.Float128Ty); 1193 1194 /* We've handled the situation where __float128 and long double have the same 1195 representation. The only other allowable conversion is if long double is 1196 really just double. 1197 */ 1198 return Float128AndLongDouble && 1199 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1200 &llvm::APFloat::IEEEdouble); 1201 } 1202 1203 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1204 1205 namespace { 1206 /// These helper callbacks are placed in an anonymous namespace to 1207 /// permit their use as function template parameters. 1208 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1209 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1210 } 1211 1212 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1213 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1214 CK_IntegralComplexCast); 1215 } 1216 } 1217 1218 /// \brief Handle integer arithmetic conversions. Helper function of 1219 /// UsualArithmeticConversions() 1220 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1221 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1222 ExprResult &RHS, QualType LHSType, 1223 QualType RHSType, bool IsCompAssign) { 1224 // The rules for this case are in C99 6.3.1.8 1225 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1226 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1227 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1228 if (LHSSigned == RHSSigned) { 1229 // Same signedness; use the higher-ranked type 1230 if (order >= 0) { 1231 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1232 return LHSType; 1233 } else if (!IsCompAssign) 1234 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1235 return RHSType; 1236 } else if (order != (LHSSigned ? 1 : -1)) { 1237 // The unsigned type has greater than or equal rank to the 1238 // signed type, so use the unsigned type 1239 if (RHSSigned) { 1240 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1241 return LHSType; 1242 } else if (!IsCompAssign) 1243 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1244 return RHSType; 1245 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1246 // The two types are different widths; if we are here, that 1247 // means the signed type is larger than the unsigned type, so 1248 // use the signed type. 1249 if (LHSSigned) { 1250 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1251 return LHSType; 1252 } else if (!IsCompAssign) 1253 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1254 return RHSType; 1255 } else { 1256 // The signed type is higher-ranked than the unsigned type, 1257 // but isn't actually any bigger (like unsigned int and long 1258 // on most 32-bit systems). Use the unsigned type corresponding 1259 // to the signed type. 1260 QualType result = 1261 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1262 RHS = (*doRHSCast)(S, RHS.get(), result); 1263 if (!IsCompAssign) 1264 LHS = (*doLHSCast)(S, LHS.get(), result); 1265 return result; 1266 } 1267 } 1268 1269 /// \brief Handle conversions with GCC complex int extension. Helper function 1270 /// of UsualArithmeticConversions() 1271 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1272 ExprResult &RHS, QualType LHSType, 1273 QualType RHSType, 1274 bool IsCompAssign) { 1275 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1276 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1277 1278 if (LHSComplexInt && RHSComplexInt) { 1279 QualType LHSEltType = LHSComplexInt->getElementType(); 1280 QualType RHSEltType = RHSComplexInt->getElementType(); 1281 QualType ScalarType = 1282 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1283 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1284 1285 return S.Context.getComplexType(ScalarType); 1286 } 1287 1288 if (LHSComplexInt) { 1289 QualType LHSEltType = LHSComplexInt->getElementType(); 1290 QualType ScalarType = 1291 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1292 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1293 QualType ComplexType = S.Context.getComplexType(ScalarType); 1294 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1295 CK_IntegralRealToComplex); 1296 1297 return ComplexType; 1298 } 1299 1300 assert(RHSComplexInt); 1301 1302 QualType RHSEltType = RHSComplexInt->getElementType(); 1303 QualType ScalarType = 1304 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1305 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1306 QualType ComplexType = S.Context.getComplexType(ScalarType); 1307 1308 if (!IsCompAssign) 1309 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1310 CK_IntegralRealToComplex); 1311 return ComplexType; 1312 } 1313 1314 /// UsualArithmeticConversions - Performs various conversions that are common to 1315 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1316 /// routine returns the first non-arithmetic type found. The client is 1317 /// responsible for emitting appropriate error diagnostics. 1318 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1319 bool IsCompAssign) { 1320 if (!IsCompAssign) { 1321 LHS = UsualUnaryConversions(LHS.get()); 1322 if (LHS.isInvalid()) 1323 return QualType(); 1324 } 1325 1326 RHS = UsualUnaryConversions(RHS.get()); 1327 if (RHS.isInvalid()) 1328 return QualType(); 1329 1330 // For conversion purposes, we ignore any qualifiers. 1331 // For example, "const float" and "float" are equivalent. 1332 QualType LHSType = 1333 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1334 QualType RHSType = 1335 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1336 1337 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1338 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1339 LHSType = AtomicLHS->getValueType(); 1340 1341 // If both types are identical, no conversion is needed. 1342 if (LHSType == RHSType) 1343 return LHSType; 1344 1345 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1346 // The caller can deal with this (e.g. pointer + int). 1347 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1348 return QualType(); 1349 1350 // Apply unary and bitfield promotions to the LHS's type. 1351 QualType LHSUnpromotedType = LHSType; 1352 if (LHSType->isPromotableIntegerType()) 1353 LHSType = Context.getPromotedIntegerType(LHSType); 1354 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1355 if (!LHSBitfieldPromoteTy.isNull()) 1356 LHSType = LHSBitfieldPromoteTy; 1357 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1358 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1359 1360 // If both types are identical, no conversion is needed. 1361 if (LHSType == RHSType) 1362 return LHSType; 1363 1364 // At this point, we have two different arithmetic types. 1365 1366 // Diagnose attempts to convert between __float128 and long double where 1367 // such conversions currently can't be handled. 1368 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1369 return QualType(); 1370 1371 // Handle complex types first (C99 6.3.1.8p1). 1372 if (LHSType->isComplexType() || RHSType->isComplexType()) 1373 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1374 IsCompAssign); 1375 1376 // Now handle "real" floating types (i.e. float, double, long double). 1377 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1378 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1379 IsCompAssign); 1380 1381 // Handle GCC complex int extension. 1382 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1383 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1384 IsCompAssign); 1385 1386 // Finally, we have two differing integer types. 1387 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1388 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1389 } 1390 1391 1392 //===----------------------------------------------------------------------===// 1393 // Semantic Analysis for various Expression Types 1394 //===----------------------------------------------------------------------===// 1395 1396 1397 ExprResult 1398 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1399 SourceLocation DefaultLoc, 1400 SourceLocation RParenLoc, 1401 Expr *ControllingExpr, 1402 ArrayRef<ParsedType> ArgTypes, 1403 ArrayRef<Expr *> ArgExprs) { 1404 unsigned NumAssocs = ArgTypes.size(); 1405 assert(NumAssocs == ArgExprs.size()); 1406 1407 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1408 for (unsigned i = 0; i < NumAssocs; ++i) { 1409 if (ArgTypes[i]) 1410 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1411 else 1412 Types[i] = nullptr; 1413 } 1414 1415 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1416 ControllingExpr, 1417 llvm::makeArrayRef(Types, NumAssocs), 1418 ArgExprs); 1419 delete [] Types; 1420 return ER; 1421 } 1422 1423 ExprResult 1424 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1425 SourceLocation DefaultLoc, 1426 SourceLocation RParenLoc, 1427 Expr *ControllingExpr, 1428 ArrayRef<TypeSourceInfo *> Types, 1429 ArrayRef<Expr *> Exprs) { 1430 unsigned NumAssocs = Types.size(); 1431 assert(NumAssocs == Exprs.size()); 1432 1433 // Decay and strip qualifiers for the controlling expression type, and handle 1434 // placeholder type replacement. See committee discussion from WG14 DR423. 1435 { 1436 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1437 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1438 if (R.isInvalid()) 1439 return ExprError(); 1440 ControllingExpr = R.get(); 1441 } 1442 1443 // The controlling expression is an unevaluated operand, so side effects are 1444 // likely unintended. 1445 if (ActiveTemplateInstantiations.empty() && 1446 ControllingExpr->HasSideEffects(Context, false)) 1447 Diag(ControllingExpr->getExprLoc(), 1448 diag::warn_side_effects_unevaluated_context); 1449 1450 bool TypeErrorFound = false, 1451 IsResultDependent = ControllingExpr->isTypeDependent(), 1452 ContainsUnexpandedParameterPack 1453 = ControllingExpr->containsUnexpandedParameterPack(); 1454 1455 for (unsigned i = 0; i < NumAssocs; ++i) { 1456 if (Exprs[i]->containsUnexpandedParameterPack()) 1457 ContainsUnexpandedParameterPack = true; 1458 1459 if (Types[i]) { 1460 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1461 ContainsUnexpandedParameterPack = true; 1462 1463 if (Types[i]->getType()->isDependentType()) { 1464 IsResultDependent = true; 1465 } else { 1466 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1467 // complete object type other than a variably modified type." 1468 unsigned D = 0; 1469 if (Types[i]->getType()->isIncompleteType()) 1470 D = diag::err_assoc_type_incomplete; 1471 else if (!Types[i]->getType()->isObjectType()) 1472 D = diag::err_assoc_type_nonobject; 1473 else if (Types[i]->getType()->isVariablyModifiedType()) 1474 D = diag::err_assoc_type_variably_modified; 1475 1476 if (D != 0) { 1477 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1478 << Types[i]->getTypeLoc().getSourceRange() 1479 << Types[i]->getType(); 1480 TypeErrorFound = true; 1481 } 1482 1483 // C11 6.5.1.1p2 "No two generic associations in the same generic 1484 // selection shall specify compatible types." 1485 for (unsigned j = i+1; j < NumAssocs; ++j) 1486 if (Types[j] && !Types[j]->getType()->isDependentType() && 1487 Context.typesAreCompatible(Types[i]->getType(), 1488 Types[j]->getType())) { 1489 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1490 diag::err_assoc_compatible_types) 1491 << Types[j]->getTypeLoc().getSourceRange() 1492 << Types[j]->getType() 1493 << Types[i]->getType(); 1494 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1495 diag::note_compat_assoc) 1496 << Types[i]->getTypeLoc().getSourceRange() 1497 << Types[i]->getType(); 1498 TypeErrorFound = true; 1499 } 1500 } 1501 } 1502 } 1503 if (TypeErrorFound) 1504 return ExprError(); 1505 1506 // If we determined that the generic selection is result-dependent, don't 1507 // try to compute the result expression. 1508 if (IsResultDependent) 1509 return new (Context) GenericSelectionExpr( 1510 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1511 ContainsUnexpandedParameterPack); 1512 1513 SmallVector<unsigned, 1> CompatIndices; 1514 unsigned DefaultIndex = -1U; 1515 for (unsigned i = 0; i < NumAssocs; ++i) { 1516 if (!Types[i]) 1517 DefaultIndex = i; 1518 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1519 Types[i]->getType())) 1520 CompatIndices.push_back(i); 1521 } 1522 1523 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1524 // type compatible with at most one of the types named in its generic 1525 // association list." 1526 if (CompatIndices.size() > 1) { 1527 // We strip parens here because the controlling expression is typically 1528 // parenthesized in macro definitions. 1529 ControllingExpr = ControllingExpr->IgnoreParens(); 1530 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1531 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1532 << (unsigned) CompatIndices.size(); 1533 for (unsigned I : CompatIndices) { 1534 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1535 diag::note_compat_assoc) 1536 << Types[I]->getTypeLoc().getSourceRange() 1537 << Types[I]->getType(); 1538 } 1539 return ExprError(); 1540 } 1541 1542 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1543 // its controlling expression shall have type compatible with exactly one of 1544 // the types named in its generic association list." 1545 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1546 // We strip parens here because the controlling expression is typically 1547 // parenthesized in macro definitions. 1548 ControllingExpr = ControllingExpr->IgnoreParens(); 1549 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1550 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1551 return ExprError(); 1552 } 1553 1554 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1555 // type name that is compatible with the type of the controlling expression, 1556 // then the result expression of the generic selection is the expression 1557 // in that generic association. Otherwise, the result expression of the 1558 // generic selection is the expression in the default generic association." 1559 unsigned ResultIndex = 1560 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1561 1562 return new (Context) GenericSelectionExpr( 1563 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1564 ContainsUnexpandedParameterPack, ResultIndex); 1565 } 1566 1567 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1568 /// location of the token and the offset of the ud-suffix within it. 1569 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1570 unsigned Offset) { 1571 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1572 S.getLangOpts()); 1573 } 1574 1575 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1576 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1577 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1578 IdentifierInfo *UDSuffix, 1579 SourceLocation UDSuffixLoc, 1580 ArrayRef<Expr*> Args, 1581 SourceLocation LitEndLoc) { 1582 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1583 1584 QualType ArgTy[2]; 1585 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1586 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1587 if (ArgTy[ArgIdx]->isArrayType()) 1588 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1589 } 1590 1591 DeclarationName OpName = 1592 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1593 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1594 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1595 1596 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1597 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1598 /*AllowRaw*/false, /*AllowTemplate*/false, 1599 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1600 return ExprError(); 1601 1602 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1603 } 1604 1605 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1606 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1607 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1608 /// multiple tokens. However, the common case is that StringToks points to one 1609 /// string. 1610 /// 1611 ExprResult 1612 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1613 assert(!StringToks.empty() && "Must have at least one string!"); 1614 1615 StringLiteralParser Literal(StringToks, PP); 1616 if (Literal.hadError) 1617 return ExprError(); 1618 1619 SmallVector<SourceLocation, 4> StringTokLocs; 1620 for (const Token &Tok : StringToks) 1621 StringTokLocs.push_back(Tok.getLocation()); 1622 1623 QualType CharTy = Context.CharTy; 1624 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1625 if (Literal.isWide()) { 1626 CharTy = Context.getWideCharType(); 1627 Kind = StringLiteral::Wide; 1628 } else if (Literal.isUTF8()) { 1629 Kind = StringLiteral::UTF8; 1630 } else if (Literal.isUTF16()) { 1631 CharTy = Context.Char16Ty; 1632 Kind = StringLiteral::UTF16; 1633 } else if (Literal.isUTF32()) { 1634 CharTy = Context.Char32Ty; 1635 Kind = StringLiteral::UTF32; 1636 } else if (Literal.isPascal()) { 1637 CharTy = Context.UnsignedCharTy; 1638 } 1639 1640 QualType CharTyConst = CharTy; 1641 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1642 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1643 CharTyConst.addConst(); 1644 1645 // Get an array type for the string, according to C99 6.4.5. This includes 1646 // the nul terminator character as well as the string length for pascal 1647 // strings. 1648 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1649 llvm::APInt(32, Literal.GetNumStringChars()+1), 1650 ArrayType::Normal, 0); 1651 1652 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1653 if (getLangOpts().OpenCL) { 1654 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1655 } 1656 1657 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1658 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1659 Kind, Literal.Pascal, StrTy, 1660 &StringTokLocs[0], 1661 StringTokLocs.size()); 1662 if (Literal.getUDSuffix().empty()) 1663 return Lit; 1664 1665 // We're building a user-defined literal. 1666 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1667 SourceLocation UDSuffixLoc = 1668 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1669 Literal.getUDSuffixOffset()); 1670 1671 // Make sure we're allowed user-defined literals here. 1672 if (!UDLScope) 1673 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1674 1675 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1676 // operator "" X (str, len) 1677 QualType SizeType = Context.getSizeType(); 1678 1679 DeclarationName OpName = 1680 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1681 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1682 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1683 1684 QualType ArgTy[] = { 1685 Context.getArrayDecayedType(StrTy), SizeType 1686 }; 1687 1688 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1689 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1690 /*AllowRaw*/false, /*AllowTemplate*/false, 1691 /*AllowStringTemplate*/true)) { 1692 1693 case LOLR_Cooked: { 1694 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1695 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1696 StringTokLocs[0]); 1697 Expr *Args[] = { Lit, LenArg }; 1698 1699 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1700 } 1701 1702 case LOLR_StringTemplate: { 1703 TemplateArgumentListInfo ExplicitArgs; 1704 1705 unsigned CharBits = Context.getIntWidth(CharTy); 1706 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1707 llvm::APSInt Value(CharBits, CharIsUnsigned); 1708 1709 TemplateArgument TypeArg(CharTy); 1710 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1711 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1712 1713 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1714 Value = Lit->getCodeUnit(I); 1715 TemplateArgument Arg(Context, Value, CharTy); 1716 TemplateArgumentLocInfo ArgInfo; 1717 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1718 } 1719 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1720 &ExplicitArgs); 1721 } 1722 case LOLR_Raw: 1723 case LOLR_Template: 1724 llvm_unreachable("unexpected literal operator lookup result"); 1725 case LOLR_Error: 1726 return ExprError(); 1727 } 1728 llvm_unreachable("unexpected literal operator lookup result"); 1729 } 1730 1731 ExprResult 1732 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1733 SourceLocation Loc, 1734 const CXXScopeSpec *SS) { 1735 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1736 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1737 } 1738 1739 /// BuildDeclRefExpr - Build an expression that references a 1740 /// declaration that does not require a closure capture. 1741 ExprResult 1742 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1743 const DeclarationNameInfo &NameInfo, 1744 const CXXScopeSpec *SS, NamedDecl *FoundD, 1745 const TemplateArgumentListInfo *TemplateArgs) { 1746 if (getLangOpts().CUDA) 1747 if (FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) 1748 if (!CheckCUDACall(NameInfo.getLoc(), Callee)) 1749 return ExprError(); 1750 1751 bool RefersToCapturedVariable = 1752 isa<VarDecl>(D) && 1753 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1754 1755 DeclRefExpr *E; 1756 if (isa<VarTemplateSpecializationDecl>(D)) { 1757 VarTemplateSpecializationDecl *VarSpec = 1758 cast<VarTemplateSpecializationDecl>(D); 1759 1760 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1761 : NestedNameSpecifierLoc(), 1762 VarSpec->getTemplateKeywordLoc(), D, 1763 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1764 FoundD, TemplateArgs); 1765 } else { 1766 assert(!TemplateArgs && "No template arguments for non-variable" 1767 " template specialization references"); 1768 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1769 : NestedNameSpecifierLoc(), 1770 SourceLocation(), D, RefersToCapturedVariable, 1771 NameInfo, Ty, VK, FoundD); 1772 } 1773 1774 MarkDeclRefReferenced(E); 1775 1776 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1777 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1778 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1779 recordUseOfEvaluatedWeak(E); 1780 1781 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1782 UnusedPrivateFields.remove(FD); 1783 // Just in case we're building an illegal pointer-to-member. 1784 if (FD->isBitField()) 1785 E->setObjectKind(OK_BitField); 1786 } 1787 1788 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1789 // designates a bit-field. 1790 if (auto *BD = dyn_cast<BindingDecl>(D)) 1791 if (auto *BE = BD->getBinding()) 1792 E->setObjectKind(BE->getObjectKind()); 1793 1794 return E; 1795 } 1796 1797 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1798 /// possibly a list of template arguments. 1799 /// 1800 /// If this produces template arguments, it is permitted to call 1801 /// DecomposeTemplateName. 1802 /// 1803 /// This actually loses a lot of source location information for 1804 /// non-standard name kinds; we should consider preserving that in 1805 /// some way. 1806 void 1807 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1808 TemplateArgumentListInfo &Buffer, 1809 DeclarationNameInfo &NameInfo, 1810 const TemplateArgumentListInfo *&TemplateArgs) { 1811 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1812 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1813 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1814 1815 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1816 Id.TemplateId->NumArgs); 1817 translateTemplateArguments(TemplateArgsPtr, Buffer); 1818 1819 TemplateName TName = Id.TemplateId->Template.get(); 1820 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1821 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1822 TemplateArgs = &Buffer; 1823 } else { 1824 NameInfo = GetNameFromUnqualifiedId(Id); 1825 TemplateArgs = nullptr; 1826 } 1827 } 1828 1829 static void emitEmptyLookupTypoDiagnostic( 1830 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1831 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1832 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1833 DeclContext *Ctx = 1834 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1835 if (!TC) { 1836 // Emit a special diagnostic for failed member lookups. 1837 // FIXME: computing the declaration context might fail here (?) 1838 if (Ctx) 1839 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1840 << SS.getRange(); 1841 else 1842 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1843 return; 1844 } 1845 1846 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1847 bool DroppedSpecifier = 1848 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1849 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1850 ? diag::note_implicit_param_decl 1851 : diag::note_previous_decl; 1852 if (!Ctx) 1853 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1854 SemaRef.PDiag(NoteID)); 1855 else 1856 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1857 << Typo << Ctx << DroppedSpecifier 1858 << SS.getRange(), 1859 SemaRef.PDiag(NoteID)); 1860 } 1861 1862 /// Diagnose an empty lookup. 1863 /// 1864 /// \return false if new lookup candidates were found 1865 bool 1866 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1867 std::unique_ptr<CorrectionCandidateCallback> CCC, 1868 TemplateArgumentListInfo *ExplicitTemplateArgs, 1869 ArrayRef<Expr *> Args, TypoExpr **Out) { 1870 DeclarationName Name = R.getLookupName(); 1871 1872 unsigned diagnostic = diag::err_undeclared_var_use; 1873 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1874 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1875 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1876 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1877 diagnostic = diag::err_undeclared_use; 1878 diagnostic_suggest = diag::err_undeclared_use_suggest; 1879 } 1880 1881 // If the original lookup was an unqualified lookup, fake an 1882 // unqualified lookup. This is useful when (for example) the 1883 // original lookup would not have found something because it was a 1884 // dependent name. 1885 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1886 while (DC) { 1887 if (isa<CXXRecordDecl>(DC)) { 1888 LookupQualifiedName(R, DC); 1889 1890 if (!R.empty()) { 1891 // Don't give errors about ambiguities in this lookup. 1892 R.suppressDiagnostics(); 1893 1894 // During a default argument instantiation the CurContext points 1895 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1896 // function parameter list, hence add an explicit check. 1897 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1898 ActiveTemplateInstantiations.back().Kind == 1899 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1900 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1901 bool isInstance = CurMethod && 1902 CurMethod->isInstance() && 1903 DC == CurMethod->getParent() && !isDefaultArgument; 1904 1905 // Give a code modification hint to insert 'this->'. 1906 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1907 // Actually quite difficult! 1908 if (getLangOpts().MSVCCompat) 1909 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1910 if (isInstance) { 1911 Diag(R.getNameLoc(), diagnostic) << Name 1912 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1913 CheckCXXThisCapture(R.getNameLoc()); 1914 } else { 1915 Diag(R.getNameLoc(), diagnostic) << Name; 1916 } 1917 1918 // Do we really want to note all of these? 1919 for (NamedDecl *D : R) 1920 Diag(D->getLocation(), diag::note_dependent_var_use); 1921 1922 // Return true if we are inside a default argument instantiation 1923 // and the found name refers to an instance member function, otherwise 1924 // the function calling DiagnoseEmptyLookup will try to create an 1925 // implicit member call and this is wrong for default argument. 1926 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1927 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1928 return true; 1929 } 1930 1931 // Tell the callee to try to recover. 1932 return false; 1933 } 1934 1935 R.clear(); 1936 } 1937 1938 // In Microsoft mode, if we are performing lookup from within a friend 1939 // function definition declared at class scope then we must set 1940 // DC to the lexical parent to be able to search into the parent 1941 // class. 1942 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1943 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1944 DC->getLexicalParent()->isRecord()) 1945 DC = DC->getLexicalParent(); 1946 else 1947 DC = DC->getParent(); 1948 } 1949 1950 // We didn't find anything, so try to correct for a typo. 1951 TypoCorrection Corrected; 1952 if (S && Out) { 1953 SourceLocation TypoLoc = R.getNameLoc(); 1954 assert(!ExplicitTemplateArgs && 1955 "Diagnosing an empty lookup with explicit template args!"); 1956 *Out = CorrectTypoDelayed( 1957 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1958 [=](const TypoCorrection &TC) { 1959 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1960 diagnostic, diagnostic_suggest); 1961 }, 1962 nullptr, CTK_ErrorRecovery); 1963 if (*Out) 1964 return true; 1965 } else if (S && (Corrected = 1966 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1967 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1968 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1969 bool DroppedSpecifier = 1970 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1971 R.setLookupName(Corrected.getCorrection()); 1972 1973 bool AcceptableWithRecovery = false; 1974 bool AcceptableWithoutRecovery = false; 1975 NamedDecl *ND = Corrected.getFoundDecl(); 1976 if (ND) { 1977 if (Corrected.isOverloaded()) { 1978 OverloadCandidateSet OCS(R.getNameLoc(), 1979 OverloadCandidateSet::CSK_Normal); 1980 OverloadCandidateSet::iterator Best; 1981 for (NamedDecl *CD : Corrected) { 1982 if (FunctionTemplateDecl *FTD = 1983 dyn_cast<FunctionTemplateDecl>(CD)) 1984 AddTemplateOverloadCandidate( 1985 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1986 Args, OCS); 1987 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1988 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1989 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1990 Args, OCS); 1991 } 1992 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1993 case OR_Success: 1994 ND = Best->FoundDecl; 1995 Corrected.setCorrectionDecl(ND); 1996 break; 1997 default: 1998 // FIXME: Arbitrarily pick the first declaration for the note. 1999 Corrected.setCorrectionDecl(ND); 2000 break; 2001 } 2002 } 2003 R.addDecl(ND); 2004 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2005 CXXRecordDecl *Record = nullptr; 2006 if (Corrected.getCorrectionSpecifier()) { 2007 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2008 Record = Ty->getAsCXXRecordDecl(); 2009 } 2010 if (!Record) 2011 Record = cast<CXXRecordDecl>( 2012 ND->getDeclContext()->getRedeclContext()); 2013 R.setNamingClass(Record); 2014 } 2015 2016 auto *UnderlyingND = ND->getUnderlyingDecl(); 2017 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2018 isa<FunctionTemplateDecl>(UnderlyingND); 2019 // FIXME: If we ended up with a typo for a type name or 2020 // Objective-C class name, we're in trouble because the parser 2021 // is in the wrong place to recover. Suggest the typo 2022 // correction, but don't make it a fix-it since we're not going 2023 // to recover well anyway. 2024 AcceptableWithoutRecovery = 2025 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2026 } else { 2027 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2028 // because we aren't able to recover. 2029 AcceptableWithoutRecovery = true; 2030 } 2031 2032 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2033 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2034 ? diag::note_implicit_param_decl 2035 : diag::note_previous_decl; 2036 if (SS.isEmpty()) 2037 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2038 PDiag(NoteID), AcceptableWithRecovery); 2039 else 2040 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2041 << Name << computeDeclContext(SS, false) 2042 << DroppedSpecifier << SS.getRange(), 2043 PDiag(NoteID), AcceptableWithRecovery); 2044 2045 // Tell the callee whether to try to recover. 2046 return !AcceptableWithRecovery; 2047 } 2048 } 2049 R.clear(); 2050 2051 // Emit a special diagnostic for failed member lookups. 2052 // FIXME: computing the declaration context might fail here (?) 2053 if (!SS.isEmpty()) { 2054 Diag(R.getNameLoc(), diag::err_no_member) 2055 << Name << computeDeclContext(SS, false) 2056 << SS.getRange(); 2057 return true; 2058 } 2059 2060 // Give up, we can't recover. 2061 Diag(R.getNameLoc(), diagnostic) << Name; 2062 return true; 2063 } 2064 2065 /// In Microsoft mode, if we are inside a template class whose parent class has 2066 /// dependent base classes, and we can't resolve an unqualified identifier, then 2067 /// assume the identifier is a member of a dependent base class. We can only 2068 /// recover successfully in static methods, instance methods, and other contexts 2069 /// where 'this' is available. This doesn't precisely match MSVC's 2070 /// instantiation model, but it's close enough. 2071 static Expr * 2072 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2073 DeclarationNameInfo &NameInfo, 2074 SourceLocation TemplateKWLoc, 2075 const TemplateArgumentListInfo *TemplateArgs) { 2076 // Only try to recover from lookup into dependent bases in static methods or 2077 // contexts where 'this' is available. 2078 QualType ThisType = S.getCurrentThisType(); 2079 const CXXRecordDecl *RD = nullptr; 2080 if (!ThisType.isNull()) 2081 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2082 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2083 RD = MD->getParent(); 2084 if (!RD || !RD->hasAnyDependentBases()) 2085 return nullptr; 2086 2087 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2088 // is available, suggest inserting 'this->' as a fixit. 2089 SourceLocation Loc = NameInfo.getLoc(); 2090 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2091 DB << NameInfo.getName() << RD; 2092 2093 if (!ThisType.isNull()) { 2094 DB << FixItHint::CreateInsertion(Loc, "this->"); 2095 return CXXDependentScopeMemberExpr::Create( 2096 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2097 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2098 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2099 } 2100 2101 // Synthesize a fake NNS that points to the derived class. This will 2102 // perform name lookup during template instantiation. 2103 CXXScopeSpec SS; 2104 auto *NNS = 2105 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2106 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2107 return DependentScopeDeclRefExpr::Create( 2108 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2109 TemplateArgs); 2110 } 2111 2112 ExprResult 2113 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2114 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2115 bool HasTrailingLParen, bool IsAddressOfOperand, 2116 std::unique_ptr<CorrectionCandidateCallback> CCC, 2117 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2118 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2119 "cannot be direct & operand and have a trailing lparen"); 2120 if (SS.isInvalid()) 2121 return ExprError(); 2122 2123 TemplateArgumentListInfo TemplateArgsBuffer; 2124 2125 // Decompose the UnqualifiedId into the following data. 2126 DeclarationNameInfo NameInfo; 2127 const TemplateArgumentListInfo *TemplateArgs; 2128 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2129 2130 DeclarationName Name = NameInfo.getName(); 2131 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2132 SourceLocation NameLoc = NameInfo.getLoc(); 2133 2134 // C++ [temp.dep.expr]p3: 2135 // An id-expression is type-dependent if it contains: 2136 // -- an identifier that was declared with a dependent type, 2137 // (note: handled after lookup) 2138 // -- a template-id that is dependent, 2139 // (note: handled in BuildTemplateIdExpr) 2140 // -- a conversion-function-id that specifies a dependent type, 2141 // -- a nested-name-specifier that contains a class-name that 2142 // names a dependent type. 2143 // Determine whether this is a member of an unknown specialization; 2144 // we need to handle these differently. 2145 bool DependentID = false; 2146 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2147 Name.getCXXNameType()->isDependentType()) { 2148 DependentID = true; 2149 } else if (SS.isSet()) { 2150 if (DeclContext *DC = computeDeclContext(SS, false)) { 2151 if (RequireCompleteDeclContext(SS, DC)) 2152 return ExprError(); 2153 } else { 2154 DependentID = true; 2155 } 2156 } 2157 2158 if (DependentID) 2159 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2160 IsAddressOfOperand, TemplateArgs); 2161 2162 // Perform the required lookup. 2163 LookupResult R(*this, NameInfo, 2164 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2165 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2166 if (TemplateArgs) { 2167 // Lookup the template name again to correctly establish the context in 2168 // which it was found. This is really unfortunate as we already did the 2169 // lookup to determine that it was a template name in the first place. If 2170 // this becomes a performance hit, we can work harder to preserve those 2171 // results until we get here but it's likely not worth it. 2172 bool MemberOfUnknownSpecialization; 2173 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2174 MemberOfUnknownSpecialization); 2175 2176 if (MemberOfUnknownSpecialization || 2177 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2178 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2179 IsAddressOfOperand, TemplateArgs); 2180 } else { 2181 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2182 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2183 2184 // If the result might be in a dependent base class, this is a dependent 2185 // id-expression. 2186 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2187 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2188 IsAddressOfOperand, TemplateArgs); 2189 2190 // If this reference is in an Objective-C method, then we need to do 2191 // some special Objective-C lookup, too. 2192 if (IvarLookupFollowUp) { 2193 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2194 if (E.isInvalid()) 2195 return ExprError(); 2196 2197 if (Expr *Ex = E.getAs<Expr>()) 2198 return Ex; 2199 } 2200 } 2201 2202 if (R.isAmbiguous()) 2203 return ExprError(); 2204 2205 // This could be an implicitly declared function reference (legal in C90, 2206 // extension in C99, forbidden in C++). 2207 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2208 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2209 if (D) R.addDecl(D); 2210 } 2211 2212 // Determine whether this name might be a candidate for 2213 // argument-dependent lookup. 2214 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2215 2216 if (R.empty() && !ADL) { 2217 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2218 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2219 TemplateKWLoc, TemplateArgs)) 2220 return E; 2221 } 2222 2223 // Don't diagnose an empty lookup for inline assembly. 2224 if (IsInlineAsmIdentifier) 2225 return ExprError(); 2226 2227 // If this name wasn't predeclared and if this is not a function 2228 // call, diagnose the problem. 2229 TypoExpr *TE = nullptr; 2230 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2231 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2232 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2233 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2234 "Typo correction callback misconfigured"); 2235 if (CCC) { 2236 // Make sure the callback knows what the typo being diagnosed is. 2237 CCC->setTypoName(II); 2238 if (SS.isValid()) 2239 CCC->setTypoNNS(SS.getScopeRep()); 2240 } 2241 if (DiagnoseEmptyLookup(S, SS, R, 2242 CCC ? std::move(CCC) : std::move(DefaultValidator), 2243 nullptr, None, &TE)) { 2244 if (TE && KeywordReplacement) { 2245 auto &State = getTypoExprState(TE); 2246 auto BestTC = State.Consumer->getNextCorrection(); 2247 if (BestTC.isKeyword()) { 2248 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2249 if (State.DiagHandler) 2250 State.DiagHandler(BestTC); 2251 KeywordReplacement->startToken(); 2252 KeywordReplacement->setKind(II->getTokenID()); 2253 KeywordReplacement->setIdentifierInfo(II); 2254 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2255 // Clean up the state associated with the TypoExpr, since it has 2256 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2257 clearDelayedTypo(TE); 2258 // Signal that a correction to a keyword was performed by returning a 2259 // valid-but-null ExprResult. 2260 return (Expr*)nullptr; 2261 } 2262 State.Consumer->resetCorrectionStream(); 2263 } 2264 return TE ? TE : ExprError(); 2265 } 2266 2267 assert(!R.empty() && 2268 "DiagnoseEmptyLookup returned false but added no results"); 2269 2270 // If we found an Objective-C instance variable, let 2271 // LookupInObjCMethod build the appropriate expression to 2272 // reference the ivar. 2273 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2274 R.clear(); 2275 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2276 // In a hopelessly buggy code, Objective-C instance variable 2277 // lookup fails and no expression will be built to reference it. 2278 if (!E.isInvalid() && !E.get()) 2279 return ExprError(); 2280 return E; 2281 } 2282 } 2283 2284 // This is guaranteed from this point on. 2285 assert(!R.empty() || ADL); 2286 2287 // Check whether this might be a C++ implicit instance member access. 2288 // C++ [class.mfct.non-static]p3: 2289 // When an id-expression that is not part of a class member access 2290 // syntax and not used to form a pointer to member is used in the 2291 // body of a non-static member function of class X, if name lookup 2292 // resolves the name in the id-expression to a non-static non-type 2293 // member of some class C, the id-expression is transformed into a 2294 // class member access expression using (*this) as the 2295 // postfix-expression to the left of the . operator. 2296 // 2297 // But we don't actually need to do this for '&' operands if R 2298 // resolved to a function or overloaded function set, because the 2299 // expression is ill-formed if it actually works out to be a 2300 // non-static member function: 2301 // 2302 // C++ [expr.ref]p4: 2303 // Otherwise, if E1.E2 refers to a non-static member function. . . 2304 // [t]he expression can be used only as the left-hand operand of a 2305 // member function call. 2306 // 2307 // There are other safeguards against such uses, but it's important 2308 // to get this right here so that we don't end up making a 2309 // spuriously dependent expression if we're inside a dependent 2310 // instance method. 2311 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2312 bool MightBeImplicitMember; 2313 if (!IsAddressOfOperand) 2314 MightBeImplicitMember = true; 2315 else if (!SS.isEmpty()) 2316 MightBeImplicitMember = false; 2317 else if (R.isOverloadedResult()) 2318 MightBeImplicitMember = false; 2319 else if (R.isUnresolvableResult()) 2320 MightBeImplicitMember = true; 2321 else 2322 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2323 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2324 isa<MSPropertyDecl>(R.getFoundDecl()); 2325 2326 if (MightBeImplicitMember) 2327 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2328 R, TemplateArgs, S); 2329 } 2330 2331 if (TemplateArgs || TemplateKWLoc.isValid()) { 2332 2333 // In C++1y, if this is a variable template id, then check it 2334 // in BuildTemplateIdExpr(). 2335 // The single lookup result must be a variable template declaration. 2336 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2337 Id.TemplateId->Kind == TNK_Var_template) { 2338 assert(R.getAsSingle<VarTemplateDecl>() && 2339 "There should only be one declaration found."); 2340 } 2341 2342 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2343 } 2344 2345 return BuildDeclarationNameExpr(SS, R, ADL); 2346 } 2347 2348 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2349 /// declaration name, generally during template instantiation. 2350 /// There's a large number of things which don't need to be done along 2351 /// this path. 2352 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2353 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2354 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2355 DeclContext *DC = computeDeclContext(SS, false); 2356 if (!DC) 2357 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2358 NameInfo, /*TemplateArgs=*/nullptr); 2359 2360 if (RequireCompleteDeclContext(SS, DC)) 2361 return ExprError(); 2362 2363 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2364 LookupQualifiedName(R, DC); 2365 2366 if (R.isAmbiguous()) 2367 return ExprError(); 2368 2369 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2370 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2371 NameInfo, /*TemplateArgs=*/nullptr); 2372 2373 if (R.empty()) { 2374 Diag(NameInfo.getLoc(), diag::err_no_member) 2375 << NameInfo.getName() << DC << SS.getRange(); 2376 return ExprError(); 2377 } 2378 2379 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2380 // Diagnose a missing typename if this resolved unambiguously to a type in 2381 // a dependent context. If we can recover with a type, downgrade this to 2382 // a warning in Microsoft compatibility mode. 2383 unsigned DiagID = diag::err_typename_missing; 2384 if (RecoveryTSI && getLangOpts().MSVCCompat) 2385 DiagID = diag::ext_typename_missing; 2386 SourceLocation Loc = SS.getBeginLoc(); 2387 auto D = Diag(Loc, DiagID); 2388 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2389 << SourceRange(Loc, NameInfo.getEndLoc()); 2390 2391 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2392 // context. 2393 if (!RecoveryTSI) 2394 return ExprError(); 2395 2396 // Only issue the fixit if we're prepared to recover. 2397 D << FixItHint::CreateInsertion(Loc, "typename "); 2398 2399 // Recover by pretending this was an elaborated type. 2400 QualType Ty = Context.getTypeDeclType(TD); 2401 TypeLocBuilder TLB; 2402 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2403 2404 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2405 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2406 QTL.setElaboratedKeywordLoc(SourceLocation()); 2407 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2408 2409 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2410 2411 return ExprEmpty(); 2412 } 2413 2414 // Defend against this resolving to an implicit member access. We usually 2415 // won't get here if this might be a legitimate a class member (we end up in 2416 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2417 // a pointer-to-member or in an unevaluated context in C++11. 2418 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2419 return BuildPossibleImplicitMemberExpr(SS, 2420 /*TemplateKWLoc=*/SourceLocation(), 2421 R, /*TemplateArgs=*/nullptr, S); 2422 2423 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2424 } 2425 2426 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2427 /// detected that we're currently inside an ObjC method. Perform some 2428 /// additional lookup. 2429 /// 2430 /// Ideally, most of this would be done by lookup, but there's 2431 /// actually quite a lot of extra work involved. 2432 /// 2433 /// Returns a null sentinel to indicate trivial success. 2434 ExprResult 2435 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2436 IdentifierInfo *II, bool AllowBuiltinCreation) { 2437 SourceLocation Loc = Lookup.getNameLoc(); 2438 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2439 2440 // Check for error condition which is already reported. 2441 if (!CurMethod) 2442 return ExprError(); 2443 2444 // There are two cases to handle here. 1) scoped lookup could have failed, 2445 // in which case we should look for an ivar. 2) scoped lookup could have 2446 // found a decl, but that decl is outside the current instance method (i.e. 2447 // a global variable). In these two cases, we do a lookup for an ivar with 2448 // this name, if the lookup sucedes, we replace it our current decl. 2449 2450 // If we're in a class method, we don't normally want to look for 2451 // ivars. But if we don't find anything else, and there's an 2452 // ivar, that's an error. 2453 bool IsClassMethod = CurMethod->isClassMethod(); 2454 2455 bool LookForIvars; 2456 if (Lookup.empty()) 2457 LookForIvars = true; 2458 else if (IsClassMethod) 2459 LookForIvars = false; 2460 else 2461 LookForIvars = (Lookup.isSingleResult() && 2462 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2463 ObjCInterfaceDecl *IFace = nullptr; 2464 if (LookForIvars) { 2465 IFace = CurMethod->getClassInterface(); 2466 ObjCInterfaceDecl *ClassDeclared; 2467 ObjCIvarDecl *IV = nullptr; 2468 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2469 // Diagnose using an ivar in a class method. 2470 if (IsClassMethod) 2471 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2472 << IV->getDeclName()); 2473 2474 // If we're referencing an invalid decl, just return this as a silent 2475 // error node. The error diagnostic was already emitted on the decl. 2476 if (IV->isInvalidDecl()) 2477 return ExprError(); 2478 2479 // Check if referencing a field with __attribute__((deprecated)). 2480 if (DiagnoseUseOfDecl(IV, Loc)) 2481 return ExprError(); 2482 2483 // Diagnose the use of an ivar outside of the declaring class. 2484 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2485 !declaresSameEntity(ClassDeclared, IFace) && 2486 !getLangOpts().DebuggerSupport) 2487 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2488 2489 // FIXME: This should use a new expr for a direct reference, don't 2490 // turn this into Self->ivar, just return a BareIVarExpr or something. 2491 IdentifierInfo &II = Context.Idents.get("self"); 2492 UnqualifiedId SelfName; 2493 SelfName.setIdentifier(&II, SourceLocation()); 2494 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2495 CXXScopeSpec SelfScopeSpec; 2496 SourceLocation TemplateKWLoc; 2497 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2498 SelfName, false, false); 2499 if (SelfExpr.isInvalid()) 2500 return ExprError(); 2501 2502 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2503 if (SelfExpr.isInvalid()) 2504 return ExprError(); 2505 2506 MarkAnyDeclReferenced(Loc, IV, true); 2507 2508 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2509 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2510 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2511 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2512 2513 ObjCIvarRefExpr *Result = new (Context) 2514 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2515 IV->getLocation(), SelfExpr.get(), true, true); 2516 2517 if (getLangOpts().ObjCAutoRefCount) { 2518 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2519 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2520 recordUseOfEvaluatedWeak(Result); 2521 } 2522 if (CurContext->isClosure()) 2523 Diag(Loc, diag::warn_implicitly_retains_self) 2524 << FixItHint::CreateInsertion(Loc, "self->"); 2525 } 2526 2527 return Result; 2528 } 2529 } else if (CurMethod->isInstanceMethod()) { 2530 // We should warn if a local variable hides an ivar. 2531 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2532 ObjCInterfaceDecl *ClassDeclared; 2533 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2534 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2535 declaresSameEntity(IFace, ClassDeclared)) 2536 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2537 } 2538 } 2539 } else if (Lookup.isSingleResult() && 2540 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2541 // If accessing a stand-alone ivar in a class method, this is an error. 2542 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2543 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2544 << IV->getDeclName()); 2545 } 2546 2547 if (Lookup.empty() && II && AllowBuiltinCreation) { 2548 // FIXME. Consolidate this with similar code in LookupName. 2549 if (unsigned BuiltinID = II->getBuiltinID()) { 2550 if (!(getLangOpts().CPlusPlus && 2551 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2552 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2553 S, Lookup.isForRedeclaration(), 2554 Lookup.getNameLoc()); 2555 if (D) Lookup.addDecl(D); 2556 } 2557 } 2558 } 2559 // Sentinel value saying that we didn't do anything special. 2560 return ExprResult((Expr *)nullptr); 2561 } 2562 2563 /// \brief Cast a base object to a member's actual type. 2564 /// 2565 /// Logically this happens in three phases: 2566 /// 2567 /// * First we cast from the base type to the naming class. 2568 /// The naming class is the class into which we were looking 2569 /// when we found the member; it's the qualifier type if a 2570 /// qualifier was provided, and otherwise it's the base type. 2571 /// 2572 /// * Next we cast from the naming class to the declaring class. 2573 /// If the member we found was brought into a class's scope by 2574 /// a using declaration, this is that class; otherwise it's 2575 /// the class declaring the member. 2576 /// 2577 /// * Finally we cast from the declaring class to the "true" 2578 /// declaring class of the member. This conversion does not 2579 /// obey access control. 2580 ExprResult 2581 Sema::PerformObjectMemberConversion(Expr *From, 2582 NestedNameSpecifier *Qualifier, 2583 NamedDecl *FoundDecl, 2584 NamedDecl *Member) { 2585 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2586 if (!RD) 2587 return From; 2588 2589 QualType DestRecordType; 2590 QualType DestType; 2591 QualType FromRecordType; 2592 QualType FromType = From->getType(); 2593 bool PointerConversions = false; 2594 if (isa<FieldDecl>(Member)) { 2595 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2596 2597 if (FromType->getAs<PointerType>()) { 2598 DestType = Context.getPointerType(DestRecordType); 2599 FromRecordType = FromType->getPointeeType(); 2600 PointerConversions = true; 2601 } else { 2602 DestType = DestRecordType; 2603 FromRecordType = FromType; 2604 } 2605 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2606 if (Method->isStatic()) 2607 return From; 2608 2609 DestType = Method->getThisType(Context); 2610 DestRecordType = DestType->getPointeeType(); 2611 2612 if (FromType->getAs<PointerType>()) { 2613 FromRecordType = FromType->getPointeeType(); 2614 PointerConversions = true; 2615 } else { 2616 FromRecordType = FromType; 2617 DestType = DestRecordType; 2618 } 2619 } else { 2620 // No conversion necessary. 2621 return From; 2622 } 2623 2624 if (DestType->isDependentType() || FromType->isDependentType()) 2625 return From; 2626 2627 // If the unqualified types are the same, no conversion is necessary. 2628 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2629 return From; 2630 2631 SourceRange FromRange = From->getSourceRange(); 2632 SourceLocation FromLoc = FromRange.getBegin(); 2633 2634 ExprValueKind VK = From->getValueKind(); 2635 2636 // C++ [class.member.lookup]p8: 2637 // [...] Ambiguities can often be resolved by qualifying a name with its 2638 // class name. 2639 // 2640 // If the member was a qualified name and the qualified referred to a 2641 // specific base subobject type, we'll cast to that intermediate type 2642 // first and then to the object in which the member is declared. That allows 2643 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2644 // 2645 // class Base { public: int x; }; 2646 // class Derived1 : public Base { }; 2647 // class Derived2 : public Base { }; 2648 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2649 // 2650 // void VeryDerived::f() { 2651 // x = 17; // error: ambiguous base subobjects 2652 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2653 // } 2654 if (Qualifier && Qualifier->getAsType()) { 2655 QualType QType = QualType(Qualifier->getAsType(), 0); 2656 assert(QType->isRecordType() && "lookup done with non-record type"); 2657 2658 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2659 2660 // In C++98, the qualifier type doesn't actually have to be a base 2661 // type of the object type, in which case we just ignore it. 2662 // Otherwise build the appropriate casts. 2663 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2664 CXXCastPath BasePath; 2665 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2666 FromLoc, FromRange, &BasePath)) 2667 return ExprError(); 2668 2669 if (PointerConversions) 2670 QType = Context.getPointerType(QType); 2671 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2672 VK, &BasePath).get(); 2673 2674 FromType = QType; 2675 FromRecordType = QRecordType; 2676 2677 // If the qualifier type was the same as the destination type, 2678 // we're done. 2679 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2680 return From; 2681 } 2682 } 2683 2684 bool IgnoreAccess = false; 2685 2686 // If we actually found the member through a using declaration, cast 2687 // down to the using declaration's type. 2688 // 2689 // Pointer equality is fine here because only one declaration of a 2690 // class ever has member declarations. 2691 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2692 assert(isa<UsingShadowDecl>(FoundDecl)); 2693 QualType URecordType = Context.getTypeDeclType( 2694 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2695 2696 // We only need to do this if the naming-class to declaring-class 2697 // conversion is non-trivial. 2698 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2699 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2700 CXXCastPath BasePath; 2701 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2702 FromLoc, FromRange, &BasePath)) 2703 return ExprError(); 2704 2705 QualType UType = URecordType; 2706 if (PointerConversions) 2707 UType = Context.getPointerType(UType); 2708 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2709 VK, &BasePath).get(); 2710 FromType = UType; 2711 FromRecordType = URecordType; 2712 } 2713 2714 // We don't do access control for the conversion from the 2715 // declaring class to the true declaring class. 2716 IgnoreAccess = true; 2717 } 2718 2719 CXXCastPath BasePath; 2720 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2721 FromLoc, FromRange, &BasePath, 2722 IgnoreAccess)) 2723 return ExprError(); 2724 2725 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2726 VK, &BasePath); 2727 } 2728 2729 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2730 const LookupResult &R, 2731 bool HasTrailingLParen) { 2732 // Only when used directly as the postfix-expression of a call. 2733 if (!HasTrailingLParen) 2734 return false; 2735 2736 // Never if a scope specifier was provided. 2737 if (SS.isSet()) 2738 return false; 2739 2740 // Only in C++ or ObjC++. 2741 if (!getLangOpts().CPlusPlus) 2742 return false; 2743 2744 // Turn off ADL when we find certain kinds of declarations during 2745 // normal lookup: 2746 for (NamedDecl *D : R) { 2747 // C++0x [basic.lookup.argdep]p3: 2748 // -- a declaration of a class member 2749 // Since using decls preserve this property, we check this on the 2750 // original decl. 2751 if (D->isCXXClassMember()) 2752 return false; 2753 2754 // C++0x [basic.lookup.argdep]p3: 2755 // -- a block-scope function declaration that is not a 2756 // using-declaration 2757 // NOTE: we also trigger this for function templates (in fact, we 2758 // don't check the decl type at all, since all other decl types 2759 // turn off ADL anyway). 2760 if (isa<UsingShadowDecl>(D)) 2761 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2762 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2763 return false; 2764 2765 // C++0x [basic.lookup.argdep]p3: 2766 // -- a declaration that is neither a function or a function 2767 // template 2768 // And also for builtin functions. 2769 if (isa<FunctionDecl>(D)) { 2770 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2771 2772 // But also builtin functions. 2773 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2774 return false; 2775 } else if (!isa<FunctionTemplateDecl>(D)) 2776 return false; 2777 } 2778 2779 return true; 2780 } 2781 2782 2783 /// Diagnoses obvious problems with the use of the given declaration 2784 /// as an expression. This is only actually called for lookups that 2785 /// were not overloaded, and it doesn't promise that the declaration 2786 /// will in fact be used. 2787 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2788 if (isa<TypedefNameDecl>(D)) { 2789 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2790 return true; 2791 } 2792 2793 if (isa<ObjCInterfaceDecl>(D)) { 2794 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2795 return true; 2796 } 2797 2798 if (isa<NamespaceDecl>(D)) { 2799 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2800 return true; 2801 } 2802 2803 return false; 2804 } 2805 2806 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2807 LookupResult &R, bool NeedsADL, 2808 bool AcceptInvalidDecl) { 2809 // If this is a single, fully-resolved result and we don't need ADL, 2810 // just build an ordinary singleton decl ref. 2811 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2812 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2813 R.getRepresentativeDecl(), nullptr, 2814 AcceptInvalidDecl); 2815 2816 // We only need to check the declaration if there's exactly one 2817 // result, because in the overloaded case the results can only be 2818 // functions and function templates. 2819 if (R.isSingleResult() && 2820 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2821 return ExprError(); 2822 2823 // Otherwise, just build an unresolved lookup expression. Suppress 2824 // any lookup-related diagnostics; we'll hash these out later, when 2825 // we've picked a target. 2826 R.suppressDiagnostics(); 2827 2828 UnresolvedLookupExpr *ULE 2829 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2830 SS.getWithLocInContext(Context), 2831 R.getLookupNameInfo(), 2832 NeedsADL, R.isOverloadedResult(), 2833 R.begin(), R.end()); 2834 2835 return ULE; 2836 } 2837 2838 static void 2839 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2840 ValueDecl *var, DeclContext *DC); 2841 2842 /// \brief Complete semantic analysis for a reference to the given declaration. 2843 ExprResult Sema::BuildDeclarationNameExpr( 2844 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2845 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2846 bool AcceptInvalidDecl) { 2847 assert(D && "Cannot refer to a NULL declaration"); 2848 assert(!isa<FunctionTemplateDecl>(D) && 2849 "Cannot refer unambiguously to a function template"); 2850 2851 SourceLocation Loc = NameInfo.getLoc(); 2852 if (CheckDeclInExpr(*this, Loc, D)) 2853 return ExprError(); 2854 2855 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2856 // Specifically diagnose references to class templates that are missing 2857 // a template argument list. 2858 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2859 << Template << SS.getRange(); 2860 Diag(Template->getLocation(), diag::note_template_decl_here); 2861 return ExprError(); 2862 } 2863 2864 // Make sure that we're referring to a value. 2865 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2866 if (!VD) { 2867 Diag(Loc, diag::err_ref_non_value) 2868 << D << SS.getRange(); 2869 Diag(D->getLocation(), diag::note_declared_at); 2870 return ExprError(); 2871 } 2872 2873 // Check whether this declaration can be used. Note that we suppress 2874 // this check when we're going to perform argument-dependent lookup 2875 // on this function name, because this might not be the function 2876 // that overload resolution actually selects. 2877 if (DiagnoseUseOfDecl(VD, Loc)) 2878 return ExprError(); 2879 2880 // Only create DeclRefExpr's for valid Decl's. 2881 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2882 return ExprError(); 2883 2884 // Handle members of anonymous structs and unions. If we got here, 2885 // and the reference is to a class member indirect field, then this 2886 // must be the subject of a pointer-to-member expression. 2887 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2888 if (!indirectField->isCXXClassMember()) 2889 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2890 indirectField); 2891 2892 { 2893 QualType type = VD->getType(); 2894 ExprValueKind valueKind = VK_RValue; 2895 2896 switch (D->getKind()) { 2897 // Ignore all the non-ValueDecl kinds. 2898 #define ABSTRACT_DECL(kind) 2899 #define VALUE(type, base) 2900 #define DECL(type, base) \ 2901 case Decl::type: 2902 #include "clang/AST/DeclNodes.inc" 2903 llvm_unreachable("invalid value decl kind"); 2904 2905 // These shouldn't make it here. 2906 case Decl::ObjCAtDefsField: 2907 case Decl::ObjCIvar: 2908 llvm_unreachable("forming non-member reference to ivar?"); 2909 2910 // Enum constants are always r-values and never references. 2911 // Unresolved using declarations are dependent. 2912 case Decl::EnumConstant: 2913 case Decl::UnresolvedUsingValue: 2914 case Decl::OMPDeclareReduction: 2915 valueKind = VK_RValue; 2916 break; 2917 2918 // Fields and indirect fields that got here must be for 2919 // pointer-to-member expressions; we just call them l-values for 2920 // internal consistency, because this subexpression doesn't really 2921 // exist in the high-level semantics. 2922 case Decl::Field: 2923 case Decl::IndirectField: 2924 assert(getLangOpts().CPlusPlus && 2925 "building reference to field in C?"); 2926 2927 // These can't have reference type in well-formed programs, but 2928 // for internal consistency we do this anyway. 2929 type = type.getNonReferenceType(); 2930 valueKind = VK_LValue; 2931 break; 2932 2933 // Non-type template parameters are either l-values or r-values 2934 // depending on the type. 2935 case Decl::NonTypeTemplateParm: { 2936 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2937 type = reftype->getPointeeType(); 2938 valueKind = VK_LValue; // even if the parameter is an r-value reference 2939 break; 2940 } 2941 2942 // For non-references, we need to strip qualifiers just in case 2943 // the template parameter was declared as 'const int' or whatever. 2944 valueKind = VK_RValue; 2945 type = type.getUnqualifiedType(); 2946 break; 2947 } 2948 2949 case Decl::Var: 2950 case Decl::VarTemplateSpecialization: 2951 case Decl::VarTemplatePartialSpecialization: 2952 case Decl::Decomposition: 2953 case Decl::OMPCapturedExpr: 2954 // In C, "extern void blah;" is valid and is an r-value. 2955 if (!getLangOpts().CPlusPlus && 2956 !type.hasQualifiers() && 2957 type->isVoidType()) { 2958 valueKind = VK_RValue; 2959 break; 2960 } 2961 // fallthrough 2962 2963 case Decl::ImplicitParam: 2964 case Decl::ParmVar: { 2965 // These are always l-values. 2966 valueKind = VK_LValue; 2967 type = type.getNonReferenceType(); 2968 2969 // FIXME: Does the addition of const really only apply in 2970 // potentially-evaluated contexts? Since the variable isn't actually 2971 // captured in an unevaluated context, it seems that the answer is no. 2972 if (!isUnevaluatedContext()) { 2973 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2974 if (!CapturedType.isNull()) 2975 type = CapturedType; 2976 } 2977 2978 break; 2979 } 2980 2981 case Decl::Binding: { 2982 // These are always lvalues. 2983 valueKind = VK_LValue; 2984 type = type.getNonReferenceType(); 2985 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2986 // decides how that's supposed to work. 2987 auto *BD = cast<BindingDecl>(VD); 2988 if (BD->getDeclContext()->isFunctionOrMethod() && 2989 BD->getDeclContext() != CurContext) 2990 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2991 break; 2992 } 2993 2994 case Decl::Function: { 2995 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2996 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2997 type = Context.BuiltinFnTy; 2998 valueKind = VK_RValue; 2999 break; 3000 } 3001 } 3002 3003 const FunctionType *fty = type->castAs<FunctionType>(); 3004 3005 // If we're referring to a function with an __unknown_anytype 3006 // result type, make the entire expression __unknown_anytype. 3007 if (fty->getReturnType() == Context.UnknownAnyTy) { 3008 type = Context.UnknownAnyTy; 3009 valueKind = VK_RValue; 3010 break; 3011 } 3012 3013 // Functions are l-values in C++. 3014 if (getLangOpts().CPlusPlus) { 3015 valueKind = VK_LValue; 3016 break; 3017 } 3018 3019 // C99 DR 316 says that, if a function type comes from a 3020 // function definition (without a prototype), that type is only 3021 // used for checking compatibility. Therefore, when referencing 3022 // the function, we pretend that we don't have the full function 3023 // type. 3024 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3025 isa<FunctionProtoType>(fty)) 3026 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3027 fty->getExtInfo()); 3028 3029 // Functions are r-values in C. 3030 valueKind = VK_RValue; 3031 break; 3032 } 3033 3034 case Decl::MSProperty: 3035 valueKind = VK_LValue; 3036 break; 3037 3038 case Decl::CXXMethod: 3039 // If we're referring to a method with an __unknown_anytype 3040 // result type, make the entire expression __unknown_anytype. 3041 // This should only be possible with a type written directly. 3042 if (const FunctionProtoType *proto 3043 = dyn_cast<FunctionProtoType>(VD->getType())) 3044 if (proto->getReturnType() == Context.UnknownAnyTy) { 3045 type = Context.UnknownAnyTy; 3046 valueKind = VK_RValue; 3047 break; 3048 } 3049 3050 // C++ methods are l-values if static, r-values if non-static. 3051 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3052 valueKind = VK_LValue; 3053 break; 3054 } 3055 // fallthrough 3056 3057 case Decl::CXXConversion: 3058 case Decl::CXXDestructor: 3059 case Decl::CXXConstructor: 3060 valueKind = VK_RValue; 3061 break; 3062 } 3063 3064 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3065 TemplateArgs); 3066 } 3067 } 3068 3069 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3070 SmallString<32> &Target) { 3071 Target.resize(CharByteWidth * (Source.size() + 1)); 3072 char *ResultPtr = &Target[0]; 3073 const UTF8 *ErrorPtr; 3074 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3075 (void)success; 3076 assert(success); 3077 Target.resize(ResultPtr - &Target[0]); 3078 } 3079 3080 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3081 PredefinedExpr::IdentType IT) { 3082 // Pick the current block, lambda, captured statement or function. 3083 Decl *currentDecl = nullptr; 3084 if (const BlockScopeInfo *BSI = getCurBlock()) 3085 currentDecl = BSI->TheDecl; 3086 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3087 currentDecl = LSI->CallOperator; 3088 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3089 currentDecl = CSI->TheCapturedDecl; 3090 else 3091 currentDecl = getCurFunctionOrMethodDecl(); 3092 3093 if (!currentDecl) { 3094 Diag(Loc, diag::ext_predef_outside_function); 3095 currentDecl = Context.getTranslationUnitDecl(); 3096 } 3097 3098 QualType ResTy; 3099 StringLiteral *SL = nullptr; 3100 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3101 ResTy = Context.DependentTy; 3102 else { 3103 // Pre-defined identifiers are of type char[x], where x is the length of 3104 // the string. 3105 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3106 unsigned Length = Str.length(); 3107 3108 llvm::APInt LengthI(32, Length + 1); 3109 if (IT == PredefinedExpr::LFunction) { 3110 ResTy = Context.WideCharTy.withConst(); 3111 SmallString<32> RawChars; 3112 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3113 Str, RawChars); 3114 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3115 /*IndexTypeQuals*/ 0); 3116 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3117 /*Pascal*/ false, ResTy, Loc); 3118 } else { 3119 ResTy = Context.CharTy.withConst(); 3120 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3121 /*IndexTypeQuals*/ 0); 3122 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3123 /*Pascal*/ false, ResTy, Loc); 3124 } 3125 } 3126 3127 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3128 } 3129 3130 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3131 PredefinedExpr::IdentType IT; 3132 3133 switch (Kind) { 3134 default: llvm_unreachable("Unknown simple primary expr!"); 3135 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3136 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3137 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3138 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3139 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3140 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3141 } 3142 3143 return BuildPredefinedExpr(Loc, IT); 3144 } 3145 3146 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3147 SmallString<16> CharBuffer; 3148 bool Invalid = false; 3149 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3150 if (Invalid) 3151 return ExprError(); 3152 3153 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3154 PP, Tok.getKind()); 3155 if (Literal.hadError()) 3156 return ExprError(); 3157 3158 QualType Ty; 3159 if (Literal.isWide()) 3160 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3161 else if (Literal.isUTF16()) 3162 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3163 else if (Literal.isUTF32()) 3164 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3165 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3166 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3167 else 3168 Ty = Context.CharTy; // 'x' -> char in C++ 3169 3170 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3171 if (Literal.isWide()) 3172 Kind = CharacterLiteral::Wide; 3173 else if (Literal.isUTF16()) 3174 Kind = CharacterLiteral::UTF16; 3175 else if (Literal.isUTF32()) 3176 Kind = CharacterLiteral::UTF32; 3177 else if (Literal.isUTF8()) 3178 Kind = CharacterLiteral::UTF8; 3179 3180 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3181 Tok.getLocation()); 3182 3183 if (Literal.getUDSuffix().empty()) 3184 return Lit; 3185 3186 // We're building a user-defined literal. 3187 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3188 SourceLocation UDSuffixLoc = 3189 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3190 3191 // Make sure we're allowed user-defined literals here. 3192 if (!UDLScope) 3193 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3194 3195 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3196 // operator "" X (ch) 3197 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3198 Lit, Tok.getLocation()); 3199 } 3200 3201 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3202 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3203 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3204 Context.IntTy, Loc); 3205 } 3206 3207 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3208 QualType Ty, SourceLocation Loc) { 3209 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3210 3211 using llvm::APFloat; 3212 APFloat Val(Format); 3213 3214 APFloat::opStatus result = Literal.GetFloatValue(Val); 3215 3216 // Overflow is always an error, but underflow is only an error if 3217 // we underflowed to zero (APFloat reports denormals as underflow). 3218 if ((result & APFloat::opOverflow) || 3219 ((result & APFloat::opUnderflow) && Val.isZero())) { 3220 unsigned diagnostic; 3221 SmallString<20> buffer; 3222 if (result & APFloat::opOverflow) { 3223 diagnostic = diag::warn_float_overflow; 3224 APFloat::getLargest(Format).toString(buffer); 3225 } else { 3226 diagnostic = diag::warn_float_underflow; 3227 APFloat::getSmallest(Format).toString(buffer); 3228 } 3229 3230 S.Diag(Loc, diagnostic) 3231 << Ty 3232 << StringRef(buffer.data(), buffer.size()); 3233 } 3234 3235 bool isExact = (result == APFloat::opOK); 3236 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3237 } 3238 3239 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3240 assert(E && "Invalid expression"); 3241 3242 if (E->isValueDependent()) 3243 return false; 3244 3245 QualType QT = E->getType(); 3246 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3247 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3248 return true; 3249 } 3250 3251 llvm::APSInt ValueAPS; 3252 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3253 3254 if (R.isInvalid()) 3255 return true; 3256 3257 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3258 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3259 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3260 << ValueAPS.toString(10) << ValueIsPositive; 3261 return true; 3262 } 3263 3264 return false; 3265 } 3266 3267 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3268 // Fast path for a single digit (which is quite common). A single digit 3269 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3270 if (Tok.getLength() == 1) { 3271 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3272 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3273 } 3274 3275 SmallString<128> SpellingBuffer; 3276 // NumericLiteralParser wants to overread by one character. Add padding to 3277 // the buffer in case the token is copied to the buffer. If getSpelling() 3278 // returns a StringRef to the memory buffer, it should have a null char at 3279 // the EOF, so it is also safe. 3280 SpellingBuffer.resize(Tok.getLength() + 1); 3281 3282 // Get the spelling of the token, which eliminates trigraphs, etc. 3283 bool Invalid = false; 3284 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3285 if (Invalid) 3286 return ExprError(); 3287 3288 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3289 if (Literal.hadError) 3290 return ExprError(); 3291 3292 if (Literal.hasUDSuffix()) { 3293 // We're building a user-defined literal. 3294 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3295 SourceLocation UDSuffixLoc = 3296 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3297 3298 // Make sure we're allowed user-defined literals here. 3299 if (!UDLScope) 3300 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3301 3302 QualType CookedTy; 3303 if (Literal.isFloatingLiteral()) { 3304 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3305 // long double, the literal is treated as a call of the form 3306 // operator "" X (f L) 3307 CookedTy = Context.LongDoubleTy; 3308 } else { 3309 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3310 // unsigned long long, the literal is treated as a call of the form 3311 // operator "" X (n ULL) 3312 CookedTy = Context.UnsignedLongLongTy; 3313 } 3314 3315 DeclarationName OpName = 3316 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3317 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3318 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3319 3320 SourceLocation TokLoc = Tok.getLocation(); 3321 3322 // Perform literal operator lookup to determine if we're building a raw 3323 // literal or a cooked one. 3324 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3325 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3326 /*AllowRaw*/true, /*AllowTemplate*/true, 3327 /*AllowStringTemplate*/false)) { 3328 case LOLR_Error: 3329 return ExprError(); 3330 3331 case LOLR_Cooked: { 3332 Expr *Lit; 3333 if (Literal.isFloatingLiteral()) { 3334 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3335 } else { 3336 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3337 if (Literal.GetIntegerValue(ResultVal)) 3338 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3339 << /* Unsigned */ 1; 3340 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3341 Tok.getLocation()); 3342 } 3343 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3344 } 3345 3346 case LOLR_Raw: { 3347 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3348 // literal is treated as a call of the form 3349 // operator "" X ("n") 3350 unsigned Length = Literal.getUDSuffixOffset(); 3351 QualType StrTy = Context.getConstantArrayType( 3352 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3353 ArrayType::Normal, 0); 3354 Expr *Lit = StringLiteral::Create( 3355 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3356 /*Pascal*/false, StrTy, &TokLoc, 1); 3357 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3358 } 3359 3360 case LOLR_Template: { 3361 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3362 // template), L is treated as a call fo the form 3363 // operator "" X <'c1', 'c2', ... 'ck'>() 3364 // where n is the source character sequence c1 c2 ... ck. 3365 TemplateArgumentListInfo ExplicitArgs; 3366 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3367 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3368 llvm::APSInt Value(CharBits, CharIsUnsigned); 3369 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3370 Value = TokSpelling[I]; 3371 TemplateArgument Arg(Context, Value, Context.CharTy); 3372 TemplateArgumentLocInfo ArgInfo; 3373 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3374 } 3375 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3376 &ExplicitArgs); 3377 } 3378 case LOLR_StringTemplate: 3379 llvm_unreachable("unexpected literal operator lookup result"); 3380 } 3381 } 3382 3383 Expr *Res; 3384 3385 if (Literal.isFloatingLiteral()) { 3386 QualType Ty; 3387 if (Literal.isHalf){ 3388 if (getOpenCLOptions().cl_khr_fp16) 3389 Ty = Context.HalfTy; 3390 else { 3391 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3392 return ExprError(); 3393 } 3394 } else if (Literal.isFloat) 3395 Ty = Context.FloatTy; 3396 else if (Literal.isLong) 3397 Ty = Context.LongDoubleTy; 3398 else if (Literal.isFloat128) 3399 Ty = Context.Float128Ty; 3400 else 3401 Ty = Context.DoubleTy; 3402 3403 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3404 3405 if (Ty == Context.DoubleTy) { 3406 if (getLangOpts().SinglePrecisionConstants) { 3407 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3408 } else if (getLangOpts().OpenCL && 3409 !((getLangOpts().OpenCLVersion >= 120) || 3410 getOpenCLOptions().cl_khr_fp64)) { 3411 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3412 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3413 } 3414 } 3415 } else if (!Literal.isIntegerLiteral()) { 3416 return ExprError(); 3417 } else { 3418 QualType Ty; 3419 3420 // 'long long' is a C99 or C++11 feature. 3421 if (!getLangOpts().C99 && Literal.isLongLong) { 3422 if (getLangOpts().CPlusPlus) 3423 Diag(Tok.getLocation(), 3424 getLangOpts().CPlusPlus11 ? 3425 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3426 else 3427 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3428 } 3429 3430 // Get the value in the widest-possible width. 3431 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3432 llvm::APInt ResultVal(MaxWidth, 0); 3433 3434 if (Literal.GetIntegerValue(ResultVal)) { 3435 // If this value didn't fit into uintmax_t, error and force to ull. 3436 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3437 << /* Unsigned */ 1; 3438 Ty = Context.UnsignedLongLongTy; 3439 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3440 "long long is not intmax_t?"); 3441 } else { 3442 // If this value fits into a ULL, try to figure out what else it fits into 3443 // according to the rules of C99 6.4.4.1p5. 3444 3445 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3446 // be an unsigned int. 3447 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3448 3449 // Check from smallest to largest, picking the smallest type we can. 3450 unsigned Width = 0; 3451 3452 // Microsoft specific integer suffixes are explicitly sized. 3453 if (Literal.MicrosoftInteger) { 3454 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3455 Width = 8; 3456 Ty = Context.CharTy; 3457 } else { 3458 Width = Literal.MicrosoftInteger; 3459 Ty = Context.getIntTypeForBitwidth(Width, 3460 /*Signed=*/!Literal.isUnsigned); 3461 } 3462 } 3463 3464 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3465 // Are int/unsigned possibilities? 3466 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3467 3468 // Does it fit in a unsigned int? 3469 if (ResultVal.isIntN(IntSize)) { 3470 // Does it fit in a signed int? 3471 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3472 Ty = Context.IntTy; 3473 else if (AllowUnsigned) 3474 Ty = Context.UnsignedIntTy; 3475 Width = IntSize; 3476 } 3477 } 3478 3479 // Are long/unsigned long possibilities? 3480 if (Ty.isNull() && !Literal.isLongLong) { 3481 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3482 3483 // Does it fit in a unsigned long? 3484 if (ResultVal.isIntN(LongSize)) { 3485 // Does it fit in a signed long? 3486 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3487 Ty = Context.LongTy; 3488 else if (AllowUnsigned) 3489 Ty = Context.UnsignedLongTy; 3490 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3491 // is compatible. 3492 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3493 const unsigned LongLongSize = 3494 Context.getTargetInfo().getLongLongWidth(); 3495 Diag(Tok.getLocation(), 3496 getLangOpts().CPlusPlus 3497 ? Literal.isLong 3498 ? diag::warn_old_implicitly_unsigned_long_cxx 3499 : /*C++98 UB*/ diag:: 3500 ext_old_implicitly_unsigned_long_cxx 3501 : diag::warn_old_implicitly_unsigned_long) 3502 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3503 : /*will be ill-formed*/ 1); 3504 Ty = Context.UnsignedLongTy; 3505 } 3506 Width = LongSize; 3507 } 3508 } 3509 3510 // Check long long if needed. 3511 if (Ty.isNull()) { 3512 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3513 3514 // Does it fit in a unsigned long long? 3515 if (ResultVal.isIntN(LongLongSize)) { 3516 // Does it fit in a signed long long? 3517 // To be compatible with MSVC, hex integer literals ending with the 3518 // LL or i64 suffix are always signed in Microsoft mode. 3519 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3520 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3521 Ty = Context.LongLongTy; 3522 else if (AllowUnsigned) 3523 Ty = Context.UnsignedLongLongTy; 3524 Width = LongLongSize; 3525 } 3526 } 3527 3528 // If we still couldn't decide a type, we probably have something that 3529 // does not fit in a signed long long, but has no U suffix. 3530 if (Ty.isNull()) { 3531 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3532 Ty = Context.UnsignedLongLongTy; 3533 Width = Context.getTargetInfo().getLongLongWidth(); 3534 } 3535 3536 if (ResultVal.getBitWidth() != Width) 3537 ResultVal = ResultVal.trunc(Width); 3538 } 3539 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3540 } 3541 3542 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3543 if (Literal.isImaginary) 3544 Res = new (Context) ImaginaryLiteral(Res, 3545 Context.getComplexType(Res->getType())); 3546 3547 return Res; 3548 } 3549 3550 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3551 assert(E && "ActOnParenExpr() missing expr"); 3552 return new (Context) ParenExpr(L, R, E); 3553 } 3554 3555 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3556 SourceLocation Loc, 3557 SourceRange ArgRange) { 3558 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3559 // scalar or vector data type argument..." 3560 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3561 // type (C99 6.2.5p18) or void. 3562 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3563 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3564 << T << ArgRange; 3565 return true; 3566 } 3567 3568 assert((T->isVoidType() || !T->isIncompleteType()) && 3569 "Scalar types should always be complete"); 3570 return false; 3571 } 3572 3573 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3574 SourceLocation Loc, 3575 SourceRange ArgRange, 3576 UnaryExprOrTypeTrait TraitKind) { 3577 // Invalid types must be hard errors for SFINAE in C++. 3578 if (S.LangOpts.CPlusPlus) 3579 return true; 3580 3581 // C99 6.5.3.4p1: 3582 if (T->isFunctionType() && 3583 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3584 // sizeof(function)/alignof(function) is allowed as an extension. 3585 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3586 << TraitKind << ArgRange; 3587 return false; 3588 } 3589 3590 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3591 // this is an error (OpenCL v1.1 s6.3.k) 3592 if (T->isVoidType()) { 3593 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3594 : diag::ext_sizeof_alignof_void_type; 3595 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3596 return false; 3597 } 3598 3599 return true; 3600 } 3601 3602 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3603 SourceLocation Loc, 3604 SourceRange ArgRange, 3605 UnaryExprOrTypeTrait TraitKind) { 3606 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3607 // runtime doesn't allow it. 3608 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3609 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3610 << T << (TraitKind == UETT_SizeOf) 3611 << ArgRange; 3612 return true; 3613 } 3614 3615 return false; 3616 } 3617 3618 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3619 /// pointer type is equal to T) and emit a warning if it is. 3620 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3621 Expr *E) { 3622 // Don't warn if the operation changed the type. 3623 if (T != E->getType()) 3624 return; 3625 3626 // Now look for array decays. 3627 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3628 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3629 return; 3630 3631 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3632 << ICE->getType() 3633 << ICE->getSubExpr()->getType(); 3634 } 3635 3636 /// \brief Check the constraints on expression operands to unary type expression 3637 /// and type traits. 3638 /// 3639 /// Completes any types necessary and validates the constraints on the operand 3640 /// expression. The logic mostly mirrors the type-based overload, but may modify 3641 /// the expression as it completes the type for that expression through template 3642 /// instantiation, etc. 3643 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3644 UnaryExprOrTypeTrait ExprKind) { 3645 QualType ExprTy = E->getType(); 3646 assert(!ExprTy->isReferenceType()); 3647 3648 if (ExprKind == UETT_VecStep) 3649 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3650 E->getSourceRange()); 3651 3652 // Whitelist some types as extensions 3653 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3654 E->getSourceRange(), ExprKind)) 3655 return false; 3656 3657 // 'alignof' applied to an expression only requires the base element type of 3658 // the expression to be complete. 'sizeof' requires the expression's type to 3659 // be complete (and will attempt to complete it if it's an array of unknown 3660 // bound). 3661 if (ExprKind == UETT_AlignOf) { 3662 if (RequireCompleteType(E->getExprLoc(), 3663 Context.getBaseElementType(E->getType()), 3664 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3665 E->getSourceRange())) 3666 return true; 3667 } else { 3668 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3669 ExprKind, E->getSourceRange())) 3670 return true; 3671 } 3672 3673 // Completing the expression's type may have changed it. 3674 ExprTy = E->getType(); 3675 assert(!ExprTy->isReferenceType()); 3676 3677 if (ExprTy->isFunctionType()) { 3678 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3679 << ExprKind << E->getSourceRange(); 3680 return true; 3681 } 3682 3683 // The operand for sizeof and alignof is in an unevaluated expression context, 3684 // so side effects could result in unintended consequences. 3685 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3686 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3687 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3688 3689 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3690 E->getSourceRange(), ExprKind)) 3691 return true; 3692 3693 if (ExprKind == UETT_SizeOf) { 3694 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3695 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3696 QualType OType = PVD->getOriginalType(); 3697 QualType Type = PVD->getType(); 3698 if (Type->isPointerType() && OType->isArrayType()) { 3699 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3700 << Type << OType; 3701 Diag(PVD->getLocation(), diag::note_declared_at); 3702 } 3703 } 3704 } 3705 3706 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3707 // decays into a pointer and returns an unintended result. This is most 3708 // likely a typo for "sizeof(array) op x". 3709 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3710 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3711 BO->getLHS()); 3712 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3713 BO->getRHS()); 3714 } 3715 } 3716 3717 return false; 3718 } 3719 3720 /// \brief Check the constraints on operands to unary expression and type 3721 /// traits. 3722 /// 3723 /// This will complete any types necessary, and validate the various constraints 3724 /// on those operands. 3725 /// 3726 /// The UsualUnaryConversions() function is *not* called by this routine. 3727 /// C99 6.3.2.1p[2-4] all state: 3728 /// Except when it is the operand of the sizeof operator ... 3729 /// 3730 /// C++ [expr.sizeof]p4 3731 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3732 /// standard conversions are not applied to the operand of sizeof. 3733 /// 3734 /// This policy is followed for all of the unary trait expressions. 3735 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3736 SourceLocation OpLoc, 3737 SourceRange ExprRange, 3738 UnaryExprOrTypeTrait ExprKind) { 3739 if (ExprType->isDependentType()) 3740 return false; 3741 3742 // C++ [expr.sizeof]p2: 3743 // When applied to a reference or a reference type, the result 3744 // is the size of the referenced type. 3745 // C++11 [expr.alignof]p3: 3746 // When alignof is applied to a reference type, the result 3747 // shall be the alignment of the referenced type. 3748 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3749 ExprType = Ref->getPointeeType(); 3750 3751 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3752 // When alignof or _Alignof is applied to an array type, the result 3753 // is the alignment of the element type. 3754 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3755 ExprType = Context.getBaseElementType(ExprType); 3756 3757 if (ExprKind == UETT_VecStep) 3758 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3759 3760 // Whitelist some types as extensions 3761 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3762 ExprKind)) 3763 return false; 3764 3765 if (RequireCompleteType(OpLoc, ExprType, 3766 diag::err_sizeof_alignof_incomplete_type, 3767 ExprKind, ExprRange)) 3768 return true; 3769 3770 if (ExprType->isFunctionType()) { 3771 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3772 << ExprKind << ExprRange; 3773 return true; 3774 } 3775 3776 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3777 ExprKind)) 3778 return true; 3779 3780 return false; 3781 } 3782 3783 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3784 E = E->IgnoreParens(); 3785 3786 // Cannot know anything else if the expression is dependent. 3787 if (E->isTypeDependent()) 3788 return false; 3789 3790 if (E->getObjectKind() == OK_BitField) { 3791 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3792 << 1 << E->getSourceRange(); 3793 return true; 3794 } 3795 3796 ValueDecl *D = nullptr; 3797 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3798 D = DRE->getDecl(); 3799 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3800 D = ME->getMemberDecl(); 3801 } 3802 3803 // If it's a field, require the containing struct to have a 3804 // complete definition so that we can compute the layout. 3805 // 3806 // This can happen in C++11 onwards, either by naming the member 3807 // in a way that is not transformed into a member access expression 3808 // (in an unevaluated operand, for instance), or by naming the member 3809 // in a trailing-return-type. 3810 // 3811 // For the record, since __alignof__ on expressions is a GCC 3812 // extension, GCC seems to permit this but always gives the 3813 // nonsensical answer 0. 3814 // 3815 // We don't really need the layout here --- we could instead just 3816 // directly check for all the appropriate alignment-lowing 3817 // attributes --- but that would require duplicating a lot of 3818 // logic that just isn't worth duplicating for such a marginal 3819 // use-case. 3820 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3821 // Fast path this check, since we at least know the record has a 3822 // definition if we can find a member of it. 3823 if (!FD->getParent()->isCompleteDefinition()) { 3824 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3825 << E->getSourceRange(); 3826 return true; 3827 } 3828 3829 // Otherwise, if it's a field, and the field doesn't have 3830 // reference type, then it must have a complete type (or be a 3831 // flexible array member, which we explicitly want to 3832 // white-list anyway), which makes the following checks trivial. 3833 if (!FD->getType()->isReferenceType()) 3834 return false; 3835 } 3836 3837 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3838 } 3839 3840 bool Sema::CheckVecStepExpr(Expr *E) { 3841 E = E->IgnoreParens(); 3842 3843 // Cannot know anything else if the expression is dependent. 3844 if (E->isTypeDependent()) 3845 return false; 3846 3847 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3848 } 3849 3850 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3851 CapturingScopeInfo *CSI) { 3852 assert(T->isVariablyModifiedType()); 3853 assert(CSI != nullptr); 3854 3855 // We're going to walk down into the type and look for VLA expressions. 3856 do { 3857 const Type *Ty = T.getTypePtr(); 3858 switch (Ty->getTypeClass()) { 3859 #define TYPE(Class, Base) 3860 #define ABSTRACT_TYPE(Class, Base) 3861 #define NON_CANONICAL_TYPE(Class, Base) 3862 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3863 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3864 #include "clang/AST/TypeNodes.def" 3865 T = QualType(); 3866 break; 3867 // These types are never variably-modified. 3868 case Type::Builtin: 3869 case Type::Complex: 3870 case Type::Vector: 3871 case Type::ExtVector: 3872 case Type::Record: 3873 case Type::Enum: 3874 case Type::Elaborated: 3875 case Type::TemplateSpecialization: 3876 case Type::ObjCObject: 3877 case Type::ObjCInterface: 3878 case Type::ObjCObjectPointer: 3879 case Type::Pipe: 3880 llvm_unreachable("type class is never variably-modified!"); 3881 case Type::Adjusted: 3882 T = cast<AdjustedType>(Ty)->getOriginalType(); 3883 break; 3884 case Type::Decayed: 3885 T = cast<DecayedType>(Ty)->getPointeeType(); 3886 break; 3887 case Type::Pointer: 3888 T = cast<PointerType>(Ty)->getPointeeType(); 3889 break; 3890 case Type::BlockPointer: 3891 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3892 break; 3893 case Type::LValueReference: 3894 case Type::RValueReference: 3895 T = cast<ReferenceType>(Ty)->getPointeeType(); 3896 break; 3897 case Type::MemberPointer: 3898 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3899 break; 3900 case Type::ConstantArray: 3901 case Type::IncompleteArray: 3902 // Losing element qualification here is fine. 3903 T = cast<ArrayType>(Ty)->getElementType(); 3904 break; 3905 case Type::VariableArray: { 3906 // Losing element qualification here is fine. 3907 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3908 3909 // Unknown size indication requires no size computation. 3910 // Otherwise, evaluate and record it. 3911 if (auto Size = VAT->getSizeExpr()) { 3912 if (!CSI->isVLATypeCaptured(VAT)) { 3913 RecordDecl *CapRecord = nullptr; 3914 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3915 CapRecord = LSI->Lambda; 3916 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3917 CapRecord = CRSI->TheRecordDecl; 3918 } 3919 if (CapRecord) { 3920 auto ExprLoc = Size->getExprLoc(); 3921 auto SizeType = Context.getSizeType(); 3922 // Build the non-static data member. 3923 auto Field = 3924 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3925 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3926 /*BW*/ nullptr, /*Mutable*/ false, 3927 /*InitStyle*/ ICIS_NoInit); 3928 Field->setImplicit(true); 3929 Field->setAccess(AS_private); 3930 Field->setCapturedVLAType(VAT); 3931 CapRecord->addDecl(Field); 3932 3933 CSI->addVLATypeCapture(ExprLoc, SizeType); 3934 } 3935 } 3936 } 3937 T = VAT->getElementType(); 3938 break; 3939 } 3940 case Type::FunctionProto: 3941 case Type::FunctionNoProto: 3942 T = cast<FunctionType>(Ty)->getReturnType(); 3943 break; 3944 case Type::Paren: 3945 case Type::TypeOf: 3946 case Type::UnaryTransform: 3947 case Type::Attributed: 3948 case Type::SubstTemplateTypeParm: 3949 case Type::PackExpansion: 3950 // Keep walking after single level desugaring. 3951 T = T.getSingleStepDesugaredType(Context); 3952 break; 3953 case Type::Typedef: 3954 T = cast<TypedefType>(Ty)->desugar(); 3955 break; 3956 case Type::Decltype: 3957 T = cast<DecltypeType>(Ty)->desugar(); 3958 break; 3959 case Type::Auto: 3960 T = cast<AutoType>(Ty)->getDeducedType(); 3961 break; 3962 case Type::TypeOfExpr: 3963 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3964 break; 3965 case Type::Atomic: 3966 T = cast<AtomicType>(Ty)->getValueType(); 3967 break; 3968 } 3969 } while (!T.isNull() && T->isVariablyModifiedType()); 3970 } 3971 3972 /// \brief Build a sizeof or alignof expression given a type operand. 3973 ExprResult 3974 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3975 SourceLocation OpLoc, 3976 UnaryExprOrTypeTrait ExprKind, 3977 SourceRange R) { 3978 if (!TInfo) 3979 return ExprError(); 3980 3981 QualType T = TInfo->getType(); 3982 3983 if (!T->isDependentType() && 3984 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3985 return ExprError(); 3986 3987 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3988 if (auto *TT = T->getAs<TypedefType>()) { 3989 for (auto I = FunctionScopes.rbegin(), 3990 E = std::prev(FunctionScopes.rend()); 3991 I != E; ++I) { 3992 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3993 if (CSI == nullptr) 3994 break; 3995 DeclContext *DC = nullptr; 3996 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3997 DC = LSI->CallOperator; 3998 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3999 DC = CRSI->TheCapturedDecl; 4000 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4001 DC = BSI->TheDecl; 4002 if (DC) { 4003 if (DC->containsDecl(TT->getDecl())) 4004 break; 4005 captureVariablyModifiedType(Context, T, CSI); 4006 } 4007 } 4008 } 4009 } 4010 4011 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4012 return new (Context) UnaryExprOrTypeTraitExpr( 4013 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4014 } 4015 4016 /// \brief Build a sizeof or alignof expression given an expression 4017 /// operand. 4018 ExprResult 4019 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4020 UnaryExprOrTypeTrait ExprKind) { 4021 ExprResult PE = CheckPlaceholderExpr(E); 4022 if (PE.isInvalid()) 4023 return ExprError(); 4024 4025 E = PE.get(); 4026 4027 // Verify that the operand is valid. 4028 bool isInvalid = false; 4029 if (E->isTypeDependent()) { 4030 // Delay type-checking for type-dependent expressions. 4031 } else if (ExprKind == UETT_AlignOf) { 4032 isInvalid = CheckAlignOfExpr(*this, E); 4033 } else if (ExprKind == UETT_VecStep) { 4034 isInvalid = CheckVecStepExpr(E); 4035 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4036 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4037 isInvalid = true; 4038 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4039 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4040 isInvalid = true; 4041 } else { 4042 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4043 } 4044 4045 if (isInvalid) 4046 return ExprError(); 4047 4048 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4049 PE = TransformToPotentiallyEvaluated(E); 4050 if (PE.isInvalid()) return ExprError(); 4051 E = PE.get(); 4052 } 4053 4054 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4055 return new (Context) UnaryExprOrTypeTraitExpr( 4056 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4057 } 4058 4059 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4060 /// expr and the same for @c alignof and @c __alignof 4061 /// Note that the ArgRange is invalid if isType is false. 4062 ExprResult 4063 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4064 UnaryExprOrTypeTrait ExprKind, bool IsType, 4065 void *TyOrEx, SourceRange ArgRange) { 4066 // If error parsing type, ignore. 4067 if (!TyOrEx) return ExprError(); 4068 4069 if (IsType) { 4070 TypeSourceInfo *TInfo; 4071 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4072 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4073 } 4074 4075 Expr *ArgEx = (Expr *)TyOrEx; 4076 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4077 return Result; 4078 } 4079 4080 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4081 bool IsReal) { 4082 if (V.get()->isTypeDependent()) 4083 return S.Context.DependentTy; 4084 4085 // _Real and _Imag are only l-values for normal l-values. 4086 if (V.get()->getObjectKind() != OK_Ordinary) { 4087 V = S.DefaultLvalueConversion(V.get()); 4088 if (V.isInvalid()) 4089 return QualType(); 4090 } 4091 4092 // These operators return the element type of a complex type. 4093 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4094 return CT->getElementType(); 4095 4096 // Otherwise they pass through real integer and floating point types here. 4097 if (V.get()->getType()->isArithmeticType()) 4098 return V.get()->getType(); 4099 4100 // Test for placeholders. 4101 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4102 if (PR.isInvalid()) return QualType(); 4103 if (PR.get() != V.get()) { 4104 V = PR; 4105 return CheckRealImagOperand(S, V, Loc, IsReal); 4106 } 4107 4108 // Reject anything else. 4109 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4110 << (IsReal ? "__real" : "__imag"); 4111 return QualType(); 4112 } 4113 4114 4115 4116 ExprResult 4117 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4118 tok::TokenKind Kind, Expr *Input) { 4119 UnaryOperatorKind Opc; 4120 switch (Kind) { 4121 default: llvm_unreachable("Unknown unary op!"); 4122 case tok::plusplus: Opc = UO_PostInc; break; 4123 case tok::minusminus: Opc = UO_PostDec; break; 4124 } 4125 4126 // Since this might is a postfix expression, get rid of ParenListExprs. 4127 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4128 if (Result.isInvalid()) return ExprError(); 4129 Input = Result.get(); 4130 4131 return BuildUnaryOp(S, OpLoc, Opc, Input); 4132 } 4133 4134 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4135 /// 4136 /// \return true on error 4137 static bool checkArithmeticOnObjCPointer(Sema &S, 4138 SourceLocation opLoc, 4139 Expr *op) { 4140 assert(op->getType()->isObjCObjectPointerType()); 4141 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4142 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4143 return false; 4144 4145 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4146 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4147 << op->getSourceRange(); 4148 return true; 4149 } 4150 4151 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4152 auto *BaseNoParens = Base->IgnoreParens(); 4153 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4154 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4155 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4156 } 4157 4158 ExprResult 4159 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4160 Expr *idx, SourceLocation rbLoc) { 4161 if (base && !base->getType().isNull() && 4162 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4163 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4164 /*Length=*/nullptr, rbLoc); 4165 4166 // Since this might be a postfix expression, get rid of ParenListExprs. 4167 if (isa<ParenListExpr>(base)) { 4168 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4169 if (result.isInvalid()) return ExprError(); 4170 base = result.get(); 4171 } 4172 4173 // Handle any non-overload placeholder types in the base and index 4174 // expressions. We can't handle overloads here because the other 4175 // operand might be an overloadable type, in which case the overload 4176 // resolution for the operator overload should get the first crack 4177 // at the overload. 4178 bool IsMSPropertySubscript = false; 4179 if (base->getType()->isNonOverloadPlaceholderType()) { 4180 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4181 if (!IsMSPropertySubscript) { 4182 ExprResult result = CheckPlaceholderExpr(base); 4183 if (result.isInvalid()) 4184 return ExprError(); 4185 base = result.get(); 4186 } 4187 } 4188 if (idx->getType()->isNonOverloadPlaceholderType()) { 4189 ExprResult result = CheckPlaceholderExpr(idx); 4190 if (result.isInvalid()) return ExprError(); 4191 idx = result.get(); 4192 } 4193 4194 // Build an unanalyzed expression if either operand is type-dependent. 4195 if (getLangOpts().CPlusPlus && 4196 (base->isTypeDependent() || idx->isTypeDependent())) { 4197 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4198 VK_LValue, OK_Ordinary, rbLoc); 4199 } 4200 4201 // MSDN, property (C++) 4202 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4203 // This attribute can also be used in the declaration of an empty array in a 4204 // class or structure definition. For example: 4205 // __declspec(property(get=GetX, put=PutX)) int x[]; 4206 // The above statement indicates that x[] can be used with one or more array 4207 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4208 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4209 if (IsMSPropertySubscript) { 4210 // Build MS property subscript expression if base is MS property reference 4211 // or MS property subscript. 4212 return new (Context) MSPropertySubscriptExpr( 4213 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4214 } 4215 4216 // Use C++ overloaded-operator rules if either operand has record 4217 // type. The spec says to do this if either type is *overloadable*, 4218 // but enum types can't declare subscript operators or conversion 4219 // operators, so there's nothing interesting for overload resolution 4220 // to do if there aren't any record types involved. 4221 // 4222 // ObjC pointers have their own subscripting logic that is not tied 4223 // to overload resolution and so should not take this path. 4224 if (getLangOpts().CPlusPlus && 4225 (base->getType()->isRecordType() || 4226 (!base->getType()->isObjCObjectPointerType() && 4227 idx->getType()->isRecordType()))) { 4228 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4229 } 4230 4231 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4232 } 4233 4234 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4235 Expr *LowerBound, 4236 SourceLocation ColonLoc, Expr *Length, 4237 SourceLocation RBLoc) { 4238 if (Base->getType()->isPlaceholderType() && 4239 !Base->getType()->isSpecificPlaceholderType( 4240 BuiltinType::OMPArraySection)) { 4241 ExprResult Result = CheckPlaceholderExpr(Base); 4242 if (Result.isInvalid()) 4243 return ExprError(); 4244 Base = Result.get(); 4245 } 4246 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4247 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4248 if (Result.isInvalid()) 4249 return ExprError(); 4250 Result = DefaultLvalueConversion(Result.get()); 4251 if (Result.isInvalid()) 4252 return ExprError(); 4253 LowerBound = Result.get(); 4254 } 4255 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4256 ExprResult Result = CheckPlaceholderExpr(Length); 4257 if (Result.isInvalid()) 4258 return ExprError(); 4259 Result = DefaultLvalueConversion(Result.get()); 4260 if (Result.isInvalid()) 4261 return ExprError(); 4262 Length = Result.get(); 4263 } 4264 4265 // Build an unanalyzed expression if either operand is type-dependent. 4266 if (Base->isTypeDependent() || 4267 (LowerBound && 4268 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4269 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4270 return new (Context) 4271 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4272 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4273 } 4274 4275 // Perform default conversions. 4276 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4277 QualType ResultTy; 4278 if (OriginalTy->isAnyPointerType()) { 4279 ResultTy = OriginalTy->getPointeeType(); 4280 } else if (OriginalTy->isArrayType()) { 4281 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4282 } else { 4283 return ExprError( 4284 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4285 << Base->getSourceRange()); 4286 } 4287 // C99 6.5.2.1p1 4288 if (LowerBound) { 4289 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4290 LowerBound); 4291 if (Res.isInvalid()) 4292 return ExprError(Diag(LowerBound->getExprLoc(), 4293 diag::err_omp_typecheck_section_not_integer) 4294 << 0 << LowerBound->getSourceRange()); 4295 LowerBound = Res.get(); 4296 4297 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4298 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4299 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4300 << 0 << LowerBound->getSourceRange(); 4301 } 4302 if (Length) { 4303 auto Res = 4304 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4305 if (Res.isInvalid()) 4306 return ExprError(Diag(Length->getExprLoc(), 4307 diag::err_omp_typecheck_section_not_integer) 4308 << 1 << Length->getSourceRange()); 4309 Length = Res.get(); 4310 4311 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4312 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4313 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4314 << 1 << Length->getSourceRange(); 4315 } 4316 4317 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4318 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4319 // type. Note that functions are not objects, and that (in C99 parlance) 4320 // incomplete types are not object types. 4321 if (ResultTy->isFunctionType()) { 4322 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4323 << ResultTy << Base->getSourceRange(); 4324 return ExprError(); 4325 } 4326 4327 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4328 diag::err_omp_section_incomplete_type, Base)) 4329 return ExprError(); 4330 4331 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4332 llvm::APSInt LowerBoundValue; 4333 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4334 // OpenMP 4.5, [2.4 Array Sections] 4335 // The array section must be a subset of the original array. 4336 if (LowerBoundValue.isNegative()) { 4337 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4338 << LowerBound->getSourceRange(); 4339 return ExprError(); 4340 } 4341 } 4342 } 4343 4344 if (Length) { 4345 llvm::APSInt LengthValue; 4346 if (Length->EvaluateAsInt(LengthValue, Context)) { 4347 // OpenMP 4.5, [2.4 Array Sections] 4348 // The length must evaluate to non-negative integers. 4349 if (LengthValue.isNegative()) { 4350 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4351 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4352 << Length->getSourceRange(); 4353 return ExprError(); 4354 } 4355 } 4356 } else if (ColonLoc.isValid() && 4357 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4358 !OriginalTy->isVariableArrayType()))) { 4359 // OpenMP 4.5, [2.4 Array Sections] 4360 // When the size of the array dimension is not known, the length must be 4361 // specified explicitly. 4362 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4363 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4364 return ExprError(); 4365 } 4366 4367 if (!Base->getType()->isSpecificPlaceholderType( 4368 BuiltinType::OMPArraySection)) { 4369 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4370 if (Result.isInvalid()) 4371 return ExprError(); 4372 Base = Result.get(); 4373 } 4374 return new (Context) 4375 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4376 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4377 } 4378 4379 ExprResult 4380 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4381 Expr *Idx, SourceLocation RLoc) { 4382 Expr *LHSExp = Base; 4383 Expr *RHSExp = Idx; 4384 4385 // Perform default conversions. 4386 if (!LHSExp->getType()->getAs<VectorType>()) { 4387 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4388 if (Result.isInvalid()) 4389 return ExprError(); 4390 LHSExp = Result.get(); 4391 } 4392 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4393 if (Result.isInvalid()) 4394 return ExprError(); 4395 RHSExp = Result.get(); 4396 4397 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4398 ExprValueKind VK = VK_LValue; 4399 ExprObjectKind OK = OK_Ordinary; 4400 4401 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4402 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4403 // in the subscript position. As a result, we need to derive the array base 4404 // and index from the expression types. 4405 Expr *BaseExpr, *IndexExpr; 4406 QualType ResultType; 4407 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4408 BaseExpr = LHSExp; 4409 IndexExpr = RHSExp; 4410 ResultType = Context.DependentTy; 4411 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4412 BaseExpr = LHSExp; 4413 IndexExpr = RHSExp; 4414 ResultType = PTy->getPointeeType(); 4415 } else if (const ObjCObjectPointerType *PTy = 4416 LHSTy->getAs<ObjCObjectPointerType>()) { 4417 BaseExpr = LHSExp; 4418 IndexExpr = RHSExp; 4419 4420 // Use custom logic if this should be the pseudo-object subscript 4421 // expression. 4422 if (!LangOpts.isSubscriptPointerArithmetic()) 4423 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4424 nullptr); 4425 4426 ResultType = PTy->getPointeeType(); 4427 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4428 // Handle the uncommon case of "123[Ptr]". 4429 BaseExpr = RHSExp; 4430 IndexExpr = LHSExp; 4431 ResultType = PTy->getPointeeType(); 4432 } else if (const ObjCObjectPointerType *PTy = 4433 RHSTy->getAs<ObjCObjectPointerType>()) { 4434 // Handle the uncommon case of "123[Ptr]". 4435 BaseExpr = RHSExp; 4436 IndexExpr = LHSExp; 4437 ResultType = PTy->getPointeeType(); 4438 if (!LangOpts.isSubscriptPointerArithmetic()) { 4439 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4440 << ResultType << BaseExpr->getSourceRange(); 4441 return ExprError(); 4442 } 4443 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4444 BaseExpr = LHSExp; // vectors: V[123] 4445 IndexExpr = RHSExp; 4446 VK = LHSExp->getValueKind(); 4447 if (VK != VK_RValue) 4448 OK = OK_VectorComponent; 4449 4450 // FIXME: need to deal with const... 4451 ResultType = VTy->getElementType(); 4452 } else if (LHSTy->isArrayType()) { 4453 // If we see an array that wasn't promoted by 4454 // DefaultFunctionArrayLvalueConversion, it must be an array that 4455 // wasn't promoted because of the C90 rule that doesn't 4456 // allow promoting non-lvalue arrays. Warn, then 4457 // force the promotion here. 4458 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4459 LHSExp->getSourceRange(); 4460 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4461 CK_ArrayToPointerDecay).get(); 4462 LHSTy = LHSExp->getType(); 4463 4464 BaseExpr = LHSExp; 4465 IndexExpr = RHSExp; 4466 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4467 } else if (RHSTy->isArrayType()) { 4468 // Same as previous, except for 123[f().a] case 4469 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4470 RHSExp->getSourceRange(); 4471 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4472 CK_ArrayToPointerDecay).get(); 4473 RHSTy = RHSExp->getType(); 4474 4475 BaseExpr = RHSExp; 4476 IndexExpr = LHSExp; 4477 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4478 } else { 4479 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4480 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4481 } 4482 // C99 6.5.2.1p1 4483 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4484 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4485 << IndexExpr->getSourceRange()); 4486 4487 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4488 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4489 && !IndexExpr->isTypeDependent()) 4490 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4491 4492 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4493 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4494 // type. Note that Functions are not objects, and that (in C99 parlance) 4495 // incomplete types are not object types. 4496 if (ResultType->isFunctionType()) { 4497 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4498 << ResultType << BaseExpr->getSourceRange(); 4499 return ExprError(); 4500 } 4501 4502 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4503 // GNU extension: subscripting on pointer to void 4504 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4505 << BaseExpr->getSourceRange(); 4506 4507 // C forbids expressions of unqualified void type from being l-values. 4508 // See IsCForbiddenLValueType. 4509 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4510 } else if (!ResultType->isDependentType() && 4511 RequireCompleteType(LLoc, ResultType, 4512 diag::err_subscript_incomplete_type, BaseExpr)) 4513 return ExprError(); 4514 4515 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4516 !ResultType.isCForbiddenLValueType()); 4517 4518 return new (Context) 4519 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4520 } 4521 4522 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4523 FunctionDecl *FD, 4524 ParmVarDecl *Param) { 4525 if (Param->hasUnparsedDefaultArg()) { 4526 Diag(CallLoc, 4527 diag::err_use_of_default_argument_to_function_declared_later) << 4528 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4529 Diag(UnparsedDefaultArgLocs[Param], 4530 diag::note_default_argument_declared_here); 4531 return ExprError(); 4532 } 4533 4534 if (Param->hasUninstantiatedDefaultArg()) { 4535 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4536 4537 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4538 Param); 4539 4540 // Instantiate the expression. 4541 MultiLevelTemplateArgumentList MutiLevelArgList 4542 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4543 4544 InstantiatingTemplate Inst(*this, CallLoc, Param, 4545 MutiLevelArgList.getInnermost()); 4546 if (Inst.isInvalid()) 4547 return ExprError(); 4548 4549 ExprResult Result; 4550 { 4551 // C++ [dcl.fct.default]p5: 4552 // The names in the [default argument] expression are bound, and 4553 // the semantic constraints are checked, at the point where the 4554 // default argument expression appears. 4555 ContextRAII SavedContext(*this, FD); 4556 LocalInstantiationScope Local(*this); 4557 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4558 } 4559 if (Result.isInvalid()) 4560 return ExprError(); 4561 4562 // Check the expression as an initializer for the parameter. 4563 InitializedEntity Entity 4564 = InitializedEntity::InitializeParameter(Context, Param); 4565 InitializationKind Kind 4566 = InitializationKind::CreateCopy(Param->getLocation(), 4567 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4568 Expr *ResultE = Result.getAs<Expr>(); 4569 4570 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4571 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4572 if (Result.isInvalid()) 4573 return ExprError(); 4574 4575 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4576 Param->getOuterLocStart()); 4577 if (Result.isInvalid()) 4578 return ExprError(); 4579 4580 // Remember the instantiated default argument. 4581 Param->setDefaultArg(Result.getAs<Expr>()); 4582 if (ASTMutationListener *L = getASTMutationListener()) { 4583 L->DefaultArgumentInstantiated(Param); 4584 } 4585 } 4586 4587 // If the default argument expression is not set yet, we are building it now. 4588 if (!Param->hasInit()) { 4589 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4590 Param->setInvalidDecl(); 4591 return ExprError(); 4592 } 4593 4594 // If the default expression creates temporaries, we need to 4595 // push them to the current stack of expression temporaries so they'll 4596 // be properly destroyed. 4597 // FIXME: We should really be rebuilding the default argument with new 4598 // bound temporaries; see the comment in PR5810. 4599 // We don't need to do that with block decls, though, because 4600 // blocks in default argument expression can never capture anything. 4601 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4602 // Set the "needs cleanups" bit regardless of whether there are 4603 // any explicit objects. 4604 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4605 4606 // Append all the objects to the cleanup list. Right now, this 4607 // should always be a no-op, because blocks in default argument 4608 // expressions should never be able to capture anything. 4609 assert(!Init->getNumObjects() && 4610 "default argument expression has capturing blocks?"); 4611 } 4612 4613 // We already type-checked the argument, so we know it works. 4614 // Just mark all of the declarations in this potentially-evaluated expression 4615 // as being "referenced". 4616 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4617 /*SkipLocalVariables=*/true); 4618 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4619 } 4620 4621 4622 Sema::VariadicCallType 4623 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4624 Expr *Fn) { 4625 if (Proto && Proto->isVariadic()) { 4626 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4627 return VariadicConstructor; 4628 else if (Fn && Fn->getType()->isBlockPointerType()) 4629 return VariadicBlock; 4630 else if (FDecl) { 4631 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4632 if (Method->isInstance()) 4633 return VariadicMethod; 4634 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4635 return VariadicMethod; 4636 return VariadicFunction; 4637 } 4638 return VariadicDoesNotApply; 4639 } 4640 4641 namespace { 4642 class FunctionCallCCC : public FunctionCallFilterCCC { 4643 public: 4644 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4645 unsigned NumArgs, MemberExpr *ME) 4646 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4647 FunctionName(FuncName) {} 4648 4649 bool ValidateCandidate(const TypoCorrection &candidate) override { 4650 if (!candidate.getCorrectionSpecifier() || 4651 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4652 return false; 4653 } 4654 4655 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4656 } 4657 4658 private: 4659 const IdentifierInfo *const FunctionName; 4660 }; 4661 } 4662 4663 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4664 FunctionDecl *FDecl, 4665 ArrayRef<Expr *> Args) { 4666 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4667 DeclarationName FuncName = FDecl->getDeclName(); 4668 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4669 4670 if (TypoCorrection Corrected = S.CorrectTypo( 4671 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4672 S.getScopeForContext(S.CurContext), nullptr, 4673 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4674 Args.size(), ME), 4675 Sema::CTK_ErrorRecovery)) { 4676 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4677 if (Corrected.isOverloaded()) { 4678 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4679 OverloadCandidateSet::iterator Best; 4680 for (NamedDecl *CD : Corrected) { 4681 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4682 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4683 OCS); 4684 } 4685 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4686 case OR_Success: 4687 ND = Best->FoundDecl; 4688 Corrected.setCorrectionDecl(ND); 4689 break; 4690 default: 4691 break; 4692 } 4693 } 4694 ND = ND->getUnderlyingDecl(); 4695 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4696 return Corrected; 4697 } 4698 } 4699 return TypoCorrection(); 4700 } 4701 4702 /// ConvertArgumentsForCall - Converts the arguments specified in 4703 /// Args/NumArgs to the parameter types of the function FDecl with 4704 /// function prototype Proto. Call is the call expression itself, and 4705 /// Fn is the function expression. For a C++ member function, this 4706 /// routine does not attempt to convert the object argument. Returns 4707 /// true if the call is ill-formed. 4708 bool 4709 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4710 FunctionDecl *FDecl, 4711 const FunctionProtoType *Proto, 4712 ArrayRef<Expr *> Args, 4713 SourceLocation RParenLoc, 4714 bool IsExecConfig) { 4715 // Bail out early if calling a builtin with custom typechecking. 4716 if (FDecl) 4717 if (unsigned ID = FDecl->getBuiltinID()) 4718 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4719 return false; 4720 4721 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4722 // assignment, to the types of the corresponding parameter, ... 4723 unsigned NumParams = Proto->getNumParams(); 4724 bool Invalid = false; 4725 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4726 unsigned FnKind = Fn->getType()->isBlockPointerType() 4727 ? 1 /* block */ 4728 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4729 : 0 /* function */); 4730 4731 // If too few arguments are available (and we don't have default 4732 // arguments for the remaining parameters), don't make the call. 4733 if (Args.size() < NumParams) { 4734 if (Args.size() < MinArgs) { 4735 TypoCorrection TC; 4736 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4737 unsigned diag_id = 4738 MinArgs == NumParams && !Proto->isVariadic() 4739 ? diag::err_typecheck_call_too_few_args_suggest 4740 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4741 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4742 << static_cast<unsigned>(Args.size()) 4743 << TC.getCorrectionRange()); 4744 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4745 Diag(RParenLoc, 4746 MinArgs == NumParams && !Proto->isVariadic() 4747 ? diag::err_typecheck_call_too_few_args_one 4748 : diag::err_typecheck_call_too_few_args_at_least_one) 4749 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4750 else 4751 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4752 ? diag::err_typecheck_call_too_few_args 4753 : diag::err_typecheck_call_too_few_args_at_least) 4754 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4755 << Fn->getSourceRange(); 4756 4757 // Emit the location of the prototype. 4758 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4759 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4760 << FDecl; 4761 4762 return true; 4763 } 4764 Call->setNumArgs(Context, NumParams); 4765 } 4766 4767 // If too many are passed and not variadic, error on the extras and drop 4768 // them. 4769 if (Args.size() > NumParams) { 4770 if (!Proto->isVariadic()) { 4771 TypoCorrection TC; 4772 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4773 unsigned diag_id = 4774 MinArgs == NumParams && !Proto->isVariadic() 4775 ? diag::err_typecheck_call_too_many_args_suggest 4776 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4777 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4778 << static_cast<unsigned>(Args.size()) 4779 << TC.getCorrectionRange()); 4780 } else if (NumParams == 1 && FDecl && 4781 FDecl->getParamDecl(0)->getDeclName()) 4782 Diag(Args[NumParams]->getLocStart(), 4783 MinArgs == NumParams 4784 ? diag::err_typecheck_call_too_many_args_one 4785 : diag::err_typecheck_call_too_many_args_at_most_one) 4786 << FnKind << FDecl->getParamDecl(0) 4787 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4788 << SourceRange(Args[NumParams]->getLocStart(), 4789 Args.back()->getLocEnd()); 4790 else 4791 Diag(Args[NumParams]->getLocStart(), 4792 MinArgs == NumParams 4793 ? diag::err_typecheck_call_too_many_args 4794 : diag::err_typecheck_call_too_many_args_at_most) 4795 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4796 << Fn->getSourceRange() 4797 << SourceRange(Args[NumParams]->getLocStart(), 4798 Args.back()->getLocEnd()); 4799 4800 // Emit the location of the prototype. 4801 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4802 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4803 << FDecl; 4804 4805 // This deletes the extra arguments. 4806 Call->setNumArgs(Context, NumParams); 4807 return true; 4808 } 4809 } 4810 SmallVector<Expr *, 8> AllArgs; 4811 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4812 4813 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4814 Proto, 0, Args, AllArgs, CallType); 4815 if (Invalid) 4816 return true; 4817 unsigned TotalNumArgs = AllArgs.size(); 4818 for (unsigned i = 0; i < TotalNumArgs; ++i) 4819 Call->setArg(i, AllArgs[i]); 4820 4821 return false; 4822 } 4823 4824 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4825 const FunctionProtoType *Proto, 4826 unsigned FirstParam, ArrayRef<Expr *> Args, 4827 SmallVectorImpl<Expr *> &AllArgs, 4828 VariadicCallType CallType, bool AllowExplicit, 4829 bool IsListInitialization) { 4830 unsigned NumParams = Proto->getNumParams(); 4831 bool Invalid = false; 4832 size_t ArgIx = 0; 4833 // Continue to check argument types (even if we have too few/many args). 4834 for (unsigned i = FirstParam; i < NumParams; i++) { 4835 QualType ProtoArgType = Proto->getParamType(i); 4836 4837 Expr *Arg; 4838 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4839 if (ArgIx < Args.size()) { 4840 Arg = Args[ArgIx++]; 4841 4842 if (RequireCompleteType(Arg->getLocStart(), 4843 ProtoArgType, 4844 diag::err_call_incomplete_argument, Arg)) 4845 return true; 4846 4847 // Strip the unbridged-cast placeholder expression off, if applicable. 4848 bool CFAudited = false; 4849 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4850 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4851 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4852 Arg = stripARCUnbridgedCast(Arg); 4853 else if (getLangOpts().ObjCAutoRefCount && 4854 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4855 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4856 CFAudited = true; 4857 4858 InitializedEntity Entity = 4859 Param ? InitializedEntity::InitializeParameter(Context, Param, 4860 ProtoArgType) 4861 : InitializedEntity::InitializeParameter( 4862 Context, ProtoArgType, Proto->isParamConsumed(i)); 4863 4864 // Remember that parameter belongs to a CF audited API. 4865 if (CFAudited) 4866 Entity.setParameterCFAudited(); 4867 4868 ExprResult ArgE = PerformCopyInitialization( 4869 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4870 if (ArgE.isInvalid()) 4871 return true; 4872 4873 Arg = ArgE.getAs<Expr>(); 4874 } else { 4875 assert(Param && "can't use default arguments without a known callee"); 4876 4877 ExprResult ArgExpr = 4878 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4879 if (ArgExpr.isInvalid()) 4880 return true; 4881 4882 Arg = ArgExpr.getAs<Expr>(); 4883 } 4884 4885 // Check for array bounds violations for each argument to the call. This 4886 // check only triggers warnings when the argument isn't a more complex Expr 4887 // with its own checking, such as a BinaryOperator. 4888 CheckArrayAccess(Arg); 4889 4890 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4891 CheckStaticArrayArgument(CallLoc, Param, Arg); 4892 4893 AllArgs.push_back(Arg); 4894 } 4895 4896 // If this is a variadic call, handle args passed through "...". 4897 if (CallType != VariadicDoesNotApply) { 4898 // Assume that extern "C" functions with variadic arguments that 4899 // return __unknown_anytype aren't *really* variadic. 4900 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4901 FDecl->isExternC()) { 4902 for (Expr *A : Args.slice(ArgIx)) { 4903 QualType paramType; // ignored 4904 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4905 Invalid |= arg.isInvalid(); 4906 AllArgs.push_back(arg.get()); 4907 } 4908 4909 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4910 } else { 4911 for (Expr *A : Args.slice(ArgIx)) { 4912 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4913 Invalid |= Arg.isInvalid(); 4914 AllArgs.push_back(Arg.get()); 4915 } 4916 } 4917 4918 // Check for array bounds violations. 4919 for (Expr *A : Args.slice(ArgIx)) 4920 CheckArrayAccess(A); 4921 } 4922 return Invalid; 4923 } 4924 4925 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4926 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4927 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4928 TL = DTL.getOriginalLoc(); 4929 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4930 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4931 << ATL.getLocalSourceRange(); 4932 } 4933 4934 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4935 /// array parameter, check that it is non-null, and that if it is formed by 4936 /// array-to-pointer decay, the underlying array is sufficiently large. 4937 /// 4938 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4939 /// array type derivation, then for each call to the function, the value of the 4940 /// corresponding actual argument shall provide access to the first element of 4941 /// an array with at least as many elements as specified by the size expression. 4942 void 4943 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4944 ParmVarDecl *Param, 4945 const Expr *ArgExpr) { 4946 // Static array parameters are not supported in C++. 4947 if (!Param || getLangOpts().CPlusPlus) 4948 return; 4949 4950 QualType OrigTy = Param->getOriginalType(); 4951 4952 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4953 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4954 return; 4955 4956 if (ArgExpr->isNullPointerConstant(Context, 4957 Expr::NPC_NeverValueDependent)) { 4958 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4959 DiagnoseCalleeStaticArrayParam(*this, Param); 4960 return; 4961 } 4962 4963 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4964 if (!CAT) 4965 return; 4966 4967 const ConstantArrayType *ArgCAT = 4968 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4969 if (!ArgCAT) 4970 return; 4971 4972 if (ArgCAT->getSize().ult(CAT->getSize())) { 4973 Diag(CallLoc, diag::warn_static_array_too_small) 4974 << ArgExpr->getSourceRange() 4975 << (unsigned) ArgCAT->getSize().getZExtValue() 4976 << (unsigned) CAT->getSize().getZExtValue(); 4977 DiagnoseCalleeStaticArrayParam(*this, Param); 4978 } 4979 } 4980 4981 /// Given a function expression of unknown-any type, try to rebuild it 4982 /// to have a function type. 4983 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4984 4985 /// Is the given type a placeholder that we need to lower out 4986 /// immediately during argument processing? 4987 static bool isPlaceholderToRemoveAsArg(QualType type) { 4988 // Placeholders are never sugared. 4989 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4990 if (!placeholder) return false; 4991 4992 switch (placeholder->getKind()) { 4993 // Ignore all the non-placeholder types. 4994 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4995 case BuiltinType::Id: 4996 #include "clang/Basic/OpenCLImageTypes.def" 4997 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4998 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4999 #include "clang/AST/BuiltinTypes.def" 5000 return false; 5001 5002 // We cannot lower out overload sets; they might validly be resolved 5003 // by the call machinery. 5004 case BuiltinType::Overload: 5005 return false; 5006 5007 // Unbridged casts in ARC can be handled in some call positions and 5008 // should be left in place. 5009 case BuiltinType::ARCUnbridgedCast: 5010 return false; 5011 5012 // Pseudo-objects should be converted as soon as possible. 5013 case BuiltinType::PseudoObject: 5014 return true; 5015 5016 // The debugger mode could theoretically but currently does not try 5017 // to resolve unknown-typed arguments based on known parameter types. 5018 case BuiltinType::UnknownAny: 5019 return true; 5020 5021 // These are always invalid as call arguments and should be reported. 5022 case BuiltinType::BoundMember: 5023 case BuiltinType::BuiltinFn: 5024 case BuiltinType::OMPArraySection: 5025 return true; 5026 5027 } 5028 llvm_unreachable("bad builtin type kind"); 5029 } 5030 5031 /// Check an argument list for placeholders that we won't try to 5032 /// handle later. 5033 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5034 // Apply this processing to all the arguments at once instead of 5035 // dying at the first failure. 5036 bool hasInvalid = false; 5037 for (size_t i = 0, e = args.size(); i != e; i++) { 5038 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5039 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5040 if (result.isInvalid()) hasInvalid = true; 5041 else args[i] = result.get(); 5042 } else if (hasInvalid) { 5043 (void)S.CorrectDelayedTyposInExpr(args[i]); 5044 } 5045 } 5046 return hasInvalid; 5047 } 5048 5049 /// If a builtin function has a pointer argument with no explicit address 5050 /// space, then it should be able to accept a pointer to any address 5051 /// space as input. In order to do this, we need to replace the 5052 /// standard builtin declaration with one that uses the same address space 5053 /// as the call. 5054 /// 5055 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5056 /// it does not contain any pointer arguments without 5057 /// an address space qualifer. Otherwise the rewritten 5058 /// FunctionDecl is returned. 5059 /// TODO: Handle pointer return types. 5060 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5061 const FunctionDecl *FDecl, 5062 MultiExprArg ArgExprs) { 5063 5064 QualType DeclType = FDecl->getType(); 5065 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5066 5067 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5068 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5069 return nullptr; 5070 5071 bool NeedsNewDecl = false; 5072 unsigned i = 0; 5073 SmallVector<QualType, 8> OverloadParams; 5074 5075 for (QualType ParamType : FT->param_types()) { 5076 5077 // Convert array arguments to pointer to simplify type lookup. 5078 ExprResult ArgRes = 5079 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5080 if (ArgRes.isInvalid()) 5081 return nullptr; 5082 Expr *Arg = ArgRes.get(); 5083 QualType ArgType = Arg->getType(); 5084 if (!ParamType->isPointerType() || 5085 ParamType.getQualifiers().hasAddressSpace() || 5086 !ArgType->isPointerType() || 5087 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5088 OverloadParams.push_back(ParamType); 5089 continue; 5090 } 5091 5092 NeedsNewDecl = true; 5093 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5094 5095 QualType PointeeType = ParamType->getPointeeType(); 5096 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5097 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5098 } 5099 5100 if (!NeedsNewDecl) 5101 return nullptr; 5102 5103 FunctionProtoType::ExtProtoInfo EPI; 5104 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5105 OverloadParams, EPI); 5106 DeclContext *Parent = Context.getTranslationUnitDecl(); 5107 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5108 FDecl->getLocation(), 5109 FDecl->getLocation(), 5110 FDecl->getIdentifier(), 5111 OverloadTy, 5112 /*TInfo=*/nullptr, 5113 SC_Extern, false, 5114 /*hasPrototype=*/true); 5115 SmallVector<ParmVarDecl*, 16> Params; 5116 FT = cast<FunctionProtoType>(OverloadTy); 5117 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5118 QualType ParamType = FT->getParamType(i); 5119 ParmVarDecl *Parm = 5120 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5121 SourceLocation(), nullptr, ParamType, 5122 /*TInfo=*/nullptr, SC_None, nullptr); 5123 Parm->setScopeInfo(0, i); 5124 Params.push_back(Parm); 5125 } 5126 OverloadDecl->setParams(Params); 5127 return OverloadDecl; 5128 } 5129 5130 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5131 std::size_t NumArgs) { 5132 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5133 /*PartialOverloading=*/false)) 5134 return Callee->isVariadic(); 5135 return Callee->getMinRequiredArguments() <= NumArgs; 5136 } 5137 5138 static ExprResult ActOnCallExprImpl(Sema &S, Scope *Scope, Expr *Fn, 5139 SourceLocation LParenLoc, 5140 MultiExprArg ArgExprs, 5141 SourceLocation RParenLoc, Expr *ExecConfig, 5142 bool IsExecConfig) { 5143 // Since this might be a postfix expression, get rid of ParenListExprs. 5144 ExprResult Result = S.MaybeConvertParenListExprToParenExpr(Scope, Fn); 5145 if (Result.isInvalid()) return ExprError(); 5146 Fn = Result.get(); 5147 5148 if (checkArgsForPlaceholders(S, ArgExprs)) 5149 return ExprError(); 5150 5151 if (S.getLangOpts().CPlusPlus) { 5152 // If this is a pseudo-destructor expression, build the call immediately. 5153 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5154 if (!ArgExprs.empty()) { 5155 // Pseudo-destructor calls should not have any arguments. 5156 S.Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5157 << FixItHint::CreateRemoval( 5158 SourceRange(ArgExprs.front()->getLocStart(), 5159 ArgExprs.back()->getLocEnd())); 5160 } 5161 5162 return new (S.Context) 5163 CallExpr(S.Context, Fn, None, S.Context.VoidTy, VK_RValue, RParenLoc); 5164 } 5165 if (Fn->getType() == S.Context.PseudoObjectTy) { 5166 ExprResult result = S.CheckPlaceholderExpr(Fn); 5167 if (result.isInvalid()) return ExprError(); 5168 Fn = result.get(); 5169 } 5170 5171 // Determine whether this is a dependent call inside a C++ template, 5172 // in which case we won't do any semantic analysis now. 5173 bool Dependent = false; 5174 if (Fn->isTypeDependent()) 5175 Dependent = true; 5176 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5177 Dependent = true; 5178 5179 if (Dependent) { 5180 if (ExecConfig) { 5181 return new (S.Context) CUDAKernelCallExpr( 5182 S.Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5183 S.Context.DependentTy, VK_RValue, RParenLoc); 5184 } else { 5185 return new (S.Context) 5186 CallExpr(S.Context, Fn, ArgExprs, S.Context.DependentTy, VK_RValue, 5187 RParenLoc); 5188 } 5189 } 5190 5191 // Determine whether this is a call to an object (C++ [over.call.object]). 5192 if (Fn->getType()->isRecordType()) 5193 return S.BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5194 RParenLoc); 5195 5196 if (Fn->getType() == S.Context.UnknownAnyTy) { 5197 ExprResult result = rebuildUnknownAnyFunction(S, Fn); 5198 if (result.isInvalid()) return ExprError(); 5199 Fn = result.get(); 5200 } 5201 5202 if (Fn->getType() == S.Context.BoundMemberTy) { 5203 return S.BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5204 RParenLoc); 5205 } 5206 } 5207 5208 // Check for overloaded calls. This can happen even in C due to extensions. 5209 if (Fn->getType() == S.Context.OverloadTy) { 5210 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5211 5212 // We aren't supposed to apply this logic for if there'Scope an '&' 5213 // involved. 5214 if (!find.HasFormOfMemberPointer) { 5215 OverloadExpr *ovl = find.Expression; 5216 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5217 return S.BuildOverloadedCallExpr( 5218 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5219 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5220 return S.BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5221 RParenLoc); 5222 } 5223 } 5224 5225 // If we're directly calling a function, get the appropriate declaration. 5226 if (Fn->getType() == S.Context.UnknownAnyTy) { 5227 ExprResult result = rebuildUnknownAnyFunction(S, Fn); 5228 if (result.isInvalid()) return ExprError(); 5229 Fn = result.get(); 5230 } 5231 5232 Expr *NakedFn = Fn->IgnoreParens(); 5233 5234 bool CallingNDeclIndirectly = false; 5235 NamedDecl *NDecl = nullptr; 5236 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5237 if (UnOp->getOpcode() == UO_AddrOf) { 5238 CallingNDeclIndirectly = true; 5239 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5240 } 5241 } 5242 5243 if (isa<DeclRefExpr>(NakedFn)) { 5244 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5245 5246 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5247 if (FDecl && FDecl->getBuiltinID()) { 5248 // Rewrite the function decl for this builtin by replacing parameters 5249 // with no explicit address space with the address space of the arguments 5250 // in ArgExprs. 5251 if ((FDecl = 5252 rewriteBuiltinFunctionDecl(&S, S.Context, FDecl, ArgExprs))) { 5253 NDecl = FDecl; 5254 Fn = DeclRefExpr::Create( 5255 S.Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5256 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5257 } 5258 } 5259 } else if (isa<MemberExpr>(NakedFn)) 5260 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5261 5262 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5263 if (CallingNDeclIndirectly && 5264 !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5265 Fn->getLocStart())) 5266 return ExprError(); 5267 5268 // CheckEnableIf assumes that the we're passing in a sane number of args for 5269 // FD, but that doesn't always hold true here. This is because, in some 5270 // cases, we'll emit a diag about an ill-formed function call, but then 5271 // we'll continue on as if the function call wasn't ill-formed. So, if the 5272 // number of args looks incorrect, don't do enable_if checks; we should've 5273 // already emitted an error about the bad call. 5274 if (FD->hasAttr<EnableIfAttr>() && 5275 isNumberOfArgsValidForCall(S, FD, ArgExprs.size())) { 5276 if (const EnableIfAttr *Attr = S.CheckEnableIf(FD, ArgExprs, true)) { 5277 S.Diag(Fn->getLocStart(), 5278 isa<CXXMethodDecl>(FD) 5279 ? diag::err_ovl_no_viable_member_function_in_call 5280 : diag::err_ovl_no_viable_function_in_call) 5281 << FD << FD->getSourceRange(); 5282 S.Diag(FD->getLocation(), 5283 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5284 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5285 } 5286 } 5287 } 5288 5289 return S.BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5290 ExecConfig, IsExecConfig); 5291 } 5292 5293 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5294 /// This provides the location of the left/right parens and a list of comma 5295 /// locations. 5296 ExprResult Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5297 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5298 Expr *ExecConfig, bool IsExecConfig) { 5299 ExprResult Ret = ActOnCallExprImpl(*this, S, Fn, LParenLoc, ArgExprs, 5300 RParenLoc, ExecConfig, IsExecConfig); 5301 5302 // If appropriate, check that this is a valid CUDA call (and emit an error if 5303 // the call is not allowed). 5304 if (getLangOpts().CUDA && Ret.isUsable()) 5305 if (auto *Call = dyn_cast<CallExpr>(Ret.get())) 5306 if (auto *FD = Call->getDirectCallee()) 5307 if (!CheckCUDACall(Call->getLocStart(), FD)) 5308 return ExprError(); 5309 5310 return Ret; 5311 } 5312 5313 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5314 /// 5315 /// __builtin_astype( value, dst type ) 5316 /// 5317 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5318 SourceLocation BuiltinLoc, 5319 SourceLocation RParenLoc) { 5320 ExprValueKind VK = VK_RValue; 5321 ExprObjectKind OK = OK_Ordinary; 5322 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5323 QualType SrcTy = E->getType(); 5324 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5325 return ExprError(Diag(BuiltinLoc, 5326 diag::err_invalid_astype_of_different_size) 5327 << DstTy 5328 << SrcTy 5329 << E->getSourceRange()); 5330 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5331 } 5332 5333 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5334 /// provided arguments. 5335 /// 5336 /// __builtin_convertvector( value, dst type ) 5337 /// 5338 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5339 SourceLocation BuiltinLoc, 5340 SourceLocation RParenLoc) { 5341 TypeSourceInfo *TInfo; 5342 GetTypeFromParser(ParsedDestTy, &TInfo); 5343 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5344 } 5345 5346 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5347 /// i.e. an expression not of \p OverloadTy. The expression should 5348 /// unary-convert to an expression of function-pointer or 5349 /// block-pointer type. 5350 /// 5351 /// \param NDecl the declaration being called, if available 5352 ExprResult 5353 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5354 SourceLocation LParenLoc, 5355 ArrayRef<Expr *> Args, 5356 SourceLocation RParenLoc, 5357 Expr *Config, bool IsExecConfig) { 5358 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5359 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5360 5361 // Functions with 'interrupt' attribute cannot be called directly. 5362 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5363 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5364 return ExprError(); 5365 } 5366 5367 // Promote the function operand. 5368 // We special-case function promotion here because we only allow promoting 5369 // builtin functions to function pointers in the callee of a call. 5370 ExprResult Result; 5371 if (BuiltinID && 5372 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5373 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5374 CK_BuiltinFnToFnPtr).get(); 5375 } else { 5376 Result = CallExprUnaryConversions(Fn); 5377 } 5378 if (Result.isInvalid()) 5379 return ExprError(); 5380 Fn = Result.get(); 5381 5382 // Make the call expr early, before semantic checks. This guarantees cleanup 5383 // of arguments and function on error. 5384 CallExpr *TheCall; 5385 if (Config) 5386 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5387 cast<CallExpr>(Config), Args, 5388 Context.BoolTy, VK_RValue, 5389 RParenLoc); 5390 else 5391 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5392 VK_RValue, RParenLoc); 5393 5394 if (!getLangOpts().CPlusPlus) { 5395 // C cannot always handle TypoExpr nodes in builtin calls and direct 5396 // function calls as their argument checking don't necessarily handle 5397 // dependent types properly, so make sure any TypoExprs have been 5398 // dealt with. 5399 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5400 if (!Result.isUsable()) return ExprError(); 5401 TheCall = dyn_cast<CallExpr>(Result.get()); 5402 if (!TheCall) return Result; 5403 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5404 } 5405 5406 // Bail out early if calling a builtin with custom typechecking. 5407 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5408 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5409 5410 retry: 5411 const FunctionType *FuncT; 5412 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5413 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5414 // have type pointer to function". 5415 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5416 if (!FuncT) 5417 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5418 << Fn->getType() << Fn->getSourceRange()); 5419 } else if (const BlockPointerType *BPT = 5420 Fn->getType()->getAs<BlockPointerType>()) { 5421 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5422 } else { 5423 // Handle calls to expressions of unknown-any type. 5424 if (Fn->getType() == Context.UnknownAnyTy) { 5425 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5426 if (rewrite.isInvalid()) return ExprError(); 5427 Fn = rewrite.get(); 5428 TheCall->setCallee(Fn); 5429 goto retry; 5430 } 5431 5432 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5433 << Fn->getType() << Fn->getSourceRange()); 5434 } 5435 5436 if (getLangOpts().CUDA) { 5437 if (Config) { 5438 // CUDA: Kernel calls must be to global functions 5439 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5440 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5441 << FDecl->getName() << Fn->getSourceRange()); 5442 5443 // CUDA: Kernel function must have 'void' return type 5444 if (!FuncT->getReturnType()->isVoidType()) 5445 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5446 << Fn->getType() << Fn->getSourceRange()); 5447 } else { 5448 // CUDA: Calls to global functions must be configured 5449 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5450 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5451 << FDecl->getName() << Fn->getSourceRange()); 5452 } 5453 } 5454 5455 // Check for a valid return type 5456 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5457 FDecl)) 5458 return ExprError(); 5459 5460 // We know the result type of the call, set it. 5461 TheCall->setType(FuncT->getCallResultType(Context)); 5462 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5463 5464 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5465 if (Proto) { 5466 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5467 IsExecConfig)) 5468 return ExprError(); 5469 } else { 5470 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5471 5472 if (FDecl) { 5473 // Check if we have too few/too many template arguments, based 5474 // on our knowledge of the function definition. 5475 const FunctionDecl *Def = nullptr; 5476 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5477 Proto = Def->getType()->getAs<FunctionProtoType>(); 5478 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5479 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5480 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5481 } 5482 5483 // If the function we're calling isn't a function prototype, but we have 5484 // a function prototype from a prior declaratiom, use that prototype. 5485 if (!FDecl->hasPrototype()) 5486 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5487 } 5488 5489 // Promote the arguments (C99 6.5.2.2p6). 5490 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5491 Expr *Arg = Args[i]; 5492 5493 if (Proto && i < Proto->getNumParams()) { 5494 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5495 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5496 ExprResult ArgE = 5497 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5498 if (ArgE.isInvalid()) 5499 return true; 5500 5501 Arg = ArgE.getAs<Expr>(); 5502 5503 } else { 5504 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5505 5506 if (ArgE.isInvalid()) 5507 return true; 5508 5509 Arg = ArgE.getAs<Expr>(); 5510 } 5511 5512 if (RequireCompleteType(Arg->getLocStart(), 5513 Arg->getType(), 5514 diag::err_call_incomplete_argument, Arg)) 5515 return ExprError(); 5516 5517 TheCall->setArg(i, Arg); 5518 } 5519 } 5520 5521 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5522 if (!Method->isStatic()) 5523 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5524 << Fn->getSourceRange()); 5525 5526 // Check for sentinels 5527 if (NDecl) 5528 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5529 5530 // Do special checking on direct calls to functions. 5531 if (FDecl) { 5532 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5533 return ExprError(); 5534 5535 if (BuiltinID) 5536 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5537 } else if (NDecl) { 5538 if (CheckPointerCall(NDecl, TheCall, Proto)) 5539 return ExprError(); 5540 } else { 5541 if (CheckOtherCall(TheCall, Proto)) 5542 return ExprError(); 5543 } 5544 5545 return MaybeBindToTemporary(TheCall); 5546 } 5547 5548 ExprResult 5549 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5550 SourceLocation RParenLoc, Expr *InitExpr) { 5551 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5552 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5553 5554 TypeSourceInfo *TInfo; 5555 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5556 if (!TInfo) 5557 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5558 5559 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5560 } 5561 5562 ExprResult 5563 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5564 SourceLocation RParenLoc, Expr *LiteralExpr) { 5565 QualType literalType = TInfo->getType(); 5566 5567 if (literalType->isArrayType()) { 5568 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5569 diag::err_illegal_decl_array_incomplete_type, 5570 SourceRange(LParenLoc, 5571 LiteralExpr->getSourceRange().getEnd()))) 5572 return ExprError(); 5573 if (literalType->isVariableArrayType()) 5574 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5575 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5576 } else if (!literalType->isDependentType() && 5577 RequireCompleteType(LParenLoc, literalType, 5578 diag::err_typecheck_decl_incomplete_type, 5579 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5580 return ExprError(); 5581 5582 InitializedEntity Entity 5583 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5584 InitializationKind Kind 5585 = InitializationKind::CreateCStyleCast(LParenLoc, 5586 SourceRange(LParenLoc, RParenLoc), 5587 /*InitList=*/true); 5588 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5589 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5590 &literalType); 5591 if (Result.isInvalid()) 5592 return ExprError(); 5593 LiteralExpr = Result.get(); 5594 5595 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5596 if (isFileScope && 5597 !LiteralExpr->isTypeDependent() && 5598 !LiteralExpr->isValueDependent() && 5599 !literalType->isDependentType()) { // 6.5.2.5p3 5600 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5601 return ExprError(); 5602 } 5603 5604 // In C, compound literals are l-values for some reason. 5605 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5606 5607 return MaybeBindToTemporary( 5608 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5609 VK, LiteralExpr, isFileScope)); 5610 } 5611 5612 ExprResult 5613 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5614 SourceLocation RBraceLoc) { 5615 // Immediately handle non-overload placeholders. Overloads can be 5616 // resolved contextually, but everything else here can't. 5617 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5618 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5619 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5620 5621 // Ignore failures; dropping the entire initializer list because 5622 // of one failure would be terrible for indexing/etc. 5623 if (result.isInvalid()) continue; 5624 5625 InitArgList[I] = result.get(); 5626 } 5627 } 5628 5629 // Semantic analysis for initializers is done by ActOnDeclarator() and 5630 // CheckInitializer() - it requires knowledge of the object being intialized. 5631 5632 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5633 RBraceLoc); 5634 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5635 return E; 5636 } 5637 5638 /// Do an explicit extend of the given block pointer if we're in ARC. 5639 void Sema::maybeExtendBlockObject(ExprResult &E) { 5640 assert(E.get()->getType()->isBlockPointerType()); 5641 assert(E.get()->isRValue()); 5642 5643 // Only do this in an r-value context. 5644 if (!getLangOpts().ObjCAutoRefCount) return; 5645 5646 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5647 CK_ARCExtendBlockObject, E.get(), 5648 /*base path*/ nullptr, VK_RValue); 5649 Cleanup.setExprNeedsCleanups(true); 5650 } 5651 5652 /// Prepare a conversion of the given expression to an ObjC object 5653 /// pointer type. 5654 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5655 QualType type = E.get()->getType(); 5656 if (type->isObjCObjectPointerType()) { 5657 return CK_BitCast; 5658 } else if (type->isBlockPointerType()) { 5659 maybeExtendBlockObject(E); 5660 return CK_BlockPointerToObjCPointerCast; 5661 } else { 5662 assert(type->isPointerType()); 5663 return CK_CPointerToObjCPointerCast; 5664 } 5665 } 5666 5667 /// Prepares for a scalar cast, performing all the necessary stages 5668 /// except the final cast and returning the kind required. 5669 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5670 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5671 // Also, callers should have filtered out the invalid cases with 5672 // pointers. Everything else should be possible. 5673 5674 QualType SrcTy = Src.get()->getType(); 5675 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5676 return CK_NoOp; 5677 5678 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5679 case Type::STK_MemberPointer: 5680 llvm_unreachable("member pointer type in C"); 5681 5682 case Type::STK_CPointer: 5683 case Type::STK_BlockPointer: 5684 case Type::STK_ObjCObjectPointer: 5685 switch (DestTy->getScalarTypeKind()) { 5686 case Type::STK_CPointer: { 5687 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5688 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5689 if (SrcAS != DestAS) 5690 return CK_AddressSpaceConversion; 5691 return CK_BitCast; 5692 } 5693 case Type::STK_BlockPointer: 5694 return (SrcKind == Type::STK_BlockPointer 5695 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5696 case Type::STK_ObjCObjectPointer: 5697 if (SrcKind == Type::STK_ObjCObjectPointer) 5698 return CK_BitCast; 5699 if (SrcKind == Type::STK_CPointer) 5700 return CK_CPointerToObjCPointerCast; 5701 maybeExtendBlockObject(Src); 5702 return CK_BlockPointerToObjCPointerCast; 5703 case Type::STK_Bool: 5704 return CK_PointerToBoolean; 5705 case Type::STK_Integral: 5706 return CK_PointerToIntegral; 5707 case Type::STK_Floating: 5708 case Type::STK_FloatingComplex: 5709 case Type::STK_IntegralComplex: 5710 case Type::STK_MemberPointer: 5711 llvm_unreachable("illegal cast from pointer"); 5712 } 5713 llvm_unreachable("Should have returned before this"); 5714 5715 case Type::STK_Bool: // casting from bool is like casting from an integer 5716 case Type::STK_Integral: 5717 switch (DestTy->getScalarTypeKind()) { 5718 case Type::STK_CPointer: 5719 case Type::STK_ObjCObjectPointer: 5720 case Type::STK_BlockPointer: 5721 if (Src.get()->isNullPointerConstant(Context, 5722 Expr::NPC_ValueDependentIsNull)) 5723 return CK_NullToPointer; 5724 return CK_IntegralToPointer; 5725 case Type::STK_Bool: 5726 return CK_IntegralToBoolean; 5727 case Type::STK_Integral: 5728 return CK_IntegralCast; 5729 case Type::STK_Floating: 5730 return CK_IntegralToFloating; 5731 case Type::STK_IntegralComplex: 5732 Src = ImpCastExprToType(Src.get(), 5733 DestTy->castAs<ComplexType>()->getElementType(), 5734 CK_IntegralCast); 5735 return CK_IntegralRealToComplex; 5736 case Type::STK_FloatingComplex: 5737 Src = ImpCastExprToType(Src.get(), 5738 DestTy->castAs<ComplexType>()->getElementType(), 5739 CK_IntegralToFloating); 5740 return CK_FloatingRealToComplex; 5741 case Type::STK_MemberPointer: 5742 llvm_unreachable("member pointer type in C"); 5743 } 5744 llvm_unreachable("Should have returned before this"); 5745 5746 case Type::STK_Floating: 5747 switch (DestTy->getScalarTypeKind()) { 5748 case Type::STK_Floating: 5749 return CK_FloatingCast; 5750 case Type::STK_Bool: 5751 return CK_FloatingToBoolean; 5752 case Type::STK_Integral: 5753 return CK_FloatingToIntegral; 5754 case Type::STK_FloatingComplex: 5755 Src = ImpCastExprToType(Src.get(), 5756 DestTy->castAs<ComplexType>()->getElementType(), 5757 CK_FloatingCast); 5758 return CK_FloatingRealToComplex; 5759 case Type::STK_IntegralComplex: 5760 Src = ImpCastExprToType(Src.get(), 5761 DestTy->castAs<ComplexType>()->getElementType(), 5762 CK_FloatingToIntegral); 5763 return CK_IntegralRealToComplex; 5764 case Type::STK_CPointer: 5765 case Type::STK_ObjCObjectPointer: 5766 case Type::STK_BlockPointer: 5767 llvm_unreachable("valid float->pointer cast?"); 5768 case Type::STK_MemberPointer: 5769 llvm_unreachable("member pointer type in C"); 5770 } 5771 llvm_unreachable("Should have returned before this"); 5772 5773 case Type::STK_FloatingComplex: 5774 switch (DestTy->getScalarTypeKind()) { 5775 case Type::STK_FloatingComplex: 5776 return CK_FloatingComplexCast; 5777 case Type::STK_IntegralComplex: 5778 return CK_FloatingComplexToIntegralComplex; 5779 case Type::STK_Floating: { 5780 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5781 if (Context.hasSameType(ET, DestTy)) 5782 return CK_FloatingComplexToReal; 5783 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5784 return CK_FloatingCast; 5785 } 5786 case Type::STK_Bool: 5787 return CK_FloatingComplexToBoolean; 5788 case Type::STK_Integral: 5789 Src = ImpCastExprToType(Src.get(), 5790 SrcTy->castAs<ComplexType>()->getElementType(), 5791 CK_FloatingComplexToReal); 5792 return CK_FloatingToIntegral; 5793 case Type::STK_CPointer: 5794 case Type::STK_ObjCObjectPointer: 5795 case Type::STK_BlockPointer: 5796 llvm_unreachable("valid complex float->pointer cast?"); 5797 case Type::STK_MemberPointer: 5798 llvm_unreachable("member pointer type in C"); 5799 } 5800 llvm_unreachable("Should have returned before this"); 5801 5802 case Type::STK_IntegralComplex: 5803 switch (DestTy->getScalarTypeKind()) { 5804 case Type::STK_FloatingComplex: 5805 return CK_IntegralComplexToFloatingComplex; 5806 case Type::STK_IntegralComplex: 5807 return CK_IntegralComplexCast; 5808 case Type::STK_Integral: { 5809 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5810 if (Context.hasSameType(ET, DestTy)) 5811 return CK_IntegralComplexToReal; 5812 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5813 return CK_IntegralCast; 5814 } 5815 case Type::STK_Bool: 5816 return CK_IntegralComplexToBoolean; 5817 case Type::STK_Floating: 5818 Src = ImpCastExprToType(Src.get(), 5819 SrcTy->castAs<ComplexType>()->getElementType(), 5820 CK_IntegralComplexToReal); 5821 return CK_IntegralToFloating; 5822 case Type::STK_CPointer: 5823 case Type::STK_ObjCObjectPointer: 5824 case Type::STK_BlockPointer: 5825 llvm_unreachable("valid complex int->pointer cast?"); 5826 case Type::STK_MemberPointer: 5827 llvm_unreachable("member pointer type in C"); 5828 } 5829 llvm_unreachable("Should have returned before this"); 5830 } 5831 5832 llvm_unreachable("Unhandled scalar cast"); 5833 } 5834 5835 static bool breakDownVectorType(QualType type, uint64_t &len, 5836 QualType &eltType) { 5837 // Vectors are simple. 5838 if (const VectorType *vecType = type->getAs<VectorType>()) { 5839 len = vecType->getNumElements(); 5840 eltType = vecType->getElementType(); 5841 assert(eltType->isScalarType()); 5842 return true; 5843 } 5844 5845 // We allow lax conversion to and from non-vector types, but only if 5846 // they're real types (i.e. non-complex, non-pointer scalar types). 5847 if (!type->isRealType()) return false; 5848 5849 len = 1; 5850 eltType = type; 5851 return true; 5852 } 5853 5854 /// Are the two types lax-compatible vector types? That is, given 5855 /// that one of them is a vector, do they have equal storage sizes, 5856 /// where the storage size is the number of elements times the element 5857 /// size? 5858 /// 5859 /// This will also return false if either of the types is neither a 5860 /// vector nor a real type. 5861 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5862 assert(destTy->isVectorType() || srcTy->isVectorType()); 5863 5864 // Disallow lax conversions between scalars and ExtVectors (these 5865 // conversions are allowed for other vector types because common headers 5866 // depend on them). Most scalar OP ExtVector cases are handled by the 5867 // splat path anyway, which does what we want (convert, not bitcast). 5868 // What this rules out for ExtVectors is crazy things like char4*float. 5869 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5870 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5871 5872 uint64_t srcLen, destLen; 5873 QualType srcEltTy, destEltTy; 5874 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5875 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5876 5877 // ASTContext::getTypeSize will return the size rounded up to a 5878 // power of 2, so instead of using that, we need to use the raw 5879 // element size multiplied by the element count. 5880 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5881 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5882 5883 return (srcLen * srcEltSize == destLen * destEltSize); 5884 } 5885 5886 /// Is this a legal conversion between two types, one of which is 5887 /// known to be a vector type? 5888 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5889 assert(destTy->isVectorType() || srcTy->isVectorType()); 5890 5891 if (!Context.getLangOpts().LaxVectorConversions) 5892 return false; 5893 return areLaxCompatibleVectorTypes(srcTy, destTy); 5894 } 5895 5896 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5897 CastKind &Kind) { 5898 assert(VectorTy->isVectorType() && "Not a vector type!"); 5899 5900 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5901 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5902 return Diag(R.getBegin(), 5903 Ty->isVectorType() ? 5904 diag::err_invalid_conversion_between_vectors : 5905 diag::err_invalid_conversion_between_vector_and_integer) 5906 << VectorTy << Ty << R; 5907 } else 5908 return Diag(R.getBegin(), 5909 diag::err_invalid_conversion_between_vector_and_scalar) 5910 << VectorTy << Ty << R; 5911 5912 Kind = CK_BitCast; 5913 return false; 5914 } 5915 5916 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5917 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5918 5919 if (DestElemTy == SplattedExpr->getType()) 5920 return SplattedExpr; 5921 5922 assert(DestElemTy->isFloatingType() || 5923 DestElemTy->isIntegralOrEnumerationType()); 5924 5925 CastKind CK; 5926 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5927 // OpenCL requires that we convert `true` boolean expressions to -1, but 5928 // only when splatting vectors. 5929 if (DestElemTy->isFloatingType()) { 5930 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5931 // in two steps: boolean to signed integral, then to floating. 5932 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5933 CK_BooleanToSignedIntegral); 5934 SplattedExpr = CastExprRes.get(); 5935 CK = CK_IntegralToFloating; 5936 } else { 5937 CK = CK_BooleanToSignedIntegral; 5938 } 5939 } else { 5940 ExprResult CastExprRes = SplattedExpr; 5941 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5942 if (CastExprRes.isInvalid()) 5943 return ExprError(); 5944 SplattedExpr = CastExprRes.get(); 5945 } 5946 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5947 } 5948 5949 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5950 Expr *CastExpr, CastKind &Kind) { 5951 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5952 5953 QualType SrcTy = CastExpr->getType(); 5954 5955 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5956 // an ExtVectorType. 5957 // In OpenCL, casts between vectors of different types are not allowed. 5958 // (See OpenCL 6.2). 5959 if (SrcTy->isVectorType()) { 5960 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5961 || (getLangOpts().OpenCL && 5962 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5963 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5964 << DestTy << SrcTy << R; 5965 return ExprError(); 5966 } 5967 Kind = CK_BitCast; 5968 return CastExpr; 5969 } 5970 5971 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5972 // conversion will take place first from scalar to elt type, and then 5973 // splat from elt type to vector. 5974 if (SrcTy->isPointerType()) 5975 return Diag(R.getBegin(), 5976 diag::err_invalid_conversion_between_vector_and_scalar) 5977 << DestTy << SrcTy << R; 5978 5979 Kind = CK_VectorSplat; 5980 return prepareVectorSplat(DestTy, CastExpr); 5981 } 5982 5983 ExprResult 5984 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5985 Declarator &D, ParsedType &Ty, 5986 SourceLocation RParenLoc, Expr *CastExpr) { 5987 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5988 "ActOnCastExpr(): missing type or expr"); 5989 5990 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5991 if (D.isInvalidType()) 5992 return ExprError(); 5993 5994 if (getLangOpts().CPlusPlus) { 5995 // Check that there are no default arguments (C++ only). 5996 CheckExtraCXXDefaultArguments(D); 5997 } else { 5998 // Make sure any TypoExprs have been dealt with. 5999 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6000 if (!Res.isUsable()) 6001 return ExprError(); 6002 CastExpr = Res.get(); 6003 } 6004 6005 checkUnusedDeclAttributes(D); 6006 6007 QualType castType = castTInfo->getType(); 6008 Ty = CreateParsedType(castType, castTInfo); 6009 6010 bool isVectorLiteral = false; 6011 6012 // Check for an altivec or OpenCL literal, 6013 // i.e. all the elements are integer constants. 6014 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6015 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6016 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6017 && castType->isVectorType() && (PE || PLE)) { 6018 if (PLE && PLE->getNumExprs() == 0) { 6019 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6020 return ExprError(); 6021 } 6022 if (PE || PLE->getNumExprs() == 1) { 6023 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6024 if (!E->getType()->isVectorType()) 6025 isVectorLiteral = true; 6026 } 6027 else 6028 isVectorLiteral = true; 6029 } 6030 6031 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6032 // then handle it as such. 6033 if (isVectorLiteral) 6034 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6035 6036 // If the Expr being casted is a ParenListExpr, handle it specially. 6037 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6038 // sequence of BinOp comma operators. 6039 if (isa<ParenListExpr>(CastExpr)) { 6040 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6041 if (Result.isInvalid()) return ExprError(); 6042 CastExpr = Result.get(); 6043 } 6044 6045 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6046 !getSourceManager().isInSystemMacro(LParenLoc)) 6047 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6048 6049 CheckTollFreeBridgeCast(castType, CastExpr); 6050 6051 CheckObjCBridgeRelatedCast(castType, CastExpr); 6052 6053 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6054 6055 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6056 } 6057 6058 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6059 SourceLocation RParenLoc, Expr *E, 6060 TypeSourceInfo *TInfo) { 6061 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6062 "Expected paren or paren list expression"); 6063 6064 Expr **exprs; 6065 unsigned numExprs; 6066 Expr *subExpr; 6067 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6068 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6069 LiteralLParenLoc = PE->getLParenLoc(); 6070 LiteralRParenLoc = PE->getRParenLoc(); 6071 exprs = PE->getExprs(); 6072 numExprs = PE->getNumExprs(); 6073 } else { // isa<ParenExpr> by assertion at function entrance 6074 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6075 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6076 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6077 exprs = &subExpr; 6078 numExprs = 1; 6079 } 6080 6081 QualType Ty = TInfo->getType(); 6082 assert(Ty->isVectorType() && "Expected vector type"); 6083 6084 SmallVector<Expr *, 8> initExprs; 6085 const VectorType *VTy = Ty->getAs<VectorType>(); 6086 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6087 6088 // '(...)' form of vector initialization in AltiVec: the number of 6089 // initializers must be one or must match the size of the vector. 6090 // If a single value is specified in the initializer then it will be 6091 // replicated to all the components of the vector 6092 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6093 // The number of initializers must be one or must match the size of the 6094 // vector. If a single value is specified in the initializer then it will 6095 // be replicated to all the components of the vector 6096 if (numExprs == 1) { 6097 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6098 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6099 if (Literal.isInvalid()) 6100 return ExprError(); 6101 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6102 PrepareScalarCast(Literal, ElemTy)); 6103 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6104 } 6105 else if (numExprs < numElems) { 6106 Diag(E->getExprLoc(), 6107 diag::err_incorrect_number_of_vector_initializers); 6108 return ExprError(); 6109 } 6110 else 6111 initExprs.append(exprs, exprs + numExprs); 6112 } 6113 else { 6114 // For OpenCL, when the number of initializers is a single value, 6115 // it will be replicated to all components of the vector. 6116 if (getLangOpts().OpenCL && 6117 VTy->getVectorKind() == VectorType::GenericVector && 6118 numExprs == 1) { 6119 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6120 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6121 if (Literal.isInvalid()) 6122 return ExprError(); 6123 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6124 PrepareScalarCast(Literal, ElemTy)); 6125 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6126 } 6127 6128 initExprs.append(exprs, exprs + numExprs); 6129 } 6130 // FIXME: This means that pretty-printing the final AST will produce curly 6131 // braces instead of the original commas. 6132 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6133 initExprs, LiteralRParenLoc); 6134 initE->setType(Ty); 6135 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6136 } 6137 6138 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6139 /// the ParenListExpr into a sequence of comma binary operators. 6140 ExprResult 6141 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6142 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6143 if (!E) 6144 return OrigExpr; 6145 6146 ExprResult Result(E->getExpr(0)); 6147 6148 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6149 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6150 E->getExpr(i)); 6151 6152 if (Result.isInvalid()) return ExprError(); 6153 6154 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6155 } 6156 6157 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6158 SourceLocation R, 6159 MultiExprArg Val) { 6160 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6161 return expr; 6162 } 6163 6164 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6165 /// constant and the other is not a pointer. Returns true if a diagnostic is 6166 /// emitted. 6167 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6168 SourceLocation QuestionLoc) { 6169 Expr *NullExpr = LHSExpr; 6170 Expr *NonPointerExpr = RHSExpr; 6171 Expr::NullPointerConstantKind NullKind = 6172 NullExpr->isNullPointerConstant(Context, 6173 Expr::NPC_ValueDependentIsNotNull); 6174 6175 if (NullKind == Expr::NPCK_NotNull) { 6176 NullExpr = RHSExpr; 6177 NonPointerExpr = LHSExpr; 6178 NullKind = 6179 NullExpr->isNullPointerConstant(Context, 6180 Expr::NPC_ValueDependentIsNotNull); 6181 } 6182 6183 if (NullKind == Expr::NPCK_NotNull) 6184 return false; 6185 6186 if (NullKind == Expr::NPCK_ZeroExpression) 6187 return false; 6188 6189 if (NullKind == Expr::NPCK_ZeroLiteral) { 6190 // In this case, check to make sure that we got here from a "NULL" 6191 // string in the source code. 6192 NullExpr = NullExpr->IgnoreParenImpCasts(); 6193 SourceLocation loc = NullExpr->getExprLoc(); 6194 if (!findMacroSpelling(loc, "NULL")) 6195 return false; 6196 } 6197 6198 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6199 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6200 << NonPointerExpr->getType() << DiagType 6201 << NonPointerExpr->getSourceRange(); 6202 return true; 6203 } 6204 6205 /// \brief Return false if the condition expression is valid, true otherwise. 6206 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6207 QualType CondTy = Cond->getType(); 6208 6209 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6210 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6211 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6212 << CondTy << Cond->getSourceRange(); 6213 return true; 6214 } 6215 6216 // C99 6.5.15p2 6217 if (CondTy->isScalarType()) return false; 6218 6219 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6220 << CondTy << Cond->getSourceRange(); 6221 return true; 6222 } 6223 6224 /// \brief Handle when one or both operands are void type. 6225 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6226 ExprResult &RHS) { 6227 Expr *LHSExpr = LHS.get(); 6228 Expr *RHSExpr = RHS.get(); 6229 6230 if (!LHSExpr->getType()->isVoidType()) 6231 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6232 << RHSExpr->getSourceRange(); 6233 if (!RHSExpr->getType()->isVoidType()) 6234 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6235 << LHSExpr->getSourceRange(); 6236 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6237 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6238 return S.Context.VoidTy; 6239 } 6240 6241 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6242 /// true otherwise. 6243 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6244 QualType PointerTy) { 6245 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6246 !NullExpr.get()->isNullPointerConstant(S.Context, 6247 Expr::NPC_ValueDependentIsNull)) 6248 return true; 6249 6250 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6251 return false; 6252 } 6253 6254 /// \brief Checks compatibility between two pointers and return the resulting 6255 /// type. 6256 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6257 ExprResult &RHS, 6258 SourceLocation Loc) { 6259 QualType LHSTy = LHS.get()->getType(); 6260 QualType RHSTy = RHS.get()->getType(); 6261 6262 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6263 // Two identical pointers types are always compatible. 6264 return LHSTy; 6265 } 6266 6267 QualType lhptee, rhptee; 6268 6269 // Get the pointee types. 6270 bool IsBlockPointer = false; 6271 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6272 lhptee = LHSBTy->getPointeeType(); 6273 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6274 IsBlockPointer = true; 6275 } else { 6276 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6277 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6278 } 6279 6280 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6281 // differently qualified versions of compatible types, the result type is 6282 // a pointer to an appropriately qualified version of the composite 6283 // type. 6284 6285 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6286 // clause doesn't make sense for our extensions. E.g. address space 2 should 6287 // be incompatible with address space 3: they may live on different devices or 6288 // anything. 6289 Qualifiers lhQual = lhptee.getQualifiers(); 6290 Qualifiers rhQual = rhptee.getQualifiers(); 6291 6292 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6293 lhQual.removeCVRQualifiers(); 6294 rhQual.removeCVRQualifiers(); 6295 6296 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6297 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6298 6299 // For OpenCL: 6300 // 1. If LHS and RHS types match exactly and: 6301 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6302 // (b) AS overlap => generate addrspacecast 6303 // (c) AS don't overlap => give an error 6304 // 2. if LHS and RHS types don't match: 6305 // (a) AS match => use standard C rules, generate bitcast 6306 // (b) AS overlap => generate addrspacecast instead of bitcast 6307 // (c) AS don't overlap => give an error 6308 6309 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6310 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6311 6312 // OpenCL cases 1c, 2a, 2b, and 2c. 6313 if (CompositeTy.isNull()) { 6314 // In this situation, we assume void* type. No especially good 6315 // reason, but this is what gcc does, and we do have to pick 6316 // to get a consistent AST. 6317 QualType incompatTy; 6318 if (S.getLangOpts().OpenCL) { 6319 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6320 // spaces is disallowed. 6321 unsigned ResultAddrSpace; 6322 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6323 // Cases 2a and 2b. 6324 ResultAddrSpace = lhQual.getAddressSpace(); 6325 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6326 // Cases 2a and 2b. 6327 ResultAddrSpace = rhQual.getAddressSpace(); 6328 } else { 6329 // Cases 1c and 2c. 6330 S.Diag(Loc, 6331 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6332 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6333 << RHS.get()->getSourceRange(); 6334 return QualType(); 6335 } 6336 6337 // Continue handling cases 2a and 2b. 6338 incompatTy = S.Context.getPointerType( 6339 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6340 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6341 (lhQual.getAddressSpace() != ResultAddrSpace) 6342 ? CK_AddressSpaceConversion /* 2b */ 6343 : CK_BitCast /* 2a */); 6344 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6345 (rhQual.getAddressSpace() != ResultAddrSpace) 6346 ? CK_AddressSpaceConversion /* 2b */ 6347 : CK_BitCast /* 2a */); 6348 } else { 6349 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6350 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6351 << RHS.get()->getSourceRange(); 6352 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6353 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6354 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6355 } 6356 return incompatTy; 6357 } 6358 6359 // The pointer types are compatible. 6360 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6361 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6362 if (IsBlockPointer) 6363 ResultTy = S.Context.getBlockPointerType(ResultTy); 6364 else { 6365 // Cases 1a and 1b for OpenCL. 6366 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6367 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6368 ? CK_BitCast /* 1a */ 6369 : CK_AddressSpaceConversion /* 1b */; 6370 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6371 ? CK_BitCast /* 1a */ 6372 : CK_AddressSpaceConversion /* 1b */; 6373 ResultTy = S.Context.getPointerType(ResultTy); 6374 } 6375 6376 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6377 // if the target type does not change. 6378 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6379 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6380 return ResultTy; 6381 } 6382 6383 /// \brief Return the resulting type when the operands are both block pointers. 6384 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6385 ExprResult &LHS, 6386 ExprResult &RHS, 6387 SourceLocation Loc) { 6388 QualType LHSTy = LHS.get()->getType(); 6389 QualType RHSTy = RHS.get()->getType(); 6390 6391 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6392 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6393 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6394 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6395 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6396 return destType; 6397 } 6398 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6399 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6400 << RHS.get()->getSourceRange(); 6401 return QualType(); 6402 } 6403 6404 // We have 2 block pointer types. 6405 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6406 } 6407 6408 /// \brief Return the resulting type when the operands are both pointers. 6409 static QualType 6410 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6411 ExprResult &RHS, 6412 SourceLocation Loc) { 6413 // get the pointer types 6414 QualType LHSTy = LHS.get()->getType(); 6415 QualType RHSTy = RHS.get()->getType(); 6416 6417 // get the "pointed to" types 6418 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6419 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6420 6421 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6422 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6423 // Figure out necessary qualifiers (C99 6.5.15p6) 6424 QualType destPointee 6425 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6426 QualType destType = S.Context.getPointerType(destPointee); 6427 // Add qualifiers if necessary. 6428 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6429 // Promote to void*. 6430 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6431 return destType; 6432 } 6433 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6434 QualType destPointee 6435 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6436 QualType destType = S.Context.getPointerType(destPointee); 6437 // Add qualifiers if necessary. 6438 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6439 // Promote to void*. 6440 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6441 return destType; 6442 } 6443 6444 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6445 } 6446 6447 /// \brief Return false if the first expression is not an integer and the second 6448 /// expression is not a pointer, true otherwise. 6449 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6450 Expr* PointerExpr, SourceLocation Loc, 6451 bool IsIntFirstExpr) { 6452 if (!PointerExpr->getType()->isPointerType() || 6453 !Int.get()->getType()->isIntegerType()) 6454 return false; 6455 6456 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6457 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6458 6459 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6460 << Expr1->getType() << Expr2->getType() 6461 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6462 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6463 CK_IntegralToPointer); 6464 return true; 6465 } 6466 6467 /// \brief Simple conversion between integer and floating point types. 6468 /// 6469 /// Used when handling the OpenCL conditional operator where the 6470 /// condition is a vector while the other operands are scalar. 6471 /// 6472 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6473 /// types are either integer or floating type. Between the two 6474 /// operands, the type with the higher rank is defined as the "result 6475 /// type". The other operand needs to be promoted to the same type. No 6476 /// other type promotion is allowed. We cannot use 6477 /// UsualArithmeticConversions() for this purpose, since it always 6478 /// promotes promotable types. 6479 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6480 ExprResult &RHS, 6481 SourceLocation QuestionLoc) { 6482 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6483 if (LHS.isInvalid()) 6484 return QualType(); 6485 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6486 if (RHS.isInvalid()) 6487 return QualType(); 6488 6489 // For conversion purposes, we ignore any qualifiers. 6490 // For example, "const float" and "float" are equivalent. 6491 QualType LHSType = 6492 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6493 QualType RHSType = 6494 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6495 6496 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6497 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6498 << LHSType << LHS.get()->getSourceRange(); 6499 return QualType(); 6500 } 6501 6502 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6503 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6504 << RHSType << RHS.get()->getSourceRange(); 6505 return QualType(); 6506 } 6507 6508 // If both types are identical, no conversion is needed. 6509 if (LHSType == RHSType) 6510 return LHSType; 6511 6512 // Now handle "real" floating types (i.e. float, double, long double). 6513 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6514 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6515 /*IsCompAssign = */ false); 6516 6517 // Finally, we have two differing integer types. 6518 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6519 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6520 } 6521 6522 /// \brief Convert scalar operands to a vector that matches the 6523 /// condition in length. 6524 /// 6525 /// Used when handling the OpenCL conditional operator where the 6526 /// condition is a vector while the other operands are scalar. 6527 /// 6528 /// We first compute the "result type" for the scalar operands 6529 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6530 /// into a vector of that type where the length matches the condition 6531 /// vector type. s6.11.6 requires that the element types of the result 6532 /// and the condition must have the same number of bits. 6533 static QualType 6534 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6535 QualType CondTy, SourceLocation QuestionLoc) { 6536 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6537 if (ResTy.isNull()) return QualType(); 6538 6539 const VectorType *CV = CondTy->getAs<VectorType>(); 6540 assert(CV); 6541 6542 // Determine the vector result type 6543 unsigned NumElements = CV->getNumElements(); 6544 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6545 6546 // Ensure that all types have the same number of bits 6547 if (S.Context.getTypeSize(CV->getElementType()) 6548 != S.Context.getTypeSize(ResTy)) { 6549 // Since VectorTy is created internally, it does not pretty print 6550 // with an OpenCL name. Instead, we just print a description. 6551 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6552 SmallString<64> Str; 6553 llvm::raw_svector_ostream OS(Str); 6554 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6555 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6556 << CondTy << OS.str(); 6557 return QualType(); 6558 } 6559 6560 // Convert operands to the vector result type 6561 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6562 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6563 6564 return VectorTy; 6565 } 6566 6567 /// \brief Return false if this is a valid OpenCL condition vector 6568 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6569 SourceLocation QuestionLoc) { 6570 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6571 // integral type. 6572 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6573 assert(CondTy); 6574 QualType EleTy = CondTy->getElementType(); 6575 if (EleTy->isIntegerType()) return false; 6576 6577 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6578 << Cond->getType() << Cond->getSourceRange(); 6579 return true; 6580 } 6581 6582 /// \brief Return false if the vector condition type and the vector 6583 /// result type are compatible. 6584 /// 6585 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6586 /// number of elements, and their element types have the same number 6587 /// of bits. 6588 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6589 SourceLocation QuestionLoc) { 6590 const VectorType *CV = CondTy->getAs<VectorType>(); 6591 const VectorType *RV = VecResTy->getAs<VectorType>(); 6592 assert(CV && RV); 6593 6594 if (CV->getNumElements() != RV->getNumElements()) { 6595 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6596 << CondTy << VecResTy; 6597 return true; 6598 } 6599 6600 QualType CVE = CV->getElementType(); 6601 QualType RVE = RV->getElementType(); 6602 6603 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6604 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6605 << CondTy << VecResTy; 6606 return true; 6607 } 6608 6609 return false; 6610 } 6611 6612 /// \brief Return the resulting type for the conditional operator in 6613 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6614 /// s6.3.i) when the condition is a vector type. 6615 static QualType 6616 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6617 ExprResult &LHS, ExprResult &RHS, 6618 SourceLocation QuestionLoc) { 6619 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6620 if (Cond.isInvalid()) 6621 return QualType(); 6622 QualType CondTy = Cond.get()->getType(); 6623 6624 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6625 return QualType(); 6626 6627 // If either operand is a vector then find the vector type of the 6628 // result as specified in OpenCL v1.1 s6.3.i. 6629 if (LHS.get()->getType()->isVectorType() || 6630 RHS.get()->getType()->isVectorType()) { 6631 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6632 /*isCompAssign*/false, 6633 /*AllowBothBool*/true, 6634 /*AllowBoolConversions*/false); 6635 if (VecResTy.isNull()) return QualType(); 6636 // The result type must match the condition type as specified in 6637 // OpenCL v1.1 s6.11.6. 6638 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6639 return QualType(); 6640 return VecResTy; 6641 } 6642 6643 // Both operands are scalar. 6644 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6645 } 6646 6647 /// \brief Return true if the Expr is block type 6648 static bool checkBlockType(Sema &S, const Expr *E) { 6649 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6650 QualType Ty = CE->getCallee()->getType(); 6651 if (Ty->isBlockPointerType()) { 6652 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6653 return true; 6654 } 6655 } 6656 return false; 6657 } 6658 6659 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6660 /// In that case, LHS = cond. 6661 /// C99 6.5.15 6662 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6663 ExprResult &RHS, ExprValueKind &VK, 6664 ExprObjectKind &OK, 6665 SourceLocation QuestionLoc) { 6666 6667 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6668 if (!LHSResult.isUsable()) return QualType(); 6669 LHS = LHSResult; 6670 6671 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6672 if (!RHSResult.isUsable()) return QualType(); 6673 RHS = RHSResult; 6674 6675 // C++ is sufficiently different to merit its own checker. 6676 if (getLangOpts().CPlusPlus) 6677 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6678 6679 VK = VK_RValue; 6680 OK = OK_Ordinary; 6681 6682 // The OpenCL operator with a vector condition is sufficiently 6683 // different to merit its own checker. 6684 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6685 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6686 6687 // First, check the condition. 6688 Cond = UsualUnaryConversions(Cond.get()); 6689 if (Cond.isInvalid()) 6690 return QualType(); 6691 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6692 return QualType(); 6693 6694 // Now check the two expressions. 6695 if (LHS.get()->getType()->isVectorType() || 6696 RHS.get()->getType()->isVectorType()) 6697 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6698 /*AllowBothBool*/true, 6699 /*AllowBoolConversions*/false); 6700 6701 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6702 if (LHS.isInvalid() || RHS.isInvalid()) 6703 return QualType(); 6704 6705 QualType LHSTy = LHS.get()->getType(); 6706 QualType RHSTy = RHS.get()->getType(); 6707 6708 // Diagnose attempts to convert between __float128 and long double where 6709 // such conversions currently can't be handled. 6710 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6711 Diag(QuestionLoc, 6712 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6713 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6714 return QualType(); 6715 } 6716 6717 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6718 // selection operator (?:). 6719 if (getLangOpts().OpenCL && 6720 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6721 return QualType(); 6722 } 6723 6724 // If both operands have arithmetic type, do the usual arithmetic conversions 6725 // to find a common type: C99 6.5.15p3,5. 6726 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6727 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6728 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6729 6730 return ResTy; 6731 } 6732 6733 // If both operands are the same structure or union type, the result is that 6734 // type. 6735 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6736 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6737 if (LHSRT->getDecl() == RHSRT->getDecl()) 6738 // "If both the operands have structure or union type, the result has 6739 // that type." This implies that CV qualifiers are dropped. 6740 return LHSTy.getUnqualifiedType(); 6741 // FIXME: Type of conditional expression must be complete in C mode. 6742 } 6743 6744 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6745 // The following || allows only one side to be void (a GCC-ism). 6746 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6747 return checkConditionalVoidType(*this, LHS, RHS); 6748 } 6749 6750 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6751 // the type of the other operand." 6752 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6753 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6754 6755 // All objective-c pointer type analysis is done here. 6756 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6757 QuestionLoc); 6758 if (LHS.isInvalid() || RHS.isInvalid()) 6759 return QualType(); 6760 if (!compositeType.isNull()) 6761 return compositeType; 6762 6763 6764 // Handle block pointer types. 6765 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6766 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6767 QuestionLoc); 6768 6769 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6770 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6771 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6772 QuestionLoc); 6773 6774 // GCC compatibility: soften pointer/integer mismatch. Note that 6775 // null pointers have been filtered out by this point. 6776 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6777 /*isIntFirstExpr=*/true)) 6778 return RHSTy; 6779 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6780 /*isIntFirstExpr=*/false)) 6781 return LHSTy; 6782 6783 // Emit a better diagnostic if one of the expressions is a null pointer 6784 // constant and the other is not a pointer type. In this case, the user most 6785 // likely forgot to take the address of the other expression. 6786 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6787 return QualType(); 6788 6789 // Otherwise, the operands are not compatible. 6790 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6791 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6792 << RHS.get()->getSourceRange(); 6793 return QualType(); 6794 } 6795 6796 /// FindCompositeObjCPointerType - Helper method to find composite type of 6797 /// two objective-c pointer types of the two input expressions. 6798 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6799 SourceLocation QuestionLoc) { 6800 QualType LHSTy = LHS.get()->getType(); 6801 QualType RHSTy = RHS.get()->getType(); 6802 6803 // Handle things like Class and struct objc_class*. Here we case the result 6804 // to the pseudo-builtin, because that will be implicitly cast back to the 6805 // redefinition type if an attempt is made to access its fields. 6806 if (LHSTy->isObjCClassType() && 6807 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6808 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6809 return LHSTy; 6810 } 6811 if (RHSTy->isObjCClassType() && 6812 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6813 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6814 return RHSTy; 6815 } 6816 // And the same for struct objc_object* / id 6817 if (LHSTy->isObjCIdType() && 6818 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6819 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6820 return LHSTy; 6821 } 6822 if (RHSTy->isObjCIdType() && 6823 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6824 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6825 return RHSTy; 6826 } 6827 // And the same for struct objc_selector* / SEL 6828 if (Context.isObjCSelType(LHSTy) && 6829 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6830 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6831 return LHSTy; 6832 } 6833 if (Context.isObjCSelType(RHSTy) && 6834 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6835 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6836 return RHSTy; 6837 } 6838 // Check constraints for Objective-C object pointers types. 6839 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6840 6841 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6842 // Two identical object pointer types are always compatible. 6843 return LHSTy; 6844 } 6845 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6846 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6847 QualType compositeType = LHSTy; 6848 6849 // If both operands are interfaces and either operand can be 6850 // assigned to the other, use that type as the composite 6851 // type. This allows 6852 // xxx ? (A*) a : (B*) b 6853 // where B is a subclass of A. 6854 // 6855 // Additionally, as for assignment, if either type is 'id' 6856 // allow silent coercion. Finally, if the types are 6857 // incompatible then make sure to use 'id' as the composite 6858 // type so the result is acceptable for sending messages to. 6859 6860 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6861 // It could return the composite type. 6862 if (!(compositeType = 6863 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6864 // Nothing more to do. 6865 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6866 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6867 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6868 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6869 } else if ((LHSTy->isObjCQualifiedIdType() || 6870 RHSTy->isObjCQualifiedIdType()) && 6871 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6872 // Need to handle "id<xx>" explicitly. 6873 // GCC allows qualified id and any Objective-C type to devolve to 6874 // id. Currently localizing to here until clear this should be 6875 // part of ObjCQualifiedIdTypesAreCompatible. 6876 compositeType = Context.getObjCIdType(); 6877 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6878 compositeType = Context.getObjCIdType(); 6879 } else { 6880 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6881 << LHSTy << RHSTy 6882 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6883 QualType incompatTy = Context.getObjCIdType(); 6884 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6885 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6886 return incompatTy; 6887 } 6888 // The object pointer types are compatible. 6889 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6890 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6891 return compositeType; 6892 } 6893 // Check Objective-C object pointer types and 'void *' 6894 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6895 if (getLangOpts().ObjCAutoRefCount) { 6896 // ARC forbids the implicit conversion of object pointers to 'void *', 6897 // so these types are not compatible. 6898 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6899 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6900 LHS = RHS = true; 6901 return QualType(); 6902 } 6903 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6904 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6905 QualType destPointee 6906 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6907 QualType destType = Context.getPointerType(destPointee); 6908 // Add qualifiers if necessary. 6909 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6910 // Promote to void*. 6911 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6912 return destType; 6913 } 6914 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6915 if (getLangOpts().ObjCAutoRefCount) { 6916 // ARC forbids the implicit conversion of object pointers to 'void *', 6917 // so these types are not compatible. 6918 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6919 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6920 LHS = RHS = true; 6921 return QualType(); 6922 } 6923 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6924 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6925 QualType destPointee 6926 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6927 QualType destType = Context.getPointerType(destPointee); 6928 // Add qualifiers if necessary. 6929 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6930 // Promote to void*. 6931 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6932 return destType; 6933 } 6934 return QualType(); 6935 } 6936 6937 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6938 /// ParenRange in parentheses. 6939 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6940 const PartialDiagnostic &Note, 6941 SourceRange ParenRange) { 6942 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6943 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6944 EndLoc.isValid()) { 6945 Self.Diag(Loc, Note) 6946 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6947 << FixItHint::CreateInsertion(EndLoc, ")"); 6948 } else { 6949 // We can't display the parentheses, so just show the bare note. 6950 Self.Diag(Loc, Note) << ParenRange; 6951 } 6952 } 6953 6954 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6955 return BinaryOperator::isAdditiveOp(Opc) || 6956 BinaryOperator::isMultiplicativeOp(Opc) || 6957 BinaryOperator::isShiftOp(Opc); 6958 } 6959 6960 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6961 /// expression, either using a built-in or overloaded operator, 6962 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6963 /// expression. 6964 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6965 Expr **RHSExprs) { 6966 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6967 E = E->IgnoreImpCasts(); 6968 E = E->IgnoreConversionOperator(); 6969 E = E->IgnoreImpCasts(); 6970 6971 // Built-in binary operator. 6972 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6973 if (IsArithmeticOp(OP->getOpcode())) { 6974 *Opcode = OP->getOpcode(); 6975 *RHSExprs = OP->getRHS(); 6976 return true; 6977 } 6978 } 6979 6980 // Overloaded operator. 6981 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6982 if (Call->getNumArgs() != 2) 6983 return false; 6984 6985 // Make sure this is really a binary operator that is safe to pass into 6986 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6987 OverloadedOperatorKind OO = Call->getOperator(); 6988 if (OO < OO_Plus || OO > OO_Arrow || 6989 OO == OO_PlusPlus || OO == OO_MinusMinus) 6990 return false; 6991 6992 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6993 if (IsArithmeticOp(OpKind)) { 6994 *Opcode = OpKind; 6995 *RHSExprs = Call->getArg(1); 6996 return true; 6997 } 6998 } 6999 7000 return false; 7001 } 7002 7003 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7004 /// or is a logical expression such as (x==y) which has int type, but is 7005 /// commonly interpreted as boolean. 7006 static bool ExprLooksBoolean(Expr *E) { 7007 E = E->IgnoreParenImpCasts(); 7008 7009 if (E->getType()->isBooleanType()) 7010 return true; 7011 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7012 return OP->isComparisonOp() || OP->isLogicalOp(); 7013 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7014 return OP->getOpcode() == UO_LNot; 7015 if (E->getType()->isPointerType()) 7016 return true; 7017 7018 return false; 7019 } 7020 7021 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7022 /// and binary operator are mixed in a way that suggests the programmer assumed 7023 /// the conditional operator has higher precedence, for example: 7024 /// "int x = a + someBinaryCondition ? 1 : 2". 7025 static void DiagnoseConditionalPrecedence(Sema &Self, 7026 SourceLocation OpLoc, 7027 Expr *Condition, 7028 Expr *LHSExpr, 7029 Expr *RHSExpr) { 7030 BinaryOperatorKind CondOpcode; 7031 Expr *CondRHS; 7032 7033 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7034 return; 7035 if (!ExprLooksBoolean(CondRHS)) 7036 return; 7037 7038 // The condition is an arithmetic binary expression, with a right- 7039 // hand side that looks boolean, so warn. 7040 7041 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7042 << Condition->getSourceRange() 7043 << BinaryOperator::getOpcodeStr(CondOpcode); 7044 7045 SuggestParentheses(Self, OpLoc, 7046 Self.PDiag(diag::note_precedence_silence) 7047 << BinaryOperator::getOpcodeStr(CondOpcode), 7048 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7049 7050 SuggestParentheses(Self, OpLoc, 7051 Self.PDiag(diag::note_precedence_conditional_first), 7052 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7053 } 7054 7055 /// Compute the nullability of a conditional expression. 7056 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7057 QualType LHSTy, QualType RHSTy, 7058 ASTContext &Ctx) { 7059 if (!ResTy->isAnyPointerType()) 7060 return ResTy; 7061 7062 auto GetNullability = [&Ctx](QualType Ty) { 7063 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7064 if (Kind) 7065 return *Kind; 7066 return NullabilityKind::Unspecified; 7067 }; 7068 7069 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7070 NullabilityKind MergedKind; 7071 7072 // Compute nullability of a binary conditional expression. 7073 if (IsBin) { 7074 if (LHSKind == NullabilityKind::NonNull) 7075 MergedKind = NullabilityKind::NonNull; 7076 else 7077 MergedKind = RHSKind; 7078 // Compute nullability of a normal conditional expression. 7079 } else { 7080 if (LHSKind == NullabilityKind::Nullable || 7081 RHSKind == NullabilityKind::Nullable) 7082 MergedKind = NullabilityKind::Nullable; 7083 else if (LHSKind == NullabilityKind::NonNull) 7084 MergedKind = RHSKind; 7085 else if (RHSKind == NullabilityKind::NonNull) 7086 MergedKind = LHSKind; 7087 else 7088 MergedKind = NullabilityKind::Unspecified; 7089 } 7090 7091 // Return if ResTy already has the correct nullability. 7092 if (GetNullability(ResTy) == MergedKind) 7093 return ResTy; 7094 7095 // Strip all nullability from ResTy. 7096 while (ResTy->getNullability(Ctx)) 7097 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7098 7099 // Create a new AttributedType with the new nullability kind. 7100 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7101 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7102 } 7103 7104 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7105 /// in the case of a the GNU conditional expr extension. 7106 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7107 SourceLocation ColonLoc, 7108 Expr *CondExpr, Expr *LHSExpr, 7109 Expr *RHSExpr) { 7110 if (!getLangOpts().CPlusPlus) { 7111 // C cannot handle TypoExpr nodes in the condition because it 7112 // doesn't handle dependent types properly, so make sure any TypoExprs have 7113 // been dealt with before checking the operands. 7114 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7115 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7116 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7117 7118 if (!CondResult.isUsable()) 7119 return ExprError(); 7120 7121 if (LHSExpr) { 7122 if (!LHSResult.isUsable()) 7123 return ExprError(); 7124 } 7125 7126 if (!RHSResult.isUsable()) 7127 return ExprError(); 7128 7129 CondExpr = CondResult.get(); 7130 LHSExpr = LHSResult.get(); 7131 RHSExpr = RHSResult.get(); 7132 } 7133 7134 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7135 // was the condition. 7136 OpaqueValueExpr *opaqueValue = nullptr; 7137 Expr *commonExpr = nullptr; 7138 if (!LHSExpr) { 7139 commonExpr = CondExpr; 7140 // Lower out placeholder types first. This is important so that we don't 7141 // try to capture a placeholder. This happens in few cases in C++; such 7142 // as Objective-C++'s dictionary subscripting syntax. 7143 if (commonExpr->hasPlaceholderType()) { 7144 ExprResult result = CheckPlaceholderExpr(commonExpr); 7145 if (!result.isUsable()) return ExprError(); 7146 commonExpr = result.get(); 7147 } 7148 // We usually want to apply unary conversions *before* saving, except 7149 // in the special case of a C++ l-value conditional. 7150 if (!(getLangOpts().CPlusPlus 7151 && !commonExpr->isTypeDependent() 7152 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7153 && commonExpr->isGLValue() 7154 && commonExpr->isOrdinaryOrBitFieldObject() 7155 && RHSExpr->isOrdinaryOrBitFieldObject() 7156 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7157 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7158 if (commonRes.isInvalid()) 7159 return ExprError(); 7160 commonExpr = commonRes.get(); 7161 } 7162 7163 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7164 commonExpr->getType(), 7165 commonExpr->getValueKind(), 7166 commonExpr->getObjectKind(), 7167 commonExpr); 7168 LHSExpr = CondExpr = opaqueValue; 7169 } 7170 7171 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7172 ExprValueKind VK = VK_RValue; 7173 ExprObjectKind OK = OK_Ordinary; 7174 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7175 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7176 VK, OK, QuestionLoc); 7177 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7178 RHS.isInvalid()) 7179 return ExprError(); 7180 7181 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7182 RHS.get()); 7183 7184 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7185 7186 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7187 Context); 7188 7189 if (!commonExpr) 7190 return new (Context) 7191 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7192 RHS.get(), result, VK, OK); 7193 7194 return new (Context) BinaryConditionalOperator( 7195 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7196 ColonLoc, result, VK, OK); 7197 } 7198 7199 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7200 // being closely modeled after the C99 spec:-). The odd characteristic of this 7201 // routine is it effectively iqnores the qualifiers on the top level pointee. 7202 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7203 // FIXME: add a couple examples in this comment. 7204 static Sema::AssignConvertType 7205 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7206 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7207 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7208 7209 // get the "pointed to" type (ignoring qualifiers at the top level) 7210 const Type *lhptee, *rhptee; 7211 Qualifiers lhq, rhq; 7212 std::tie(lhptee, lhq) = 7213 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7214 std::tie(rhptee, rhq) = 7215 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7216 7217 Sema::AssignConvertType ConvTy = Sema::Compatible; 7218 7219 // C99 6.5.16.1p1: This following citation is common to constraints 7220 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7221 // qualifiers of the type *pointed to* by the right; 7222 7223 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7224 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7225 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7226 // Ignore lifetime for further calculation. 7227 lhq.removeObjCLifetime(); 7228 rhq.removeObjCLifetime(); 7229 } 7230 7231 if (!lhq.compatiblyIncludes(rhq)) { 7232 // Treat address-space mismatches as fatal. TODO: address subspaces 7233 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7234 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7235 7236 // It's okay to add or remove GC or lifetime qualifiers when converting to 7237 // and from void*. 7238 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7239 .compatiblyIncludes( 7240 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7241 && (lhptee->isVoidType() || rhptee->isVoidType())) 7242 ; // keep old 7243 7244 // Treat lifetime mismatches as fatal. 7245 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7246 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7247 7248 // For GCC/MS compatibility, other qualifier mismatches are treated 7249 // as still compatible in C. 7250 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7251 } 7252 7253 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7254 // incomplete type and the other is a pointer to a qualified or unqualified 7255 // version of void... 7256 if (lhptee->isVoidType()) { 7257 if (rhptee->isIncompleteOrObjectType()) 7258 return ConvTy; 7259 7260 // As an extension, we allow cast to/from void* to function pointer. 7261 assert(rhptee->isFunctionType()); 7262 return Sema::FunctionVoidPointer; 7263 } 7264 7265 if (rhptee->isVoidType()) { 7266 if (lhptee->isIncompleteOrObjectType()) 7267 return ConvTy; 7268 7269 // As an extension, we allow cast to/from void* to function pointer. 7270 assert(lhptee->isFunctionType()); 7271 return Sema::FunctionVoidPointer; 7272 } 7273 7274 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7275 // unqualified versions of compatible types, ... 7276 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7277 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7278 // Check if the pointee types are compatible ignoring the sign. 7279 // We explicitly check for char so that we catch "char" vs 7280 // "unsigned char" on systems where "char" is unsigned. 7281 if (lhptee->isCharType()) 7282 ltrans = S.Context.UnsignedCharTy; 7283 else if (lhptee->hasSignedIntegerRepresentation()) 7284 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7285 7286 if (rhptee->isCharType()) 7287 rtrans = S.Context.UnsignedCharTy; 7288 else if (rhptee->hasSignedIntegerRepresentation()) 7289 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7290 7291 if (ltrans == rtrans) { 7292 // Types are compatible ignoring the sign. Qualifier incompatibility 7293 // takes priority over sign incompatibility because the sign 7294 // warning can be disabled. 7295 if (ConvTy != Sema::Compatible) 7296 return ConvTy; 7297 7298 return Sema::IncompatiblePointerSign; 7299 } 7300 7301 // If we are a multi-level pointer, it's possible that our issue is simply 7302 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7303 // the eventual target type is the same and the pointers have the same 7304 // level of indirection, this must be the issue. 7305 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7306 do { 7307 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7308 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7309 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7310 7311 if (lhptee == rhptee) 7312 return Sema::IncompatibleNestedPointerQualifiers; 7313 } 7314 7315 // General pointer incompatibility takes priority over qualifiers. 7316 return Sema::IncompatiblePointer; 7317 } 7318 if (!S.getLangOpts().CPlusPlus && 7319 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7320 return Sema::IncompatiblePointer; 7321 return ConvTy; 7322 } 7323 7324 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7325 /// block pointer types are compatible or whether a block and normal pointer 7326 /// are compatible. It is more restrict than comparing two function pointer 7327 // types. 7328 static Sema::AssignConvertType 7329 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7330 QualType RHSType) { 7331 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7332 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7333 7334 QualType lhptee, rhptee; 7335 7336 // get the "pointed to" type (ignoring qualifiers at the top level) 7337 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7338 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7339 7340 // In C++, the types have to match exactly. 7341 if (S.getLangOpts().CPlusPlus) 7342 return Sema::IncompatibleBlockPointer; 7343 7344 Sema::AssignConvertType ConvTy = Sema::Compatible; 7345 7346 // For blocks we enforce that qualifiers are identical. 7347 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7348 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7349 7350 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7351 return Sema::IncompatibleBlockPointer; 7352 7353 return ConvTy; 7354 } 7355 7356 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7357 /// for assignment compatibility. 7358 static Sema::AssignConvertType 7359 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7360 QualType RHSType) { 7361 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7362 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7363 7364 if (LHSType->isObjCBuiltinType()) { 7365 // Class is not compatible with ObjC object pointers. 7366 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7367 !RHSType->isObjCQualifiedClassType()) 7368 return Sema::IncompatiblePointer; 7369 return Sema::Compatible; 7370 } 7371 if (RHSType->isObjCBuiltinType()) { 7372 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7373 !LHSType->isObjCQualifiedClassType()) 7374 return Sema::IncompatiblePointer; 7375 return Sema::Compatible; 7376 } 7377 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7378 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7379 7380 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7381 // make an exception for id<P> 7382 !LHSType->isObjCQualifiedIdType()) 7383 return Sema::CompatiblePointerDiscardsQualifiers; 7384 7385 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7386 return Sema::Compatible; 7387 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7388 return Sema::IncompatibleObjCQualifiedId; 7389 return Sema::IncompatiblePointer; 7390 } 7391 7392 Sema::AssignConvertType 7393 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7394 QualType LHSType, QualType RHSType) { 7395 // Fake up an opaque expression. We don't actually care about what 7396 // cast operations are required, so if CheckAssignmentConstraints 7397 // adds casts to this they'll be wasted, but fortunately that doesn't 7398 // usually happen on valid code. 7399 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7400 ExprResult RHSPtr = &RHSExpr; 7401 CastKind K = CK_Invalid; 7402 7403 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7404 } 7405 7406 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7407 /// has code to accommodate several GCC extensions when type checking 7408 /// pointers. Here are some objectionable examples that GCC considers warnings: 7409 /// 7410 /// int a, *pint; 7411 /// short *pshort; 7412 /// struct foo *pfoo; 7413 /// 7414 /// pint = pshort; // warning: assignment from incompatible pointer type 7415 /// a = pint; // warning: assignment makes integer from pointer without a cast 7416 /// pint = a; // warning: assignment makes pointer from integer without a cast 7417 /// pint = pfoo; // warning: assignment from incompatible pointer type 7418 /// 7419 /// As a result, the code for dealing with pointers is more complex than the 7420 /// C99 spec dictates. 7421 /// 7422 /// Sets 'Kind' for any result kind except Incompatible. 7423 Sema::AssignConvertType 7424 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7425 CastKind &Kind, bool ConvertRHS) { 7426 QualType RHSType = RHS.get()->getType(); 7427 QualType OrigLHSType = LHSType; 7428 7429 // Get canonical types. We're not formatting these types, just comparing 7430 // them. 7431 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7432 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7433 7434 // Common case: no conversion required. 7435 if (LHSType == RHSType) { 7436 Kind = CK_NoOp; 7437 return Compatible; 7438 } 7439 7440 // If we have an atomic type, try a non-atomic assignment, then just add an 7441 // atomic qualification step. 7442 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7443 Sema::AssignConvertType result = 7444 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7445 if (result != Compatible) 7446 return result; 7447 if (Kind != CK_NoOp && ConvertRHS) 7448 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7449 Kind = CK_NonAtomicToAtomic; 7450 return Compatible; 7451 } 7452 7453 // If the left-hand side is a reference type, then we are in a 7454 // (rare!) case where we've allowed the use of references in C, 7455 // e.g., as a parameter type in a built-in function. In this case, 7456 // just make sure that the type referenced is compatible with the 7457 // right-hand side type. The caller is responsible for adjusting 7458 // LHSType so that the resulting expression does not have reference 7459 // type. 7460 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7461 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7462 Kind = CK_LValueBitCast; 7463 return Compatible; 7464 } 7465 return Incompatible; 7466 } 7467 7468 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7469 // to the same ExtVector type. 7470 if (LHSType->isExtVectorType()) { 7471 if (RHSType->isExtVectorType()) 7472 return Incompatible; 7473 if (RHSType->isArithmeticType()) { 7474 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7475 if (ConvertRHS) 7476 RHS = prepareVectorSplat(LHSType, RHS.get()); 7477 Kind = CK_VectorSplat; 7478 return Compatible; 7479 } 7480 } 7481 7482 // Conversions to or from vector type. 7483 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7484 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7485 // Allow assignments of an AltiVec vector type to an equivalent GCC 7486 // vector type and vice versa 7487 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7488 Kind = CK_BitCast; 7489 return Compatible; 7490 } 7491 7492 // If we are allowing lax vector conversions, and LHS and RHS are both 7493 // vectors, the total size only needs to be the same. This is a bitcast; 7494 // no bits are changed but the result type is different. 7495 if (isLaxVectorConversion(RHSType, LHSType)) { 7496 Kind = CK_BitCast; 7497 return IncompatibleVectors; 7498 } 7499 } 7500 7501 // When the RHS comes from another lax conversion (e.g. binops between 7502 // scalars and vectors) the result is canonicalized as a vector. When the 7503 // LHS is also a vector, the lax is allowed by the condition above. Handle 7504 // the case where LHS is a scalar. 7505 if (LHSType->isScalarType()) { 7506 const VectorType *VecType = RHSType->getAs<VectorType>(); 7507 if (VecType && VecType->getNumElements() == 1 && 7508 isLaxVectorConversion(RHSType, LHSType)) { 7509 ExprResult *VecExpr = &RHS; 7510 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7511 Kind = CK_BitCast; 7512 return Compatible; 7513 } 7514 } 7515 7516 return Incompatible; 7517 } 7518 7519 // Diagnose attempts to convert between __float128 and long double where 7520 // such conversions currently can't be handled. 7521 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7522 return Incompatible; 7523 7524 // Arithmetic conversions. 7525 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7526 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7527 if (ConvertRHS) 7528 Kind = PrepareScalarCast(RHS, LHSType); 7529 return Compatible; 7530 } 7531 7532 // Conversions to normal pointers. 7533 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7534 // U* -> T* 7535 if (isa<PointerType>(RHSType)) { 7536 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7537 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7538 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7539 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7540 } 7541 7542 // int -> T* 7543 if (RHSType->isIntegerType()) { 7544 Kind = CK_IntegralToPointer; // FIXME: null? 7545 return IntToPointer; 7546 } 7547 7548 // C pointers are not compatible with ObjC object pointers, 7549 // with two exceptions: 7550 if (isa<ObjCObjectPointerType>(RHSType)) { 7551 // - conversions to void* 7552 if (LHSPointer->getPointeeType()->isVoidType()) { 7553 Kind = CK_BitCast; 7554 return Compatible; 7555 } 7556 7557 // - conversions from 'Class' to the redefinition type 7558 if (RHSType->isObjCClassType() && 7559 Context.hasSameType(LHSType, 7560 Context.getObjCClassRedefinitionType())) { 7561 Kind = CK_BitCast; 7562 return Compatible; 7563 } 7564 7565 Kind = CK_BitCast; 7566 return IncompatiblePointer; 7567 } 7568 7569 // U^ -> void* 7570 if (RHSType->getAs<BlockPointerType>()) { 7571 if (LHSPointer->getPointeeType()->isVoidType()) { 7572 Kind = CK_BitCast; 7573 return Compatible; 7574 } 7575 } 7576 7577 return Incompatible; 7578 } 7579 7580 // Conversions to block pointers. 7581 if (isa<BlockPointerType>(LHSType)) { 7582 // U^ -> T^ 7583 if (RHSType->isBlockPointerType()) { 7584 Kind = CK_BitCast; 7585 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7586 } 7587 7588 // int or null -> T^ 7589 if (RHSType->isIntegerType()) { 7590 Kind = CK_IntegralToPointer; // FIXME: null 7591 return IntToBlockPointer; 7592 } 7593 7594 // id -> T^ 7595 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7596 Kind = CK_AnyPointerToBlockPointerCast; 7597 return Compatible; 7598 } 7599 7600 // void* -> T^ 7601 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7602 if (RHSPT->getPointeeType()->isVoidType()) { 7603 Kind = CK_AnyPointerToBlockPointerCast; 7604 return Compatible; 7605 } 7606 7607 return Incompatible; 7608 } 7609 7610 // Conversions to Objective-C pointers. 7611 if (isa<ObjCObjectPointerType>(LHSType)) { 7612 // A* -> B* 7613 if (RHSType->isObjCObjectPointerType()) { 7614 Kind = CK_BitCast; 7615 Sema::AssignConvertType result = 7616 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7617 if (getLangOpts().ObjCAutoRefCount && 7618 result == Compatible && 7619 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7620 result = IncompatibleObjCWeakRef; 7621 return result; 7622 } 7623 7624 // int or null -> A* 7625 if (RHSType->isIntegerType()) { 7626 Kind = CK_IntegralToPointer; // FIXME: null 7627 return IntToPointer; 7628 } 7629 7630 // In general, C pointers are not compatible with ObjC object pointers, 7631 // with two exceptions: 7632 if (isa<PointerType>(RHSType)) { 7633 Kind = CK_CPointerToObjCPointerCast; 7634 7635 // - conversions from 'void*' 7636 if (RHSType->isVoidPointerType()) { 7637 return Compatible; 7638 } 7639 7640 // - conversions to 'Class' from its redefinition type 7641 if (LHSType->isObjCClassType() && 7642 Context.hasSameType(RHSType, 7643 Context.getObjCClassRedefinitionType())) { 7644 return Compatible; 7645 } 7646 7647 return IncompatiblePointer; 7648 } 7649 7650 // Only under strict condition T^ is compatible with an Objective-C pointer. 7651 if (RHSType->isBlockPointerType() && 7652 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7653 if (ConvertRHS) 7654 maybeExtendBlockObject(RHS); 7655 Kind = CK_BlockPointerToObjCPointerCast; 7656 return Compatible; 7657 } 7658 7659 return Incompatible; 7660 } 7661 7662 // Conversions from pointers that are not covered by the above. 7663 if (isa<PointerType>(RHSType)) { 7664 // T* -> _Bool 7665 if (LHSType == Context.BoolTy) { 7666 Kind = CK_PointerToBoolean; 7667 return Compatible; 7668 } 7669 7670 // T* -> int 7671 if (LHSType->isIntegerType()) { 7672 Kind = CK_PointerToIntegral; 7673 return PointerToInt; 7674 } 7675 7676 return Incompatible; 7677 } 7678 7679 // Conversions from Objective-C pointers that are not covered by the above. 7680 if (isa<ObjCObjectPointerType>(RHSType)) { 7681 // T* -> _Bool 7682 if (LHSType == Context.BoolTy) { 7683 Kind = CK_PointerToBoolean; 7684 return Compatible; 7685 } 7686 7687 // T* -> int 7688 if (LHSType->isIntegerType()) { 7689 Kind = CK_PointerToIntegral; 7690 return PointerToInt; 7691 } 7692 7693 return Incompatible; 7694 } 7695 7696 // struct A -> struct B 7697 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7698 if (Context.typesAreCompatible(LHSType, RHSType)) { 7699 Kind = CK_NoOp; 7700 return Compatible; 7701 } 7702 } 7703 7704 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7705 Kind = CK_IntToOCLSampler; 7706 return Compatible; 7707 } 7708 7709 return Incompatible; 7710 } 7711 7712 /// \brief Constructs a transparent union from an expression that is 7713 /// used to initialize the transparent union. 7714 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7715 ExprResult &EResult, QualType UnionType, 7716 FieldDecl *Field) { 7717 // Build an initializer list that designates the appropriate member 7718 // of the transparent union. 7719 Expr *E = EResult.get(); 7720 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7721 E, SourceLocation()); 7722 Initializer->setType(UnionType); 7723 Initializer->setInitializedFieldInUnion(Field); 7724 7725 // Build a compound literal constructing a value of the transparent 7726 // union type from this initializer list. 7727 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7728 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7729 VK_RValue, Initializer, false); 7730 } 7731 7732 Sema::AssignConvertType 7733 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7734 ExprResult &RHS) { 7735 QualType RHSType = RHS.get()->getType(); 7736 7737 // If the ArgType is a Union type, we want to handle a potential 7738 // transparent_union GCC extension. 7739 const RecordType *UT = ArgType->getAsUnionType(); 7740 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7741 return Incompatible; 7742 7743 // The field to initialize within the transparent union. 7744 RecordDecl *UD = UT->getDecl(); 7745 FieldDecl *InitField = nullptr; 7746 // It's compatible if the expression matches any of the fields. 7747 for (auto *it : UD->fields()) { 7748 if (it->getType()->isPointerType()) { 7749 // If the transparent union contains a pointer type, we allow: 7750 // 1) void pointer 7751 // 2) null pointer constant 7752 if (RHSType->isPointerType()) 7753 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7754 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7755 InitField = it; 7756 break; 7757 } 7758 7759 if (RHS.get()->isNullPointerConstant(Context, 7760 Expr::NPC_ValueDependentIsNull)) { 7761 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7762 CK_NullToPointer); 7763 InitField = it; 7764 break; 7765 } 7766 } 7767 7768 CastKind Kind = CK_Invalid; 7769 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7770 == Compatible) { 7771 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7772 InitField = it; 7773 break; 7774 } 7775 } 7776 7777 if (!InitField) 7778 return Incompatible; 7779 7780 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7781 return Compatible; 7782 } 7783 7784 Sema::AssignConvertType 7785 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7786 bool Diagnose, 7787 bool DiagnoseCFAudited, 7788 bool ConvertRHS) { 7789 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7790 // we can't avoid *all* modifications at the moment, so we need some somewhere 7791 // to put the updated value. 7792 ExprResult LocalRHS = CallerRHS; 7793 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7794 7795 if (getLangOpts().CPlusPlus) { 7796 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7797 // C++ 5.17p3: If the left operand is not of class type, the 7798 // expression is implicitly converted (C++ 4) to the 7799 // cv-unqualified type of the left operand. 7800 ExprResult Res; 7801 if (Diagnose) { 7802 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7803 AA_Assigning); 7804 } else { 7805 ImplicitConversionSequence ICS = 7806 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7807 /*SuppressUserConversions=*/false, 7808 /*AllowExplicit=*/false, 7809 /*InOverloadResolution=*/false, 7810 /*CStyle=*/false, 7811 /*AllowObjCWritebackConversion=*/false); 7812 if (ICS.isFailure()) 7813 return Incompatible; 7814 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7815 ICS, AA_Assigning); 7816 } 7817 if (Res.isInvalid()) 7818 return Incompatible; 7819 Sema::AssignConvertType result = Compatible; 7820 if (getLangOpts().ObjCAutoRefCount && 7821 !CheckObjCARCUnavailableWeakConversion(LHSType, 7822 RHS.get()->getType())) 7823 result = IncompatibleObjCWeakRef; 7824 RHS = Res; 7825 return result; 7826 } 7827 7828 // FIXME: Currently, we fall through and treat C++ classes like C 7829 // structures. 7830 // FIXME: We also fall through for atomics; not sure what should 7831 // happen there, though. 7832 } else if (RHS.get()->getType() == Context.OverloadTy) { 7833 // As a set of extensions to C, we support overloading on functions. These 7834 // functions need to be resolved here. 7835 DeclAccessPair DAP; 7836 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7837 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7838 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7839 else 7840 return Incompatible; 7841 } 7842 7843 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7844 // a null pointer constant. 7845 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7846 LHSType->isBlockPointerType()) && 7847 RHS.get()->isNullPointerConstant(Context, 7848 Expr::NPC_ValueDependentIsNull)) { 7849 if (Diagnose || ConvertRHS) { 7850 CastKind Kind; 7851 CXXCastPath Path; 7852 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7853 /*IgnoreBaseAccess=*/false, Diagnose); 7854 if (ConvertRHS) 7855 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7856 } 7857 return Compatible; 7858 } 7859 7860 // This check seems unnatural, however it is necessary to ensure the proper 7861 // conversion of functions/arrays. If the conversion were done for all 7862 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7863 // expressions that suppress this implicit conversion (&, sizeof). 7864 // 7865 // Suppress this for references: C++ 8.5.3p5. 7866 if (!LHSType->isReferenceType()) { 7867 // FIXME: We potentially allocate here even if ConvertRHS is false. 7868 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7869 if (RHS.isInvalid()) 7870 return Incompatible; 7871 } 7872 7873 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7874 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7875 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7876 if (PDecl && !PDecl->hasDefinition()) { 7877 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7878 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7879 } 7880 } 7881 7882 CastKind Kind = CK_Invalid; 7883 Sema::AssignConvertType result = 7884 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7885 7886 // C99 6.5.16.1p2: The value of the right operand is converted to the 7887 // type of the assignment expression. 7888 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7889 // so that we can use references in built-in functions even in C. 7890 // The getNonReferenceType() call makes sure that the resulting expression 7891 // does not have reference type. 7892 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7893 QualType Ty = LHSType.getNonLValueExprType(Context); 7894 Expr *E = RHS.get(); 7895 7896 // Check for various Objective-C errors. If we are not reporting 7897 // diagnostics and just checking for errors, e.g., during overload 7898 // resolution, return Incompatible to indicate the failure. 7899 if (getLangOpts().ObjCAutoRefCount && 7900 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7901 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7902 if (!Diagnose) 7903 return Incompatible; 7904 } 7905 if (getLangOpts().ObjC1 && 7906 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7907 E->getType(), E, Diagnose) || 7908 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7909 if (!Diagnose) 7910 return Incompatible; 7911 // Replace the expression with a corrected version and continue so we 7912 // can find further errors. 7913 RHS = E; 7914 return Compatible; 7915 } 7916 7917 if (ConvertRHS) 7918 RHS = ImpCastExprToType(E, Ty, Kind); 7919 } 7920 return result; 7921 } 7922 7923 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7924 ExprResult &RHS) { 7925 Diag(Loc, diag::err_typecheck_invalid_operands) 7926 << LHS.get()->getType() << RHS.get()->getType() 7927 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7928 return QualType(); 7929 } 7930 7931 /// Try to convert a value of non-vector type to a vector type by converting 7932 /// the type to the element type of the vector and then performing a splat. 7933 /// If the language is OpenCL, we only use conversions that promote scalar 7934 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7935 /// for float->int. 7936 /// 7937 /// \param scalar - if non-null, actually perform the conversions 7938 /// \return true if the operation fails (but without diagnosing the failure) 7939 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7940 QualType scalarTy, 7941 QualType vectorEltTy, 7942 QualType vectorTy) { 7943 // The conversion to apply to the scalar before splatting it, 7944 // if necessary. 7945 CastKind scalarCast = CK_Invalid; 7946 7947 if (vectorEltTy->isIntegralType(S.Context)) { 7948 if (!scalarTy->isIntegralType(S.Context)) 7949 return true; 7950 if (S.getLangOpts().OpenCL && 7951 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7952 return true; 7953 scalarCast = CK_IntegralCast; 7954 } else if (vectorEltTy->isRealFloatingType()) { 7955 if (scalarTy->isRealFloatingType()) { 7956 if (S.getLangOpts().OpenCL && 7957 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7958 return true; 7959 scalarCast = CK_FloatingCast; 7960 } 7961 else if (scalarTy->isIntegralType(S.Context)) 7962 scalarCast = CK_IntegralToFloating; 7963 else 7964 return true; 7965 } else { 7966 return true; 7967 } 7968 7969 // Adjust scalar if desired. 7970 if (scalar) { 7971 if (scalarCast != CK_Invalid) 7972 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7973 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7974 } 7975 return false; 7976 } 7977 7978 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7979 SourceLocation Loc, bool IsCompAssign, 7980 bool AllowBothBool, 7981 bool AllowBoolConversions) { 7982 if (!IsCompAssign) { 7983 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7984 if (LHS.isInvalid()) 7985 return QualType(); 7986 } 7987 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7988 if (RHS.isInvalid()) 7989 return QualType(); 7990 7991 // For conversion purposes, we ignore any qualifiers. 7992 // For example, "const float" and "float" are equivalent. 7993 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7994 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7995 7996 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7997 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7998 assert(LHSVecType || RHSVecType); 7999 8000 // AltiVec-style "vector bool op vector bool" combinations are allowed 8001 // for some operators but not others. 8002 if (!AllowBothBool && 8003 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8004 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8005 return InvalidOperands(Loc, LHS, RHS); 8006 8007 // If the vector types are identical, return. 8008 if (Context.hasSameType(LHSType, RHSType)) 8009 return LHSType; 8010 8011 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8012 if (LHSVecType && RHSVecType && 8013 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8014 if (isa<ExtVectorType>(LHSVecType)) { 8015 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8016 return LHSType; 8017 } 8018 8019 if (!IsCompAssign) 8020 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8021 return RHSType; 8022 } 8023 8024 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8025 // can be mixed, with the result being the non-bool type. The non-bool 8026 // operand must have integer element type. 8027 if (AllowBoolConversions && LHSVecType && RHSVecType && 8028 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8029 (Context.getTypeSize(LHSVecType->getElementType()) == 8030 Context.getTypeSize(RHSVecType->getElementType()))) { 8031 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8032 LHSVecType->getElementType()->isIntegerType() && 8033 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8034 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8035 return LHSType; 8036 } 8037 if (!IsCompAssign && 8038 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8039 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8040 RHSVecType->getElementType()->isIntegerType()) { 8041 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8042 return RHSType; 8043 } 8044 } 8045 8046 // If there's an ext-vector type and a scalar, try to convert the scalar to 8047 // the vector element type and splat. 8048 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8049 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8050 LHSVecType->getElementType(), LHSType)) 8051 return LHSType; 8052 } 8053 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8054 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8055 LHSType, RHSVecType->getElementType(), 8056 RHSType)) 8057 return RHSType; 8058 } 8059 8060 // If we're allowing lax vector conversions, only the total (data) size needs 8061 // to be the same. If one of the types is scalar, the result is always the 8062 // vector type. Don't allow this if the scalar operand is an lvalue. 8063 QualType VecType = LHSVecType ? LHSType : RHSType; 8064 QualType ScalarType = LHSVecType ? RHSType : LHSType; 8065 ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS; 8066 if (isLaxVectorConversion(ScalarType, VecType) && 8067 !ScalarExpr->get()->isLValue()) { 8068 *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast); 8069 return VecType; 8070 } 8071 8072 // Okay, the expression is invalid. 8073 8074 // If there's a non-vector, non-real operand, diagnose that. 8075 if ((!RHSVecType && !RHSType->isRealType()) || 8076 (!LHSVecType && !LHSType->isRealType())) { 8077 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8078 << LHSType << RHSType 8079 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8080 return QualType(); 8081 } 8082 8083 // OpenCL V1.1 6.2.6.p1: 8084 // If the operands are of more than one vector type, then an error shall 8085 // occur. Implicit conversions between vector types are not permitted, per 8086 // section 6.2.1. 8087 if (getLangOpts().OpenCL && 8088 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8089 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8090 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8091 << RHSType; 8092 return QualType(); 8093 } 8094 8095 // Otherwise, use the generic diagnostic. 8096 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8097 << LHSType << RHSType 8098 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8099 return QualType(); 8100 } 8101 8102 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8103 // expression. These are mainly cases where the null pointer is used as an 8104 // integer instead of a pointer. 8105 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8106 SourceLocation Loc, bool IsCompare) { 8107 // The canonical way to check for a GNU null is with isNullPointerConstant, 8108 // but we use a bit of a hack here for speed; this is a relatively 8109 // hot path, and isNullPointerConstant is slow. 8110 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8111 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8112 8113 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8114 8115 // Avoid analyzing cases where the result will either be invalid (and 8116 // diagnosed as such) or entirely valid and not something to warn about. 8117 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8118 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8119 return; 8120 8121 // Comparison operations would not make sense with a null pointer no matter 8122 // what the other expression is. 8123 if (!IsCompare) { 8124 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8125 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8126 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8127 return; 8128 } 8129 8130 // The rest of the operations only make sense with a null pointer 8131 // if the other expression is a pointer. 8132 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8133 NonNullType->canDecayToPointerType()) 8134 return; 8135 8136 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8137 << LHSNull /* LHS is NULL */ << NonNullType 8138 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8139 } 8140 8141 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8142 ExprResult &RHS, 8143 SourceLocation Loc, bool IsDiv) { 8144 // Check for division/remainder by zero. 8145 llvm::APSInt RHSValue; 8146 if (!RHS.get()->isValueDependent() && 8147 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8148 S.DiagRuntimeBehavior(Loc, RHS.get(), 8149 S.PDiag(diag::warn_remainder_division_by_zero) 8150 << IsDiv << RHS.get()->getSourceRange()); 8151 } 8152 8153 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8154 SourceLocation Loc, 8155 bool IsCompAssign, bool IsDiv) { 8156 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8157 8158 if (LHS.get()->getType()->isVectorType() || 8159 RHS.get()->getType()->isVectorType()) 8160 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8161 /*AllowBothBool*/getLangOpts().AltiVec, 8162 /*AllowBoolConversions*/false); 8163 8164 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8165 if (LHS.isInvalid() || RHS.isInvalid()) 8166 return QualType(); 8167 8168 8169 if (compType.isNull() || !compType->isArithmeticType()) 8170 return InvalidOperands(Loc, LHS, RHS); 8171 if (IsDiv) 8172 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8173 return compType; 8174 } 8175 8176 QualType Sema::CheckRemainderOperands( 8177 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8178 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8179 8180 if (LHS.get()->getType()->isVectorType() || 8181 RHS.get()->getType()->isVectorType()) { 8182 if (LHS.get()->getType()->hasIntegerRepresentation() && 8183 RHS.get()->getType()->hasIntegerRepresentation()) 8184 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8185 /*AllowBothBool*/getLangOpts().AltiVec, 8186 /*AllowBoolConversions*/false); 8187 return InvalidOperands(Loc, LHS, RHS); 8188 } 8189 8190 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8191 if (LHS.isInvalid() || RHS.isInvalid()) 8192 return QualType(); 8193 8194 if (compType.isNull() || !compType->isIntegerType()) 8195 return InvalidOperands(Loc, LHS, RHS); 8196 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8197 return compType; 8198 } 8199 8200 /// \brief Diagnose invalid arithmetic on two void pointers. 8201 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8202 Expr *LHSExpr, Expr *RHSExpr) { 8203 S.Diag(Loc, S.getLangOpts().CPlusPlus 8204 ? diag::err_typecheck_pointer_arith_void_type 8205 : diag::ext_gnu_void_ptr) 8206 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8207 << RHSExpr->getSourceRange(); 8208 } 8209 8210 /// \brief Diagnose invalid arithmetic on a void pointer. 8211 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8212 Expr *Pointer) { 8213 S.Diag(Loc, S.getLangOpts().CPlusPlus 8214 ? diag::err_typecheck_pointer_arith_void_type 8215 : diag::ext_gnu_void_ptr) 8216 << 0 /* one pointer */ << Pointer->getSourceRange(); 8217 } 8218 8219 /// \brief Diagnose invalid arithmetic on two function pointers. 8220 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8221 Expr *LHS, Expr *RHS) { 8222 assert(LHS->getType()->isAnyPointerType()); 8223 assert(RHS->getType()->isAnyPointerType()); 8224 S.Diag(Loc, S.getLangOpts().CPlusPlus 8225 ? diag::err_typecheck_pointer_arith_function_type 8226 : diag::ext_gnu_ptr_func_arith) 8227 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8228 // We only show the second type if it differs from the first. 8229 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8230 RHS->getType()) 8231 << RHS->getType()->getPointeeType() 8232 << LHS->getSourceRange() << RHS->getSourceRange(); 8233 } 8234 8235 /// \brief Diagnose invalid arithmetic on a function pointer. 8236 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8237 Expr *Pointer) { 8238 assert(Pointer->getType()->isAnyPointerType()); 8239 S.Diag(Loc, S.getLangOpts().CPlusPlus 8240 ? diag::err_typecheck_pointer_arith_function_type 8241 : diag::ext_gnu_ptr_func_arith) 8242 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8243 << 0 /* one pointer, so only one type */ 8244 << Pointer->getSourceRange(); 8245 } 8246 8247 /// \brief Emit error if Operand is incomplete pointer type 8248 /// 8249 /// \returns True if pointer has incomplete type 8250 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8251 Expr *Operand) { 8252 QualType ResType = Operand->getType(); 8253 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8254 ResType = ResAtomicType->getValueType(); 8255 8256 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8257 QualType PointeeTy = ResType->getPointeeType(); 8258 return S.RequireCompleteType(Loc, PointeeTy, 8259 diag::err_typecheck_arithmetic_incomplete_type, 8260 PointeeTy, Operand->getSourceRange()); 8261 } 8262 8263 /// \brief Check the validity of an arithmetic pointer operand. 8264 /// 8265 /// If the operand has pointer type, this code will check for pointer types 8266 /// which are invalid in arithmetic operations. These will be diagnosed 8267 /// appropriately, including whether or not the use is supported as an 8268 /// extension. 8269 /// 8270 /// \returns True when the operand is valid to use (even if as an extension). 8271 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8272 Expr *Operand) { 8273 QualType ResType = Operand->getType(); 8274 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8275 ResType = ResAtomicType->getValueType(); 8276 8277 if (!ResType->isAnyPointerType()) return true; 8278 8279 QualType PointeeTy = ResType->getPointeeType(); 8280 if (PointeeTy->isVoidType()) { 8281 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8282 return !S.getLangOpts().CPlusPlus; 8283 } 8284 if (PointeeTy->isFunctionType()) { 8285 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8286 return !S.getLangOpts().CPlusPlus; 8287 } 8288 8289 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8290 8291 return true; 8292 } 8293 8294 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8295 /// operands. 8296 /// 8297 /// This routine will diagnose any invalid arithmetic on pointer operands much 8298 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8299 /// for emitting a single diagnostic even for operations where both LHS and RHS 8300 /// are (potentially problematic) pointers. 8301 /// 8302 /// \returns True when the operand is valid to use (even if as an extension). 8303 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8304 Expr *LHSExpr, Expr *RHSExpr) { 8305 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8306 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8307 if (!isLHSPointer && !isRHSPointer) return true; 8308 8309 QualType LHSPointeeTy, RHSPointeeTy; 8310 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8311 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8312 8313 // if both are pointers check if operation is valid wrt address spaces 8314 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8315 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8316 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8317 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8318 S.Diag(Loc, 8319 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8320 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8321 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8322 return false; 8323 } 8324 } 8325 8326 // Check for arithmetic on pointers to incomplete types. 8327 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8328 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8329 if (isLHSVoidPtr || isRHSVoidPtr) { 8330 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8331 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8332 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8333 8334 return !S.getLangOpts().CPlusPlus; 8335 } 8336 8337 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8338 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8339 if (isLHSFuncPtr || isRHSFuncPtr) { 8340 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8341 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8342 RHSExpr); 8343 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8344 8345 return !S.getLangOpts().CPlusPlus; 8346 } 8347 8348 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8349 return false; 8350 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8351 return false; 8352 8353 return true; 8354 } 8355 8356 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8357 /// literal. 8358 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8359 Expr *LHSExpr, Expr *RHSExpr) { 8360 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8361 Expr* IndexExpr = RHSExpr; 8362 if (!StrExpr) { 8363 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8364 IndexExpr = LHSExpr; 8365 } 8366 8367 bool IsStringPlusInt = StrExpr && 8368 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8369 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8370 return; 8371 8372 llvm::APSInt index; 8373 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8374 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8375 if (index.isNonNegative() && 8376 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8377 index.isUnsigned())) 8378 return; 8379 } 8380 8381 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8382 Self.Diag(OpLoc, diag::warn_string_plus_int) 8383 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8384 8385 // Only print a fixit for "str" + int, not for int + "str". 8386 if (IndexExpr == RHSExpr) { 8387 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8388 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8389 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8390 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8391 << FixItHint::CreateInsertion(EndLoc, "]"); 8392 } else 8393 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8394 } 8395 8396 /// \brief Emit a warning when adding a char literal to a string. 8397 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8398 Expr *LHSExpr, Expr *RHSExpr) { 8399 const Expr *StringRefExpr = LHSExpr; 8400 const CharacterLiteral *CharExpr = 8401 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8402 8403 if (!CharExpr) { 8404 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8405 StringRefExpr = RHSExpr; 8406 } 8407 8408 if (!CharExpr || !StringRefExpr) 8409 return; 8410 8411 const QualType StringType = StringRefExpr->getType(); 8412 8413 // Return if not a PointerType. 8414 if (!StringType->isAnyPointerType()) 8415 return; 8416 8417 // Return if not a CharacterType. 8418 if (!StringType->getPointeeType()->isAnyCharacterType()) 8419 return; 8420 8421 ASTContext &Ctx = Self.getASTContext(); 8422 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8423 8424 const QualType CharType = CharExpr->getType(); 8425 if (!CharType->isAnyCharacterType() && 8426 CharType->isIntegerType() && 8427 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8428 Self.Diag(OpLoc, diag::warn_string_plus_char) 8429 << DiagRange << Ctx.CharTy; 8430 } else { 8431 Self.Diag(OpLoc, diag::warn_string_plus_char) 8432 << DiagRange << CharExpr->getType(); 8433 } 8434 8435 // Only print a fixit for str + char, not for char + str. 8436 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8437 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8438 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8439 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8440 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8441 << FixItHint::CreateInsertion(EndLoc, "]"); 8442 } else { 8443 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8444 } 8445 } 8446 8447 /// \brief Emit error when two pointers are incompatible. 8448 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8449 Expr *LHSExpr, Expr *RHSExpr) { 8450 assert(LHSExpr->getType()->isAnyPointerType()); 8451 assert(RHSExpr->getType()->isAnyPointerType()); 8452 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8453 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8454 << RHSExpr->getSourceRange(); 8455 } 8456 8457 // C99 6.5.6 8458 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8459 SourceLocation Loc, BinaryOperatorKind Opc, 8460 QualType* CompLHSTy) { 8461 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8462 8463 if (LHS.get()->getType()->isVectorType() || 8464 RHS.get()->getType()->isVectorType()) { 8465 QualType compType = CheckVectorOperands( 8466 LHS, RHS, Loc, CompLHSTy, 8467 /*AllowBothBool*/getLangOpts().AltiVec, 8468 /*AllowBoolConversions*/getLangOpts().ZVector); 8469 if (CompLHSTy) *CompLHSTy = compType; 8470 return compType; 8471 } 8472 8473 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8474 if (LHS.isInvalid() || RHS.isInvalid()) 8475 return QualType(); 8476 8477 // Diagnose "string literal" '+' int and string '+' "char literal". 8478 if (Opc == BO_Add) { 8479 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8480 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8481 } 8482 8483 // handle the common case first (both operands are arithmetic). 8484 if (!compType.isNull() && compType->isArithmeticType()) { 8485 if (CompLHSTy) *CompLHSTy = compType; 8486 return compType; 8487 } 8488 8489 // Type-checking. Ultimately the pointer's going to be in PExp; 8490 // note that we bias towards the LHS being the pointer. 8491 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8492 8493 bool isObjCPointer; 8494 if (PExp->getType()->isPointerType()) { 8495 isObjCPointer = false; 8496 } else if (PExp->getType()->isObjCObjectPointerType()) { 8497 isObjCPointer = true; 8498 } else { 8499 std::swap(PExp, IExp); 8500 if (PExp->getType()->isPointerType()) { 8501 isObjCPointer = false; 8502 } else if (PExp->getType()->isObjCObjectPointerType()) { 8503 isObjCPointer = true; 8504 } else { 8505 return InvalidOperands(Loc, LHS, RHS); 8506 } 8507 } 8508 assert(PExp->getType()->isAnyPointerType()); 8509 8510 if (!IExp->getType()->isIntegerType()) 8511 return InvalidOperands(Loc, LHS, RHS); 8512 8513 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8514 return QualType(); 8515 8516 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8517 return QualType(); 8518 8519 // Check array bounds for pointer arithemtic 8520 CheckArrayAccess(PExp, IExp); 8521 8522 if (CompLHSTy) { 8523 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8524 if (LHSTy.isNull()) { 8525 LHSTy = LHS.get()->getType(); 8526 if (LHSTy->isPromotableIntegerType()) 8527 LHSTy = Context.getPromotedIntegerType(LHSTy); 8528 } 8529 *CompLHSTy = LHSTy; 8530 } 8531 8532 return PExp->getType(); 8533 } 8534 8535 // C99 6.5.6 8536 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8537 SourceLocation Loc, 8538 QualType* CompLHSTy) { 8539 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8540 8541 if (LHS.get()->getType()->isVectorType() || 8542 RHS.get()->getType()->isVectorType()) { 8543 QualType compType = CheckVectorOperands( 8544 LHS, RHS, Loc, CompLHSTy, 8545 /*AllowBothBool*/getLangOpts().AltiVec, 8546 /*AllowBoolConversions*/getLangOpts().ZVector); 8547 if (CompLHSTy) *CompLHSTy = compType; 8548 return compType; 8549 } 8550 8551 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8552 if (LHS.isInvalid() || RHS.isInvalid()) 8553 return QualType(); 8554 8555 // Enforce type constraints: C99 6.5.6p3. 8556 8557 // Handle the common case first (both operands are arithmetic). 8558 if (!compType.isNull() && compType->isArithmeticType()) { 8559 if (CompLHSTy) *CompLHSTy = compType; 8560 return compType; 8561 } 8562 8563 // Either ptr - int or ptr - ptr. 8564 if (LHS.get()->getType()->isAnyPointerType()) { 8565 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8566 8567 // Diagnose bad cases where we step over interface counts. 8568 if (LHS.get()->getType()->isObjCObjectPointerType() && 8569 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8570 return QualType(); 8571 8572 // The result type of a pointer-int computation is the pointer type. 8573 if (RHS.get()->getType()->isIntegerType()) { 8574 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8575 return QualType(); 8576 8577 // Check array bounds for pointer arithemtic 8578 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8579 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8580 8581 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8582 return LHS.get()->getType(); 8583 } 8584 8585 // Handle pointer-pointer subtractions. 8586 if (const PointerType *RHSPTy 8587 = RHS.get()->getType()->getAs<PointerType>()) { 8588 QualType rpointee = RHSPTy->getPointeeType(); 8589 8590 if (getLangOpts().CPlusPlus) { 8591 // Pointee types must be the same: C++ [expr.add] 8592 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8593 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8594 } 8595 } else { 8596 // Pointee types must be compatible C99 6.5.6p3 8597 if (!Context.typesAreCompatible( 8598 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8599 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8600 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8601 return QualType(); 8602 } 8603 } 8604 8605 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8606 LHS.get(), RHS.get())) 8607 return QualType(); 8608 8609 // The pointee type may have zero size. As an extension, a structure or 8610 // union may have zero size or an array may have zero length. In this 8611 // case subtraction does not make sense. 8612 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8613 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8614 if (ElementSize.isZero()) { 8615 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8616 << rpointee.getUnqualifiedType() 8617 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8618 } 8619 } 8620 8621 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8622 return Context.getPointerDiffType(); 8623 } 8624 } 8625 8626 return InvalidOperands(Loc, LHS, RHS); 8627 } 8628 8629 static bool isScopedEnumerationType(QualType T) { 8630 if (const EnumType *ET = T->getAs<EnumType>()) 8631 return ET->getDecl()->isScoped(); 8632 return false; 8633 } 8634 8635 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8636 SourceLocation Loc, BinaryOperatorKind Opc, 8637 QualType LHSType) { 8638 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8639 // so skip remaining warnings as we don't want to modify values within Sema. 8640 if (S.getLangOpts().OpenCL) 8641 return; 8642 8643 llvm::APSInt Right; 8644 // Check right/shifter operand 8645 if (RHS.get()->isValueDependent() || 8646 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8647 return; 8648 8649 if (Right.isNegative()) { 8650 S.DiagRuntimeBehavior(Loc, RHS.get(), 8651 S.PDiag(diag::warn_shift_negative) 8652 << RHS.get()->getSourceRange()); 8653 return; 8654 } 8655 llvm::APInt LeftBits(Right.getBitWidth(), 8656 S.Context.getTypeSize(LHS.get()->getType())); 8657 if (Right.uge(LeftBits)) { 8658 S.DiagRuntimeBehavior(Loc, RHS.get(), 8659 S.PDiag(diag::warn_shift_gt_typewidth) 8660 << RHS.get()->getSourceRange()); 8661 return; 8662 } 8663 if (Opc != BO_Shl) 8664 return; 8665 8666 // When left shifting an ICE which is signed, we can check for overflow which 8667 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8668 // integers have defined behavior modulo one more than the maximum value 8669 // representable in the result type, so never warn for those. 8670 llvm::APSInt Left; 8671 if (LHS.get()->isValueDependent() || 8672 LHSType->hasUnsignedIntegerRepresentation() || 8673 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8674 return; 8675 8676 // If LHS does not have a signed type and non-negative value 8677 // then, the behavior is undefined. Warn about it. 8678 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8679 S.DiagRuntimeBehavior(Loc, LHS.get(), 8680 S.PDiag(diag::warn_shift_lhs_negative) 8681 << LHS.get()->getSourceRange()); 8682 return; 8683 } 8684 8685 llvm::APInt ResultBits = 8686 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8687 if (LeftBits.uge(ResultBits)) 8688 return; 8689 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8690 Result = Result.shl(Right); 8691 8692 // Print the bit representation of the signed integer as an unsigned 8693 // hexadecimal number. 8694 SmallString<40> HexResult; 8695 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8696 8697 // If we are only missing a sign bit, this is less likely to result in actual 8698 // bugs -- if the result is cast back to an unsigned type, it will have the 8699 // expected value. Thus we place this behind a different warning that can be 8700 // turned off separately if needed. 8701 if (LeftBits == ResultBits - 1) { 8702 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8703 << HexResult << LHSType 8704 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8705 return; 8706 } 8707 8708 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8709 << HexResult.str() << Result.getMinSignedBits() << LHSType 8710 << Left.getBitWidth() << LHS.get()->getSourceRange() 8711 << RHS.get()->getSourceRange(); 8712 } 8713 8714 /// \brief Return the resulting type when a vector is shifted 8715 /// by a scalar or vector shift amount. 8716 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8717 SourceLocation Loc, bool IsCompAssign) { 8718 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8719 if (!LHS.get()->getType()->isVectorType()) { 8720 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8721 << RHS.get()->getType() << LHS.get()->getType() 8722 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8723 return QualType(); 8724 } 8725 8726 if (!IsCompAssign) { 8727 LHS = S.UsualUnaryConversions(LHS.get()); 8728 if (LHS.isInvalid()) return QualType(); 8729 } 8730 8731 RHS = S.UsualUnaryConversions(RHS.get()); 8732 if (RHS.isInvalid()) return QualType(); 8733 8734 QualType LHSType = LHS.get()->getType(); 8735 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8736 QualType LHSEleType = LHSVecTy->getElementType(); 8737 8738 // Note that RHS might not be a vector. 8739 QualType RHSType = RHS.get()->getType(); 8740 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8741 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8742 8743 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8744 if (!LHSEleType->isIntegerType()) { 8745 S.Diag(Loc, diag::err_typecheck_expect_int) 8746 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8747 return QualType(); 8748 } 8749 8750 if (!RHSEleType->isIntegerType()) { 8751 S.Diag(Loc, diag::err_typecheck_expect_int) 8752 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8753 return QualType(); 8754 } 8755 8756 if (RHSVecTy) { 8757 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8758 // are applied component-wise. So if RHS is a vector, then ensure 8759 // that the number of elements is the same as LHS... 8760 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8761 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8762 << LHS.get()->getType() << RHS.get()->getType() 8763 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8764 return QualType(); 8765 } 8766 } else { 8767 // ...else expand RHS to match the number of elements in LHS. 8768 QualType VecTy = 8769 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8770 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8771 } 8772 8773 return LHSType; 8774 } 8775 8776 // C99 6.5.7 8777 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8778 SourceLocation Loc, BinaryOperatorKind Opc, 8779 bool IsCompAssign) { 8780 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8781 8782 // Vector shifts promote their scalar inputs to vector type. 8783 if (LHS.get()->getType()->isVectorType() || 8784 RHS.get()->getType()->isVectorType()) { 8785 if (LangOpts.ZVector) { 8786 // The shift operators for the z vector extensions work basically 8787 // like general shifts, except that neither the LHS nor the RHS is 8788 // allowed to be a "vector bool". 8789 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8790 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8791 return InvalidOperands(Loc, LHS, RHS); 8792 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8793 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8794 return InvalidOperands(Loc, LHS, RHS); 8795 } 8796 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8797 } 8798 8799 // Shifts don't perform usual arithmetic conversions, they just do integer 8800 // promotions on each operand. C99 6.5.7p3 8801 8802 // For the LHS, do usual unary conversions, but then reset them away 8803 // if this is a compound assignment. 8804 ExprResult OldLHS = LHS; 8805 LHS = UsualUnaryConversions(LHS.get()); 8806 if (LHS.isInvalid()) 8807 return QualType(); 8808 QualType LHSType = LHS.get()->getType(); 8809 if (IsCompAssign) LHS = OldLHS; 8810 8811 // The RHS is simpler. 8812 RHS = UsualUnaryConversions(RHS.get()); 8813 if (RHS.isInvalid()) 8814 return QualType(); 8815 QualType RHSType = RHS.get()->getType(); 8816 8817 // C99 6.5.7p2: Each of the operands shall have integer type. 8818 if (!LHSType->hasIntegerRepresentation() || 8819 !RHSType->hasIntegerRepresentation()) 8820 return InvalidOperands(Loc, LHS, RHS); 8821 8822 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8823 // hasIntegerRepresentation() above instead of this. 8824 if (isScopedEnumerationType(LHSType) || 8825 isScopedEnumerationType(RHSType)) { 8826 return InvalidOperands(Loc, LHS, RHS); 8827 } 8828 // Sanity-check shift operands 8829 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8830 8831 // "The type of the result is that of the promoted left operand." 8832 return LHSType; 8833 } 8834 8835 static bool IsWithinTemplateSpecialization(Decl *D) { 8836 if (DeclContext *DC = D->getDeclContext()) { 8837 if (isa<ClassTemplateSpecializationDecl>(DC)) 8838 return true; 8839 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8840 return FD->isFunctionTemplateSpecialization(); 8841 } 8842 return false; 8843 } 8844 8845 /// If two different enums are compared, raise a warning. 8846 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8847 Expr *RHS) { 8848 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8849 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8850 8851 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8852 if (!LHSEnumType) 8853 return; 8854 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8855 if (!RHSEnumType) 8856 return; 8857 8858 // Ignore anonymous enums. 8859 if (!LHSEnumType->getDecl()->getIdentifier()) 8860 return; 8861 if (!RHSEnumType->getDecl()->getIdentifier()) 8862 return; 8863 8864 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8865 return; 8866 8867 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8868 << LHSStrippedType << RHSStrippedType 8869 << LHS->getSourceRange() << RHS->getSourceRange(); 8870 } 8871 8872 /// \brief Diagnose bad pointer comparisons. 8873 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8874 ExprResult &LHS, ExprResult &RHS, 8875 bool IsError) { 8876 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8877 : diag::ext_typecheck_comparison_of_distinct_pointers) 8878 << LHS.get()->getType() << RHS.get()->getType() 8879 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8880 } 8881 8882 /// \brief Returns false if the pointers are converted to a composite type, 8883 /// true otherwise. 8884 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8885 ExprResult &LHS, ExprResult &RHS) { 8886 // C++ [expr.rel]p2: 8887 // [...] Pointer conversions (4.10) and qualification 8888 // conversions (4.4) are performed on pointer operands (or on 8889 // a pointer operand and a null pointer constant) to bring 8890 // them to their composite pointer type. [...] 8891 // 8892 // C++ [expr.eq]p1 uses the same notion for (in)equality 8893 // comparisons of pointers. 8894 8895 // C++ [expr.eq]p2: 8896 // In addition, pointers to members can be compared, or a pointer to 8897 // member and a null pointer constant. Pointer to member conversions 8898 // (4.11) and qualification conversions (4.4) are performed to bring 8899 // them to a common type. If one operand is a null pointer constant, 8900 // the common type is the type of the other operand. Otherwise, the 8901 // common type is a pointer to member type similar (4.4) to the type 8902 // of one of the operands, with a cv-qualification signature (4.4) 8903 // that is the union of the cv-qualification signatures of the operand 8904 // types. 8905 8906 QualType LHSType = LHS.get()->getType(); 8907 QualType RHSType = RHS.get()->getType(); 8908 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8909 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8910 8911 bool NonStandardCompositeType = false; 8912 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8913 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8914 if (T.isNull()) { 8915 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8916 return true; 8917 } 8918 8919 if (NonStandardCompositeType) 8920 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8921 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8922 << RHS.get()->getSourceRange(); 8923 8924 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8925 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8926 return false; 8927 } 8928 8929 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8930 ExprResult &LHS, 8931 ExprResult &RHS, 8932 bool IsError) { 8933 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8934 : diag::ext_typecheck_comparison_of_fptr_to_void) 8935 << LHS.get()->getType() << RHS.get()->getType() 8936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8937 } 8938 8939 static bool isObjCObjectLiteral(ExprResult &E) { 8940 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8941 case Stmt::ObjCArrayLiteralClass: 8942 case Stmt::ObjCDictionaryLiteralClass: 8943 case Stmt::ObjCStringLiteralClass: 8944 case Stmt::ObjCBoxedExprClass: 8945 return true; 8946 default: 8947 // Note that ObjCBoolLiteral is NOT an object literal! 8948 return false; 8949 } 8950 } 8951 8952 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8953 const ObjCObjectPointerType *Type = 8954 LHS->getType()->getAs<ObjCObjectPointerType>(); 8955 8956 // If this is not actually an Objective-C object, bail out. 8957 if (!Type) 8958 return false; 8959 8960 // Get the LHS object's interface type. 8961 QualType InterfaceType = Type->getPointeeType(); 8962 8963 // If the RHS isn't an Objective-C object, bail out. 8964 if (!RHS->getType()->isObjCObjectPointerType()) 8965 return false; 8966 8967 // Try to find the -isEqual: method. 8968 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8969 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8970 InterfaceType, 8971 /*instance=*/true); 8972 if (!Method) { 8973 if (Type->isObjCIdType()) { 8974 // For 'id', just check the global pool. 8975 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8976 /*receiverId=*/true); 8977 } else { 8978 // Check protocols. 8979 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8980 /*instance=*/true); 8981 } 8982 } 8983 8984 if (!Method) 8985 return false; 8986 8987 QualType T = Method->parameters()[0]->getType(); 8988 if (!T->isObjCObjectPointerType()) 8989 return false; 8990 8991 QualType R = Method->getReturnType(); 8992 if (!R->isScalarType()) 8993 return false; 8994 8995 return true; 8996 } 8997 8998 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8999 FromE = FromE->IgnoreParenImpCasts(); 9000 switch (FromE->getStmtClass()) { 9001 default: 9002 break; 9003 case Stmt::ObjCStringLiteralClass: 9004 // "string literal" 9005 return LK_String; 9006 case Stmt::ObjCArrayLiteralClass: 9007 // "array literal" 9008 return LK_Array; 9009 case Stmt::ObjCDictionaryLiteralClass: 9010 // "dictionary literal" 9011 return LK_Dictionary; 9012 case Stmt::BlockExprClass: 9013 return LK_Block; 9014 case Stmt::ObjCBoxedExprClass: { 9015 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9016 switch (Inner->getStmtClass()) { 9017 case Stmt::IntegerLiteralClass: 9018 case Stmt::FloatingLiteralClass: 9019 case Stmt::CharacterLiteralClass: 9020 case Stmt::ObjCBoolLiteralExprClass: 9021 case Stmt::CXXBoolLiteralExprClass: 9022 // "numeric literal" 9023 return LK_Numeric; 9024 case Stmt::ImplicitCastExprClass: { 9025 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9026 // Boolean literals can be represented by implicit casts. 9027 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9028 return LK_Numeric; 9029 break; 9030 } 9031 default: 9032 break; 9033 } 9034 return LK_Boxed; 9035 } 9036 } 9037 return LK_None; 9038 } 9039 9040 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9041 ExprResult &LHS, ExprResult &RHS, 9042 BinaryOperator::Opcode Opc){ 9043 Expr *Literal; 9044 Expr *Other; 9045 if (isObjCObjectLiteral(LHS)) { 9046 Literal = LHS.get(); 9047 Other = RHS.get(); 9048 } else { 9049 Literal = RHS.get(); 9050 Other = LHS.get(); 9051 } 9052 9053 // Don't warn on comparisons against nil. 9054 Other = Other->IgnoreParenCasts(); 9055 if (Other->isNullPointerConstant(S.getASTContext(), 9056 Expr::NPC_ValueDependentIsNotNull)) 9057 return; 9058 9059 // This should be kept in sync with warn_objc_literal_comparison. 9060 // LK_String should always be after the other literals, since it has its own 9061 // warning flag. 9062 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9063 assert(LiteralKind != Sema::LK_Block); 9064 if (LiteralKind == Sema::LK_None) { 9065 llvm_unreachable("Unknown Objective-C object literal kind"); 9066 } 9067 9068 if (LiteralKind == Sema::LK_String) 9069 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9070 << Literal->getSourceRange(); 9071 else 9072 S.Diag(Loc, diag::warn_objc_literal_comparison) 9073 << LiteralKind << Literal->getSourceRange(); 9074 9075 if (BinaryOperator::isEqualityOp(Opc) && 9076 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9077 SourceLocation Start = LHS.get()->getLocStart(); 9078 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9079 CharSourceRange OpRange = 9080 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9081 9082 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9083 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9084 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9085 << FixItHint::CreateInsertion(End, "]"); 9086 } 9087 } 9088 9089 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 9090 ExprResult &RHS, 9091 SourceLocation Loc, 9092 BinaryOperatorKind Opc) { 9093 // Check that left hand side is !something. 9094 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9095 if (!UO || UO->getOpcode() != UO_LNot) return; 9096 9097 // Only check if the right hand side is non-bool arithmetic type. 9098 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9099 9100 // Make sure that the something in !something is not bool. 9101 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9102 if (SubExpr->isKnownToHaveBooleanValue()) return; 9103 9104 // Emit warning. 9105 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 9106 << Loc; 9107 9108 // First note suggest !(x < y) 9109 SourceLocation FirstOpen = SubExpr->getLocStart(); 9110 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9111 FirstClose = S.getLocForEndOfToken(FirstClose); 9112 if (FirstClose.isInvalid()) 9113 FirstOpen = SourceLocation(); 9114 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9115 << FixItHint::CreateInsertion(FirstOpen, "(") 9116 << FixItHint::CreateInsertion(FirstClose, ")"); 9117 9118 // Second note suggests (!x) < y 9119 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9120 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9121 SecondClose = S.getLocForEndOfToken(SecondClose); 9122 if (SecondClose.isInvalid()) 9123 SecondOpen = SourceLocation(); 9124 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9125 << FixItHint::CreateInsertion(SecondOpen, "(") 9126 << FixItHint::CreateInsertion(SecondClose, ")"); 9127 } 9128 9129 // Get the decl for a simple expression: a reference to a variable, 9130 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9131 static ValueDecl *getCompareDecl(Expr *E) { 9132 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9133 return DR->getDecl(); 9134 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9135 if (Ivar->isFreeIvar()) 9136 return Ivar->getDecl(); 9137 } 9138 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9139 if (Mem->isImplicitAccess()) 9140 return Mem->getMemberDecl(); 9141 } 9142 return nullptr; 9143 } 9144 9145 // C99 6.5.8, C++ [expr.rel] 9146 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9147 SourceLocation Loc, BinaryOperatorKind Opc, 9148 bool IsRelational) { 9149 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9150 9151 // Handle vector comparisons separately. 9152 if (LHS.get()->getType()->isVectorType() || 9153 RHS.get()->getType()->isVectorType()) 9154 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9155 9156 QualType LHSType = LHS.get()->getType(); 9157 QualType RHSType = RHS.get()->getType(); 9158 9159 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9160 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9161 9162 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9163 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9164 9165 if (!LHSType->hasFloatingRepresentation() && 9166 !(LHSType->isBlockPointerType() && IsRelational) && 9167 !LHS.get()->getLocStart().isMacroID() && 9168 !RHS.get()->getLocStart().isMacroID() && 9169 ActiveTemplateInstantiations.empty()) { 9170 // For non-floating point types, check for self-comparisons of the form 9171 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9172 // often indicate logic errors in the program. 9173 // 9174 // NOTE: Don't warn about comparison expressions resulting from macro 9175 // expansion. Also don't warn about comparisons which are only self 9176 // comparisons within a template specialization. The warnings should catch 9177 // obvious cases in the definition of the template anyways. The idea is to 9178 // warn when the typed comparison operator will always evaluate to the same 9179 // result. 9180 ValueDecl *DL = getCompareDecl(LHSStripped); 9181 ValueDecl *DR = getCompareDecl(RHSStripped); 9182 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9183 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9184 << 0 // self- 9185 << (Opc == BO_EQ 9186 || Opc == BO_LE 9187 || Opc == BO_GE)); 9188 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9189 !DL->getType()->isReferenceType() && 9190 !DR->getType()->isReferenceType()) { 9191 // what is it always going to eval to? 9192 char always_evals_to; 9193 switch(Opc) { 9194 case BO_EQ: // e.g. array1 == array2 9195 always_evals_to = 0; // false 9196 break; 9197 case BO_NE: // e.g. array1 != array2 9198 always_evals_to = 1; // true 9199 break; 9200 default: 9201 // best we can say is 'a constant' 9202 always_evals_to = 2; // e.g. array1 <= array2 9203 break; 9204 } 9205 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9206 << 1 // array 9207 << always_evals_to); 9208 } 9209 9210 if (isa<CastExpr>(LHSStripped)) 9211 LHSStripped = LHSStripped->IgnoreParenCasts(); 9212 if (isa<CastExpr>(RHSStripped)) 9213 RHSStripped = RHSStripped->IgnoreParenCasts(); 9214 9215 // Warn about comparisons against a string constant (unless the other 9216 // operand is null), the user probably wants strcmp. 9217 Expr *literalString = nullptr; 9218 Expr *literalStringStripped = nullptr; 9219 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9220 !RHSStripped->isNullPointerConstant(Context, 9221 Expr::NPC_ValueDependentIsNull)) { 9222 literalString = LHS.get(); 9223 literalStringStripped = LHSStripped; 9224 } else if ((isa<StringLiteral>(RHSStripped) || 9225 isa<ObjCEncodeExpr>(RHSStripped)) && 9226 !LHSStripped->isNullPointerConstant(Context, 9227 Expr::NPC_ValueDependentIsNull)) { 9228 literalString = RHS.get(); 9229 literalStringStripped = RHSStripped; 9230 } 9231 9232 if (literalString) { 9233 DiagRuntimeBehavior(Loc, nullptr, 9234 PDiag(diag::warn_stringcompare) 9235 << isa<ObjCEncodeExpr>(literalStringStripped) 9236 << literalString->getSourceRange()); 9237 } 9238 } 9239 9240 // C99 6.5.8p3 / C99 6.5.9p4 9241 UsualArithmeticConversions(LHS, RHS); 9242 if (LHS.isInvalid() || RHS.isInvalid()) 9243 return QualType(); 9244 9245 LHSType = LHS.get()->getType(); 9246 RHSType = RHS.get()->getType(); 9247 9248 // The result of comparisons is 'bool' in C++, 'int' in C. 9249 QualType ResultTy = Context.getLogicalOperationType(); 9250 9251 if (IsRelational) { 9252 if (LHSType->isRealType() && RHSType->isRealType()) 9253 return ResultTy; 9254 } else { 9255 // Check for comparisons of floating point operands using != and ==. 9256 if (LHSType->hasFloatingRepresentation()) 9257 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9258 9259 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9260 return ResultTy; 9261 } 9262 9263 const Expr::NullPointerConstantKind LHSNullKind = 9264 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9265 const Expr::NullPointerConstantKind RHSNullKind = 9266 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9267 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9268 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9269 9270 if (!IsRelational && LHSIsNull != RHSIsNull) { 9271 bool IsEquality = Opc == BO_EQ; 9272 if (RHSIsNull) 9273 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9274 RHS.get()->getSourceRange()); 9275 else 9276 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9277 LHS.get()->getSourceRange()); 9278 } 9279 9280 // All of the following pointer-related warnings are GCC extensions, except 9281 // when handling null pointer constants. 9282 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9283 QualType LCanPointeeTy = 9284 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9285 QualType RCanPointeeTy = 9286 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9287 9288 if (getLangOpts().CPlusPlus) { 9289 if (LCanPointeeTy == RCanPointeeTy) 9290 return ResultTy; 9291 if (!IsRelational && 9292 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9293 // Valid unless comparison between non-null pointer and function pointer 9294 // This is a gcc extension compatibility comparison. 9295 // In a SFINAE context, we treat this as a hard error to maintain 9296 // conformance with the C++ standard. 9297 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9298 && !LHSIsNull && !RHSIsNull) { 9299 diagnoseFunctionPointerToVoidComparison( 9300 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9301 9302 if (isSFINAEContext()) 9303 return QualType(); 9304 9305 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9306 return ResultTy; 9307 } 9308 } 9309 9310 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9311 return QualType(); 9312 else 9313 return ResultTy; 9314 } 9315 // C99 6.5.9p2 and C99 6.5.8p2 9316 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9317 RCanPointeeTy.getUnqualifiedType())) { 9318 // Valid unless a relational comparison of function pointers 9319 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9320 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9321 << LHSType << RHSType << LHS.get()->getSourceRange() 9322 << RHS.get()->getSourceRange(); 9323 } 9324 } else if (!IsRelational && 9325 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9326 // Valid unless comparison between non-null pointer and function pointer 9327 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9328 && !LHSIsNull && !RHSIsNull) 9329 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9330 /*isError*/false); 9331 } else { 9332 // Invalid 9333 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9334 } 9335 if (LCanPointeeTy != RCanPointeeTy) { 9336 // Treat NULL constant as a special case in OpenCL. 9337 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9338 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9339 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9340 Diag(Loc, 9341 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9342 << LHSType << RHSType << 0 /* comparison */ 9343 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9344 } 9345 } 9346 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9347 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9348 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9349 : CK_BitCast; 9350 if (LHSIsNull && !RHSIsNull) 9351 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9352 else 9353 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9354 } 9355 return ResultTy; 9356 } 9357 9358 if (getLangOpts().CPlusPlus) { 9359 // Comparison of nullptr_t with itself. 9360 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9361 return ResultTy; 9362 9363 // Comparison of pointers with null pointer constants and equality 9364 // comparisons of member pointers to null pointer constants. 9365 if (RHSIsNull && 9366 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9367 (!IsRelational && 9368 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9369 RHS = ImpCastExprToType(RHS.get(), LHSType, 9370 LHSType->isMemberPointerType() 9371 ? CK_NullToMemberPointer 9372 : CK_NullToPointer); 9373 return ResultTy; 9374 } 9375 if (LHSIsNull && 9376 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9377 (!IsRelational && 9378 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9379 LHS = ImpCastExprToType(LHS.get(), RHSType, 9380 RHSType->isMemberPointerType() 9381 ? CK_NullToMemberPointer 9382 : CK_NullToPointer); 9383 return ResultTy; 9384 } 9385 9386 // Comparison of member pointers. 9387 if (!IsRelational && 9388 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9389 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9390 return QualType(); 9391 else 9392 return ResultTy; 9393 } 9394 9395 // Handle scoped enumeration types specifically, since they don't promote 9396 // to integers. 9397 if (LHS.get()->getType()->isEnumeralType() && 9398 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9399 RHS.get()->getType())) 9400 return ResultTy; 9401 } 9402 9403 // Handle block pointer types. 9404 if (!IsRelational && LHSType->isBlockPointerType() && 9405 RHSType->isBlockPointerType()) { 9406 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9407 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9408 9409 if (!LHSIsNull && !RHSIsNull && 9410 !Context.typesAreCompatible(lpointee, rpointee)) { 9411 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9412 << LHSType << RHSType << LHS.get()->getSourceRange() 9413 << RHS.get()->getSourceRange(); 9414 } 9415 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9416 return ResultTy; 9417 } 9418 9419 // Allow block pointers to be compared with null pointer constants. 9420 if (!IsRelational 9421 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9422 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9423 if (!LHSIsNull && !RHSIsNull) { 9424 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9425 ->getPointeeType()->isVoidType()) 9426 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9427 ->getPointeeType()->isVoidType()))) 9428 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9429 << LHSType << RHSType << LHS.get()->getSourceRange() 9430 << RHS.get()->getSourceRange(); 9431 } 9432 if (LHSIsNull && !RHSIsNull) 9433 LHS = ImpCastExprToType(LHS.get(), RHSType, 9434 RHSType->isPointerType() ? CK_BitCast 9435 : CK_AnyPointerToBlockPointerCast); 9436 else 9437 RHS = ImpCastExprToType(RHS.get(), LHSType, 9438 LHSType->isPointerType() ? CK_BitCast 9439 : CK_AnyPointerToBlockPointerCast); 9440 return ResultTy; 9441 } 9442 9443 if (LHSType->isObjCObjectPointerType() || 9444 RHSType->isObjCObjectPointerType()) { 9445 const PointerType *LPT = LHSType->getAs<PointerType>(); 9446 const PointerType *RPT = RHSType->getAs<PointerType>(); 9447 if (LPT || RPT) { 9448 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9449 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9450 9451 if (!LPtrToVoid && !RPtrToVoid && 9452 !Context.typesAreCompatible(LHSType, RHSType)) { 9453 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9454 /*isError*/false); 9455 } 9456 if (LHSIsNull && !RHSIsNull) { 9457 Expr *E = LHS.get(); 9458 if (getLangOpts().ObjCAutoRefCount) 9459 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9460 LHS = ImpCastExprToType(E, RHSType, 9461 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9462 } 9463 else { 9464 Expr *E = RHS.get(); 9465 if (getLangOpts().ObjCAutoRefCount) 9466 CheckObjCARCConversion(SourceRange(), LHSType, E, 9467 CCK_ImplicitConversion, /*Diagnose=*/true, 9468 /*DiagnoseCFAudited=*/false, Opc); 9469 RHS = ImpCastExprToType(E, LHSType, 9470 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9471 } 9472 return ResultTy; 9473 } 9474 if (LHSType->isObjCObjectPointerType() && 9475 RHSType->isObjCObjectPointerType()) { 9476 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9477 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9478 /*isError*/false); 9479 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9480 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9481 9482 if (LHSIsNull && !RHSIsNull) 9483 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9484 else 9485 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9486 return ResultTy; 9487 } 9488 } 9489 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9490 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9491 unsigned DiagID = 0; 9492 bool isError = false; 9493 if (LangOpts.DebuggerSupport) { 9494 // Under a debugger, allow the comparison of pointers to integers, 9495 // since users tend to want to compare addresses. 9496 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9497 (RHSIsNull && RHSType->isIntegerType())) { 9498 if (IsRelational && !getLangOpts().CPlusPlus) 9499 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9500 } else if (IsRelational && !getLangOpts().CPlusPlus) 9501 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9502 else if (getLangOpts().CPlusPlus) { 9503 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9504 isError = true; 9505 } else 9506 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9507 9508 if (DiagID) { 9509 Diag(Loc, DiagID) 9510 << LHSType << RHSType << LHS.get()->getSourceRange() 9511 << RHS.get()->getSourceRange(); 9512 if (isError) 9513 return QualType(); 9514 } 9515 9516 if (LHSType->isIntegerType()) 9517 LHS = ImpCastExprToType(LHS.get(), RHSType, 9518 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9519 else 9520 RHS = ImpCastExprToType(RHS.get(), LHSType, 9521 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9522 return ResultTy; 9523 } 9524 9525 // Handle block pointers. 9526 if (!IsRelational && RHSIsNull 9527 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9528 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9529 return ResultTy; 9530 } 9531 if (!IsRelational && LHSIsNull 9532 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9533 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9534 return ResultTy; 9535 } 9536 9537 return InvalidOperands(Loc, LHS, RHS); 9538 } 9539 9540 9541 // Return a signed type that is of identical size and number of elements. 9542 // For floating point vectors, return an integer type of identical size 9543 // and number of elements. 9544 QualType Sema::GetSignedVectorType(QualType V) { 9545 const VectorType *VTy = V->getAs<VectorType>(); 9546 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9547 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9548 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9549 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9550 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9551 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9552 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9553 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9554 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9555 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9556 "Unhandled vector element size in vector compare"); 9557 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9558 } 9559 9560 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9561 /// operates on extended vector types. Instead of producing an IntTy result, 9562 /// like a scalar comparison, a vector comparison produces a vector of integer 9563 /// types. 9564 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9565 SourceLocation Loc, 9566 bool IsRelational) { 9567 // Check to make sure we're operating on vectors of the same type and width, 9568 // Allowing one side to be a scalar of element type. 9569 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9570 /*AllowBothBool*/true, 9571 /*AllowBoolConversions*/getLangOpts().ZVector); 9572 if (vType.isNull()) 9573 return vType; 9574 9575 QualType LHSType = LHS.get()->getType(); 9576 9577 // If AltiVec, the comparison results in a numeric type, i.e. 9578 // bool for C++, int for C 9579 if (getLangOpts().AltiVec && 9580 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9581 return Context.getLogicalOperationType(); 9582 9583 // For non-floating point types, check for self-comparisons of the form 9584 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9585 // often indicate logic errors in the program. 9586 if (!LHSType->hasFloatingRepresentation() && 9587 ActiveTemplateInstantiations.empty()) { 9588 if (DeclRefExpr* DRL 9589 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9590 if (DeclRefExpr* DRR 9591 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9592 if (DRL->getDecl() == DRR->getDecl()) 9593 DiagRuntimeBehavior(Loc, nullptr, 9594 PDiag(diag::warn_comparison_always) 9595 << 0 // self- 9596 << 2 // "a constant" 9597 ); 9598 } 9599 9600 // Check for comparisons of floating point operands using != and ==. 9601 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9602 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9603 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9604 } 9605 9606 // Return a signed type for the vector. 9607 return GetSignedVectorType(vType); 9608 } 9609 9610 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9611 SourceLocation Loc) { 9612 // Ensure that either both operands are of the same vector type, or 9613 // one operand is of a vector type and the other is of its element type. 9614 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9615 /*AllowBothBool*/true, 9616 /*AllowBoolConversions*/false); 9617 if (vType.isNull()) 9618 return InvalidOperands(Loc, LHS, RHS); 9619 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9620 vType->hasFloatingRepresentation()) 9621 return InvalidOperands(Loc, LHS, RHS); 9622 9623 return GetSignedVectorType(LHS.get()->getType()); 9624 } 9625 9626 inline QualType Sema::CheckBitwiseOperands( 9627 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9628 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9629 9630 if (LHS.get()->getType()->isVectorType() || 9631 RHS.get()->getType()->isVectorType()) { 9632 if (LHS.get()->getType()->hasIntegerRepresentation() && 9633 RHS.get()->getType()->hasIntegerRepresentation()) 9634 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9635 /*AllowBothBool*/true, 9636 /*AllowBoolConversions*/getLangOpts().ZVector); 9637 return InvalidOperands(Loc, LHS, RHS); 9638 } 9639 9640 ExprResult LHSResult = LHS, RHSResult = RHS; 9641 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9642 IsCompAssign); 9643 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9644 return QualType(); 9645 LHS = LHSResult.get(); 9646 RHS = RHSResult.get(); 9647 9648 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9649 return compType; 9650 return InvalidOperands(Loc, LHS, RHS); 9651 } 9652 9653 // C99 6.5.[13,14] 9654 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9655 SourceLocation Loc, 9656 BinaryOperatorKind Opc) { 9657 // Check vector operands differently. 9658 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9659 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9660 9661 // Diagnose cases where the user write a logical and/or but probably meant a 9662 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9663 // is a constant. 9664 if (LHS.get()->getType()->isIntegerType() && 9665 !LHS.get()->getType()->isBooleanType() && 9666 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9667 // Don't warn in macros or template instantiations. 9668 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9669 // If the RHS can be constant folded, and if it constant folds to something 9670 // that isn't 0 or 1 (which indicate a potential logical operation that 9671 // happened to fold to true/false) then warn. 9672 // Parens on the RHS are ignored. 9673 llvm::APSInt Result; 9674 if (RHS.get()->EvaluateAsInt(Result, Context)) 9675 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9676 !RHS.get()->getExprLoc().isMacroID()) || 9677 (Result != 0 && Result != 1)) { 9678 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9679 << RHS.get()->getSourceRange() 9680 << (Opc == BO_LAnd ? "&&" : "||"); 9681 // Suggest replacing the logical operator with the bitwise version 9682 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9683 << (Opc == BO_LAnd ? "&" : "|") 9684 << FixItHint::CreateReplacement(SourceRange( 9685 Loc, getLocForEndOfToken(Loc)), 9686 Opc == BO_LAnd ? "&" : "|"); 9687 if (Opc == BO_LAnd) 9688 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9689 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9690 << FixItHint::CreateRemoval( 9691 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9692 RHS.get()->getLocEnd())); 9693 } 9694 } 9695 9696 if (!Context.getLangOpts().CPlusPlus) { 9697 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9698 // not operate on the built-in scalar and vector float types. 9699 if (Context.getLangOpts().OpenCL && 9700 Context.getLangOpts().OpenCLVersion < 120) { 9701 if (LHS.get()->getType()->isFloatingType() || 9702 RHS.get()->getType()->isFloatingType()) 9703 return InvalidOperands(Loc, LHS, RHS); 9704 } 9705 9706 LHS = UsualUnaryConversions(LHS.get()); 9707 if (LHS.isInvalid()) 9708 return QualType(); 9709 9710 RHS = UsualUnaryConversions(RHS.get()); 9711 if (RHS.isInvalid()) 9712 return QualType(); 9713 9714 if (!LHS.get()->getType()->isScalarType() || 9715 !RHS.get()->getType()->isScalarType()) 9716 return InvalidOperands(Loc, LHS, RHS); 9717 9718 return Context.IntTy; 9719 } 9720 9721 // The following is safe because we only use this method for 9722 // non-overloadable operands. 9723 9724 // C++ [expr.log.and]p1 9725 // C++ [expr.log.or]p1 9726 // The operands are both contextually converted to type bool. 9727 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9728 if (LHSRes.isInvalid()) 9729 return InvalidOperands(Loc, LHS, RHS); 9730 LHS = LHSRes; 9731 9732 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9733 if (RHSRes.isInvalid()) 9734 return InvalidOperands(Loc, LHS, RHS); 9735 RHS = RHSRes; 9736 9737 // C++ [expr.log.and]p2 9738 // C++ [expr.log.or]p2 9739 // The result is a bool. 9740 return Context.BoolTy; 9741 } 9742 9743 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9744 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9745 if (!ME) return false; 9746 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9747 ObjCMessageExpr *Base = 9748 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9749 if (!Base) return false; 9750 return Base->getMethodDecl() != nullptr; 9751 } 9752 9753 /// Is the given expression (which must be 'const') a reference to a 9754 /// variable which was originally non-const, but which has become 9755 /// 'const' due to being captured within a block? 9756 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9757 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9758 assert(E->isLValue() && E->getType().isConstQualified()); 9759 E = E->IgnoreParens(); 9760 9761 // Must be a reference to a declaration from an enclosing scope. 9762 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9763 if (!DRE) return NCCK_None; 9764 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9765 9766 // The declaration must be a variable which is not declared 'const'. 9767 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9768 if (!var) return NCCK_None; 9769 if (var->getType().isConstQualified()) return NCCK_None; 9770 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9771 9772 // Decide whether the first capture was for a block or a lambda. 9773 DeclContext *DC = S.CurContext, *Prev = nullptr; 9774 // Decide whether the first capture was for a block or a lambda. 9775 while (DC) { 9776 // For init-capture, it is possible that the variable belongs to the 9777 // template pattern of the current context. 9778 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9779 if (var->isInitCapture() && 9780 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9781 break; 9782 if (DC == var->getDeclContext()) 9783 break; 9784 Prev = DC; 9785 DC = DC->getParent(); 9786 } 9787 // Unless we have an init-capture, we've gone one step too far. 9788 if (!var->isInitCapture()) 9789 DC = Prev; 9790 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9791 } 9792 9793 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9794 Ty = Ty.getNonReferenceType(); 9795 if (IsDereference && Ty->isPointerType()) 9796 Ty = Ty->getPointeeType(); 9797 return !Ty.isConstQualified(); 9798 } 9799 9800 /// Emit the "read-only variable not assignable" error and print notes to give 9801 /// more information about why the variable is not assignable, such as pointing 9802 /// to the declaration of a const variable, showing that a method is const, or 9803 /// that the function is returning a const reference. 9804 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9805 SourceLocation Loc) { 9806 // Update err_typecheck_assign_const and note_typecheck_assign_const 9807 // when this enum is changed. 9808 enum { 9809 ConstFunction, 9810 ConstVariable, 9811 ConstMember, 9812 ConstMethod, 9813 ConstUnknown, // Keep as last element 9814 }; 9815 9816 SourceRange ExprRange = E->getSourceRange(); 9817 9818 // Only emit one error on the first const found. All other consts will emit 9819 // a note to the error. 9820 bool DiagnosticEmitted = false; 9821 9822 // Track if the current expression is the result of a derefence, and if the 9823 // next checked expression is the result of a derefence. 9824 bool IsDereference = false; 9825 bool NextIsDereference = false; 9826 9827 // Loop to process MemberExpr chains. 9828 while (true) { 9829 IsDereference = NextIsDereference; 9830 NextIsDereference = false; 9831 9832 E = E->IgnoreParenImpCasts(); 9833 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9834 NextIsDereference = ME->isArrow(); 9835 const ValueDecl *VD = ME->getMemberDecl(); 9836 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9837 // Mutable fields can be modified even if the class is const. 9838 if (Field->isMutable()) { 9839 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9840 break; 9841 } 9842 9843 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9844 if (!DiagnosticEmitted) { 9845 S.Diag(Loc, diag::err_typecheck_assign_const) 9846 << ExprRange << ConstMember << false /*static*/ << Field 9847 << Field->getType(); 9848 DiagnosticEmitted = true; 9849 } 9850 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9851 << ConstMember << false /*static*/ << Field << Field->getType() 9852 << Field->getSourceRange(); 9853 } 9854 E = ME->getBase(); 9855 continue; 9856 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9857 if (VDecl->getType().isConstQualified()) { 9858 if (!DiagnosticEmitted) { 9859 S.Diag(Loc, diag::err_typecheck_assign_const) 9860 << ExprRange << ConstMember << true /*static*/ << VDecl 9861 << VDecl->getType(); 9862 DiagnosticEmitted = true; 9863 } 9864 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9865 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9866 << VDecl->getSourceRange(); 9867 } 9868 // Static fields do not inherit constness from parents. 9869 break; 9870 } 9871 break; 9872 } // End MemberExpr 9873 break; 9874 } 9875 9876 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9877 // Function calls 9878 const FunctionDecl *FD = CE->getDirectCallee(); 9879 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9880 if (!DiagnosticEmitted) { 9881 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9882 << ConstFunction << FD; 9883 DiagnosticEmitted = true; 9884 } 9885 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9886 diag::note_typecheck_assign_const) 9887 << ConstFunction << FD << FD->getReturnType() 9888 << FD->getReturnTypeSourceRange(); 9889 } 9890 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9891 // Point to variable declaration. 9892 if (const ValueDecl *VD = DRE->getDecl()) { 9893 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9894 if (!DiagnosticEmitted) { 9895 S.Diag(Loc, diag::err_typecheck_assign_const) 9896 << ExprRange << ConstVariable << VD << VD->getType(); 9897 DiagnosticEmitted = true; 9898 } 9899 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9900 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9901 } 9902 } 9903 } else if (isa<CXXThisExpr>(E)) { 9904 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9905 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9906 if (MD->isConst()) { 9907 if (!DiagnosticEmitted) { 9908 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9909 << ConstMethod << MD; 9910 DiagnosticEmitted = true; 9911 } 9912 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9913 << ConstMethod << MD << MD->getSourceRange(); 9914 } 9915 } 9916 } 9917 } 9918 9919 if (DiagnosticEmitted) 9920 return; 9921 9922 // Can't determine a more specific message, so display the generic error. 9923 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9924 } 9925 9926 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9927 /// emit an error and return true. If so, return false. 9928 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9929 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9930 9931 S.CheckShadowingDeclModification(E, Loc); 9932 9933 SourceLocation OrigLoc = Loc; 9934 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9935 &Loc); 9936 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9937 IsLV = Expr::MLV_InvalidMessageExpression; 9938 if (IsLV == Expr::MLV_Valid) 9939 return false; 9940 9941 unsigned DiagID = 0; 9942 bool NeedType = false; 9943 switch (IsLV) { // C99 6.5.16p2 9944 case Expr::MLV_ConstQualified: 9945 // Use a specialized diagnostic when we're assigning to an object 9946 // from an enclosing function or block. 9947 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9948 if (NCCK == NCCK_Block) 9949 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9950 else 9951 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9952 break; 9953 } 9954 9955 // In ARC, use some specialized diagnostics for occasions where we 9956 // infer 'const'. These are always pseudo-strong variables. 9957 if (S.getLangOpts().ObjCAutoRefCount) { 9958 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9959 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9960 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9961 9962 // Use the normal diagnostic if it's pseudo-__strong but the 9963 // user actually wrote 'const'. 9964 if (var->isARCPseudoStrong() && 9965 (!var->getTypeSourceInfo() || 9966 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9967 // There are two pseudo-strong cases: 9968 // - self 9969 ObjCMethodDecl *method = S.getCurMethodDecl(); 9970 if (method && var == method->getSelfDecl()) 9971 DiagID = method->isClassMethod() 9972 ? diag::err_typecheck_arc_assign_self_class_method 9973 : diag::err_typecheck_arc_assign_self; 9974 9975 // - fast enumeration variables 9976 else 9977 DiagID = diag::err_typecheck_arr_assign_enumeration; 9978 9979 SourceRange Assign; 9980 if (Loc != OrigLoc) 9981 Assign = SourceRange(OrigLoc, OrigLoc); 9982 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9983 // We need to preserve the AST regardless, so migration tool 9984 // can do its job. 9985 return false; 9986 } 9987 } 9988 } 9989 9990 // If none of the special cases above are triggered, then this is a 9991 // simple const assignment. 9992 if (DiagID == 0) { 9993 DiagnoseConstAssignment(S, E, Loc); 9994 return true; 9995 } 9996 9997 break; 9998 case Expr::MLV_ConstAddrSpace: 9999 DiagnoseConstAssignment(S, E, Loc); 10000 return true; 10001 case Expr::MLV_ArrayType: 10002 case Expr::MLV_ArrayTemporary: 10003 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10004 NeedType = true; 10005 break; 10006 case Expr::MLV_NotObjectType: 10007 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10008 NeedType = true; 10009 break; 10010 case Expr::MLV_LValueCast: 10011 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10012 break; 10013 case Expr::MLV_Valid: 10014 llvm_unreachable("did not take early return for MLV_Valid"); 10015 case Expr::MLV_InvalidExpression: 10016 case Expr::MLV_MemberFunction: 10017 case Expr::MLV_ClassTemporary: 10018 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10019 break; 10020 case Expr::MLV_IncompleteType: 10021 case Expr::MLV_IncompleteVoidType: 10022 return S.RequireCompleteType(Loc, E->getType(), 10023 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10024 case Expr::MLV_DuplicateVectorComponents: 10025 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10026 break; 10027 case Expr::MLV_NoSetterProperty: 10028 llvm_unreachable("readonly properties should be processed differently"); 10029 case Expr::MLV_InvalidMessageExpression: 10030 DiagID = diag::error_readonly_message_assignment; 10031 break; 10032 case Expr::MLV_SubObjCPropertySetting: 10033 DiagID = diag::error_no_subobject_property_setting; 10034 break; 10035 } 10036 10037 SourceRange Assign; 10038 if (Loc != OrigLoc) 10039 Assign = SourceRange(OrigLoc, OrigLoc); 10040 if (NeedType) 10041 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10042 else 10043 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10044 return true; 10045 } 10046 10047 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10048 SourceLocation Loc, 10049 Sema &Sema) { 10050 // C / C++ fields 10051 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10052 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10053 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10054 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10055 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10056 } 10057 10058 // Objective-C instance variables 10059 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10060 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10061 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10062 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10063 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10064 if (RL && RR && RL->getDecl() == RR->getDecl()) 10065 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10066 } 10067 } 10068 10069 // C99 6.5.16.1 10070 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10071 SourceLocation Loc, 10072 QualType CompoundType) { 10073 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10074 10075 // Verify that LHS is a modifiable lvalue, and emit error if not. 10076 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10077 return QualType(); 10078 10079 QualType LHSType = LHSExpr->getType(); 10080 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10081 CompoundType; 10082 AssignConvertType ConvTy; 10083 if (CompoundType.isNull()) { 10084 Expr *RHSCheck = RHS.get(); 10085 10086 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10087 10088 QualType LHSTy(LHSType); 10089 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10090 if (RHS.isInvalid()) 10091 return QualType(); 10092 // Special case of NSObject attributes on c-style pointer types. 10093 if (ConvTy == IncompatiblePointer && 10094 ((Context.isObjCNSObjectType(LHSType) && 10095 RHSType->isObjCObjectPointerType()) || 10096 (Context.isObjCNSObjectType(RHSType) && 10097 LHSType->isObjCObjectPointerType()))) 10098 ConvTy = Compatible; 10099 10100 if (ConvTy == Compatible && 10101 LHSType->isObjCObjectType()) 10102 Diag(Loc, diag::err_objc_object_assignment) 10103 << LHSType; 10104 10105 // If the RHS is a unary plus or minus, check to see if they = and + are 10106 // right next to each other. If so, the user may have typo'd "x =+ 4" 10107 // instead of "x += 4". 10108 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10109 RHSCheck = ICE->getSubExpr(); 10110 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10111 if ((UO->getOpcode() == UO_Plus || 10112 UO->getOpcode() == UO_Minus) && 10113 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10114 // Only if the two operators are exactly adjacent. 10115 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10116 // And there is a space or other character before the subexpr of the 10117 // unary +/-. We don't want to warn on "x=-1". 10118 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10119 UO->getSubExpr()->getLocStart().isFileID()) { 10120 Diag(Loc, diag::warn_not_compound_assign) 10121 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10122 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10123 } 10124 } 10125 10126 if (ConvTy == Compatible) { 10127 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10128 // Warn about retain cycles where a block captures the LHS, but 10129 // not if the LHS is a simple variable into which the block is 10130 // being stored...unless that variable can be captured by reference! 10131 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10132 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10133 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10134 checkRetainCycles(LHSExpr, RHS.get()); 10135 10136 // It is safe to assign a weak reference into a strong variable. 10137 // Although this code can still have problems: 10138 // id x = self.weakProp; 10139 // id y = self.weakProp; 10140 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10141 // paths through the function. This should be revisited if 10142 // -Wrepeated-use-of-weak is made flow-sensitive. 10143 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10144 RHS.get()->getLocStart())) 10145 getCurFunction()->markSafeWeakUse(RHS.get()); 10146 10147 } else if (getLangOpts().ObjCAutoRefCount) { 10148 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10149 } 10150 } 10151 } else { 10152 // Compound assignment "x += y" 10153 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10154 } 10155 10156 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10157 RHS.get(), AA_Assigning)) 10158 return QualType(); 10159 10160 CheckForNullPointerDereference(*this, LHSExpr); 10161 10162 // C99 6.5.16p3: The type of an assignment expression is the type of the 10163 // left operand unless the left operand has qualified type, in which case 10164 // it is the unqualified version of the type of the left operand. 10165 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10166 // is converted to the type of the assignment expression (above). 10167 // C++ 5.17p1: the type of the assignment expression is that of its left 10168 // operand. 10169 return (getLangOpts().CPlusPlus 10170 ? LHSType : LHSType.getUnqualifiedType()); 10171 } 10172 10173 // Only ignore explicit casts to void. 10174 static bool IgnoreCommaOperand(const Expr *E) { 10175 E = E->IgnoreParens(); 10176 10177 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10178 if (CE->getCastKind() == CK_ToVoid) { 10179 return true; 10180 } 10181 } 10182 10183 return false; 10184 } 10185 10186 // Look for instances where it is likely the comma operator is confused with 10187 // another operator. There is a whitelist of acceptable expressions for the 10188 // left hand side of the comma operator, otherwise emit a warning. 10189 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10190 // No warnings in macros 10191 if (Loc.isMacroID()) 10192 return; 10193 10194 // Don't warn in template instantiations. 10195 if (!ActiveTemplateInstantiations.empty()) 10196 return; 10197 10198 // Scope isn't fine-grained enough to whitelist the specific cases, so 10199 // instead, skip more than needed, then call back into here with the 10200 // CommaVisitor in SemaStmt.cpp. 10201 // The whitelisted locations are the initialization and increment portions 10202 // of a for loop. The additional checks are on the condition of 10203 // if statements, do/while loops, and for loops. 10204 const unsigned ForIncrementFlags = 10205 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10206 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10207 const unsigned ScopeFlags = getCurScope()->getFlags(); 10208 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10209 (ScopeFlags & ForInitFlags) == ForInitFlags) 10210 return; 10211 10212 // If there are multiple comma operators used together, get the RHS of the 10213 // of the comma operator as the LHS. 10214 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10215 if (BO->getOpcode() != BO_Comma) 10216 break; 10217 LHS = BO->getRHS(); 10218 } 10219 10220 // Only allow some expressions on LHS to not warn. 10221 if (IgnoreCommaOperand(LHS)) 10222 return; 10223 10224 Diag(Loc, diag::warn_comma_operator); 10225 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10226 << LHS->getSourceRange() 10227 << FixItHint::CreateInsertion(LHS->getLocStart(), 10228 LangOpts.CPlusPlus ? "static_cast<void>(" 10229 : "(void)(") 10230 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10231 ")"); 10232 } 10233 10234 // C99 6.5.17 10235 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10236 SourceLocation Loc) { 10237 LHS = S.CheckPlaceholderExpr(LHS.get()); 10238 RHS = S.CheckPlaceholderExpr(RHS.get()); 10239 if (LHS.isInvalid() || RHS.isInvalid()) 10240 return QualType(); 10241 10242 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10243 // operands, but not unary promotions. 10244 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10245 10246 // So we treat the LHS as a ignored value, and in C++ we allow the 10247 // containing site to determine what should be done with the RHS. 10248 LHS = S.IgnoredValueConversions(LHS.get()); 10249 if (LHS.isInvalid()) 10250 return QualType(); 10251 10252 S.DiagnoseUnusedExprResult(LHS.get()); 10253 10254 if (!S.getLangOpts().CPlusPlus) { 10255 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10256 if (RHS.isInvalid()) 10257 return QualType(); 10258 if (!RHS.get()->getType()->isVoidType()) 10259 S.RequireCompleteType(Loc, RHS.get()->getType(), 10260 diag::err_incomplete_type); 10261 } 10262 10263 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10264 S.DiagnoseCommaOperator(LHS.get(), Loc); 10265 10266 return RHS.get()->getType(); 10267 } 10268 10269 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10270 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10271 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10272 ExprValueKind &VK, 10273 ExprObjectKind &OK, 10274 SourceLocation OpLoc, 10275 bool IsInc, bool IsPrefix) { 10276 if (Op->isTypeDependent()) 10277 return S.Context.DependentTy; 10278 10279 QualType ResType = Op->getType(); 10280 // Atomic types can be used for increment / decrement where the non-atomic 10281 // versions can, so ignore the _Atomic() specifier for the purpose of 10282 // checking. 10283 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10284 ResType = ResAtomicType->getValueType(); 10285 10286 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10287 10288 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10289 // Decrement of bool is not allowed. 10290 if (!IsInc) { 10291 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10292 return QualType(); 10293 } 10294 // Increment of bool sets it to true, but is deprecated. 10295 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10296 : diag::warn_increment_bool) 10297 << Op->getSourceRange(); 10298 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10299 // Error on enum increments and decrements in C++ mode 10300 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10301 return QualType(); 10302 } else if (ResType->isRealType()) { 10303 // OK! 10304 } else if (ResType->isPointerType()) { 10305 // C99 6.5.2.4p2, 6.5.6p2 10306 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10307 return QualType(); 10308 } else if (ResType->isObjCObjectPointerType()) { 10309 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10310 // Otherwise, we just need a complete type. 10311 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10312 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10313 return QualType(); 10314 } else if (ResType->isAnyComplexType()) { 10315 // C99 does not support ++/-- on complex types, we allow as an extension. 10316 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10317 << ResType << Op->getSourceRange(); 10318 } else if (ResType->isPlaceholderType()) { 10319 ExprResult PR = S.CheckPlaceholderExpr(Op); 10320 if (PR.isInvalid()) return QualType(); 10321 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10322 IsInc, IsPrefix); 10323 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10324 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10325 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10326 (ResType->getAs<VectorType>()->getVectorKind() != 10327 VectorType::AltiVecBool)) { 10328 // The z vector extensions allow ++ and -- for non-bool vectors. 10329 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10330 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10331 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10332 } else { 10333 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10334 << ResType << int(IsInc) << Op->getSourceRange(); 10335 return QualType(); 10336 } 10337 // At this point, we know we have a real, complex or pointer type. 10338 // Now make sure the operand is a modifiable lvalue. 10339 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10340 return QualType(); 10341 // In C++, a prefix increment is the same type as the operand. Otherwise 10342 // (in C or with postfix), the increment is the unqualified type of the 10343 // operand. 10344 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10345 VK = VK_LValue; 10346 OK = Op->getObjectKind(); 10347 return ResType; 10348 } else { 10349 VK = VK_RValue; 10350 return ResType.getUnqualifiedType(); 10351 } 10352 } 10353 10354 10355 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10356 /// This routine allows us to typecheck complex/recursive expressions 10357 /// where the declaration is needed for type checking. We only need to 10358 /// handle cases when the expression references a function designator 10359 /// or is an lvalue. Here are some examples: 10360 /// - &(x) => x 10361 /// - &*****f => f for f a function designator. 10362 /// - &s.xx => s 10363 /// - &s.zz[1].yy -> s, if zz is an array 10364 /// - *(x + 1) -> x, if x is an array 10365 /// - &"123"[2] -> 0 10366 /// - & __real__ x -> x 10367 static ValueDecl *getPrimaryDecl(Expr *E) { 10368 switch (E->getStmtClass()) { 10369 case Stmt::DeclRefExprClass: 10370 return cast<DeclRefExpr>(E)->getDecl(); 10371 case Stmt::MemberExprClass: 10372 // If this is an arrow operator, the address is an offset from 10373 // the base's value, so the object the base refers to is 10374 // irrelevant. 10375 if (cast<MemberExpr>(E)->isArrow()) 10376 return nullptr; 10377 // Otherwise, the expression refers to a part of the base 10378 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10379 case Stmt::ArraySubscriptExprClass: { 10380 // FIXME: This code shouldn't be necessary! We should catch the implicit 10381 // promotion of register arrays earlier. 10382 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10383 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10384 if (ICE->getSubExpr()->getType()->isArrayType()) 10385 return getPrimaryDecl(ICE->getSubExpr()); 10386 } 10387 return nullptr; 10388 } 10389 case Stmt::UnaryOperatorClass: { 10390 UnaryOperator *UO = cast<UnaryOperator>(E); 10391 10392 switch(UO->getOpcode()) { 10393 case UO_Real: 10394 case UO_Imag: 10395 case UO_Extension: 10396 return getPrimaryDecl(UO->getSubExpr()); 10397 default: 10398 return nullptr; 10399 } 10400 } 10401 case Stmt::ParenExprClass: 10402 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10403 case Stmt::ImplicitCastExprClass: 10404 // If the result of an implicit cast is an l-value, we care about 10405 // the sub-expression; otherwise, the result here doesn't matter. 10406 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10407 default: 10408 return nullptr; 10409 } 10410 } 10411 10412 namespace { 10413 enum { 10414 AO_Bit_Field = 0, 10415 AO_Vector_Element = 1, 10416 AO_Property_Expansion = 2, 10417 AO_Register_Variable = 3, 10418 AO_No_Error = 4 10419 }; 10420 } 10421 /// \brief Diagnose invalid operand for address of operations. 10422 /// 10423 /// \param Type The type of operand which cannot have its address taken. 10424 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10425 Expr *E, unsigned Type) { 10426 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10427 } 10428 10429 /// CheckAddressOfOperand - The operand of & must be either a function 10430 /// designator or an lvalue designating an object. If it is an lvalue, the 10431 /// object cannot be declared with storage class register or be a bit field. 10432 /// Note: The usual conversions are *not* applied to the operand of the & 10433 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10434 /// In C++, the operand might be an overloaded function name, in which case 10435 /// we allow the '&' but retain the overloaded-function type. 10436 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10437 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10438 if (PTy->getKind() == BuiltinType::Overload) { 10439 Expr *E = OrigOp.get()->IgnoreParens(); 10440 if (!isa<OverloadExpr>(E)) { 10441 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10442 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10443 << OrigOp.get()->getSourceRange(); 10444 return QualType(); 10445 } 10446 10447 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10448 if (isa<UnresolvedMemberExpr>(Ovl)) 10449 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10450 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10451 << OrigOp.get()->getSourceRange(); 10452 return QualType(); 10453 } 10454 10455 return Context.OverloadTy; 10456 } 10457 10458 if (PTy->getKind() == BuiltinType::UnknownAny) 10459 return Context.UnknownAnyTy; 10460 10461 if (PTy->getKind() == BuiltinType::BoundMember) { 10462 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10463 << OrigOp.get()->getSourceRange(); 10464 return QualType(); 10465 } 10466 10467 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10468 if (OrigOp.isInvalid()) return QualType(); 10469 } 10470 10471 if (OrigOp.get()->isTypeDependent()) 10472 return Context.DependentTy; 10473 10474 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10475 10476 // Make sure to ignore parentheses in subsequent checks 10477 Expr *op = OrigOp.get()->IgnoreParens(); 10478 10479 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10480 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10481 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10482 return QualType(); 10483 } 10484 10485 if (getLangOpts().C99) { 10486 // Implement C99-only parts of addressof rules. 10487 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10488 if (uOp->getOpcode() == UO_Deref) 10489 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10490 // (assuming the deref expression is valid). 10491 return uOp->getSubExpr()->getType(); 10492 } 10493 // Technically, there should be a check for array subscript 10494 // expressions here, but the result of one is always an lvalue anyway. 10495 } 10496 ValueDecl *dcl = getPrimaryDecl(op); 10497 10498 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10499 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10500 op->getLocStart())) 10501 return QualType(); 10502 10503 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10504 unsigned AddressOfError = AO_No_Error; 10505 10506 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10507 bool sfinae = (bool)isSFINAEContext(); 10508 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10509 : diag::ext_typecheck_addrof_temporary) 10510 << op->getType() << op->getSourceRange(); 10511 if (sfinae) 10512 return QualType(); 10513 // Materialize the temporary as an lvalue so that we can take its address. 10514 OrigOp = op = 10515 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10516 } else if (isa<ObjCSelectorExpr>(op)) { 10517 return Context.getPointerType(op->getType()); 10518 } else if (lval == Expr::LV_MemberFunction) { 10519 // If it's an instance method, make a member pointer. 10520 // The expression must have exactly the form &A::foo. 10521 10522 // If the underlying expression isn't a decl ref, give up. 10523 if (!isa<DeclRefExpr>(op)) { 10524 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10525 << OrigOp.get()->getSourceRange(); 10526 return QualType(); 10527 } 10528 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10529 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10530 10531 // The id-expression was parenthesized. 10532 if (OrigOp.get() != DRE) { 10533 Diag(OpLoc, diag::err_parens_pointer_member_function) 10534 << OrigOp.get()->getSourceRange(); 10535 10536 // The method was named without a qualifier. 10537 } else if (!DRE->getQualifier()) { 10538 if (MD->getParent()->getName().empty()) 10539 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10540 << op->getSourceRange(); 10541 else { 10542 SmallString<32> Str; 10543 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10544 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10545 << op->getSourceRange() 10546 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10547 } 10548 } 10549 10550 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10551 if (isa<CXXDestructorDecl>(MD)) 10552 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10553 10554 QualType MPTy = Context.getMemberPointerType( 10555 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10556 // Under the MS ABI, lock down the inheritance model now. 10557 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10558 (void)isCompleteType(OpLoc, MPTy); 10559 return MPTy; 10560 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10561 // C99 6.5.3.2p1 10562 // The operand must be either an l-value or a function designator 10563 if (!op->getType()->isFunctionType()) { 10564 // Use a special diagnostic for loads from property references. 10565 if (isa<PseudoObjectExpr>(op)) { 10566 AddressOfError = AO_Property_Expansion; 10567 } else { 10568 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10569 << op->getType() << op->getSourceRange(); 10570 return QualType(); 10571 } 10572 } 10573 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10574 // The operand cannot be a bit-field 10575 AddressOfError = AO_Bit_Field; 10576 } else if (op->getObjectKind() == OK_VectorComponent) { 10577 // The operand cannot be an element of a vector 10578 AddressOfError = AO_Vector_Element; 10579 } else if (dcl) { // C99 6.5.3.2p1 10580 // We have an lvalue with a decl. Make sure the decl is not declared 10581 // with the register storage-class specifier. 10582 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10583 // in C++ it is not error to take address of a register 10584 // variable (c++03 7.1.1P3) 10585 if (vd->getStorageClass() == SC_Register && 10586 !getLangOpts().CPlusPlus) { 10587 AddressOfError = AO_Register_Variable; 10588 } 10589 } else if (isa<MSPropertyDecl>(dcl)) { 10590 AddressOfError = AO_Property_Expansion; 10591 } else if (isa<FunctionTemplateDecl>(dcl)) { 10592 return Context.OverloadTy; 10593 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10594 // Okay: we can take the address of a field. 10595 // Could be a pointer to member, though, if there is an explicit 10596 // scope qualifier for the class. 10597 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10598 DeclContext *Ctx = dcl->getDeclContext(); 10599 if (Ctx && Ctx->isRecord()) { 10600 if (dcl->getType()->isReferenceType()) { 10601 Diag(OpLoc, 10602 diag::err_cannot_form_pointer_to_member_of_reference_type) 10603 << dcl->getDeclName() << dcl->getType(); 10604 return QualType(); 10605 } 10606 10607 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10608 Ctx = Ctx->getParent(); 10609 10610 QualType MPTy = Context.getMemberPointerType( 10611 op->getType(), 10612 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10613 // Under the MS ABI, lock down the inheritance model now. 10614 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10615 (void)isCompleteType(OpLoc, MPTy); 10616 return MPTy; 10617 } 10618 } 10619 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10620 !isa<BindingDecl>(dcl)) 10621 llvm_unreachable("Unknown/unexpected decl type"); 10622 } 10623 10624 if (AddressOfError != AO_No_Error) { 10625 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10626 return QualType(); 10627 } 10628 10629 if (lval == Expr::LV_IncompleteVoidType) { 10630 // Taking the address of a void variable is technically illegal, but we 10631 // allow it in cases which are otherwise valid. 10632 // Example: "extern void x; void* y = &x;". 10633 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10634 } 10635 10636 // If the operand has type "type", the result has type "pointer to type". 10637 if (op->getType()->isObjCObjectType()) 10638 return Context.getObjCObjectPointerType(op->getType()); 10639 10640 CheckAddressOfPackedMember(op); 10641 10642 return Context.getPointerType(op->getType()); 10643 } 10644 10645 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10646 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10647 if (!DRE) 10648 return; 10649 const Decl *D = DRE->getDecl(); 10650 if (!D) 10651 return; 10652 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10653 if (!Param) 10654 return; 10655 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10656 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10657 return; 10658 if (FunctionScopeInfo *FD = S.getCurFunction()) 10659 if (!FD->ModifiedNonNullParams.count(Param)) 10660 FD->ModifiedNonNullParams.insert(Param); 10661 } 10662 10663 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10664 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10665 SourceLocation OpLoc) { 10666 if (Op->isTypeDependent()) 10667 return S.Context.DependentTy; 10668 10669 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10670 if (ConvResult.isInvalid()) 10671 return QualType(); 10672 Op = ConvResult.get(); 10673 QualType OpTy = Op->getType(); 10674 QualType Result; 10675 10676 if (isa<CXXReinterpretCastExpr>(Op)) { 10677 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10678 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10679 Op->getSourceRange()); 10680 } 10681 10682 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10683 { 10684 Result = PT->getPointeeType(); 10685 } 10686 else if (const ObjCObjectPointerType *OPT = 10687 OpTy->getAs<ObjCObjectPointerType>()) 10688 Result = OPT->getPointeeType(); 10689 else { 10690 ExprResult PR = S.CheckPlaceholderExpr(Op); 10691 if (PR.isInvalid()) return QualType(); 10692 if (PR.get() != Op) 10693 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10694 } 10695 10696 if (Result.isNull()) { 10697 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10698 << OpTy << Op->getSourceRange(); 10699 return QualType(); 10700 } 10701 10702 // Note that per both C89 and C99, indirection is always legal, even if Result 10703 // is an incomplete type or void. It would be possible to warn about 10704 // dereferencing a void pointer, but it's completely well-defined, and such a 10705 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10706 // for pointers to 'void' but is fine for any other pointer type: 10707 // 10708 // C++ [expr.unary.op]p1: 10709 // [...] the expression to which [the unary * operator] is applied shall 10710 // be a pointer to an object type, or a pointer to a function type 10711 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10712 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10713 << OpTy << Op->getSourceRange(); 10714 10715 // Dereferences are usually l-values... 10716 VK = VK_LValue; 10717 10718 // ...except that certain expressions are never l-values in C. 10719 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10720 VK = VK_RValue; 10721 10722 return Result; 10723 } 10724 10725 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10726 BinaryOperatorKind Opc; 10727 switch (Kind) { 10728 default: llvm_unreachable("Unknown binop!"); 10729 case tok::periodstar: Opc = BO_PtrMemD; break; 10730 case tok::arrowstar: Opc = BO_PtrMemI; break; 10731 case tok::star: Opc = BO_Mul; break; 10732 case tok::slash: Opc = BO_Div; break; 10733 case tok::percent: Opc = BO_Rem; break; 10734 case tok::plus: Opc = BO_Add; break; 10735 case tok::minus: Opc = BO_Sub; break; 10736 case tok::lessless: Opc = BO_Shl; break; 10737 case tok::greatergreater: Opc = BO_Shr; break; 10738 case tok::lessequal: Opc = BO_LE; break; 10739 case tok::less: Opc = BO_LT; break; 10740 case tok::greaterequal: Opc = BO_GE; break; 10741 case tok::greater: Opc = BO_GT; break; 10742 case tok::exclaimequal: Opc = BO_NE; break; 10743 case tok::equalequal: Opc = BO_EQ; break; 10744 case tok::amp: Opc = BO_And; break; 10745 case tok::caret: Opc = BO_Xor; break; 10746 case tok::pipe: Opc = BO_Or; break; 10747 case tok::ampamp: Opc = BO_LAnd; break; 10748 case tok::pipepipe: Opc = BO_LOr; break; 10749 case tok::equal: Opc = BO_Assign; break; 10750 case tok::starequal: Opc = BO_MulAssign; break; 10751 case tok::slashequal: Opc = BO_DivAssign; break; 10752 case tok::percentequal: Opc = BO_RemAssign; break; 10753 case tok::plusequal: Opc = BO_AddAssign; break; 10754 case tok::minusequal: Opc = BO_SubAssign; break; 10755 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10756 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10757 case tok::ampequal: Opc = BO_AndAssign; break; 10758 case tok::caretequal: Opc = BO_XorAssign; break; 10759 case tok::pipeequal: Opc = BO_OrAssign; break; 10760 case tok::comma: Opc = BO_Comma; break; 10761 } 10762 return Opc; 10763 } 10764 10765 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10766 tok::TokenKind Kind) { 10767 UnaryOperatorKind Opc; 10768 switch (Kind) { 10769 default: llvm_unreachable("Unknown unary op!"); 10770 case tok::plusplus: Opc = UO_PreInc; break; 10771 case tok::minusminus: Opc = UO_PreDec; break; 10772 case tok::amp: Opc = UO_AddrOf; break; 10773 case tok::star: Opc = UO_Deref; break; 10774 case tok::plus: Opc = UO_Plus; break; 10775 case tok::minus: Opc = UO_Minus; break; 10776 case tok::tilde: Opc = UO_Not; break; 10777 case tok::exclaim: Opc = UO_LNot; break; 10778 case tok::kw___real: Opc = UO_Real; break; 10779 case tok::kw___imag: Opc = UO_Imag; break; 10780 case tok::kw___extension__: Opc = UO_Extension; break; 10781 } 10782 return Opc; 10783 } 10784 10785 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10786 /// This warning is only emitted for builtin assignment operations. It is also 10787 /// suppressed in the event of macro expansions. 10788 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10789 SourceLocation OpLoc) { 10790 if (!S.ActiveTemplateInstantiations.empty()) 10791 return; 10792 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10793 return; 10794 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10795 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10796 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10797 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10798 if (!LHSDeclRef || !RHSDeclRef || 10799 LHSDeclRef->getLocation().isMacroID() || 10800 RHSDeclRef->getLocation().isMacroID()) 10801 return; 10802 const ValueDecl *LHSDecl = 10803 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10804 const ValueDecl *RHSDecl = 10805 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10806 if (LHSDecl != RHSDecl) 10807 return; 10808 if (LHSDecl->getType().isVolatileQualified()) 10809 return; 10810 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10811 if (RefTy->getPointeeType().isVolatileQualified()) 10812 return; 10813 10814 S.Diag(OpLoc, diag::warn_self_assignment) 10815 << LHSDeclRef->getType() 10816 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10817 } 10818 10819 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10820 /// is usually indicative of introspection within the Objective-C pointer. 10821 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10822 SourceLocation OpLoc) { 10823 if (!S.getLangOpts().ObjC1) 10824 return; 10825 10826 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10827 const Expr *LHS = L.get(); 10828 const Expr *RHS = R.get(); 10829 10830 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10831 ObjCPointerExpr = LHS; 10832 OtherExpr = RHS; 10833 } 10834 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10835 ObjCPointerExpr = RHS; 10836 OtherExpr = LHS; 10837 } 10838 10839 // This warning is deliberately made very specific to reduce false 10840 // positives with logic that uses '&' for hashing. This logic mainly 10841 // looks for code trying to introspect into tagged pointers, which 10842 // code should generally never do. 10843 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10844 unsigned Diag = diag::warn_objc_pointer_masking; 10845 // Determine if we are introspecting the result of performSelectorXXX. 10846 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10847 // Special case messages to -performSelector and friends, which 10848 // can return non-pointer values boxed in a pointer value. 10849 // Some clients may wish to silence warnings in this subcase. 10850 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10851 Selector S = ME->getSelector(); 10852 StringRef SelArg0 = S.getNameForSlot(0); 10853 if (SelArg0.startswith("performSelector")) 10854 Diag = diag::warn_objc_pointer_masking_performSelector; 10855 } 10856 10857 S.Diag(OpLoc, Diag) 10858 << ObjCPointerExpr->getSourceRange(); 10859 } 10860 } 10861 10862 static NamedDecl *getDeclFromExpr(Expr *E) { 10863 if (!E) 10864 return nullptr; 10865 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10866 return DRE->getDecl(); 10867 if (auto *ME = dyn_cast<MemberExpr>(E)) 10868 return ME->getMemberDecl(); 10869 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10870 return IRE->getDecl(); 10871 return nullptr; 10872 } 10873 10874 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10875 /// operator @p Opc at location @c TokLoc. This routine only supports 10876 /// built-in operations; ActOnBinOp handles overloaded operators. 10877 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10878 BinaryOperatorKind Opc, 10879 Expr *LHSExpr, Expr *RHSExpr) { 10880 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10881 // The syntax only allows initializer lists on the RHS of assignment, 10882 // so we don't need to worry about accepting invalid code for 10883 // non-assignment operators. 10884 // C++11 5.17p9: 10885 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10886 // of x = {} is x = T(). 10887 InitializationKind Kind = 10888 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10889 InitializedEntity Entity = 10890 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10891 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10892 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10893 if (Init.isInvalid()) 10894 return Init; 10895 RHSExpr = Init.get(); 10896 } 10897 10898 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10899 QualType ResultTy; // Result type of the binary operator. 10900 // The following two variables are used for compound assignment operators 10901 QualType CompLHSTy; // Type of LHS after promotions for computation 10902 QualType CompResultTy; // Type of computation result 10903 ExprValueKind VK = VK_RValue; 10904 ExprObjectKind OK = OK_Ordinary; 10905 10906 if (!getLangOpts().CPlusPlus) { 10907 // C cannot handle TypoExpr nodes on either side of a binop because it 10908 // doesn't handle dependent types properly, so make sure any TypoExprs have 10909 // been dealt with before checking the operands. 10910 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10911 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10912 if (Opc != BO_Assign) 10913 return ExprResult(E); 10914 // Avoid correcting the RHS to the same Expr as the LHS. 10915 Decl *D = getDeclFromExpr(E); 10916 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10917 }); 10918 if (!LHS.isUsable() || !RHS.isUsable()) 10919 return ExprError(); 10920 } 10921 10922 if (getLangOpts().OpenCL) { 10923 QualType LHSTy = LHSExpr->getType(); 10924 QualType RHSTy = RHSExpr->getType(); 10925 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10926 // the ATOMIC_VAR_INIT macro. 10927 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 10928 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10929 if (BO_Assign == Opc) 10930 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10931 else 10932 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10933 return ExprError(); 10934 } 10935 10936 // OpenCL special types - image, sampler, pipe, and blocks are to be used 10937 // only with a builtin functions and therefore should be disallowed here. 10938 if (LHSTy->isImageType() || RHSTy->isImageType() || 10939 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 10940 LHSTy->isPipeType() || RHSTy->isPipeType() || 10941 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 10942 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10943 return ExprError(); 10944 } 10945 } 10946 10947 switch (Opc) { 10948 case BO_Assign: 10949 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10950 if (getLangOpts().CPlusPlus && 10951 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10952 VK = LHS.get()->getValueKind(); 10953 OK = LHS.get()->getObjectKind(); 10954 } 10955 if (!ResultTy.isNull()) { 10956 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10957 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10958 } 10959 RecordModifiableNonNullParam(*this, LHS.get()); 10960 break; 10961 case BO_PtrMemD: 10962 case BO_PtrMemI: 10963 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10964 Opc == BO_PtrMemI); 10965 break; 10966 case BO_Mul: 10967 case BO_Div: 10968 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10969 Opc == BO_Div); 10970 break; 10971 case BO_Rem: 10972 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10973 break; 10974 case BO_Add: 10975 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10976 break; 10977 case BO_Sub: 10978 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10979 break; 10980 case BO_Shl: 10981 case BO_Shr: 10982 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10983 break; 10984 case BO_LE: 10985 case BO_LT: 10986 case BO_GE: 10987 case BO_GT: 10988 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10989 break; 10990 case BO_EQ: 10991 case BO_NE: 10992 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10993 break; 10994 case BO_And: 10995 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10996 case BO_Xor: 10997 case BO_Or: 10998 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10999 break; 11000 case BO_LAnd: 11001 case BO_LOr: 11002 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11003 break; 11004 case BO_MulAssign: 11005 case BO_DivAssign: 11006 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11007 Opc == BO_DivAssign); 11008 CompLHSTy = CompResultTy; 11009 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11010 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11011 break; 11012 case BO_RemAssign: 11013 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11014 CompLHSTy = CompResultTy; 11015 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11016 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11017 break; 11018 case BO_AddAssign: 11019 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11020 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11021 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11022 break; 11023 case BO_SubAssign: 11024 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11025 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11026 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11027 break; 11028 case BO_ShlAssign: 11029 case BO_ShrAssign: 11030 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11031 CompLHSTy = CompResultTy; 11032 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11033 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11034 break; 11035 case BO_AndAssign: 11036 case BO_OrAssign: // fallthrough 11037 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11038 case BO_XorAssign: 11039 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 11040 CompLHSTy = CompResultTy; 11041 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11042 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11043 break; 11044 case BO_Comma: 11045 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11046 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11047 VK = RHS.get()->getValueKind(); 11048 OK = RHS.get()->getObjectKind(); 11049 } 11050 break; 11051 } 11052 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11053 return ExprError(); 11054 11055 // Check for array bounds violations for both sides of the BinaryOperator 11056 CheckArrayAccess(LHS.get()); 11057 CheckArrayAccess(RHS.get()); 11058 11059 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11060 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11061 &Context.Idents.get("object_setClass"), 11062 SourceLocation(), LookupOrdinaryName); 11063 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11064 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11065 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11066 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11067 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11068 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11069 } 11070 else 11071 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11072 } 11073 else if (const ObjCIvarRefExpr *OIRE = 11074 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11075 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11076 11077 if (CompResultTy.isNull()) 11078 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11079 OK, OpLoc, FPFeatures.fp_contract); 11080 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11081 OK_ObjCProperty) { 11082 VK = VK_LValue; 11083 OK = LHS.get()->getObjectKind(); 11084 } 11085 return new (Context) CompoundAssignOperator( 11086 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11087 OpLoc, FPFeatures.fp_contract); 11088 } 11089 11090 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11091 /// operators are mixed in a way that suggests that the programmer forgot that 11092 /// comparison operators have higher precedence. The most typical example of 11093 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11094 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11095 SourceLocation OpLoc, Expr *LHSExpr, 11096 Expr *RHSExpr) { 11097 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11098 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11099 11100 // Check that one of the sides is a comparison operator and the other isn't. 11101 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11102 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11103 if (isLeftComp == isRightComp) 11104 return; 11105 11106 // Bitwise operations are sometimes used as eager logical ops. 11107 // Don't diagnose this. 11108 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11109 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11110 if (isLeftBitwise || isRightBitwise) 11111 return; 11112 11113 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11114 OpLoc) 11115 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11116 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11117 SourceRange ParensRange = isLeftComp ? 11118 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11119 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11120 11121 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11122 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11123 SuggestParentheses(Self, OpLoc, 11124 Self.PDiag(diag::note_precedence_silence) << OpStr, 11125 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11126 SuggestParentheses(Self, OpLoc, 11127 Self.PDiag(diag::note_precedence_bitwise_first) 11128 << BinaryOperator::getOpcodeStr(Opc), 11129 ParensRange); 11130 } 11131 11132 /// \brief It accepts a '&&' expr that is inside a '||' one. 11133 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11134 /// in parentheses. 11135 static void 11136 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11137 BinaryOperator *Bop) { 11138 assert(Bop->getOpcode() == BO_LAnd); 11139 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11140 << Bop->getSourceRange() << OpLoc; 11141 SuggestParentheses(Self, Bop->getOperatorLoc(), 11142 Self.PDiag(diag::note_precedence_silence) 11143 << Bop->getOpcodeStr(), 11144 Bop->getSourceRange()); 11145 } 11146 11147 /// \brief Returns true if the given expression can be evaluated as a constant 11148 /// 'true'. 11149 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11150 bool Res; 11151 return !E->isValueDependent() && 11152 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11153 } 11154 11155 /// \brief Returns true if the given expression can be evaluated as a constant 11156 /// 'false'. 11157 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11158 bool Res; 11159 return !E->isValueDependent() && 11160 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11161 } 11162 11163 /// \brief Look for '&&' in the left hand of a '||' expr. 11164 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11165 Expr *LHSExpr, Expr *RHSExpr) { 11166 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11167 if (Bop->getOpcode() == BO_LAnd) { 11168 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11169 if (EvaluatesAsFalse(S, RHSExpr)) 11170 return; 11171 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11172 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11173 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11174 } else if (Bop->getOpcode() == BO_LOr) { 11175 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11176 // If it's "a || b && 1 || c" we didn't warn earlier for 11177 // "a || b && 1", but warn now. 11178 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11179 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11180 } 11181 } 11182 } 11183 } 11184 11185 /// \brief Look for '&&' in the right hand of a '||' expr. 11186 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11187 Expr *LHSExpr, Expr *RHSExpr) { 11188 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11189 if (Bop->getOpcode() == BO_LAnd) { 11190 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11191 if (EvaluatesAsFalse(S, LHSExpr)) 11192 return; 11193 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11194 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11195 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11196 } 11197 } 11198 } 11199 11200 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11201 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11202 /// the '&' expression in parentheses. 11203 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11204 SourceLocation OpLoc, Expr *SubExpr) { 11205 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11206 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11207 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11208 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11209 << Bop->getSourceRange() << OpLoc; 11210 SuggestParentheses(S, Bop->getOperatorLoc(), 11211 S.PDiag(diag::note_precedence_silence) 11212 << Bop->getOpcodeStr(), 11213 Bop->getSourceRange()); 11214 } 11215 } 11216 } 11217 11218 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11219 Expr *SubExpr, StringRef Shift) { 11220 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11221 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11222 StringRef Op = Bop->getOpcodeStr(); 11223 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11224 << Bop->getSourceRange() << OpLoc << Shift << Op; 11225 SuggestParentheses(S, Bop->getOperatorLoc(), 11226 S.PDiag(diag::note_precedence_silence) << Op, 11227 Bop->getSourceRange()); 11228 } 11229 } 11230 } 11231 11232 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11233 Expr *LHSExpr, Expr *RHSExpr) { 11234 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11235 if (!OCE) 11236 return; 11237 11238 FunctionDecl *FD = OCE->getDirectCallee(); 11239 if (!FD || !FD->isOverloadedOperator()) 11240 return; 11241 11242 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11243 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11244 return; 11245 11246 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11247 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11248 << (Kind == OO_LessLess); 11249 SuggestParentheses(S, OCE->getOperatorLoc(), 11250 S.PDiag(diag::note_precedence_silence) 11251 << (Kind == OO_LessLess ? "<<" : ">>"), 11252 OCE->getSourceRange()); 11253 SuggestParentheses(S, OpLoc, 11254 S.PDiag(diag::note_evaluate_comparison_first), 11255 SourceRange(OCE->getArg(1)->getLocStart(), 11256 RHSExpr->getLocEnd())); 11257 } 11258 11259 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11260 /// precedence. 11261 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11262 SourceLocation OpLoc, Expr *LHSExpr, 11263 Expr *RHSExpr){ 11264 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11265 if (BinaryOperator::isBitwiseOp(Opc)) 11266 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11267 11268 // Diagnose "arg1 & arg2 | arg3" 11269 if ((Opc == BO_Or || Opc == BO_Xor) && 11270 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11271 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11272 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11273 } 11274 11275 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11276 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11277 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11278 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11279 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11280 } 11281 11282 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11283 || Opc == BO_Shr) { 11284 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11285 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11286 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11287 } 11288 11289 // Warn on overloaded shift operators and comparisons, such as: 11290 // cout << 5 == 4; 11291 if (BinaryOperator::isComparisonOp(Opc)) 11292 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11293 } 11294 11295 // Binary Operators. 'Tok' is the token for the operator. 11296 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11297 tok::TokenKind Kind, 11298 Expr *LHSExpr, Expr *RHSExpr) { 11299 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11300 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11301 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11302 11303 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11304 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11305 11306 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11307 } 11308 11309 /// Build an overloaded binary operator expression in the given scope. 11310 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11311 BinaryOperatorKind Opc, 11312 Expr *LHS, Expr *RHS) { 11313 // Find all of the overloaded operators visible from this 11314 // point. We perform both an operator-name lookup from the local 11315 // scope and an argument-dependent lookup based on the types of 11316 // the arguments. 11317 UnresolvedSet<16> Functions; 11318 OverloadedOperatorKind OverOp 11319 = BinaryOperator::getOverloadedOperator(Opc); 11320 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11321 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11322 RHS->getType(), Functions); 11323 11324 // Build the (potentially-overloaded, potentially-dependent) 11325 // binary operation. 11326 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11327 } 11328 11329 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11330 BinaryOperatorKind Opc, 11331 Expr *LHSExpr, Expr *RHSExpr) { 11332 // We want to end up calling one of checkPseudoObjectAssignment 11333 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11334 // both expressions are overloadable or either is type-dependent), 11335 // or CreateBuiltinBinOp (in any other case). We also want to get 11336 // any placeholder types out of the way. 11337 11338 // Handle pseudo-objects in the LHS. 11339 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11340 // Assignments with a pseudo-object l-value need special analysis. 11341 if (pty->getKind() == BuiltinType::PseudoObject && 11342 BinaryOperator::isAssignmentOp(Opc)) 11343 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11344 11345 // Don't resolve overloads if the other type is overloadable. 11346 if (pty->getKind() == BuiltinType::Overload) { 11347 // We can't actually test that if we still have a placeholder, 11348 // though. Fortunately, none of the exceptions we see in that 11349 // code below are valid when the LHS is an overload set. Note 11350 // that an overload set can be dependently-typed, but it never 11351 // instantiates to having an overloadable type. 11352 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11353 if (resolvedRHS.isInvalid()) return ExprError(); 11354 RHSExpr = resolvedRHS.get(); 11355 11356 if (RHSExpr->isTypeDependent() || 11357 RHSExpr->getType()->isOverloadableType()) 11358 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11359 } 11360 11361 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11362 if (LHS.isInvalid()) return ExprError(); 11363 LHSExpr = LHS.get(); 11364 } 11365 11366 // Handle pseudo-objects in the RHS. 11367 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11368 // An overload in the RHS can potentially be resolved by the type 11369 // being assigned to. 11370 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11371 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11372 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11373 11374 if (LHSExpr->getType()->isOverloadableType()) 11375 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11376 11377 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11378 } 11379 11380 // Don't resolve overloads if the other type is overloadable. 11381 if (pty->getKind() == BuiltinType::Overload && 11382 LHSExpr->getType()->isOverloadableType()) 11383 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11384 11385 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11386 if (!resolvedRHS.isUsable()) return ExprError(); 11387 RHSExpr = resolvedRHS.get(); 11388 } 11389 11390 if (getLangOpts().CPlusPlus) { 11391 // If either expression is type-dependent, always build an 11392 // overloaded op. 11393 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11394 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11395 11396 // Otherwise, build an overloaded op if either expression has an 11397 // overloadable type. 11398 if (LHSExpr->getType()->isOverloadableType() || 11399 RHSExpr->getType()->isOverloadableType()) 11400 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11401 } 11402 11403 // Build a built-in binary operation. 11404 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11405 } 11406 11407 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11408 UnaryOperatorKind Opc, 11409 Expr *InputExpr) { 11410 ExprResult Input = InputExpr; 11411 ExprValueKind VK = VK_RValue; 11412 ExprObjectKind OK = OK_Ordinary; 11413 QualType resultType; 11414 if (getLangOpts().OpenCL) { 11415 QualType Ty = InputExpr->getType(); 11416 // The only legal unary operation for atomics is '&'. 11417 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11418 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11419 // only with a builtin functions and therefore should be disallowed here. 11420 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11421 || Ty->isBlockPointerType())) { 11422 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11423 << InputExpr->getType() 11424 << Input.get()->getSourceRange()); 11425 } 11426 } 11427 switch (Opc) { 11428 case UO_PreInc: 11429 case UO_PreDec: 11430 case UO_PostInc: 11431 case UO_PostDec: 11432 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11433 OpLoc, 11434 Opc == UO_PreInc || 11435 Opc == UO_PostInc, 11436 Opc == UO_PreInc || 11437 Opc == UO_PreDec); 11438 break; 11439 case UO_AddrOf: 11440 resultType = CheckAddressOfOperand(Input, OpLoc); 11441 RecordModifiableNonNullParam(*this, InputExpr); 11442 break; 11443 case UO_Deref: { 11444 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11445 if (Input.isInvalid()) return ExprError(); 11446 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11447 break; 11448 } 11449 case UO_Plus: 11450 case UO_Minus: 11451 Input = UsualUnaryConversions(Input.get()); 11452 if (Input.isInvalid()) return ExprError(); 11453 resultType = Input.get()->getType(); 11454 if (resultType->isDependentType()) 11455 break; 11456 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11457 break; 11458 else if (resultType->isVectorType() && 11459 // The z vector extensions don't allow + or - with bool vectors. 11460 (!Context.getLangOpts().ZVector || 11461 resultType->getAs<VectorType>()->getVectorKind() != 11462 VectorType::AltiVecBool)) 11463 break; 11464 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11465 Opc == UO_Plus && 11466 resultType->isPointerType()) 11467 break; 11468 11469 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11470 << resultType << Input.get()->getSourceRange()); 11471 11472 case UO_Not: // bitwise complement 11473 Input = UsualUnaryConversions(Input.get()); 11474 if (Input.isInvalid()) 11475 return ExprError(); 11476 resultType = Input.get()->getType(); 11477 if (resultType->isDependentType()) 11478 break; 11479 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11480 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11481 // C99 does not support '~' for complex conjugation. 11482 Diag(OpLoc, diag::ext_integer_complement_complex) 11483 << resultType << Input.get()->getSourceRange(); 11484 else if (resultType->hasIntegerRepresentation()) 11485 break; 11486 else if (resultType->isExtVectorType()) { 11487 if (Context.getLangOpts().OpenCL) { 11488 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11489 // on vector float types. 11490 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11491 if (!T->isIntegerType()) 11492 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11493 << resultType << Input.get()->getSourceRange()); 11494 } 11495 break; 11496 } else { 11497 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11498 << resultType << Input.get()->getSourceRange()); 11499 } 11500 break; 11501 11502 case UO_LNot: // logical negation 11503 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11504 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11505 if (Input.isInvalid()) return ExprError(); 11506 resultType = Input.get()->getType(); 11507 11508 // Though we still have to promote half FP to float... 11509 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11510 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11511 resultType = Context.FloatTy; 11512 } 11513 11514 if (resultType->isDependentType()) 11515 break; 11516 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11517 // C99 6.5.3.3p1: ok, fallthrough; 11518 if (Context.getLangOpts().CPlusPlus) { 11519 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11520 // operand contextually converted to bool. 11521 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11522 ScalarTypeToBooleanCastKind(resultType)); 11523 } else if (Context.getLangOpts().OpenCL && 11524 Context.getLangOpts().OpenCLVersion < 120) { 11525 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11526 // operate on scalar float types. 11527 if (!resultType->isIntegerType()) 11528 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11529 << resultType << Input.get()->getSourceRange()); 11530 } 11531 } else if (resultType->isExtVectorType()) { 11532 if (Context.getLangOpts().OpenCL && 11533 Context.getLangOpts().OpenCLVersion < 120) { 11534 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11535 // operate on vector float types. 11536 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11537 if (!T->isIntegerType()) 11538 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11539 << resultType << Input.get()->getSourceRange()); 11540 } 11541 // Vector logical not returns the signed variant of the operand type. 11542 resultType = GetSignedVectorType(resultType); 11543 break; 11544 } else { 11545 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11546 << resultType << Input.get()->getSourceRange()); 11547 } 11548 11549 // LNot always has type int. C99 6.5.3.3p5. 11550 // In C++, it's bool. C++ 5.3.1p8 11551 resultType = Context.getLogicalOperationType(); 11552 break; 11553 case UO_Real: 11554 case UO_Imag: 11555 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11556 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11557 // complex l-values to ordinary l-values and all other values to r-values. 11558 if (Input.isInvalid()) return ExprError(); 11559 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11560 if (Input.get()->getValueKind() != VK_RValue && 11561 Input.get()->getObjectKind() == OK_Ordinary) 11562 VK = Input.get()->getValueKind(); 11563 } else if (!getLangOpts().CPlusPlus) { 11564 // In C, a volatile scalar is read by __imag. In C++, it is not. 11565 Input = DefaultLvalueConversion(Input.get()); 11566 } 11567 break; 11568 case UO_Extension: 11569 case UO_Coawait: 11570 resultType = Input.get()->getType(); 11571 VK = Input.get()->getValueKind(); 11572 OK = Input.get()->getObjectKind(); 11573 break; 11574 } 11575 if (resultType.isNull() || Input.isInvalid()) 11576 return ExprError(); 11577 11578 // Check for array bounds violations in the operand of the UnaryOperator, 11579 // except for the '*' and '&' operators that have to be handled specially 11580 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11581 // that are explicitly defined as valid by the standard). 11582 if (Opc != UO_AddrOf && Opc != UO_Deref) 11583 CheckArrayAccess(Input.get()); 11584 11585 return new (Context) 11586 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11587 } 11588 11589 /// \brief Determine whether the given expression is a qualified member 11590 /// access expression, of a form that could be turned into a pointer to member 11591 /// with the address-of operator. 11592 static bool isQualifiedMemberAccess(Expr *E) { 11593 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11594 if (!DRE->getQualifier()) 11595 return false; 11596 11597 ValueDecl *VD = DRE->getDecl(); 11598 if (!VD->isCXXClassMember()) 11599 return false; 11600 11601 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11602 return true; 11603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11604 return Method->isInstance(); 11605 11606 return false; 11607 } 11608 11609 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11610 if (!ULE->getQualifier()) 11611 return false; 11612 11613 for (NamedDecl *D : ULE->decls()) { 11614 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11615 if (Method->isInstance()) 11616 return true; 11617 } else { 11618 // Overload set does not contain methods. 11619 break; 11620 } 11621 } 11622 11623 return false; 11624 } 11625 11626 return false; 11627 } 11628 11629 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11630 UnaryOperatorKind Opc, Expr *Input) { 11631 // First things first: handle placeholders so that the 11632 // overloaded-operator check considers the right type. 11633 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11634 // Increment and decrement of pseudo-object references. 11635 if (pty->getKind() == BuiltinType::PseudoObject && 11636 UnaryOperator::isIncrementDecrementOp(Opc)) 11637 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11638 11639 // extension is always a builtin operator. 11640 if (Opc == UO_Extension) 11641 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11642 11643 // & gets special logic for several kinds of placeholder. 11644 // The builtin code knows what to do. 11645 if (Opc == UO_AddrOf && 11646 (pty->getKind() == BuiltinType::Overload || 11647 pty->getKind() == BuiltinType::UnknownAny || 11648 pty->getKind() == BuiltinType::BoundMember)) 11649 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11650 11651 // Anything else needs to be handled now. 11652 ExprResult Result = CheckPlaceholderExpr(Input); 11653 if (Result.isInvalid()) return ExprError(); 11654 Input = Result.get(); 11655 } 11656 11657 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11658 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11659 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11660 // Find all of the overloaded operators visible from this 11661 // point. We perform both an operator-name lookup from the local 11662 // scope and an argument-dependent lookup based on the types of 11663 // the arguments. 11664 UnresolvedSet<16> Functions; 11665 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11666 if (S && OverOp != OO_None) 11667 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11668 Functions); 11669 11670 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11671 } 11672 11673 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11674 } 11675 11676 // Unary Operators. 'Tok' is the token for the operator. 11677 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11678 tok::TokenKind Op, Expr *Input) { 11679 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11680 } 11681 11682 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11683 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11684 LabelDecl *TheDecl) { 11685 TheDecl->markUsed(Context); 11686 // Create the AST node. The address of a label always has type 'void*'. 11687 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11688 Context.getPointerType(Context.VoidTy)); 11689 } 11690 11691 /// Given the last statement in a statement-expression, check whether 11692 /// the result is a producing expression (like a call to an 11693 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11694 /// release out of the full-expression. Otherwise, return null. 11695 /// Cannot fail. 11696 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11697 // Should always be wrapped with one of these. 11698 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11699 if (!cleanups) return nullptr; 11700 11701 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11702 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11703 return nullptr; 11704 11705 // Splice out the cast. This shouldn't modify any interesting 11706 // features of the statement. 11707 Expr *producer = cast->getSubExpr(); 11708 assert(producer->getType() == cast->getType()); 11709 assert(producer->getValueKind() == cast->getValueKind()); 11710 cleanups->setSubExpr(producer); 11711 return cleanups; 11712 } 11713 11714 void Sema::ActOnStartStmtExpr() { 11715 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11716 } 11717 11718 void Sema::ActOnStmtExprError() { 11719 // Note that function is also called by TreeTransform when leaving a 11720 // StmtExpr scope without rebuilding anything. 11721 11722 DiscardCleanupsInEvaluationContext(); 11723 PopExpressionEvaluationContext(); 11724 } 11725 11726 ExprResult 11727 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11728 SourceLocation RPLoc) { // "({..})" 11729 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11730 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11731 11732 if (hasAnyUnrecoverableErrorsInThisFunction()) 11733 DiscardCleanupsInEvaluationContext(); 11734 assert(!Cleanup.exprNeedsCleanups() && 11735 "cleanups within StmtExpr not correctly bound!"); 11736 PopExpressionEvaluationContext(); 11737 11738 // FIXME: there are a variety of strange constraints to enforce here, for 11739 // example, it is not possible to goto into a stmt expression apparently. 11740 // More semantic analysis is needed. 11741 11742 // If there are sub-stmts in the compound stmt, take the type of the last one 11743 // as the type of the stmtexpr. 11744 QualType Ty = Context.VoidTy; 11745 bool StmtExprMayBindToTemp = false; 11746 if (!Compound->body_empty()) { 11747 Stmt *LastStmt = Compound->body_back(); 11748 LabelStmt *LastLabelStmt = nullptr; 11749 // If LastStmt is a label, skip down through into the body. 11750 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11751 LastLabelStmt = Label; 11752 LastStmt = Label->getSubStmt(); 11753 } 11754 11755 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11756 // Do function/array conversion on the last expression, but not 11757 // lvalue-to-rvalue. However, initialize an unqualified type. 11758 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11759 if (LastExpr.isInvalid()) 11760 return ExprError(); 11761 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11762 11763 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11764 // In ARC, if the final expression ends in a consume, splice 11765 // the consume out and bind it later. In the alternate case 11766 // (when dealing with a retainable type), the result 11767 // initialization will create a produce. In both cases the 11768 // result will be +1, and we'll need to balance that out with 11769 // a bind. 11770 if (Expr *rebuiltLastStmt 11771 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11772 LastExpr = rebuiltLastStmt; 11773 } else { 11774 LastExpr = PerformCopyInitialization( 11775 InitializedEntity::InitializeResult(LPLoc, 11776 Ty, 11777 false), 11778 SourceLocation(), 11779 LastExpr); 11780 } 11781 11782 if (LastExpr.isInvalid()) 11783 return ExprError(); 11784 if (LastExpr.get() != nullptr) { 11785 if (!LastLabelStmt) 11786 Compound->setLastStmt(LastExpr.get()); 11787 else 11788 LastLabelStmt->setSubStmt(LastExpr.get()); 11789 StmtExprMayBindToTemp = true; 11790 } 11791 } 11792 } 11793 } 11794 11795 // FIXME: Check that expression type is complete/non-abstract; statement 11796 // expressions are not lvalues. 11797 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11798 if (StmtExprMayBindToTemp) 11799 return MaybeBindToTemporary(ResStmtExpr); 11800 return ResStmtExpr; 11801 } 11802 11803 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11804 TypeSourceInfo *TInfo, 11805 ArrayRef<OffsetOfComponent> Components, 11806 SourceLocation RParenLoc) { 11807 QualType ArgTy = TInfo->getType(); 11808 bool Dependent = ArgTy->isDependentType(); 11809 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11810 11811 // We must have at least one component that refers to the type, and the first 11812 // one is known to be a field designator. Verify that the ArgTy represents 11813 // a struct/union/class. 11814 if (!Dependent && !ArgTy->isRecordType()) 11815 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11816 << ArgTy << TypeRange); 11817 11818 // Type must be complete per C99 7.17p3 because a declaring a variable 11819 // with an incomplete type would be ill-formed. 11820 if (!Dependent 11821 && RequireCompleteType(BuiltinLoc, ArgTy, 11822 diag::err_offsetof_incomplete_type, TypeRange)) 11823 return ExprError(); 11824 11825 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11826 // GCC extension, diagnose them. 11827 // FIXME: This diagnostic isn't actually visible because the location is in 11828 // a system header! 11829 if (Components.size() != 1) 11830 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11831 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11832 11833 bool DidWarnAboutNonPOD = false; 11834 QualType CurrentType = ArgTy; 11835 SmallVector<OffsetOfNode, 4> Comps; 11836 SmallVector<Expr*, 4> Exprs; 11837 for (const OffsetOfComponent &OC : Components) { 11838 if (OC.isBrackets) { 11839 // Offset of an array sub-field. TODO: Should we allow vector elements? 11840 if (!CurrentType->isDependentType()) { 11841 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11842 if(!AT) 11843 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11844 << CurrentType); 11845 CurrentType = AT->getElementType(); 11846 } else 11847 CurrentType = Context.DependentTy; 11848 11849 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11850 if (IdxRval.isInvalid()) 11851 return ExprError(); 11852 Expr *Idx = IdxRval.get(); 11853 11854 // The expression must be an integral expression. 11855 // FIXME: An integral constant expression? 11856 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11857 !Idx->getType()->isIntegerType()) 11858 return ExprError(Diag(Idx->getLocStart(), 11859 diag::err_typecheck_subscript_not_integer) 11860 << Idx->getSourceRange()); 11861 11862 // Record this array index. 11863 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11864 Exprs.push_back(Idx); 11865 continue; 11866 } 11867 11868 // Offset of a field. 11869 if (CurrentType->isDependentType()) { 11870 // We have the offset of a field, but we can't look into the dependent 11871 // type. Just record the identifier of the field. 11872 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11873 CurrentType = Context.DependentTy; 11874 continue; 11875 } 11876 11877 // We need to have a complete type to look into. 11878 if (RequireCompleteType(OC.LocStart, CurrentType, 11879 diag::err_offsetof_incomplete_type)) 11880 return ExprError(); 11881 11882 // Look for the designated field. 11883 const RecordType *RC = CurrentType->getAs<RecordType>(); 11884 if (!RC) 11885 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11886 << CurrentType); 11887 RecordDecl *RD = RC->getDecl(); 11888 11889 // C++ [lib.support.types]p5: 11890 // The macro offsetof accepts a restricted set of type arguments in this 11891 // International Standard. type shall be a POD structure or a POD union 11892 // (clause 9). 11893 // C++11 [support.types]p4: 11894 // If type is not a standard-layout class (Clause 9), the results are 11895 // undefined. 11896 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11897 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11898 unsigned DiagID = 11899 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11900 : diag::ext_offsetof_non_pod_type; 11901 11902 if (!IsSafe && !DidWarnAboutNonPOD && 11903 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11904 PDiag(DiagID) 11905 << SourceRange(Components[0].LocStart, OC.LocEnd) 11906 << CurrentType)) 11907 DidWarnAboutNonPOD = true; 11908 } 11909 11910 // Look for the field. 11911 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11912 LookupQualifiedName(R, RD); 11913 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11914 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11915 if (!MemberDecl) { 11916 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11917 MemberDecl = IndirectMemberDecl->getAnonField(); 11918 } 11919 11920 if (!MemberDecl) 11921 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11922 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11923 OC.LocEnd)); 11924 11925 // C99 7.17p3: 11926 // (If the specified member is a bit-field, the behavior is undefined.) 11927 // 11928 // We diagnose this as an error. 11929 if (MemberDecl->isBitField()) { 11930 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11931 << MemberDecl->getDeclName() 11932 << SourceRange(BuiltinLoc, RParenLoc); 11933 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11934 return ExprError(); 11935 } 11936 11937 RecordDecl *Parent = MemberDecl->getParent(); 11938 if (IndirectMemberDecl) 11939 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11940 11941 // If the member was found in a base class, introduce OffsetOfNodes for 11942 // the base class indirections. 11943 CXXBasePaths Paths; 11944 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11945 Paths)) { 11946 if (Paths.getDetectedVirtual()) { 11947 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11948 << MemberDecl->getDeclName() 11949 << SourceRange(BuiltinLoc, RParenLoc); 11950 return ExprError(); 11951 } 11952 11953 CXXBasePath &Path = Paths.front(); 11954 for (const CXXBasePathElement &B : Path) 11955 Comps.push_back(OffsetOfNode(B.Base)); 11956 } 11957 11958 if (IndirectMemberDecl) { 11959 for (auto *FI : IndirectMemberDecl->chain()) { 11960 assert(isa<FieldDecl>(FI)); 11961 Comps.push_back(OffsetOfNode(OC.LocStart, 11962 cast<FieldDecl>(FI), OC.LocEnd)); 11963 } 11964 } else 11965 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11966 11967 CurrentType = MemberDecl->getType().getNonReferenceType(); 11968 } 11969 11970 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11971 Comps, Exprs, RParenLoc); 11972 } 11973 11974 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11975 SourceLocation BuiltinLoc, 11976 SourceLocation TypeLoc, 11977 ParsedType ParsedArgTy, 11978 ArrayRef<OffsetOfComponent> Components, 11979 SourceLocation RParenLoc) { 11980 11981 TypeSourceInfo *ArgTInfo; 11982 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11983 if (ArgTy.isNull()) 11984 return ExprError(); 11985 11986 if (!ArgTInfo) 11987 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11988 11989 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11990 } 11991 11992 11993 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11994 Expr *CondExpr, 11995 Expr *LHSExpr, Expr *RHSExpr, 11996 SourceLocation RPLoc) { 11997 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11998 11999 ExprValueKind VK = VK_RValue; 12000 ExprObjectKind OK = OK_Ordinary; 12001 QualType resType; 12002 bool ValueDependent = false; 12003 bool CondIsTrue = false; 12004 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12005 resType = Context.DependentTy; 12006 ValueDependent = true; 12007 } else { 12008 // The conditional expression is required to be a constant expression. 12009 llvm::APSInt condEval(32); 12010 ExprResult CondICE 12011 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12012 diag::err_typecheck_choose_expr_requires_constant, false); 12013 if (CondICE.isInvalid()) 12014 return ExprError(); 12015 CondExpr = CondICE.get(); 12016 CondIsTrue = condEval.getZExtValue(); 12017 12018 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12019 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12020 12021 resType = ActiveExpr->getType(); 12022 ValueDependent = ActiveExpr->isValueDependent(); 12023 VK = ActiveExpr->getValueKind(); 12024 OK = ActiveExpr->getObjectKind(); 12025 } 12026 12027 return new (Context) 12028 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12029 CondIsTrue, resType->isDependentType(), ValueDependent); 12030 } 12031 12032 //===----------------------------------------------------------------------===// 12033 // Clang Extensions. 12034 //===----------------------------------------------------------------------===// 12035 12036 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12037 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12038 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12039 12040 if (LangOpts.CPlusPlus) { 12041 Decl *ManglingContextDecl; 12042 if (MangleNumberingContext *MCtx = 12043 getCurrentMangleNumberContext(Block->getDeclContext(), 12044 ManglingContextDecl)) { 12045 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12046 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12047 } 12048 } 12049 12050 PushBlockScope(CurScope, Block); 12051 CurContext->addDecl(Block); 12052 if (CurScope) 12053 PushDeclContext(CurScope, Block); 12054 else 12055 CurContext = Block; 12056 12057 getCurBlock()->HasImplicitReturnType = true; 12058 12059 // Enter a new evaluation context to insulate the block from any 12060 // cleanups from the enclosing full-expression. 12061 PushExpressionEvaluationContext(PotentiallyEvaluated); 12062 } 12063 12064 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12065 Scope *CurScope) { 12066 assert(ParamInfo.getIdentifier() == nullptr && 12067 "block-id should have no identifier!"); 12068 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12069 BlockScopeInfo *CurBlock = getCurBlock(); 12070 12071 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12072 QualType T = Sig->getType(); 12073 12074 // FIXME: We should allow unexpanded parameter packs here, but that would, 12075 // in turn, make the block expression contain unexpanded parameter packs. 12076 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12077 // Drop the parameters. 12078 FunctionProtoType::ExtProtoInfo EPI; 12079 EPI.HasTrailingReturn = false; 12080 EPI.TypeQuals |= DeclSpec::TQ_const; 12081 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12082 Sig = Context.getTrivialTypeSourceInfo(T); 12083 } 12084 12085 // GetTypeForDeclarator always produces a function type for a block 12086 // literal signature. Furthermore, it is always a FunctionProtoType 12087 // unless the function was written with a typedef. 12088 assert(T->isFunctionType() && 12089 "GetTypeForDeclarator made a non-function block signature"); 12090 12091 // Look for an explicit signature in that function type. 12092 FunctionProtoTypeLoc ExplicitSignature; 12093 12094 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12095 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12096 12097 // Check whether that explicit signature was synthesized by 12098 // GetTypeForDeclarator. If so, don't save that as part of the 12099 // written signature. 12100 if (ExplicitSignature.getLocalRangeBegin() == 12101 ExplicitSignature.getLocalRangeEnd()) { 12102 // This would be much cheaper if we stored TypeLocs instead of 12103 // TypeSourceInfos. 12104 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12105 unsigned Size = Result.getFullDataSize(); 12106 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12107 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12108 12109 ExplicitSignature = FunctionProtoTypeLoc(); 12110 } 12111 } 12112 12113 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12114 CurBlock->FunctionType = T; 12115 12116 const FunctionType *Fn = T->getAs<FunctionType>(); 12117 QualType RetTy = Fn->getReturnType(); 12118 bool isVariadic = 12119 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12120 12121 CurBlock->TheDecl->setIsVariadic(isVariadic); 12122 12123 // Context.DependentTy is used as a placeholder for a missing block 12124 // return type. TODO: what should we do with declarators like: 12125 // ^ * { ... } 12126 // If the answer is "apply template argument deduction".... 12127 if (RetTy != Context.DependentTy) { 12128 CurBlock->ReturnType = RetTy; 12129 CurBlock->TheDecl->setBlockMissingReturnType(false); 12130 CurBlock->HasImplicitReturnType = false; 12131 } 12132 12133 // Push block parameters from the declarator if we had them. 12134 SmallVector<ParmVarDecl*, 8> Params; 12135 if (ExplicitSignature) { 12136 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12137 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12138 if (Param->getIdentifier() == nullptr && 12139 !Param->isImplicit() && 12140 !Param->isInvalidDecl() && 12141 !getLangOpts().CPlusPlus) 12142 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12143 Params.push_back(Param); 12144 } 12145 12146 // Fake up parameter variables if we have a typedef, like 12147 // ^ fntype { ... } 12148 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12149 for (const auto &I : Fn->param_types()) { 12150 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12151 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12152 Params.push_back(Param); 12153 } 12154 } 12155 12156 // Set the parameters on the block decl. 12157 if (!Params.empty()) { 12158 CurBlock->TheDecl->setParams(Params); 12159 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12160 /*CheckParameterNames=*/false); 12161 } 12162 12163 // Finally we can process decl attributes. 12164 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12165 12166 // Put the parameter variables in scope. 12167 for (auto AI : CurBlock->TheDecl->parameters()) { 12168 AI->setOwningFunction(CurBlock->TheDecl); 12169 12170 // If this has an identifier, add it to the scope stack. 12171 if (AI->getIdentifier()) { 12172 CheckShadow(CurBlock->TheScope, AI); 12173 12174 PushOnScopeChains(AI, CurBlock->TheScope); 12175 } 12176 } 12177 } 12178 12179 /// ActOnBlockError - If there is an error parsing a block, this callback 12180 /// is invoked to pop the information about the block from the action impl. 12181 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12182 // Leave the expression-evaluation context. 12183 DiscardCleanupsInEvaluationContext(); 12184 PopExpressionEvaluationContext(); 12185 12186 // Pop off CurBlock, handle nested blocks. 12187 PopDeclContext(); 12188 PopFunctionScopeInfo(); 12189 } 12190 12191 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12192 /// literal was successfully completed. ^(int x){...} 12193 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12194 Stmt *Body, Scope *CurScope) { 12195 // If blocks are disabled, emit an error. 12196 if (!LangOpts.Blocks) 12197 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12198 12199 // Leave the expression-evaluation context. 12200 if (hasAnyUnrecoverableErrorsInThisFunction()) 12201 DiscardCleanupsInEvaluationContext(); 12202 assert(!Cleanup.exprNeedsCleanups() && 12203 "cleanups within block not correctly bound!"); 12204 PopExpressionEvaluationContext(); 12205 12206 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12207 12208 if (BSI->HasImplicitReturnType) 12209 deduceClosureReturnType(*BSI); 12210 12211 PopDeclContext(); 12212 12213 QualType RetTy = Context.VoidTy; 12214 if (!BSI->ReturnType.isNull()) 12215 RetTy = BSI->ReturnType; 12216 12217 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12218 QualType BlockTy; 12219 12220 // Set the captured variables on the block. 12221 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12222 SmallVector<BlockDecl::Capture, 4> Captures; 12223 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12224 if (Cap.isThisCapture()) 12225 continue; 12226 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12227 Cap.isNested(), Cap.getInitExpr()); 12228 Captures.push_back(NewCap); 12229 } 12230 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12231 12232 // If the user wrote a function type in some form, try to use that. 12233 if (!BSI->FunctionType.isNull()) { 12234 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12235 12236 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12237 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12238 12239 // Turn protoless block types into nullary block types. 12240 if (isa<FunctionNoProtoType>(FTy)) { 12241 FunctionProtoType::ExtProtoInfo EPI; 12242 EPI.ExtInfo = Ext; 12243 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12244 12245 // Otherwise, if we don't need to change anything about the function type, 12246 // preserve its sugar structure. 12247 } else if (FTy->getReturnType() == RetTy && 12248 (!NoReturn || FTy->getNoReturnAttr())) { 12249 BlockTy = BSI->FunctionType; 12250 12251 // Otherwise, make the minimal modifications to the function type. 12252 } else { 12253 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12254 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12255 EPI.TypeQuals = 0; // FIXME: silently? 12256 EPI.ExtInfo = Ext; 12257 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12258 } 12259 12260 // If we don't have a function type, just build one from nothing. 12261 } else { 12262 FunctionProtoType::ExtProtoInfo EPI; 12263 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12264 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12265 } 12266 12267 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12268 BlockTy = Context.getBlockPointerType(BlockTy); 12269 12270 // If needed, diagnose invalid gotos and switches in the block. 12271 if (getCurFunction()->NeedsScopeChecking() && 12272 !PP.isCodeCompletionEnabled()) 12273 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12274 12275 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12276 12277 // Try to apply the named return value optimization. We have to check again 12278 // if we can do this, though, because blocks keep return statements around 12279 // to deduce an implicit return type. 12280 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12281 !BSI->TheDecl->isDependentContext()) 12282 computeNRVO(Body, BSI); 12283 12284 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12285 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12286 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12287 12288 // If the block isn't obviously global, i.e. it captures anything at 12289 // all, then we need to do a few things in the surrounding context: 12290 if (Result->getBlockDecl()->hasCaptures()) { 12291 // First, this expression has a new cleanup object. 12292 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12293 Cleanup.setExprNeedsCleanups(true); 12294 12295 // It also gets a branch-protected scope if any of the captured 12296 // variables needs destruction. 12297 for (const auto &CI : Result->getBlockDecl()->captures()) { 12298 const VarDecl *var = CI.getVariable(); 12299 if (var->getType().isDestructedType() != QualType::DK_none) { 12300 getCurFunction()->setHasBranchProtectedScope(); 12301 break; 12302 } 12303 } 12304 } 12305 12306 return Result; 12307 } 12308 12309 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12310 SourceLocation RPLoc) { 12311 TypeSourceInfo *TInfo; 12312 GetTypeFromParser(Ty, &TInfo); 12313 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12314 } 12315 12316 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12317 Expr *E, TypeSourceInfo *TInfo, 12318 SourceLocation RPLoc) { 12319 Expr *OrigExpr = E; 12320 bool IsMS = false; 12321 12322 // CUDA device code does not support varargs. 12323 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12324 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12325 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12326 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12327 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12328 } 12329 } 12330 12331 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12332 // as Microsoft ABI on an actual Microsoft platform, where 12333 // __builtin_ms_va_list and __builtin_va_list are the same.) 12334 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12335 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12336 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12337 if (Context.hasSameType(MSVaListType, E->getType())) { 12338 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12339 return ExprError(); 12340 IsMS = true; 12341 } 12342 } 12343 12344 // Get the va_list type 12345 QualType VaListType = Context.getBuiltinVaListType(); 12346 if (!IsMS) { 12347 if (VaListType->isArrayType()) { 12348 // Deal with implicit array decay; for example, on x86-64, 12349 // va_list is an array, but it's supposed to decay to 12350 // a pointer for va_arg. 12351 VaListType = Context.getArrayDecayedType(VaListType); 12352 // Make sure the input expression also decays appropriately. 12353 ExprResult Result = UsualUnaryConversions(E); 12354 if (Result.isInvalid()) 12355 return ExprError(); 12356 E = Result.get(); 12357 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12358 // If va_list is a record type and we are compiling in C++ mode, 12359 // check the argument using reference binding. 12360 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12361 Context, Context.getLValueReferenceType(VaListType), false); 12362 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12363 if (Init.isInvalid()) 12364 return ExprError(); 12365 E = Init.getAs<Expr>(); 12366 } else { 12367 // Otherwise, the va_list argument must be an l-value because 12368 // it is modified by va_arg. 12369 if (!E->isTypeDependent() && 12370 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12371 return ExprError(); 12372 } 12373 } 12374 12375 if (!IsMS && !E->isTypeDependent() && 12376 !Context.hasSameType(VaListType, E->getType())) 12377 return ExprError(Diag(E->getLocStart(), 12378 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12379 << OrigExpr->getType() << E->getSourceRange()); 12380 12381 if (!TInfo->getType()->isDependentType()) { 12382 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12383 diag::err_second_parameter_to_va_arg_incomplete, 12384 TInfo->getTypeLoc())) 12385 return ExprError(); 12386 12387 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12388 TInfo->getType(), 12389 diag::err_second_parameter_to_va_arg_abstract, 12390 TInfo->getTypeLoc())) 12391 return ExprError(); 12392 12393 if (!TInfo->getType().isPODType(Context)) { 12394 Diag(TInfo->getTypeLoc().getBeginLoc(), 12395 TInfo->getType()->isObjCLifetimeType() 12396 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12397 : diag::warn_second_parameter_to_va_arg_not_pod) 12398 << TInfo->getType() 12399 << TInfo->getTypeLoc().getSourceRange(); 12400 } 12401 12402 // Check for va_arg where arguments of the given type will be promoted 12403 // (i.e. this va_arg is guaranteed to have undefined behavior). 12404 QualType PromoteType; 12405 if (TInfo->getType()->isPromotableIntegerType()) { 12406 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12407 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12408 PromoteType = QualType(); 12409 } 12410 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12411 PromoteType = Context.DoubleTy; 12412 if (!PromoteType.isNull()) 12413 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12414 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12415 << TInfo->getType() 12416 << PromoteType 12417 << TInfo->getTypeLoc().getSourceRange()); 12418 } 12419 12420 QualType T = TInfo->getType().getNonLValueExprType(Context); 12421 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12422 } 12423 12424 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12425 // The type of __null will be int or long, depending on the size of 12426 // pointers on the target. 12427 QualType Ty; 12428 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12429 if (pw == Context.getTargetInfo().getIntWidth()) 12430 Ty = Context.IntTy; 12431 else if (pw == Context.getTargetInfo().getLongWidth()) 12432 Ty = Context.LongTy; 12433 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12434 Ty = Context.LongLongTy; 12435 else { 12436 llvm_unreachable("I don't know size of pointer!"); 12437 } 12438 12439 return new (Context) GNUNullExpr(Ty, TokenLoc); 12440 } 12441 12442 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12443 bool Diagnose) { 12444 if (!getLangOpts().ObjC1) 12445 return false; 12446 12447 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12448 if (!PT) 12449 return false; 12450 12451 if (!PT->isObjCIdType()) { 12452 // Check if the destination is the 'NSString' interface. 12453 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12454 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12455 return false; 12456 } 12457 12458 // Ignore any parens, implicit casts (should only be 12459 // array-to-pointer decays), and not-so-opaque values. The last is 12460 // important for making this trigger for property assignments. 12461 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12462 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12463 if (OV->getSourceExpr()) 12464 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12465 12466 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12467 if (!SL || !SL->isAscii()) 12468 return false; 12469 if (Diagnose) { 12470 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12471 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12472 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12473 } 12474 return true; 12475 } 12476 12477 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12478 const Expr *SrcExpr) { 12479 if (!DstType->isFunctionPointerType() || 12480 !SrcExpr->getType()->isFunctionType()) 12481 return false; 12482 12483 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12484 if (!DRE) 12485 return false; 12486 12487 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12488 if (!FD) 12489 return false; 12490 12491 return !S.checkAddressOfFunctionIsAvailable(FD, 12492 /*Complain=*/true, 12493 SrcExpr->getLocStart()); 12494 } 12495 12496 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12497 SourceLocation Loc, 12498 QualType DstType, QualType SrcType, 12499 Expr *SrcExpr, AssignmentAction Action, 12500 bool *Complained) { 12501 if (Complained) 12502 *Complained = false; 12503 12504 // Decode the result (notice that AST's are still created for extensions). 12505 bool CheckInferredResultType = false; 12506 bool isInvalid = false; 12507 unsigned DiagKind = 0; 12508 FixItHint Hint; 12509 ConversionFixItGenerator ConvHints; 12510 bool MayHaveConvFixit = false; 12511 bool MayHaveFunctionDiff = false; 12512 const ObjCInterfaceDecl *IFace = nullptr; 12513 const ObjCProtocolDecl *PDecl = nullptr; 12514 12515 switch (ConvTy) { 12516 case Compatible: 12517 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12518 return false; 12519 12520 case PointerToInt: 12521 DiagKind = diag::ext_typecheck_convert_pointer_int; 12522 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12523 MayHaveConvFixit = true; 12524 break; 12525 case IntToPointer: 12526 DiagKind = diag::ext_typecheck_convert_int_pointer; 12527 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12528 MayHaveConvFixit = true; 12529 break; 12530 case IncompatiblePointer: 12531 if (Action == AA_Passing_CFAudited) 12532 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12533 else if (SrcType->isFunctionPointerType() && 12534 DstType->isFunctionPointerType()) 12535 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12536 else 12537 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12538 12539 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12540 SrcType->isObjCObjectPointerType(); 12541 if (Hint.isNull() && !CheckInferredResultType) { 12542 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12543 } 12544 else if (CheckInferredResultType) { 12545 SrcType = SrcType.getUnqualifiedType(); 12546 DstType = DstType.getUnqualifiedType(); 12547 } 12548 MayHaveConvFixit = true; 12549 break; 12550 case IncompatiblePointerSign: 12551 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12552 break; 12553 case FunctionVoidPointer: 12554 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12555 break; 12556 case IncompatiblePointerDiscardsQualifiers: { 12557 // Perform array-to-pointer decay if necessary. 12558 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12559 12560 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12561 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12562 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12563 DiagKind = diag::err_typecheck_incompatible_address_space; 12564 break; 12565 12566 12567 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12568 DiagKind = diag::err_typecheck_incompatible_ownership; 12569 break; 12570 } 12571 12572 llvm_unreachable("unknown error case for discarding qualifiers!"); 12573 // fallthrough 12574 } 12575 case CompatiblePointerDiscardsQualifiers: 12576 // If the qualifiers lost were because we were applying the 12577 // (deprecated) C++ conversion from a string literal to a char* 12578 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12579 // Ideally, this check would be performed in 12580 // checkPointerTypesForAssignment. However, that would require a 12581 // bit of refactoring (so that the second argument is an 12582 // expression, rather than a type), which should be done as part 12583 // of a larger effort to fix checkPointerTypesForAssignment for 12584 // C++ semantics. 12585 if (getLangOpts().CPlusPlus && 12586 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12587 return false; 12588 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12589 break; 12590 case IncompatibleNestedPointerQualifiers: 12591 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12592 break; 12593 case IntToBlockPointer: 12594 DiagKind = diag::err_int_to_block_pointer; 12595 break; 12596 case IncompatibleBlockPointer: 12597 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12598 break; 12599 case IncompatibleObjCQualifiedId: { 12600 if (SrcType->isObjCQualifiedIdType()) { 12601 const ObjCObjectPointerType *srcOPT = 12602 SrcType->getAs<ObjCObjectPointerType>(); 12603 for (auto *srcProto : srcOPT->quals()) { 12604 PDecl = srcProto; 12605 break; 12606 } 12607 if (const ObjCInterfaceType *IFaceT = 12608 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12609 IFace = IFaceT->getDecl(); 12610 } 12611 else if (DstType->isObjCQualifiedIdType()) { 12612 const ObjCObjectPointerType *dstOPT = 12613 DstType->getAs<ObjCObjectPointerType>(); 12614 for (auto *dstProto : dstOPT->quals()) { 12615 PDecl = dstProto; 12616 break; 12617 } 12618 if (const ObjCInterfaceType *IFaceT = 12619 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12620 IFace = IFaceT->getDecl(); 12621 } 12622 DiagKind = diag::warn_incompatible_qualified_id; 12623 break; 12624 } 12625 case IncompatibleVectors: 12626 DiagKind = diag::warn_incompatible_vectors; 12627 break; 12628 case IncompatibleObjCWeakRef: 12629 DiagKind = diag::err_arc_weak_unavailable_assign; 12630 break; 12631 case Incompatible: 12632 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12633 if (Complained) 12634 *Complained = true; 12635 return true; 12636 } 12637 12638 DiagKind = diag::err_typecheck_convert_incompatible; 12639 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12640 MayHaveConvFixit = true; 12641 isInvalid = true; 12642 MayHaveFunctionDiff = true; 12643 break; 12644 } 12645 12646 QualType FirstType, SecondType; 12647 switch (Action) { 12648 case AA_Assigning: 12649 case AA_Initializing: 12650 // The destination type comes first. 12651 FirstType = DstType; 12652 SecondType = SrcType; 12653 break; 12654 12655 case AA_Returning: 12656 case AA_Passing: 12657 case AA_Passing_CFAudited: 12658 case AA_Converting: 12659 case AA_Sending: 12660 case AA_Casting: 12661 // The source type comes first. 12662 FirstType = SrcType; 12663 SecondType = DstType; 12664 break; 12665 } 12666 12667 PartialDiagnostic FDiag = PDiag(DiagKind); 12668 if (Action == AA_Passing_CFAudited) 12669 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12670 else 12671 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12672 12673 // If we can fix the conversion, suggest the FixIts. 12674 assert(ConvHints.isNull() || Hint.isNull()); 12675 if (!ConvHints.isNull()) { 12676 for (FixItHint &H : ConvHints.Hints) 12677 FDiag << H; 12678 } else { 12679 FDiag << Hint; 12680 } 12681 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12682 12683 if (MayHaveFunctionDiff) 12684 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12685 12686 Diag(Loc, FDiag); 12687 if (DiagKind == diag::warn_incompatible_qualified_id && 12688 PDecl && IFace && !IFace->hasDefinition()) 12689 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12690 << IFace->getName() << PDecl->getName(); 12691 12692 if (SecondType == Context.OverloadTy) 12693 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12694 FirstType, /*TakingAddress=*/true); 12695 12696 if (CheckInferredResultType) 12697 EmitRelatedResultTypeNote(SrcExpr); 12698 12699 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12700 EmitRelatedResultTypeNoteForReturn(DstType); 12701 12702 if (Complained) 12703 *Complained = true; 12704 return isInvalid; 12705 } 12706 12707 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12708 llvm::APSInt *Result) { 12709 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12710 public: 12711 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12712 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12713 } 12714 } Diagnoser; 12715 12716 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12717 } 12718 12719 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12720 llvm::APSInt *Result, 12721 unsigned DiagID, 12722 bool AllowFold) { 12723 class IDDiagnoser : public VerifyICEDiagnoser { 12724 unsigned DiagID; 12725 12726 public: 12727 IDDiagnoser(unsigned DiagID) 12728 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12729 12730 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12731 S.Diag(Loc, DiagID) << SR; 12732 } 12733 } Diagnoser(DiagID); 12734 12735 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12736 } 12737 12738 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12739 SourceRange SR) { 12740 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12741 } 12742 12743 ExprResult 12744 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12745 VerifyICEDiagnoser &Diagnoser, 12746 bool AllowFold) { 12747 SourceLocation DiagLoc = E->getLocStart(); 12748 12749 if (getLangOpts().CPlusPlus11) { 12750 // C++11 [expr.const]p5: 12751 // If an expression of literal class type is used in a context where an 12752 // integral constant expression is required, then that class type shall 12753 // have a single non-explicit conversion function to an integral or 12754 // unscoped enumeration type 12755 ExprResult Converted; 12756 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12757 public: 12758 CXX11ConvertDiagnoser(bool Silent) 12759 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12760 Silent, true) {} 12761 12762 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12763 QualType T) override { 12764 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12765 } 12766 12767 SemaDiagnosticBuilder diagnoseIncomplete( 12768 Sema &S, SourceLocation Loc, QualType T) override { 12769 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12770 } 12771 12772 SemaDiagnosticBuilder diagnoseExplicitConv( 12773 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12774 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12775 } 12776 12777 SemaDiagnosticBuilder noteExplicitConv( 12778 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12779 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12780 << ConvTy->isEnumeralType() << ConvTy; 12781 } 12782 12783 SemaDiagnosticBuilder diagnoseAmbiguous( 12784 Sema &S, SourceLocation Loc, QualType T) override { 12785 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12786 } 12787 12788 SemaDiagnosticBuilder noteAmbiguous( 12789 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12790 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12791 << ConvTy->isEnumeralType() << ConvTy; 12792 } 12793 12794 SemaDiagnosticBuilder diagnoseConversion( 12795 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12796 llvm_unreachable("conversion functions are permitted"); 12797 } 12798 } ConvertDiagnoser(Diagnoser.Suppress); 12799 12800 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12801 ConvertDiagnoser); 12802 if (Converted.isInvalid()) 12803 return Converted; 12804 E = Converted.get(); 12805 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12806 return ExprError(); 12807 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12808 // An ICE must be of integral or unscoped enumeration type. 12809 if (!Diagnoser.Suppress) 12810 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12811 return ExprError(); 12812 } 12813 12814 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12815 // in the non-ICE case. 12816 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12817 if (Result) 12818 *Result = E->EvaluateKnownConstInt(Context); 12819 return E; 12820 } 12821 12822 Expr::EvalResult EvalResult; 12823 SmallVector<PartialDiagnosticAt, 8> Notes; 12824 EvalResult.Diag = &Notes; 12825 12826 // Try to evaluate the expression, and produce diagnostics explaining why it's 12827 // not a constant expression as a side-effect. 12828 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12829 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12830 12831 // In C++11, we can rely on diagnostics being produced for any expression 12832 // which is not a constant expression. If no diagnostics were produced, then 12833 // this is a constant expression. 12834 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12835 if (Result) 12836 *Result = EvalResult.Val.getInt(); 12837 return E; 12838 } 12839 12840 // If our only note is the usual "invalid subexpression" note, just point 12841 // the caret at its location rather than producing an essentially 12842 // redundant note. 12843 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12844 diag::note_invalid_subexpr_in_const_expr) { 12845 DiagLoc = Notes[0].first; 12846 Notes.clear(); 12847 } 12848 12849 if (!Folded || !AllowFold) { 12850 if (!Diagnoser.Suppress) { 12851 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12852 for (const PartialDiagnosticAt &Note : Notes) 12853 Diag(Note.first, Note.second); 12854 } 12855 12856 return ExprError(); 12857 } 12858 12859 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12860 for (const PartialDiagnosticAt &Note : Notes) 12861 Diag(Note.first, Note.second); 12862 12863 if (Result) 12864 *Result = EvalResult.Val.getInt(); 12865 return E; 12866 } 12867 12868 namespace { 12869 // Handle the case where we conclude a expression which we speculatively 12870 // considered to be unevaluated is actually evaluated. 12871 class TransformToPE : public TreeTransform<TransformToPE> { 12872 typedef TreeTransform<TransformToPE> BaseTransform; 12873 12874 public: 12875 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12876 12877 // Make sure we redo semantic analysis 12878 bool AlwaysRebuild() { return true; } 12879 12880 // Make sure we handle LabelStmts correctly. 12881 // FIXME: This does the right thing, but maybe we need a more general 12882 // fix to TreeTransform? 12883 StmtResult TransformLabelStmt(LabelStmt *S) { 12884 S->getDecl()->setStmt(nullptr); 12885 return BaseTransform::TransformLabelStmt(S); 12886 } 12887 12888 // We need to special-case DeclRefExprs referring to FieldDecls which 12889 // are not part of a member pointer formation; normal TreeTransforming 12890 // doesn't catch this case because of the way we represent them in the AST. 12891 // FIXME: This is a bit ugly; is it really the best way to handle this 12892 // case? 12893 // 12894 // Error on DeclRefExprs referring to FieldDecls. 12895 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12896 if (isa<FieldDecl>(E->getDecl()) && 12897 !SemaRef.isUnevaluatedContext()) 12898 return SemaRef.Diag(E->getLocation(), 12899 diag::err_invalid_non_static_member_use) 12900 << E->getDecl() << E->getSourceRange(); 12901 12902 return BaseTransform::TransformDeclRefExpr(E); 12903 } 12904 12905 // Exception: filter out member pointer formation 12906 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12907 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12908 return E; 12909 12910 return BaseTransform::TransformUnaryOperator(E); 12911 } 12912 12913 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12914 // Lambdas never need to be transformed. 12915 return E; 12916 } 12917 }; 12918 } 12919 12920 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12921 assert(isUnevaluatedContext() && 12922 "Should only transform unevaluated expressions"); 12923 ExprEvalContexts.back().Context = 12924 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12925 if (isUnevaluatedContext()) 12926 return E; 12927 return TransformToPE(*this).TransformExpr(E); 12928 } 12929 12930 void 12931 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12932 Decl *LambdaContextDecl, 12933 bool IsDecltype) { 12934 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 12935 LambdaContextDecl, IsDecltype); 12936 Cleanup.reset(); 12937 if (!MaybeODRUseExprs.empty()) 12938 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12939 } 12940 12941 void 12942 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12943 ReuseLambdaContextDecl_t, 12944 bool IsDecltype) { 12945 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12946 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12947 } 12948 12949 void Sema::PopExpressionEvaluationContext() { 12950 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12951 unsigned NumTypos = Rec.NumTypos; 12952 12953 if (!Rec.Lambdas.empty()) { 12954 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12955 unsigned D; 12956 if (Rec.isUnevaluated()) { 12957 // C++11 [expr.prim.lambda]p2: 12958 // A lambda-expression shall not appear in an unevaluated operand 12959 // (Clause 5). 12960 D = diag::err_lambda_unevaluated_operand; 12961 } else { 12962 // C++1y [expr.const]p2: 12963 // A conditional-expression e is a core constant expression unless the 12964 // evaluation of e, following the rules of the abstract machine, would 12965 // evaluate [...] a lambda-expression. 12966 D = diag::err_lambda_in_constant_expression; 12967 } 12968 for (const auto *L : Rec.Lambdas) 12969 Diag(L->getLocStart(), D); 12970 } else { 12971 // Mark the capture expressions odr-used. This was deferred 12972 // during lambda expression creation. 12973 for (auto *Lambda : Rec.Lambdas) { 12974 for (auto *C : Lambda->capture_inits()) 12975 MarkDeclarationsReferencedInExpr(C); 12976 } 12977 } 12978 } 12979 12980 // When are coming out of an unevaluated context, clear out any 12981 // temporaries that we may have created as part of the evaluation of 12982 // the expression in that context: they aren't relevant because they 12983 // will never be constructed. 12984 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12985 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12986 ExprCleanupObjects.end()); 12987 Cleanup = Rec.ParentCleanup; 12988 CleanupVarDeclMarking(); 12989 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12990 // Otherwise, merge the contexts together. 12991 } else { 12992 Cleanup.mergeFrom(Rec.ParentCleanup); 12993 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12994 Rec.SavedMaybeODRUseExprs.end()); 12995 } 12996 12997 // Pop the current expression evaluation context off the stack. 12998 ExprEvalContexts.pop_back(); 12999 13000 if (!ExprEvalContexts.empty()) 13001 ExprEvalContexts.back().NumTypos += NumTypos; 13002 else 13003 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13004 "last ExpressionEvaluationContextRecord"); 13005 } 13006 13007 void Sema::DiscardCleanupsInEvaluationContext() { 13008 ExprCleanupObjects.erase( 13009 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13010 ExprCleanupObjects.end()); 13011 Cleanup.reset(); 13012 MaybeODRUseExprs.clear(); 13013 } 13014 13015 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13016 if (!E->getType()->isVariablyModifiedType()) 13017 return E; 13018 return TransformToPotentiallyEvaluated(E); 13019 } 13020 13021 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 13022 // Do not mark anything as "used" within a dependent context; wait for 13023 // an instantiation. 13024 if (SemaRef.CurContext->isDependentContext()) 13025 return false; 13026 13027 switch (SemaRef.ExprEvalContexts.back().Context) { 13028 case Sema::Unevaluated: 13029 case Sema::UnevaluatedAbstract: 13030 // We are in an expression that is not potentially evaluated; do nothing. 13031 // (Depending on how you read the standard, we actually do need to do 13032 // something here for null pointer constants, but the standard's 13033 // definition of a null pointer constant is completely crazy.) 13034 return false; 13035 13036 case Sema::DiscardedStatement: 13037 // These are technically a potentially evaluated but they have the effect 13038 // of suppressing use marking. 13039 return false; 13040 13041 case Sema::ConstantEvaluated: 13042 case Sema::PotentiallyEvaluated: 13043 // We are in a potentially evaluated expression (or a constant-expression 13044 // in C++03); we need to do implicit template instantiation, implicitly 13045 // define class members, and mark most declarations as used. 13046 return true; 13047 13048 case Sema::PotentiallyEvaluatedIfUsed: 13049 // Referenced declarations will only be used if the construct in the 13050 // containing expression is used. 13051 return false; 13052 } 13053 llvm_unreachable("Invalid context"); 13054 } 13055 13056 /// \brief Mark a function referenced, and check whether it is odr-used 13057 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13058 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13059 bool MightBeOdrUse) { 13060 assert(Func && "No function?"); 13061 13062 Func->setReferenced(); 13063 13064 // C++11 [basic.def.odr]p3: 13065 // A function whose name appears as a potentially-evaluated expression is 13066 // odr-used if it is the unique lookup result or the selected member of a 13067 // set of overloaded functions [...]. 13068 // 13069 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13070 // can just check that here. 13071 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13072 13073 // Determine whether we require a function definition to exist, per 13074 // C++11 [temp.inst]p3: 13075 // Unless a function template specialization has been explicitly 13076 // instantiated or explicitly specialized, the function template 13077 // specialization is implicitly instantiated when the specialization is 13078 // referenced in a context that requires a function definition to exist. 13079 // 13080 // We consider constexpr function templates to be referenced in a context 13081 // that requires a definition to exist whenever they are referenced. 13082 // 13083 // FIXME: This instantiates constexpr functions too frequently. If this is 13084 // really an unevaluated context (and we're not just in the definition of a 13085 // function template or overload resolution or other cases which we 13086 // incorrectly consider to be unevaluated contexts), and we're not in a 13087 // subexpression which we actually need to evaluate (for instance, a 13088 // template argument, array bound or an expression in a braced-init-list), 13089 // we are not permitted to instantiate this constexpr function definition. 13090 // 13091 // FIXME: This also implicitly defines special members too frequently. They 13092 // are only supposed to be implicitly defined if they are odr-used, but they 13093 // are not odr-used from constant expressions in unevaluated contexts. 13094 // However, they cannot be referenced if they are deleted, and they are 13095 // deleted whenever the implicit definition of the special member would 13096 // fail (with very few exceptions). 13097 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13098 bool NeedDefinition = 13099 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13100 (MD && !MD->isUserProvided()))); 13101 13102 // C++14 [temp.expl.spec]p6: 13103 // If a template [...] is explicitly specialized then that specialization 13104 // shall be declared before the first use of that specialization that would 13105 // cause an implicit instantiation to take place, in every translation unit 13106 // in which such a use occurs 13107 if (NeedDefinition && 13108 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13109 Func->getMemberSpecializationInfo())) 13110 checkSpecializationVisibility(Loc, Func); 13111 13112 // If we don't need to mark the function as used, and we don't need to 13113 // try to provide a definition, there's nothing more to do. 13114 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13115 (!NeedDefinition || Func->getBody())) 13116 return; 13117 13118 // Note that this declaration has been used. 13119 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13120 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13121 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13122 if (Constructor->isDefaultConstructor()) { 13123 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13124 return; 13125 DefineImplicitDefaultConstructor(Loc, Constructor); 13126 } else if (Constructor->isCopyConstructor()) { 13127 DefineImplicitCopyConstructor(Loc, Constructor); 13128 } else if (Constructor->isMoveConstructor()) { 13129 DefineImplicitMoveConstructor(Loc, Constructor); 13130 } 13131 } else if (Constructor->getInheritedConstructor()) { 13132 DefineInheritingConstructor(Loc, Constructor); 13133 } 13134 } else if (CXXDestructorDecl *Destructor = 13135 dyn_cast<CXXDestructorDecl>(Func)) { 13136 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13137 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13138 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13139 return; 13140 DefineImplicitDestructor(Loc, Destructor); 13141 } 13142 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13143 MarkVTableUsed(Loc, Destructor->getParent()); 13144 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13145 if (MethodDecl->isOverloadedOperator() && 13146 MethodDecl->getOverloadedOperator() == OO_Equal) { 13147 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13148 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13149 if (MethodDecl->isCopyAssignmentOperator()) 13150 DefineImplicitCopyAssignment(Loc, MethodDecl); 13151 else if (MethodDecl->isMoveAssignmentOperator()) 13152 DefineImplicitMoveAssignment(Loc, MethodDecl); 13153 } 13154 } else if (isa<CXXConversionDecl>(MethodDecl) && 13155 MethodDecl->getParent()->isLambda()) { 13156 CXXConversionDecl *Conversion = 13157 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13158 if (Conversion->isLambdaToBlockPointerConversion()) 13159 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13160 else 13161 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13162 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13163 MarkVTableUsed(Loc, MethodDecl->getParent()); 13164 } 13165 13166 // Recursive functions should be marked when used from another function. 13167 // FIXME: Is this really right? 13168 if (CurContext == Func) return; 13169 13170 // Resolve the exception specification for any function which is 13171 // used: CodeGen will need it. 13172 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13173 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13174 ResolveExceptionSpec(Loc, FPT); 13175 13176 // Implicit instantiation of function templates and member functions of 13177 // class templates. 13178 if (Func->isImplicitlyInstantiable()) { 13179 bool AlreadyInstantiated = false; 13180 SourceLocation PointOfInstantiation = Loc; 13181 if (FunctionTemplateSpecializationInfo *SpecInfo 13182 = Func->getTemplateSpecializationInfo()) { 13183 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13184 SpecInfo->setPointOfInstantiation(Loc); 13185 else if (SpecInfo->getTemplateSpecializationKind() 13186 == TSK_ImplicitInstantiation) { 13187 AlreadyInstantiated = true; 13188 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13189 } 13190 } else if (MemberSpecializationInfo *MSInfo 13191 = Func->getMemberSpecializationInfo()) { 13192 if (MSInfo->getPointOfInstantiation().isInvalid()) 13193 MSInfo->setPointOfInstantiation(Loc); 13194 else if (MSInfo->getTemplateSpecializationKind() 13195 == TSK_ImplicitInstantiation) { 13196 AlreadyInstantiated = true; 13197 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13198 } 13199 } 13200 13201 if (!AlreadyInstantiated || Func->isConstexpr()) { 13202 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13203 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13204 ActiveTemplateInstantiations.size()) 13205 PendingLocalImplicitInstantiations.push_back( 13206 std::make_pair(Func, PointOfInstantiation)); 13207 else if (Func->isConstexpr()) 13208 // Do not defer instantiations of constexpr functions, to avoid the 13209 // expression evaluator needing to call back into Sema if it sees a 13210 // call to such a function. 13211 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13212 else { 13213 PendingInstantiations.push_back(std::make_pair(Func, 13214 PointOfInstantiation)); 13215 // Notify the consumer that a function was implicitly instantiated. 13216 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13217 } 13218 } 13219 } else { 13220 // Walk redefinitions, as some of them may be instantiable. 13221 for (auto i : Func->redecls()) { 13222 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13223 MarkFunctionReferenced(Loc, i, OdrUse); 13224 } 13225 } 13226 13227 if (!OdrUse) return; 13228 13229 // Keep track of used but undefined functions. 13230 if (!Func->isDefined()) { 13231 if (mightHaveNonExternalLinkage(Func)) 13232 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13233 else if (Func->getMostRecentDecl()->isInlined() && 13234 !LangOpts.GNUInline && 13235 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13236 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13237 } 13238 13239 Func->markUsed(Context); 13240 } 13241 13242 static void 13243 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13244 ValueDecl *var, DeclContext *DC) { 13245 DeclContext *VarDC = var->getDeclContext(); 13246 13247 // If the parameter still belongs to the translation unit, then 13248 // we're actually just using one parameter in the declaration of 13249 // the next. 13250 if (isa<ParmVarDecl>(var) && 13251 isa<TranslationUnitDecl>(VarDC)) 13252 return; 13253 13254 // For C code, don't diagnose about capture if we're not actually in code 13255 // right now; it's impossible to write a non-constant expression outside of 13256 // function context, so we'll get other (more useful) diagnostics later. 13257 // 13258 // For C++, things get a bit more nasty... it would be nice to suppress this 13259 // diagnostic for certain cases like using a local variable in an array bound 13260 // for a member of a local class, but the correct predicate is not obvious. 13261 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13262 return; 13263 13264 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13265 unsigned ContextKind = 3; // unknown 13266 if (isa<CXXMethodDecl>(VarDC) && 13267 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13268 ContextKind = 2; 13269 } else if (isa<FunctionDecl>(VarDC)) { 13270 ContextKind = 0; 13271 } else if (isa<BlockDecl>(VarDC)) { 13272 ContextKind = 1; 13273 } 13274 13275 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13276 << var << ValueKind << ContextKind << VarDC; 13277 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13278 << var; 13279 13280 // FIXME: Add additional diagnostic info about class etc. which prevents 13281 // capture. 13282 } 13283 13284 13285 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13286 bool &SubCapturesAreNested, 13287 QualType &CaptureType, 13288 QualType &DeclRefType) { 13289 // Check whether we've already captured it. 13290 if (CSI->CaptureMap.count(Var)) { 13291 // If we found a capture, any subcaptures are nested. 13292 SubCapturesAreNested = true; 13293 13294 // Retrieve the capture type for this variable. 13295 CaptureType = CSI->getCapture(Var).getCaptureType(); 13296 13297 // Compute the type of an expression that refers to this variable. 13298 DeclRefType = CaptureType.getNonReferenceType(); 13299 13300 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13301 // are mutable in the sense that user can change their value - they are 13302 // private instances of the captured declarations. 13303 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13304 if (Cap.isCopyCapture() && 13305 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13306 !(isa<CapturedRegionScopeInfo>(CSI) && 13307 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13308 DeclRefType.addConst(); 13309 return true; 13310 } 13311 return false; 13312 } 13313 13314 // Only block literals, captured statements, and lambda expressions can 13315 // capture; other scopes don't work. 13316 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13317 SourceLocation Loc, 13318 const bool Diagnose, Sema &S) { 13319 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13320 return getLambdaAwareParentOfDeclContext(DC); 13321 else if (Var->hasLocalStorage()) { 13322 if (Diagnose) 13323 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13324 } 13325 return nullptr; 13326 } 13327 13328 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13329 // certain types of variables (unnamed, variably modified types etc.) 13330 // so check for eligibility. 13331 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13332 SourceLocation Loc, 13333 const bool Diagnose, Sema &S) { 13334 13335 bool IsBlock = isa<BlockScopeInfo>(CSI); 13336 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13337 13338 // Lambdas are not allowed to capture unnamed variables 13339 // (e.g. anonymous unions). 13340 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13341 // assuming that's the intent. 13342 if (IsLambda && !Var->getDeclName()) { 13343 if (Diagnose) { 13344 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13345 S.Diag(Var->getLocation(), diag::note_declared_at); 13346 } 13347 return false; 13348 } 13349 13350 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13351 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13352 if (Diagnose) { 13353 S.Diag(Loc, diag::err_ref_vm_type); 13354 S.Diag(Var->getLocation(), diag::note_previous_decl) 13355 << Var->getDeclName(); 13356 } 13357 return false; 13358 } 13359 // Prohibit structs with flexible array members too. 13360 // We cannot capture what is in the tail end of the struct. 13361 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13362 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13363 if (Diagnose) { 13364 if (IsBlock) 13365 S.Diag(Loc, diag::err_ref_flexarray_type); 13366 else 13367 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13368 << Var->getDeclName(); 13369 S.Diag(Var->getLocation(), diag::note_previous_decl) 13370 << Var->getDeclName(); 13371 } 13372 return false; 13373 } 13374 } 13375 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13376 // Lambdas and captured statements are not allowed to capture __block 13377 // variables; they don't support the expected semantics. 13378 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13379 if (Diagnose) { 13380 S.Diag(Loc, diag::err_capture_block_variable) 13381 << Var->getDeclName() << !IsLambda; 13382 S.Diag(Var->getLocation(), diag::note_previous_decl) 13383 << Var->getDeclName(); 13384 } 13385 return false; 13386 } 13387 13388 return true; 13389 } 13390 13391 // Returns true if the capture by block was successful. 13392 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13393 SourceLocation Loc, 13394 const bool BuildAndDiagnose, 13395 QualType &CaptureType, 13396 QualType &DeclRefType, 13397 const bool Nested, 13398 Sema &S) { 13399 Expr *CopyExpr = nullptr; 13400 bool ByRef = false; 13401 13402 // Blocks are not allowed to capture arrays. 13403 if (CaptureType->isArrayType()) { 13404 if (BuildAndDiagnose) { 13405 S.Diag(Loc, diag::err_ref_array_type); 13406 S.Diag(Var->getLocation(), diag::note_previous_decl) 13407 << Var->getDeclName(); 13408 } 13409 return false; 13410 } 13411 13412 // Forbid the block-capture of autoreleasing variables. 13413 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13414 if (BuildAndDiagnose) { 13415 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13416 << /*block*/ 0; 13417 S.Diag(Var->getLocation(), diag::note_previous_decl) 13418 << Var->getDeclName(); 13419 } 13420 return false; 13421 } 13422 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13423 if (HasBlocksAttr || CaptureType->isReferenceType() || 13424 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13425 // Block capture by reference does not change the capture or 13426 // declaration reference types. 13427 ByRef = true; 13428 } else { 13429 // Block capture by copy introduces 'const'. 13430 CaptureType = CaptureType.getNonReferenceType().withConst(); 13431 DeclRefType = CaptureType; 13432 13433 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13434 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13435 // The capture logic needs the destructor, so make sure we mark it. 13436 // Usually this is unnecessary because most local variables have 13437 // their destructors marked at declaration time, but parameters are 13438 // an exception because it's technically only the call site that 13439 // actually requires the destructor. 13440 if (isa<ParmVarDecl>(Var)) 13441 S.FinalizeVarWithDestructor(Var, Record); 13442 13443 // Enter a new evaluation context to insulate the copy 13444 // full-expression. 13445 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13446 13447 // According to the blocks spec, the capture of a variable from 13448 // the stack requires a const copy constructor. This is not true 13449 // of the copy/move done to move a __block variable to the heap. 13450 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13451 DeclRefType.withConst(), 13452 VK_LValue, Loc); 13453 13454 ExprResult Result 13455 = S.PerformCopyInitialization( 13456 InitializedEntity::InitializeBlock(Var->getLocation(), 13457 CaptureType, false), 13458 Loc, DeclRef); 13459 13460 // Build a full-expression copy expression if initialization 13461 // succeeded and used a non-trivial constructor. Recover from 13462 // errors by pretending that the copy isn't necessary. 13463 if (!Result.isInvalid() && 13464 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13465 ->isTrivial()) { 13466 Result = S.MaybeCreateExprWithCleanups(Result); 13467 CopyExpr = Result.get(); 13468 } 13469 } 13470 } 13471 } 13472 13473 // Actually capture the variable. 13474 if (BuildAndDiagnose) 13475 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13476 SourceLocation(), CaptureType, CopyExpr); 13477 13478 return true; 13479 13480 } 13481 13482 13483 /// \brief Capture the given variable in the captured region. 13484 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13485 VarDecl *Var, 13486 SourceLocation Loc, 13487 const bool BuildAndDiagnose, 13488 QualType &CaptureType, 13489 QualType &DeclRefType, 13490 const bool RefersToCapturedVariable, 13491 Sema &S) { 13492 // By default, capture variables by reference. 13493 bool ByRef = true; 13494 // Using an LValue reference type is consistent with Lambdas (see below). 13495 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13496 if (S.IsOpenMPCapturedDecl(Var)) 13497 DeclRefType = DeclRefType.getUnqualifiedType(); 13498 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13499 } 13500 13501 if (ByRef) 13502 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13503 else 13504 CaptureType = DeclRefType; 13505 13506 Expr *CopyExpr = nullptr; 13507 if (BuildAndDiagnose) { 13508 // The current implementation assumes that all variables are captured 13509 // by references. Since there is no capture by copy, no expression 13510 // evaluation will be needed. 13511 RecordDecl *RD = RSI->TheRecordDecl; 13512 13513 FieldDecl *Field 13514 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13515 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13516 nullptr, false, ICIS_NoInit); 13517 Field->setImplicit(true); 13518 Field->setAccess(AS_private); 13519 RD->addDecl(Field); 13520 13521 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13522 DeclRefType, VK_LValue, Loc); 13523 Var->setReferenced(true); 13524 Var->markUsed(S.Context); 13525 } 13526 13527 // Actually capture the variable. 13528 if (BuildAndDiagnose) 13529 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13530 SourceLocation(), CaptureType, CopyExpr); 13531 13532 13533 return true; 13534 } 13535 13536 /// \brief Create a field within the lambda class for the variable 13537 /// being captured. 13538 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13539 QualType FieldType, QualType DeclRefType, 13540 SourceLocation Loc, 13541 bool RefersToCapturedVariable) { 13542 CXXRecordDecl *Lambda = LSI->Lambda; 13543 13544 // Build the non-static data member. 13545 FieldDecl *Field 13546 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13547 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13548 nullptr, false, ICIS_NoInit); 13549 Field->setImplicit(true); 13550 Field->setAccess(AS_private); 13551 Lambda->addDecl(Field); 13552 } 13553 13554 /// \brief Capture the given variable in the lambda. 13555 static bool captureInLambda(LambdaScopeInfo *LSI, 13556 VarDecl *Var, 13557 SourceLocation Loc, 13558 const bool BuildAndDiagnose, 13559 QualType &CaptureType, 13560 QualType &DeclRefType, 13561 const bool RefersToCapturedVariable, 13562 const Sema::TryCaptureKind Kind, 13563 SourceLocation EllipsisLoc, 13564 const bool IsTopScope, 13565 Sema &S) { 13566 13567 // Determine whether we are capturing by reference or by value. 13568 bool ByRef = false; 13569 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13570 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13571 } else { 13572 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13573 } 13574 13575 // Compute the type of the field that will capture this variable. 13576 if (ByRef) { 13577 // C++11 [expr.prim.lambda]p15: 13578 // An entity is captured by reference if it is implicitly or 13579 // explicitly captured but not captured by copy. It is 13580 // unspecified whether additional unnamed non-static data 13581 // members are declared in the closure type for entities 13582 // captured by reference. 13583 // 13584 // FIXME: It is not clear whether we want to build an lvalue reference 13585 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13586 // to do the former, while EDG does the latter. Core issue 1249 will 13587 // clarify, but for now we follow GCC because it's a more permissive and 13588 // easily defensible position. 13589 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13590 } else { 13591 // C++11 [expr.prim.lambda]p14: 13592 // For each entity captured by copy, an unnamed non-static 13593 // data member is declared in the closure type. The 13594 // declaration order of these members is unspecified. The type 13595 // of such a data member is the type of the corresponding 13596 // captured entity if the entity is not a reference to an 13597 // object, or the referenced type otherwise. [Note: If the 13598 // captured entity is a reference to a function, the 13599 // corresponding data member is also a reference to a 13600 // function. - end note ] 13601 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13602 if (!RefType->getPointeeType()->isFunctionType()) 13603 CaptureType = RefType->getPointeeType(); 13604 } 13605 13606 // Forbid the lambda copy-capture of autoreleasing variables. 13607 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13608 if (BuildAndDiagnose) { 13609 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13610 S.Diag(Var->getLocation(), diag::note_previous_decl) 13611 << Var->getDeclName(); 13612 } 13613 return false; 13614 } 13615 13616 // Make sure that by-copy captures are of a complete and non-abstract type. 13617 if (BuildAndDiagnose) { 13618 if (!CaptureType->isDependentType() && 13619 S.RequireCompleteType(Loc, CaptureType, 13620 diag::err_capture_of_incomplete_type, 13621 Var->getDeclName())) 13622 return false; 13623 13624 if (S.RequireNonAbstractType(Loc, CaptureType, 13625 diag::err_capture_of_abstract_type)) 13626 return false; 13627 } 13628 } 13629 13630 // Capture this variable in the lambda. 13631 if (BuildAndDiagnose) 13632 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13633 RefersToCapturedVariable); 13634 13635 // Compute the type of a reference to this captured variable. 13636 if (ByRef) 13637 DeclRefType = CaptureType.getNonReferenceType(); 13638 else { 13639 // C++ [expr.prim.lambda]p5: 13640 // The closure type for a lambda-expression has a public inline 13641 // function call operator [...]. This function call operator is 13642 // declared const (9.3.1) if and only if the lambda-expression’s 13643 // parameter-declaration-clause is not followed by mutable. 13644 DeclRefType = CaptureType.getNonReferenceType(); 13645 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13646 DeclRefType.addConst(); 13647 } 13648 13649 // Add the capture. 13650 if (BuildAndDiagnose) 13651 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13652 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13653 13654 return true; 13655 } 13656 13657 bool Sema::tryCaptureVariable( 13658 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13659 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13660 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13661 // An init-capture is notionally from the context surrounding its 13662 // declaration, but its parent DC is the lambda class. 13663 DeclContext *VarDC = Var->getDeclContext(); 13664 if (Var->isInitCapture()) 13665 VarDC = VarDC->getParent(); 13666 13667 DeclContext *DC = CurContext; 13668 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13669 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13670 // We need to sync up the Declaration Context with the 13671 // FunctionScopeIndexToStopAt 13672 if (FunctionScopeIndexToStopAt) { 13673 unsigned FSIndex = FunctionScopes.size() - 1; 13674 while (FSIndex != MaxFunctionScopesIndex) { 13675 DC = getLambdaAwareParentOfDeclContext(DC); 13676 --FSIndex; 13677 } 13678 } 13679 13680 13681 // If the variable is declared in the current context, there is no need to 13682 // capture it. 13683 if (VarDC == DC) return true; 13684 13685 // Capture global variables if it is required to use private copy of this 13686 // variable. 13687 bool IsGlobal = !Var->hasLocalStorage(); 13688 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13689 return true; 13690 13691 // Walk up the stack to determine whether we can capture the variable, 13692 // performing the "simple" checks that don't depend on type. We stop when 13693 // we've either hit the declared scope of the variable or find an existing 13694 // capture of that variable. We start from the innermost capturing-entity 13695 // (the DC) and ensure that all intervening capturing-entities 13696 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13697 // declcontext can either capture the variable or have already captured 13698 // the variable. 13699 CaptureType = Var->getType(); 13700 DeclRefType = CaptureType.getNonReferenceType(); 13701 bool Nested = false; 13702 bool Explicit = (Kind != TryCapture_Implicit); 13703 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13704 do { 13705 // Only block literals, captured statements, and lambda expressions can 13706 // capture; other scopes don't work. 13707 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13708 ExprLoc, 13709 BuildAndDiagnose, 13710 *this); 13711 // We need to check for the parent *first* because, if we *have* 13712 // private-captured a global variable, we need to recursively capture it in 13713 // intermediate blocks, lambdas, etc. 13714 if (!ParentDC) { 13715 if (IsGlobal) { 13716 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13717 break; 13718 } 13719 return true; 13720 } 13721 13722 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13723 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13724 13725 13726 // Check whether we've already captured it. 13727 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13728 DeclRefType)) 13729 break; 13730 // If we are instantiating a generic lambda call operator body, 13731 // we do not want to capture new variables. What was captured 13732 // during either a lambdas transformation or initial parsing 13733 // should be used. 13734 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13735 if (BuildAndDiagnose) { 13736 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13737 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13738 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13739 Diag(Var->getLocation(), diag::note_previous_decl) 13740 << Var->getDeclName(); 13741 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13742 } else 13743 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13744 } 13745 return true; 13746 } 13747 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13748 // certain types of variables (unnamed, variably modified types etc.) 13749 // so check for eligibility. 13750 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13751 return true; 13752 13753 // Try to capture variable-length arrays types. 13754 if (Var->getType()->isVariablyModifiedType()) { 13755 // We're going to walk down into the type and look for VLA 13756 // expressions. 13757 QualType QTy = Var->getType(); 13758 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13759 QTy = PVD->getOriginalType(); 13760 captureVariablyModifiedType(Context, QTy, CSI); 13761 } 13762 13763 if (getLangOpts().OpenMP) { 13764 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13765 // OpenMP private variables should not be captured in outer scope, so 13766 // just break here. Similarly, global variables that are captured in a 13767 // target region should not be captured outside the scope of the region. 13768 if (RSI->CapRegionKind == CR_OpenMP) { 13769 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13770 // When we detect target captures we are looking from inside the 13771 // target region, therefore we need to propagate the capture from the 13772 // enclosing region. Therefore, the capture is not initially nested. 13773 if (IsTargetCap) 13774 FunctionScopesIndex--; 13775 13776 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13777 Nested = !IsTargetCap; 13778 DeclRefType = DeclRefType.getUnqualifiedType(); 13779 CaptureType = Context.getLValueReferenceType(DeclRefType); 13780 break; 13781 } 13782 } 13783 } 13784 } 13785 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13786 // No capture-default, and this is not an explicit capture 13787 // so cannot capture this variable. 13788 if (BuildAndDiagnose) { 13789 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13790 Diag(Var->getLocation(), diag::note_previous_decl) 13791 << Var->getDeclName(); 13792 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13793 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13794 diag::note_lambda_decl); 13795 // FIXME: If we error out because an outer lambda can not implicitly 13796 // capture a variable that an inner lambda explicitly captures, we 13797 // should have the inner lambda do the explicit capture - because 13798 // it makes for cleaner diagnostics later. This would purely be done 13799 // so that the diagnostic does not misleadingly claim that a variable 13800 // can not be captured by a lambda implicitly even though it is captured 13801 // explicitly. Suggestion: 13802 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13803 // at the function head 13804 // - cache the StartingDeclContext - this must be a lambda 13805 // - captureInLambda in the innermost lambda the variable. 13806 } 13807 return true; 13808 } 13809 13810 FunctionScopesIndex--; 13811 DC = ParentDC; 13812 Explicit = false; 13813 } while (!VarDC->Equals(DC)); 13814 13815 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13816 // computing the type of the capture at each step, checking type-specific 13817 // requirements, and adding captures if requested. 13818 // If the variable had already been captured previously, we start capturing 13819 // at the lambda nested within that one. 13820 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13821 ++I) { 13822 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13823 13824 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13825 if (!captureInBlock(BSI, Var, ExprLoc, 13826 BuildAndDiagnose, CaptureType, 13827 DeclRefType, Nested, *this)) 13828 return true; 13829 Nested = true; 13830 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13831 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13832 BuildAndDiagnose, CaptureType, 13833 DeclRefType, Nested, *this)) 13834 return true; 13835 Nested = true; 13836 } else { 13837 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13838 if (!captureInLambda(LSI, Var, ExprLoc, 13839 BuildAndDiagnose, CaptureType, 13840 DeclRefType, Nested, Kind, EllipsisLoc, 13841 /*IsTopScope*/I == N - 1, *this)) 13842 return true; 13843 Nested = true; 13844 } 13845 } 13846 return false; 13847 } 13848 13849 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13850 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13851 QualType CaptureType; 13852 QualType DeclRefType; 13853 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13854 /*BuildAndDiagnose=*/true, CaptureType, 13855 DeclRefType, nullptr); 13856 } 13857 13858 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13859 QualType CaptureType; 13860 QualType DeclRefType; 13861 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13862 /*BuildAndDiagnose=*/false, CaptureType, 13863 DeclRefType, nullptr); 13864 } 13865 13866 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13867 QualType CaptureType; 13868 QualType DeclRefType; 13869 13870 // Determine whether we can capture this variable. 13871 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13872 /*BuildAndDiagnose=*/false, CaptureType, 13873 DeclRefType, nullptr)) 13874 return QualType(); 13875 13876 return DeclRefType; 13877 } 13878 13879 13880 13881 // If either the type of the variable or the initializer is dependent, 13882 // return false. Otherwise, determine whether the variable is a constant 13883 // expression. Use this if you need to know if a variable that might or 13884 // might not be dependent is truly a constant expression. 13885 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13886 ASTContext &Context) { 13887 13888 if (Var->getType()->isDependentType()) 13889 return false; 13890 const VarDecl *DefVD = nullptr; 13891 Var->getAnyInitializer(DefVD); 13892 if (!DefVD) 13893 return false; 13894 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13895 Expr *Init = cast<Expr>(Eval->Value); 13896 if (Init->isValueDependent()) 13897 return false; 13898 return IsVariableAConstantExpression(Var, Context); 13899 } 13900 13901 13902 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13903 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13904 // an object that satisfies the requirements for appearing in a 13905 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13906 // is immediately applied." This function handles the lvalue-to-rvalue 13907 // conversion part. 13908 MaybeODRUseExprs.erase(E->IgnoreParens()); 13909 13910 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13911 // to a variable that is a constant expression, and if so, identify it as 13912 // a reference to a variable that does not involve an odr-use of that 13913 // variable. 13914 if (LambdaScopeInfo *LSI = getCurLambda()) { 13915 Expr *SansParensExpr = E->IgnoreParens(); 13916 VarDecl *Var = nullptr; 13917 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13918 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13919 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13920 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13921 13922 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13923 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13924 } 13925 } 13926 13927 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13928 Res = CorrectDelayedTyposInExpr(Res); 13929 13930 if (!Res.isUsable()) 13931 return Res; 13932 13933 // If a constant-expression is a reference to a variable where we delay 13934 // deciding whether it is an odr-use, just assume we will apply the 13935 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13936 // (a non-type template argument), we have special handling anyway. 13937 UpdateMarkingForLValueToRValue(Res.get()); 13938 return Res; 13939 } 13940 13941 void Sema::CleanupVarDeclMarking() { 13942 for (Expr *E : MaybeODRUseExprs) { 13943 VarDecl *Var; 13944 SourceLocation Loc; 13945 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13946 Var = cast<VarDecl>(DRE->getDecl()); 13947 Loc = DRE->getLocation(); 13948 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13949 Var = cast<VarDecl>(ME->getMemberDecl()); 13950 Loc = ME->getMemberLoc(); 13951 } else { 13952 llvm_unreachable("Unexpected expression"); 13953 } 13954 13955 MarkVarDeclODRUsed(Var, Loc, *this, 13956 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13957 } 13958 13959 MaybeODRUseExprs.clear(); 13960 } 13961 13962 13963 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13964 VarDecl *Var, Expr *E) { 13965 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13966 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13967 Var->setReferenced(); 13968 13969 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13970 bool MarkODRUsed = true; 13971 13972 // If the context is not potentially evaluated, this is not an odr-use and 13973 // does not trigger instantiation. 13974 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13975 if (SemaRef.isUnevaluatedContext()) 13976 return; 13977 13978 // If we don't yet know whether this context is going to end up being an 13979 // evaluated context, and we're referencing a variable from an enclosing 13980 // scope, add a potential capture. 13981 // 13982 // FIXME: Is this necessary? These contexts are only used for default 13983 // arguments, where local variables can't be used. 13984 const bool RefersToEnclosingScope = 13985 (SemaRef.CurContext != Var->getDeclContext() && 13986 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13987 if (RefersToEnclosingScope) { 13988 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13989 // If a variable could potentially be odr-used, defer marking it so 13990 // until we finish analyzing the full expression for any 13991 // lvalue-to-rvalue 13992 // or discarded value conversions that would obviate odr-use. 13993 // Add it to the list of potential captures that will be analyzed 13994 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13995 // unless the variable is a reference that was initialized by a constant 13996 // expression (this will never need to be captured or odr-used). 13997 assert(E && "Capture variable should be used in an expression."); 13998 if (!Var->getType()->isReferenceType() || 13999 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14000 LSI->addPotentialCapture(E->IgnoreParens()); 14001 } 14002 } 14003 14004 if (!isTemplateInstantiation(TSK)) 14005 return; 14006 14007 // Instantiate, but do not mark as odr-used, variable templates. 14008 MarkODRUsed = false; 14009 } 14010 14011 VarTemplateSpecializationDecl *VarSpec = 14012 dyn_cast<VarTemplateSpecializationDecl>(Var); 14013 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14014 "Can't instantiate a partial template specialization."); 14015 14016 // If this might be a member specialization of a static data member, check 14017 // the specialization is visible. We already did the checks for variable 14018 // template specializations when we created them. 14019 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 14020 SemaRef.checkSpecializationVisibility(Loc, Var); 14021 14022 // Perform implicit instantiation of static data members, static data member 14023 // templates of class templates, and variable template specializations. Delay 14024 // instantiations of variable templates, except for those that could be used 14025 // in a constant expression. 14026 if (isTemplateInstantiation(TSK)) { 14027 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14028 14029 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14030 if (Var->getPointOfInstantiation().isInvalid()) { 14031 // This is a modification of an existing AST node. Notify listeners. 14032 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14033 L->StaticDataMemberInstantiated(Var); 14034 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14035 // Don't bother trying to instantiate it again, unless we might need 14036 // its initializer before we get to the end of the TU. 14037 TryInstantiating = false; 14038 } 14039 14040 if (Var->getPointOfInstantiation().isInvalid()) 14041 Var->setTemplateSpecializationKind(TSK, Loc); 14042 14043 if (TryInstantiating) { 14044 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14045 bool InstantiationDependent = false; 14046 bool IsNonDependent = 14047 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14048 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14049 : true; 14050 14051 // Do not instantiate specializations that are still type-dependent. 14052 if (IsNonDependent) { 14053 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14054 // Do not defer instantiations of variables which could be used in a 14055 // constant expression. 14056 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14057 } else { 14058 SemaRef.PendingInstantiations 14059 .push_back(std::make_pair(Var, PointOfInstantiation)); 14060 } 14061 } 14062 } 14063 } 14064 14065 if (!MarkODRUsed) 14066 return; 14067 14068 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14069 // the requirements for appearing in a constant expression (5.19) and, if 14070 // it is an object, the lvalue-to-rvalue conversion (4.1) 14071 // is immediately applied." We check the first part here, and 14072 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14073 // Note that we use the C++11 definition everywhere because nothing in 14074 // C++03 depends on whether we get the C++03 version correct. The second 14075 // part does not apply to references, since they are not objects. 14076 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14077 // A reference initialized by a constant expression can never be 14078 // odr-used, so simply ignore it. 14079 if (!Var->getType()->isReferenceType()) 14080 SemaRef.MaybeODRUseExprs.insert(E); 14081 } else 14082 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14083 /*MaxFunctionScopeIndex ptr*/ nullptr); 14084 } 14085 14086 /// \brief Mark a variable referenced, and check whether it is odr-used 14087 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14088 /// used directly for normal expressions referring to VarDecl. 14089 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14090 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14091 } 14092 14093 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14094 Decl *D, Expr *E, bool MightBeOdrUse) { 14095 if (SemaRef.isInOpenMPDeclareTargetContext()) 14096 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14097 14098 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14099 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14100 return; 14101 } 14102 14103 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14104 14105 // If this is a call to a method via a cast, also mark the method in the 14106 // derived class used in case codegen can devirtualize the call. 14107 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14108 if (!ME) 14109 return; 14110 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14111 if (!MD) 14112 return; 14113 // Only attempt to devirtualize if this is truly a virtual call. 14114 bool IsVirtualCall = MD->isVirtual() && 14115 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14116 if (!IsVirtualCall) 14117 return; 14118 const Expr *Base = ME->getBase(); 14119 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14120 if (!MostDerivedClassDecl) 14121 return; 14122 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14123 if (!DM || DM->isPure()) 14124 return; 14125 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14126 } 14127 14128 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14129 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14130 // TODO: update this with DR# once a defect report is filed. 14131 // C++11 defect. The address of a pure member should not be an ODR use, even 14132 // if it's a qualified reference. 14133 bool OdrUse = true; 14134 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14135 if (Method->isVirtual()) 14136 OdrUse = false; 14137 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14138 } 14139 14140 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14141 void Sema::MarkMemberReferenced(MemberExpr *E) { 14142 // C++11 [basic.def.odr]p2: 14143 // A non-overloaded function whose name appears as a potentially-evaluated 14144 // expression or a member of a set of candidate functions, if selected by 14145 // overload resolution when referred to from a potentially-evaluated 14146 // expression, is odr-used, unless it is a pure virtual function and its 14147 // name is not explicitly qualified. 14148 bool MightBeOdrUse = true; 14149 if (E->performsVirtualDispatch(getLangOpts())) { 14150 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14151 if (Method->isPure()) 14152 MightBeOdrUse = false; 14153 } 14154 SourceLocation Loc = E->getMemberLoc().isValid() ? 14155 E->getMemberLoc() : E->getLocStart(); 14156 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14157 } 14158 14159 /// \brief Perform marking for a reference to an arbitrary declaration. It 14160 /// marks the declaration referenced, and performs odr-use checking for 14161 /// functions and variables. This method should not be used when building a 14162 /// normal expression which refers to a variable. 14163 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14164 bool MightBeOdrUse) { 14165 if (MightBeOdrUse) { 14166 if (auto *VD = dyn_cast<VarDecl>(D)) { 14167 MarkVariableReferenced(Loc, VD); 14168 return; 14169 } 14170 } 14171 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14172 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14173 return; 14174 } 14175 D->setReferenced(); 14176 } 14177 14178 namespace { 14179 // Mark all of the declarations referenced 14180 // FIXME: Not fully implemented yet! We need to have a better understanding 14181 // of when we're entering 14182 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14183 Sema &S; 14184 SourceLocation Loc; 14185 14186 public: 14187 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14188 14189 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14190 14191 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14192 bool TraverseRecordType(RecordType *T); 14193 }; 14194 } 14195 14196 bool MarkReferencedDecls::TraverseTemplateArgument( 14197 const TemplateArgument &Arg) { 14198 if (Arg.getKind() == TemplateArgument::Declaration) { 14199 if (Decl *D = Arg.getAsDecl()) 14200 S.MarkAnyDeclReferenced(Loc, D, true); 14201 } 14202 14203 return Inherited::TraverseTemplateArgument(Arg); 14204 } 14205 14206 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14207 if (ClassTemplateSpecializationDecl *Spec 14208 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14209 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14210 return TraverseTemplateArguments(Args.data(), Args.size()); 14211 } 14212 14213 return true; 14214 } 14215 14216 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14217 MarkReferencedDecls Marker(*this, Loc); 14218 Marker.TraverseType(Context.getCanonicalType(T)); 14219 } 14220 14221 namespace { 14222 /// \brief Helper class that marks all of the declarations referenced by 14223 /// potentially-evaluated subexpressions as "referenced". 14224 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14225 Sema &S; 14226 bool SkipLocalVariables; 14227 14228 public: 14229 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14230 14231 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14232 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14233 14234 void VisitDeclRefExpr(DeclRefExpr *E) { 14235 // If we were asked not to visit local variables, don't. 14236 if (SkipLocalVariables) { 14237 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14238 if (VD->hasLocalStorage()) 14239 return; 14240 } 14241 14242 S.MarkDeclRefReferenced(E); 14243 } 14244 14245 void VisitMemberExpr(MemberExpr *E) { 14246 S.MarkMemberReferenced(E); 14247 Inherited::VisitMemberExpr(E); 14248 } 14249 14250 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14251 S.MarkFunctionReferenced(E->getLocStart(), 14252 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14253 Visit(E->getSubExpr()); 14254 } 14255 14256 void VisitCXXNewExpr(CXXNewExpr *E) { 14257 if (E->getOperatorNew()) 14258 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14259 if (E->getOperatorDelete()) 14260 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14261 Inherited::VisitCXXNewExpr(E); 14262 } 14263 14264 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14265 if (E->getOperatorDelete()) 14266 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14267 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14268 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14269 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14270 S.MarkFunctionReferenced(E->getLocStart(), 14271 S.LookupDestructor(Record)); 14272 } 14273 14274 Inherited::VisitCXXDeleteExpr(E); 14275 } 14276 14277 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14278 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14279 Inherited::VisitCXXConstructExpr(E); 14280 } 14281 14282 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14283 Visit(E->getExpr()); 14284 } 14285 14286 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14287 Inherited::VisitImplicitCastExpr(E); 14288 14289 if (E->getCastKind() == CK_LValueToRValue) 14290 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14291 } 14292 }; 14293 } 14294 14295 /// \brief Mark any declarations that appear within this expression or any 14296 /// potentially-evaluated subexpressions as "referenced". 14297 /// 14298 /// \param SkipLocalVariables If true, don't mark local variables as 14299 /// 'referenced'. 14300 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14301 bool SkipLocalVariables) { 14302 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14303 } 14304 14305 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14306 /// of the program being compiled. 14307 /// 14308 /// This routine emits the given diagnostic when the code currently being 14309 /// type-checked is "potentially evaluated", meaning that there is a 14310 /// possibility that the code will actually be executable. Code in sizeof() 14311 /// expressions, code used only during overload resolution, etc., are not 14312 /// potentially evaluated. This routine will suppress such diagnostics or, 14313 /// in the absolutely nutty case of potentially potentially evaluated 14314 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14315 /// later. 14316 /// 14317 /// This routine should be used for all diagnostics that describe the run-time 14318 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14319 /// Failure to do so will likely result in spurious diagnostics or failures 14320 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14321 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14322 const PartialDiagnostic &PD) { 14323 switch (ExprEvalContexts.back().Context) { 14324 case Unevaluated: 14325 case UnevaluatedAbstract: 14326 case DiscardedStatement: 14327 // The argument will never be evaluated, so don't complain. 14328 break; 14329 14330 case ConstantEvaluated: 14331 // Relevant diagnostics should be produced by constant evaluation. 14332 break; 14333 14334 case PotentiallyEvaluated: 14335 case PotentiallyEvaluatedIfUsed: 14336 if (Statement && getCurFunctionOrMethodDecl()) { 14337 FunctionScopes.back()->PossiblyUnreachableDiags. 14338 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14339 } 14340 else 14341 Diag(Loc, PD); 14342 14343 return true; 14344 } 14345 14346 return false; 14347 } 14348 14349 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14350 CallExpr *CE, FunctionDecl *FD) { 14351 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14352 return false; 14353 14354 // If we're inside a decltype's expression, don't check for a valid return 14355 // type or construct temporaries until we know whether this is the last call. 14356 if (ExprEvalContexts.back().IsDecltype) { 14357 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14358 return false; 14359 } 14360 14361 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14362 FunctionDecl *FD; 14363 CallExpr *CE; 14364 14365 public: 14366 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14367 : FD(FD), CE(CE) { } 14368 14369 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14370 if (!FD) { 14371 S.Diag(Loc, diag::err_call_incomplete_return) 14372 << T << CE->getSourceRange(); 14373 return; 14374 } 14375 14376 S.Diag(Loc, diag::err_call_function_incomplete_return) 14377 << CE->getSourceRange() << FD->getDeclName() << T; 14378 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14379 << FD->getDeclName(); 14380 } 14381 } Diagnoser(FD, CE); 14382 14383 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14384 return true; 14385 14386 return false; 14387 } 14388 14389 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14390 // will prevent this condition from triggering, which is what we want. 14391 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14392 SourceLocation Loc; 14393 14394 unsigned diagnostic = diag::warn_condition_is_assignment; 14395 bool IsOrAssign = false; 14396 14397 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14398 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14399 return; 14400 14401 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14402 14403 // Greylist some idioms by putting them into a warning subcategory. 14404 if (ObjCMessageExpr *ME 14405 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14406 Selector Sel = ME->getSelector(); 14407 14408 // self = [<foo> init...] 14409 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14410 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14411 14412 // <foo> = [<bar> nextObject] 14413 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14414 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14415 } 14416 14417 Loc = Op->getOperatorLoc(); 14418 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14419 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14420 return; 14421 14422 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14423 Loc = Op->getOperatorLoc(); 14424 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14425 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14426 else { 14427 // Not an assignment. 14428 return; 14429 } 14430 14431 Diag(Loc, diagnostic) << E->getSourceRange(); 14432 14433 SourceLocation Open = E->getLocStart(); 14434 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14435 Diag(Loc, diag::note_condition_assign_silence) 14436 << FixItHint::CreateInsertion(Open, "(") 14437 << FixItHint::CreateInsertion(Close, ")"); 14438 14439 if (IsOrAssign) 14440 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14441 << FixItHint::CreateReplacement(Loc, "!="); 14442 else 14443 Diag(Loc, diag::note_condition_assign_to_comparison) 14444 << FixItHint::CreateReplacement(Loc, "=="); 14445 } 14446 14447 /// \brief Redundant parentheses over an equality comparison can indicate 14448 /// that the user intended an assignment used as condition. 14449 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14450 // Don't warn if the parens came from a macro. 14451 SourceLocation parenLoc = ParenE->getLocStart(); 14452 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14453 return; 14454 // Don't warn for dependent expressions. 14455 if (ParenE->isTypeDependent()) 14456 return; 14457 14458 Expr *E = ParenE->IgnoreParens(); 14459 14460 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14461 if (opE->getOpcode() == BO_EQ && 14462 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14463 == Expr::MLV_Valid) { 14464 SourceLocation Loc = opE->getOperatorLoc(); 14465 14466 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14467 SourceRange ParenERange = ParenE->getSourceRange(); 14468 Diag(Loc, diag::note_equality_comparison_silence) 14469 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14470 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14471 Diag(Loc, diag::note_equality_comparison_to_assign) 14472 << FixItHint::CreateReplacement(Loc, "="); 14473 } 14474 } 14475 14476 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14477 bool IsConstexpr) { 14478 DiagnoseAssignmentAsCondition(E); 14479 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14480 DiagnoseEqualityWithExtraParens(parenE); 14481 14482 ExprResult result = CheckPlaceholderExpr(E); 14483 if (result.isInvalid()) return ExprError(); 14484 E = result.get(); 14485 14486 if (!E->isTypeDependent()) { 14487 if (getLangOpts().CPlusPlus) 14488 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14489 14490 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14491 if (ERes.isInvalid()) 14492 return ExprError(); 14493 E = ERes.get(); 14494 14495 QualType T = E->getType(); 14496 if (!T->isScalarType()) { // C99 6.8.4.1p1 14497 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14498 << T << E->getSourceRange(); 14499 return ExprError(); 14500 } 14501 CheckBoolLikeConversion(E, Loc); 14502 } 14503 14504 return E; 14505 } 14506 14507 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14508 Expr *SubExpr, ConditionKind CK) { 14509 // Empty conditions are valid in for-statements. 14510 if (!SubExpr) 14511 return ConditionResult(); 14512 14513 ExprResult Cond; 14514 switch (CK) { 14515 case ConditionKind::Boolean: 14516 Cond = CheckBooleanCondition(Loc, SubExpr); 14517 break; 14518 14519 case ConditionKind::ConstexprIf: 14520 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14521 break; 14522 14523 case ConditionKind::Switch: 14524 Cond = CheckSwitchCondition(Loc, SubExpr); 14525 break; 14526 } 14527 if (Cond.isInvalid()) 14528 return ConditionError(); 14529 14530 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14531 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14532 if (!FullExpr.get()) 14533 return ConditionError(); 14534 14535 return ConditionResult(*this, nullptr, FullExpr, 14536 CK == ConditionKind::ConstexprIf); 14537 } 14538 14539 namespace { 14540 /// A visitor for rebuilding a call to an __unknown_any expression 14541 /// to have an appropriate type. 14542 struct RebuildUnknownAnyFunction 14543 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14544 14545 Sema &S; 14546 14547 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14548 14549 ExprResult VisitStmt(Stmt *S) { 14550 llvm_unreachable("unexpected statement!"); 14551 } 14552 14553 ExprResult VisitExpr(Expr *E) { 14554 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14555 << E->getSourceRange(); 14556 return ExprError(); 14557 } 14558 14559 /// Rebuild an expression which simply semantically wraps another 14560 /// expression which it shares the type and value kind of. 14561 template <class T> ExprResult rebuildSugarExpr(T *E) { 14562 ExprResult SubResult = Visit(E->getSubExpr()); 14563 if (SubResult.isInvalid()) return ExprError(); 14564 14565 Expr *SubExpr = SubResult.get(); 14566 E->setSubExpr(SubExpr); 14567 E->setType(SubExpr->getType()); 14568 E->setValueKind(SubExpr->getValueKind()); 14569 assert(E->getObjectKind() == OK_Ordinary); 14570 return E; 14571 } 14572 14573 ExprResult VisitParenExpr(ParenExpr *E) { 14574 return rebuildSugarExpr(E); 14575 } 14576 14577 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14578 return rebuildSugarExpr(E); 14579 } 14580 14581 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14582 ExprResult SubResult = Visit(E->getSubExpr()); 14583 if (SubResult.isInvalid()) return ExprError(); 14584 14585 Expr *SubExpr = SubResult.get(); 14586 E->setSubExpr(SubExpr); 14587 E->setType(S.Context.getPointerType(SubExpr->getType())); 14588 assert(E->getValueKind() == VK_RValue); 14589 assert(E->getObjectKind() == OK_Ordinary); 14590 return E; 14591 } 14592 14593 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14594 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14595 14596 E->setType(VD->getType()); 14597 14598 assert(E->getValueKind() == VK_RValue); 14599 if (S.getLangOpts().CPlusPlus && 14600 !(isa<CXXMethodDecl>(VD) && 14601 cast<CXXMethodDecl>(VD)->isInstance())) 14602 E->setValueKind(VK_LValue); 14603 14604 return E; 14605 } 14606 14607 ExprResult VisitMemberExpr(MemberExpr *E) { 14608 return resolveDecl(E, E->getMemberDecl()); 14609 } 14610 14611 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14612 return resolveDecl(E, E->getDecl()); 14613 } 14614 }; 14615 } 14616 14617 /// Given a function expression of unknown-any type, try to rebuild it 14618 /// to have a function type. 14619 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14620 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14621 if (Result.isInvalid()) return ExprError(); 14622 return S.DefaultFunctionArrayConversion(Result.get()); 14623 } 14624 14625 namespace { 14626 /// A visitor for rebuilding an expression of type __unknown_anytype 14627 /// into one which resolves the type directly on the referring 14628 /// expression. Strict preservation of the original source 14629 /// structure is not a goal. 14630 struct RebuildUnknownAnyExpr 14631 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14632 14633 Sema &S; 14634 14635 /// The current destination type. 14636 QualType DestType; 14637 14638 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14639 : S(S), DestType(CastType) {} 14640 14641 ExprResult VisitStmt(Stmt *S) { 14642 llvm_unreachable("unexpected statement!"); 14643 } 14644 14645 ExprResult VisitExpr(Expr *E) { 14646 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14647 << E->getSourceRange(); 14648 return ExprError(); 14649 } 14650 14651 ExprResult VisitCallExpr(CallExpr *E); 14652 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14653 14654 /// Rebuild an expression which simply semantically wraps another 14655 /// expression which it shares the type and value kind of. 14656 template <class T> ExprResult rebuildSugarExpr(T *E) { 14657 ExprResult SubResult = Visit(E->getSubExpr()); 14658 if (SubResult.isInvalid()) return ExprError(); 14659 Expr *SubExpr = SubResult.get(); 14660 E->setSubExpr(SubExpr); 14661 E->setType(SubExpr->getType()); 14662 E->setValueKind(SubExpr->getValueKind()); 14663 assert(E->getObjectKind() == OK_Ordinary); 14664 return E; 14665 } 14666 14667 ExprResult VisitParenExpr(ParenExpr *E) { 14668 return rebuildSugarExpr(E); 14669 } 14670 14671 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14672 return rebuildSugarExpr(E); 14673 } 14674 14675 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14676 const PointerType *Ptr = DestType->getAs<PointerType>(); 14677 if (!Ptr) { 14678 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14679 << E->getSourceRange(); 14680 return ExprError(); 14681 } 14682 assert(E->getValueKind() == VK_RValue); 14683 assert(E->getObjectKind() == OK_Ordinary); 14684 E->setType(DestType); 14685 14686 // Build the sub-expression as if it were an object of the pointee type. 14687 DestType = Ptr->getPointeeType(); 14688 ExprResult SubResult = Visit(E->getSubExpr()); 14689 if (SubResult.isInvalid()) return ExprError(); 14690 E->setSubExpr(SubResult.get()); 14691 return E; 14692 } 14693 14694 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14695 14696 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14697 14698 ExprResult VisitMemberExpr(MemberExpr *E) { 14699 return resolveDecl(E, E->getMemberDecl()); 14700 } 14701 14702 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14703 return resolveDecl(E, E->getDecl()); 14704 } 14705 }; 14706 } 14707 14708 /// Rebuilds a call expression which yielded __unknown_anytype. 14709 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14710 Expr *CalleeExpr = E->getCallee(); 14711 14712 enum FnKind { 14713 FK_MemberFunction, 14714 FK_FunctionPointer, 14715 FK_BlockPointer 14716 }; 14717 14718 FnKind Kind; 14719 QualType CalleeType = CalleeExpr->getType(); 14720 if (CalleeType == S.Context.BoundMemberTy) { 14721 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14722 Kind = FK_MemberFunction; 14723 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14724 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14725 CalleeType = Ptr->getPointeeType(); 14726 Kind = FK_FunctionPointer; 14727 } else { 14728 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14729 Kind = FK_BlockPointer; 14730 } 14731 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14732 14733 // Verify that this is a legal result type of a function. 14734 if (DestType->isArrayType() || DestType->isFunctionType()) { 14735 unsigned diagID = diag::err_func_returning_array_function; 14736 if (Kind == FK_BlockPointer) 14737 diagID = diag::err_block_returning_array_function; 14738 14739 S.Diag(E->getExprLoc(), diagID) 14740 << DestType->isFunctionType() << DestType; 14741 return ExprError(); 14742 } 14743 14744 // Otherwise, go ahead and set DestType as the call's result. 14745 E->setType(DestType.getNonLValueExprType(S.Context)); 14746 E->setValueKind(Expr::getValueKindForType(DestType)); 14747 assert(E->getObjectKind() == OK_Ordinary); 14748 14749 // Rebuild the function type, replacing the result type with DestType. 14750 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14751 if (Proto) { 14752 // __unknown_anytype(...) is a special case used by the debugger when 14753 // it has no idea what a function's signature is. 14754 // 14755 // We want to build this call essentially under the K&R 14756 // unprototyped rules, but making a FunctionNoProtoType in C++ 14757 // would foul up all sorts of assumptions. However, we cannot 14758 // simply pass all arguments as variadic arguments, nor can we 14759 // portably just call the function under a non-variadic type; see 14760 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14761 // However, it turns out that in practice it is generally safe to 14762 // call a function declared as "A foo(B,C,D);" under the prototype 14763 // "A foo(B,C,D,...);". The only known exception is with the 14764 // Windows ABI, where any variadic function is implicitly cdecl 14765 // regardless of its normal CC. Therefore we change the parameter 14766 // types to match the types of the arguments. 14767 // 14768 // This is a hack, but it is far superior to moving the 14769 // corresponding target-specific code from IR-gen to Sema/AST. 14770 14771 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14772 SmallVector<QualType, 8> ArgTypes; 14773 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14774 ArgTypes.reserve(E->getNumArgs()); 14775 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14776 Expr *Arg = E->getArg(i); 14777 QualType ArgType = Arg->getType(); 14778 if (E->isLValue()) { 14779 ArgType = S.Context.getLValueReferenceType(ArgType); 14780 } else if (E->isXValue()) { 14781 ArgType = S.Context.getRValueReferenceType(ArgType); 14782 } 14783 ArgTypes.push_back(ArgType); 14784 } 14785 ParamTypes = ArgTypes; 14786 } 14787 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14788 Proto->getExtProtoInfo()); 14789 } else { 14790 DestType = S.Context.getFunctionNoProtoType(DestType, 14791 FnType->getExtInfo()); 14792 } 14793 14794 // Rebuild the appropriate pointer-to-function type. 14795 switch (Kind) { 14796 case FK_MemberFunction: 14797 // Nothing to do. 14798 break; 14799 14800 case FK_FunctionPointer: 14801 DestType = S.Context.getPointerType(DestType); 14802 break; 14803 14804 case FK_BlockPointer: 14805 DestType = S.Context.getBlockPointerType(DestType); 14806 break; 14807 } 14808 14809 // Finally, we can recurse. 14810 ExprResult CalleeResult = Visit(CalleeExpr); 14811 if (!CalleeResult.isUsable()) return ExprError(); 14812 E->setCallee(CalleeResult.get()); 14813 14814 // Bind a temporary if necessary. 14815 return S.MaybeBindToTemporary(E); 14816 } 14817 14818 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14819 // Verify that this is a legal result type of a call. 14820 if (DestType->isArrayType() || DestType->isFunctionType()) { 14821 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14822 << DestType->isFunctionType() << DestType; 14823 return ExprError(); 14824 } 14825 14826 // Rewrite the method result type if available. 14827 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14828 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14829 Method->setReturnType(DestType); 14830 } 14831 14832 // Change the type of the message. 14833 E->setType(DestType.getNonReferenceType()); 14834 E->setValueKind(Expr::getValueKindForType(DestType)); 14835 14836 return S.MaybeBindToTemporary(E); 14837 } 14838 14839 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14840 // The only case we should ever see here is a function-to-pointer decay. 14841 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14842 assert(E->getValueKind() == VK_RValue); 14843 assert(E->getObjectKind() == OK_Ordinary); 14844 14845 E->setType(DestType); 14846 14847 // Rebuild the sub-expression as the pointee (function) type. 14848 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14849 14850 ExprResult Result = Visit(E->getSubExpr()); 14851 if (!Result.isUsable()) return ExprError(); 14852 14853 E->setSubExpr(Result.get()); 14854 return E; 14855 } else if (E->getCastKind() == CK_LValueToRValue) { 14856 assert(E->getValueKind() == VK_RValue); 14857 assert(E->getObjectKind() == OK_Ordinary); 14858 14859 assert(isa<BlockPointerType>(E->getType())); 14860 14861 E->setType(DestType); 14862 14863 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14864 DestType = S.Context.getLValueReferenceType(DestType); 14865 14866 ExprResult Result = Visit(E->getSubExpr()); 14867 if (!Result.isUsable()) return ExprError(); 14868 14869 E->setSubExpr(Result.get()); 14870 return E; 14871 } else { 14872 llvm_unreachable("Unhandled cast type!"); 14873 } 14874 } 14875 14876 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14877 ExprValueKind ValueKind = VK_LValue; 14878 QualType Type = DestType; 14879 14880 // We know how to make this work for certain kinds of decls: 14881 14882 // - functions 14883 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14884 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14885 DestType = Ptr->getPointeeType(); 14886 ExprResult Result = resolveDecl(E, VD); 14887 if (Result.isInvalid()) return ExprError(); 14888 return S.ImpCastExprToType(Result.get(), Type, 14889 CK_FunctionToPointerDecay, VK_RValue); 14890 } 14891 14892 if (!Type->isFunctionType()) { 14893 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14894 << VD << E->getSourceRange(); 14895 return ExprError(); 14896 } 14897 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14898 // We must match the FunctionDecl's type to the hack introduced in 14899 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14900 // type. See the lengthy commentary in that routine. 14901 QualType FDT = FD->getType(); 14902 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14903 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14904 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14905 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14906 SourceLocation Loc = FD->getLocation(); 14907 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14908 FD->getDeclContext(), 14909 Loc, Loc, FD->getNameInfo().getName(), 14910 DestType, FD->getTypeSourceInfo(), 14911 SC_None, false/*isInlineSpecified*/, 14912 FD->hasPrototype(), 14913 false/*isConstexprSpecified*/); 14914 14915 if (FD->getQualifier()) 14916 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14917 14918 SmallVector<ParmVarDecl*, 16> Params; 14919 for (const auto &AI : FT->param_types()) { 14920 ParmVarDecl *Param = 14921 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14922 Param->setScopeInfo(0, Params.size()); 14923 Params.push_back(Param); 14924 } 14925 NewFD->setParams(Params); 14926 DRE->setDecl(NewFD); 14927 VD = DRE->getDecl(); 14928 } 14929 } 14930 14931 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14932 if (MD->isInstance()) { 14933 ValueKind = VK_RValue; 14934 Type = S.Context.BoundMemberTy; 14935 } 14936 14937 // Function references aren't l-values in C. 14938 if (!S.getLangOpts().CPlusPlus) 14939 ValueKind = VK_RValue; 14940 14941 // - variables 14942 } else if (isa<VarDecl>(VD)) { 14943 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14944 Type = RefTy->getPointeeType(); 14945 } else if (Type->isFunctionType()) { 14946 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14947 << VD << E->getSourceRange(); 14948 return ExprError(); 14949 } 14950 14951 // - nothing else 14952 } else { 14953 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14954 << VD << E->getSourceRange(); 14955 return ExprError(); 14956 } 14957 14958 // Modifying the declaration like this is friendly to IR-gen but 14959 // also really dangerous. 14960 VD->setType(DestType); 14961 E->setType(Type); 14962 E->setValueKind(ValueKind); 14963 return E; 14964 } 14965 14966 /// Check a cast of an unknown-any type. We intentionally only 14967 /// trigger this for C-style casts. 14968 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14969 Expr *CastExpr, CastKind &CastKind, 14970 ExprValueKind &VK, CXXCastPath &Path) { 14971 // The type we're casting to must be either void or complete. 14972 if (!CastType->isVoidType() && 14973 RequireCompleteType(TypeRange.getBegin(), CastType, 14974 diag::err_typecheck_cast_to_incomplete)) 14975 return ExprError(); 14976 14977 // Rewrite the casted expression from scratch. 14978 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14979 if (!result.isUsable()) return ExprError(); 14980 14981 CastExpr = result.get(); 14982 VK = CastExpr->getValueKind(); 14983 CastKind = CK_NoOp; 14984 14985 return CastExpr; 14986 } 14987 14988 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14989 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14990 } 14991 14992 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14993 Expr *arg, QualType ¶mType) { 14994 // If the syntactic form of the argument is not an explicit cast of 14995 // any sort, just do default argument promotion. 14996 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14997 if (!castArg) { 14998 ExprResult result = DefaultArgumentPromotion(arg); 14999 if (result.isInvalid()) return ExprError(); 15000 paramType = result.get()->getType(); 15001 return result; 15002 } 15003 15004 // Otherwise, use the type that was written in the explicit cast. 15005 assert(!arg->hasPlaceholderType()); 15006 paramType = castArg->getTypeAsWritten(); 15007 15008 // Copy-initialize a parameter of that type. 15009 InitializedEntity entity = 15010 InitializedEntity::InitializeParameter(Context, paramType, 15011 /*consumed*/ false); 15012 return PerformCopyInitialization(entity, callLoc, arg); 15013 } 15014 15015 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15016 Expr *orig = E; 15017 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15018 while (true) { 15019 E = E->IgnoreParenImpCasts(); 15020 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15021 E = call->getCallee(); 15022 diagID = diag::err_uncasted_call_of_unknown_any; 15023 } else { 15024 break; 15025 } 15026 } 15027 15028 SourceLocation loc; 15029 NamedDecl *d; 15030 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15031 loc = ref->getLocation(); 15032 d = ref->getDecl(); 15033 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15034 loc = mem->getMemberLoc(); 15035 d = mem->getMemberDecl(); 15036 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15037 diagID = diag::err_uncasted_call_of_unknown_any; 15038 loc = msg->getSelectorStartLoc(); 15039 d = msg->getMethodDecl(); 15040 if (!d) { 15041 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15042 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15043 << orig->getSourceRange(); 15044 return ExprError(); 15045 } 15046 } else { 15047 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15048 << E->getSourceRange(); 15049 return ExprError(); 15050 } 15051 15052 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15053 15054 // Never recoverable. 15055 return ExprError(); 15056 } 15057 15058 /// Check for operands with placeholder types and complain if found. 15059 /// Returns true if there was an error and no recovery was possible. 15060 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15061 if (!getLangOpts().CPlusPlus) { 15062 // C cannot handle TypoExpr nodes on either side of a binop because it 15063 // doesn't handle dependent types properly, so make sure any TypoExprs have 15064 // been dealt with before checking the operands. 15065 ExprResult Result = CorrectDelayedTyposInExpr(E); 15066 if (!Result.isUsable()) return ExprError(); 15067 E = Result.get(); 15068 } 15069 15070 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15071 if (!placeholderType) return E; 15072 15073 switch (placeholderType->getKind()) { 15074 15075 // Overloaded expressions. 15076 case BuiltinType::Overload: { 15077 // Try to resolve a single function template specialization. 15078 // This is obligatory. 15079 ExprResult Result = E; 15080 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15081 return Result; 15082 15083 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15084 // leaves Result unchanged on failure. 15085 Result = E; 15086 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15087 return Result; 15088 15089 // If that failed, try to recover with a call. 15090 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15091 /*complain*/ true); 15092 return Result; 15093 } 15094 15095 // Bound member functions. 15096 case BuiltinType::BoundMember: { 15097 ExprResult result = E; 15098 const Expr *BME = E->IgnoreParens(); 15099 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15100 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15101 if (isa<CXXPseudoDestructorExpr>(BME)) { 15102 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15103 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15104 if (ME->getMemberNameInfo().getName().getNameKind() == 15105 DeclarationName::CXXDestructorName) 15106 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15107 } 15108 tryToRecoverWithCall(result, PD, 15109 /*complain*/ true); 15110 return result; 15111 } 15112 15113 // ARC unbridged casts. 15114 case BuiltinType::ARCUnbridgedCast: { 15115 Expr *realCast = stripARCUnbridgedCast(E); 15116 diagnoseARCUnbridgedCast(realCast); 15117 return realCast; 15118 } 15119 15120 // Expressions of unknown type. 15121 case BuiltinType::UnknownAny: 15122 return diagnoseUnknownAnyExpr(*this, E); 15123 15124 // Pseudo-objects. 15125 case BuiltinType::PseudoObject: 15126 return checkPseudoObjectRValue(E); 15127 15128 case BuiltinType::BuiltinFn: { 15129 // Accept __noop without parens by implicitly converting it to a call expr. 15130 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15131 if (DRE) { 15132 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15133 if (FD->getBuiltinID() == Builtin::BI__noop) { 15134 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15135 CK_BuiltinFnToFnPtr).get(); 15136 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15137 VK_RValue, SourceLocation()); 15138 } 15139 } 15140 15141 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15142 return ExprError(); 15143 } 15144 15145 // Expressions of unknown type. 15146 case BuiltinType::OMPArraySection: 15147 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15148 return ExprError(); 15149 15150 // Everything else should be impossible. 15151 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15152 case BuiltinType::Id: 15153 #include "clang/Basic/OpenCLImageTypes.def" 15154 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15155 #define PLACEHOLDER_TYPE(Id, SingletonId) 15156 #include "clang/AST/BuiltinTypes.def" 15157 break; 15158 } 15159 15160 llvm_unreachable("invalid placeholder type!"); 15161 } 15162 15163 bool Sema::CheckCaseExpression(Expr *E) { 15164 if (E->isTypeDependent()) 15165 return true; 15166 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15167 return E->getType()->isIntegralOrEnumerationType(); 15168 return false; 15169 } 15170 15171 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15172 ExprResult 15173 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15174 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15175 "Unknown Objective-C Boolean value!"); 15176 QualType BoolT = Context.ObjCBuiltinBoolTy; 15177 if (!Context.getBOOLDecl()) { 15178 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15179 Sema::LookupOrdinaryName); 15180 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15181 NamedDecl *ND = Result.getFoundDecl(); 15182 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15183 Context.setBOOLDecl(TD); 15184 } 15185 } 15186 if (Context.getBOOLDecl()) 15187 BoolT = Context.getBOOLType(); 15188 return new (Context) 15189 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15190 } 15191 15192 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15193 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15194 SourceLocation RParen) { 15195 15196 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15197 15198 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15199 [&](const AvailabilitySpec &Spec) { 15200 return Spec.getPlatform() == Platform; 15201 }); 15202 15203 VersionTuple Version; 15204 if (Spec != AvailSpecs.end()) 15205 Version = Spec->getVersion(); 15206 15207 return new (Context) 15208 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15209 } 15210