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 "clang/Sema/SemaInternal.h" 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/ExprOpenMP.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.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 static AvailabilityResult 107 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 108 const ObjCInterfaceDecl *UnknownObjCClass, 109 bool ObjCPropertyAccess) { 110 // See if this declaration is unavailable or deprecated. 111 std::string Message; 112 AvailabilityResult Result = D->getAvailability(&Message); 113 114 // For typedefs, if the typedef declaration appears available look 115 // to the underlying type to see if it is more restrictive. 116 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 117 if (Result == AR_Available) { 118 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 119 D = TT->getDecl(); 120 Result = D->getAvailability(&Message); 121 continue; 122 } 123 } 124 break; 125 } 126 127 // Forward class declarations get their attributes from their definition. 128 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 129 if (IDecl->getDefinition()) { 130 D = IDecl->getDefinition(); 131 Result = D->getAvailability(&Message); 132 } 133 } 134 135 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 136 if (Result == AR_Available) { 137 const DeclContext *DC = ECD->getDeclContext(); 138 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 139 Result = TheEnumDecl->getAvailability(&Message); 140 } 141 142 const ObjCPropertyDecl *ObjCPDecl = nullptr; 143 if (Result == AR_Deprecated || Result == AR_Unavailable || 144 Result == AR_NotYetIntroduced) { 145 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 146 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 147 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 148 if (PDeclResult == Result) 149 ObjCPDecl = PD; 150 } 151 } 152 } 153 154 switch (Result) { 155 case AR_Available: 156 break; 157 158 case AR_Deprecated: 159 if (S.getCurContextAvailability() != AR_Deprecated) 160 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 161 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 162 ObjCPropertyAccess); 163 break; 164 165 case AR_NotYetIntroduced: { 166 // Don't do this for enums, they can't be redeclared. 167 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 168 break; 169 170 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 171 // Objective-C method declarations in categories are not modelled as 172 // redeclarations, so manually look for a redeclaration in a category 173 // if necessary. 174 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 175 Warn = false; 176 // In general, D will point to the most recent redeclaration. However, 177 // for `@class A;` decls, this isn't true -- manually go through the 178 // redecl chain in that case. 179 if (Warn && isa<ObjCInterfaceDecl>(D)) 180 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 181 Redecl = Redecl->getPreviousDecl()) 182 if (!Redecl->hasAttr<AvailabilityAttr>() || 183 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 184 Warn = false; 185 186 if (Warn) 187 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 188 UnknownObjCClass, ObjCPDecl, 189 ObjCPropertyAccess); 190 break; 191 } 192 193 case AR_Unavailable: 194 if (S.getCurContextAvailability() != AR_Unavailable) 195 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 196 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 197 ObjCPropertyAccess); 198 break; 199 200 } 201 return Result; 202 } 203 204 /// \brief Emit a note explaining that this function is deleted. 205 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 206 assert(Decl->isDeleted()); 207 208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 209 210 if (Method && Method->isDeleted() && Method->isDefaulted()) { 211 // If the method was explicitly defaulted, point at that declaration. 212 if (!Method->isImplicit()) 213 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 214 215 // Try to diagnose why this special member function was implicitly 216 // deleted. This might fail, if that reason no longer applies. 217 CXXSpecialMember CSM = getSpecialMember(Method); 218 if (CSM != CXXInvalid) 219 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 220 221 return; 222 } 223 224 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 225 if (Ctor && Ctor->isInheritingConstructor()) 226 return NoteDeletedInheritingConstructor(Ctor); 227 228 Diag(Decl->getLocation(), diag::note_availability_specified_here) 229 << Decl << true; 230 } 231 232 /// \brief Determine whether a FunctionDecl was ever declared with an 233 /// explicit storage class. 234 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 235 for (auto I : D->redecls()) { 236 if (I->getStorageClass() != SC_None) 237 return true; 238 } 239 return false; 240 } 241 242 /// \brief Check whether we're in an extern inline function and referring to a 243 /// variable or function with internal linkage (C11 6.7.4p3). 244 /// 245 /// This is only a warning because we used to silently accept this code, but 246 /// in many cases it will not behave correctly. This is not enabled in C++ mode 247 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 248 /// and so while there may still be user mistakes, most of the time we can't 249 /// prove that there are errors. 250 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 251 const NamedDecl *D, 252 SourceLocation Loc) { 253 // This is disabled under C++; there are too many ways for this to fire in 254 // contexts where the warning is a false positive, or where it is technically 255 // correct but benign. 256 if (S.getLangOpts().CPlusPlus) 257 return; 258 259 // Check if this is an inlined function or method. 260 FunctionDecl *Current = S.getCurFunctionDecl(); 261 if (!Current) 262 return; 263 if (!Current->isInlined()) 264 return; 265 if (!Current->isExternallyVisible()) 266 return; 267 268 // Check if the decl has internal linkage. 269 if (D->getFormalLinkage() != InternalLinkage) 270 return; 271 272 // Downgrade from ExtWarn to Extension if 273 // (1) the supposedly external inline function is in the main file, 274 // and probably won't be included anywhere else. 275 // (2) the thing we're referencing is a pure function. 276 // (3) the thing we're referencing is another inline function. 277 // This last can give us false negatives, but it's better than warning on 278 // wrappers for simple C library functions. 279 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 280 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 281 if (!DowngradeWarning && UsedFn) 282 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 283 284 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 285 : diag::ext_internal_in_extern_inline) 286 << /*IsVar=*/!UsedFn << D; 287 288 S.MaybeSuggestAddingStaticToDecl(Current); 289 290 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 291 << D; 292 } 293 294 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 295 const FunctionDecl *First = Cur->getFirstDecl(); 296 297 // Suggest "static" on the function, if possible. 298 if (!hasAnyExplicitStorageClass(First)) { 299 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 300 Diag(DeclBegin, diag::note_convert_inline_to_static) 301 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 302 } 303 } 304 305 /// \brief Determine whether the use of this declaration is valid, and 306 /// emit any corresponding diagnostics. 307 /// 308 /// This routine diagnoses various problems with referencing 309 /// declarations that can occur when using a declaration. For example, 310 /// it might warn if a deprecated or unavailable declaration is being 311 /// used, or produce an error (and return true) if a C++0x deleted 312 /// function is being used. 313 /// 314 /// \returns true if there was an error (this declaration cannot be 315 /// referenced), false otherwise. 316 /// 317 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 318 const ObjCInterfaceDecl *UnknownObjCClass, 319 bool ObjCPropertyAccess) { 320 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 321 // If there were any diagnostics suppressed by template argument deduction, 322 // emit them now. 323 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 324 if (Pos != SuppressedDiagnostics.end()) { 325 for (const PartialDiagnosticAt &Suppressed : Pos->second) 326 Diag(Suppressed.first, Suppressed.second); 327 328 // Clear out the list of suppressed diagnostics, so that we don't emit 329 // them again for this specialization. However, we don't obsolete this 330 // entry from the table, because we want to avoid ever emitting these 331 // diagnostics again. 332 Pos->second.clear(); 333 } 334 335 // C++ [basic.start.main]p3: 336 // The function 'main' shall not be used within a program. 337 if (cast<FunctionDecl>(D)->isMain()) 338 Diag(Loc, diag::ext_main_used); 339 } 340 341 // See if this is an auto-typed variable whose initializer we are parsing. 342 if (ParsingInitForAutoVars.count(D)) { 343 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 344 345 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 346 << D->getDeclName() << (unsigned)AT->getKeyword(); 347 return true; 348 } 349 350 // See if this is a deleted function. 351 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 352 if (FD->isDeleted()) { 353 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 354 if (Ctor && Ctor->isInheritingConstructor()) 355 Diag(Loc, diag::err_deleted_inherited_ctor_use) 356 << Ctor->getParent() 357 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 358 else 359 Diag(Loc, diag::err_deleted_function_use); 360 NoteDeletedFunction(FD); 361 return true; 362 } 363 364 // If the function has a deduced return type, and we can't deduce it, 365 // then we can't use it either. 366 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 367 DeduceReturnType(FD, Loc)) 368 return true; 369 } 370 371 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 372 // Only the variables omp_in and omp_out are allowed in the combiner. 373 // Only the variables omp_priv and omp_orig are allowed in the 374 // initializer-clause. 375 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 376 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 377 isa<VarDecl>(D)) { 378 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 379 << getCurFunction()->HasOMPDeclareReductionCombiner; 380 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 381 return true; 382 } 383 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 384 ObjCPropertyAccess); 385 386 DiagnoseUnusedOfDecl(*this, D, Loc); 387 388 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 389 390 return false; 391 } 392 393 /// \brief Retrieve the message suffix that should be added to a 394 /// diagnostic complaining about the given function being deleted or 395 /// unavailable. 396 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 397 std::string Message; 398 if (FD->getAvailability(&Message)) 399 return ": " + Message; 400 401 return std::string(); 402 } 403 404 /// DiagnoseSentinelCalls - This routine checks whether a call or 405 /// message-send is to a declaration with the sentinel attribute, and 406 /// if so, it checks that the requirements of the sentinel are 407 /// satisfied. 408 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 409 ArrayRef<Expr *> Args) { 410 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 411 if (!attr) 412 return; 413 414 // The number of formal parameters of the declaration. 415 unsigned numFormalParams; 416 417 // The kind of declaration. This is also an index into a %select in 418 // the diagnostic. 419 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 420 421 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 422 numFormalParams = MD->param_size(); 423 calleeType = CT_Method; 424 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 425 numFormalParams = FD->param_size(); 426 calleeType = CT_Function; 427 } else if (isa<VarDecl>(D)) { 428 QualType type = cast<ValueDecl>(D)->getType(); 429 const FunctionType *fn = nullptr; 430 if (const PointerType *ptr = type->getAs<PointerType>()) { 431 fn = ptr->getPointeeType()->getAs<FunctionType>(); 432 if (!fn) return; 433 calleeType = CT_Function; 434 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 435 fn = ptr->getPointeeType()->castAs<FunctionType>(); 436 calleeType = CT_Block; 437 } else { 438 return; 439 } 440 441 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 442 numFormalParams = proto->getNumParams(); 443 } else { 444 numFormalParams = 0; 445 } 446 } else { 447 return; 448 } 449 450 // "nullPos" is the number of formal parameters at the end which 451 // effectively count as part of the variadic arguments. This is 452 // useful if you would prefer to not have *any* formal parameters, 453 // but the language forces you to have at least one. 454 unsigned nullPos = attr->getNullPos(); 455 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 456 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 457 458 // The number of arguments which should follow the sentinel. 459 unsigned numArgsAfterSentinel = attr->getSentinel(); 460 461 // If there aren't enough arguments for all the formal parameters, 462 // the sentinel, and the args after the sentinel, complain. 463 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 464 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 465 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 466 return; 467 } 468 469 // Otherwise, find the sentinel expression. 470 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 471 if (!sentinelExpr) return; 472 if (sentinelExpr->isValueDependent()) return; 473 if (Context.isSentinelNullExpr(sentinelExpr)) return; 474 475 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 476 // or 'NULL' if those are actually defined in the context. Only use 477 // 'nil' for ObjC methods, where it's much more likely that the 478 // variadic arguments form a list of object pointers. 479 SourceLocation MissingNilLoc 480 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 481 std::string NullValue; 482 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 483 NullValue = "nil"; 484 else if (getLangOpts().CPlusPlus11) 485 NullValue = "nullptr"; 486 else if (PP.isMacroDefined("NULL")) 487 NullValue = "NULL"; 488 else 489 NullValue = "(void*) 0"; 490 491 if (MissingNilLoc.isInvalid()) 492 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 493 else 494 Diag(MissingNilLoc, diag::warn_missing_sentinel) 495 << int(calleeType) 496 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 497 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 498 } 499 500 SourceRange Sema::getExprRange(Expr *E) const { 501 return E ? E->getSourceRange() : SourceRange(); 502 } 503 504 //===----------------------------------------------------------------------===// 505 // Standard Promotions and Conversions 506 //===----------------------------------------------------------------------===// 507 508 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 509 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 510 // Handle any placeholder expressions which made it here. 511 if (E->getType()->isPlaceholderType()) { 512 ExprResult result = CheckPlaceholderExpr(E); 513 if (result.isInvalid()) return ExprError(); 514 E = result.get(); 515 } 516 517 QualType Ty = E->getType(); 518 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 519 520 if (Ty->isFunctionType()) { 521 // If we are here, we are not calling a function but taking 522 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 523 if (getLangOpts().OpenCL) { 524 if (Diagnose) 525 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 526 return ExprError(); 527 } 528 529 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 530 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 531 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 532 return ExprError(); 533 534 E = ImpCastExprToType(E, Context.getPointerType(Ty), 535 CK_FunctionToPointerDecay).get(); 536 } else if (Ty->isArrayType()) { 537 // In C90 mode, arrays only promote to pointers if the array expression is 538 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 539 // type 'array of type' is converted to an expression that has type 'pointer 540 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 541 // that has type 'array of type' ...". The relevant change is "an lvalue" 542 // (C90) to "an expression" (C99). 543 // 544 // C++ 4.2p1: 545 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 546 // T" can be converted to an rvalue of type "pointer to T". 547 // 548 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 549 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 550 CK_ArrayToPointerDecay).get(); 551 } 552 return E; 553 } 554 555 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 556 // Check to see if we are dereferencing a null pointer. If so, 557 // and if not volatile-qualified, this is undefined behavior that the 558 // optimizer will delete, so warn about it. People sometimes try to use this 559 // to get a deterministic trap and are surprised by clang's behavior. This 560 // only handles the pattern "*null", which is a very syntactic check. 561 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 562 if (UO->getOpcode() == UO_Deref && 563 UO->getSubExpr()->IgnoreParenCasts()-> 564 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 565 !UO->getType().isVolatileQualified()) { 566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 567 S.PDiag(diag::warn_indirection_through_null) 568 << UO->getSubExpr()->getSourceRange()); 569 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 570 S.PDiag(diag::note_indirection_through_null)); 571 } 572 } 573 574 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 575 SourceLocation AssignLoc, 576 const Expr* RHS) { 577 const ObjCIvarDecl *IV = OIRE->getDecl(); 578 if (!IV) 579 return; 580 581 DeclarationName MemberName = IV->getDeclName(); 582 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 583 if (!Member || !Member->isStr("isa")) 584 return; 585 586 const Expr *Base = OIRE->getBase(); 587 QualType BaseType = Base->getType(); 588 if (OIRE->isArrow()) 589 BaseType = BaseType->getPointeeType(); 590 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 591 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 592 ObjCInterfaceDecl *ClassDeclared = nullptr; 593 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 594 if (!ClassDeclared->getSuperClass() 595 && (*ClassDeclared->ivar_begin()) == IV) { 596 if (RHS) { 597 NamedDecl *ObjectSetClass = 598 S.LookupSingleName(S.TUScope, 599 &S.Context.Idents.get("object_setClass"), 600 SourceLocation(), S.LookupOrdinaryName); 601 if (ObjectSetClass) { 602 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 603 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 604 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 605 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 606 AssignLoc), ",") << 607 FixItHint::CreateInsertion(RHSLocEnd, ")"); 608 } 609 else 610 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 611 } else { 612 NamedDecl *ObjectGetClass = 613 S.LookupSingleName(S.TUScope, 614 &S.Context.Idents.get("object_getClass"), 615 SourceLocation(), S.LookupOrdinaryName); 616 if (ObjectGetClass) 617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 618 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 619 FixItHint::CreateReplacement( 620 SourceRange(OIRE->getOpLoc(), 621 OIRE->getLocEnd()), ")"); 622 else 623 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 624 } 625 S.Diag(IV->getLocation(), diag::note_ivar_decl); 626 } 627 } 628 } 629 630 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 631 // Handle any placeholder expressions which made it here. 632 if (E->getType()->isPlaceholderType()) { 633 ExprResult result = CheckPlaceholderExpr(E); 634 if (result.isInvalid()) return ExprError(); 635 E = result.get(); 636 } 637 638 // C++ [conv.lval]p1: 639 // A glvalue of a non-function, non-array type T can be 640 // converted to a prvalue. 641 if (!E->isGLValue()) return E; 642 643 QualType T = E->getType(); 644 assert(!T.isNull() && "r-value conversion on typeless expression?"); 645 646 // We don't want to throw lvalue-to-rvalue casts on top of 647 // expressions of certain types in C++. 648 if (getLangOpts().CPlusPlus && 649 (E->getType() == Context.OverloadTy || 650 T->isDependentType() || 651 T->isRecordType())) 652 return E; 653 654 // The C standard is actually really unclear on this point, and 655 // DR106 tells us what the result should be but not why. It's 656 // generally best to say that void types just doesn't undergo 657 // lvalue-to-rvalue at all. Note that expressions of unqualified 658 // 'void' type are never l-values, but qualified void can be. 659 if (T->isVoidType()) 660 return E; 661 662 // OpenCL usually rejects direct accesses to values of 'half' type. 663 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 664 T->isHalfType()) { 665 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 666 << 0 << T; 667 return ExprError(); 668 } 669 670 CheckForNullPointerDereference(*this, E); 671 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 672 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 673 &Context.Idents.get("object_getClass"), 674 SourceLocation(), LookupOrdinaryName); 675 if (ObjectGetClass) 676 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 677 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 678 FixItHint::CreateReplacement( 679 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 680 else 681 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 682 } 683 else if (const ObjCIvarRefExpr *OIRE = 684 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 685 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 686 687 // C++ [conv.lval]p1: 688 // [...] If T is a non-class type, the type of the prvalue is the 689 // cv-unqualified version of T. Otherwise, the type of the 690 // rvalue is T. 691 // 692 // C99 6.3.2.1p2: 693 // If the lvalue has qualified type, the value has the unqualified 694 // version of the type of the lvalue; otherwise, the value has the 695 // type of the lvalue. 696 if (T.hasQualifiers()) 697 T = T.getUnqualifiedType(); 698 699 // Under the MS ABI, lock down the inheritance model now. 700 if (T->isMemberPointerType() && 701 Context.getTargetInfo().getCXXABI().isMicrosoft()) 702 (void)isCompleteType(E->getExprLoc(), T); 703 704 UpdateMarkingForLValueToRValue(E); 705 706 // Loading a __weak object implicitly retains the value, so we need a cleanup to 707 // balance that. 708 if (getLangOpts().ObjCAutoRefCount && 709 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 710 Cleanup.setExprNeedsCleanups(true); 711 712 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 713 nullptr, VK_RValue); 714 715 // C11 6.3.2.1p2: 716 // ... if the lvalue has atomic type, the value has the non-atomic version 717 // of the type of the lvalue ... 718 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 719 T = Atomic->getValueType().getUnqualifiedType(); 720 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 721 nullptr, VK_RValue); 722 } 723 724 return Res; 725 } 726 727 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 728 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 729 if (Res.isInvalid()) 730 return ExprError(); 731 Res = DefaultLvalueConversion(Res.get()); 732 if (Res.isInvalid()) 733 return ExprError(); 734 return Res; 735 } 736 737 /// CallExprUnaryConversions - a special case of an unary conversion 738 /// performed on a function designator of a call expression. 739 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 740 QualType Ty = E->getType(); 741 ExprResult Res = E; 742 // Only do implicit cast for a function type, but not for a pointer 743 // to function type. 744 if (Ty->isFunctionType()) { 745 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 746 CK_FunctionToPointerDecay).get(); 747 if (Res.isInvalid()) 748 return ExprError(); 749 } 750 Res = DefaultLvalueConversion(Res.get()); 751 if (Res.isInvalid()) 752 return ExprError(); 753 return Res.get(); 754 } 755 756 /// UsualUnaryConversions - Performs various conversions that are common to most 757 /// operators (C99 6.3). The conversions of array and function types are 758 /// sometimes suppressed. For example, the array->pointer conversion doesn't 759 /// apply if the array is an argument to the sizeof or address (&) operators. 760 /// In these instances, this routine should *not* be called. 761 ExprResult Sema::UsualUnaryConversions(Expr *E) { 762 // First, convert to an r-value. 763 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 764 if (Res.isInvalid()) 765 return ExprError(); 766 E = Res.get(); 767 768 QualType Ty = E->getType(); 769 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 770 771 // Half FP have to be promoted to float unless it is natively supported 772 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 773 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 774 775 // Try to perform integral promotions if the object has a theoretically 776 // promotable type. 777 if (Ty->isIntegralOrUnscopedEnumerationType()) { 778 // C99 6.3.1.1p2: 779 // 780 // The following may be used in an expression wherever an int or 781 // unsigned int may be used: 782 // - an object or expression with an integer type whose integer 783 // conversion rank is less than or equal to the rank of int 784 // and unsigned int. 785 // - A bit-field of type _Bool, int, signed int, or unsigned int. 786 // 787 // If an int can represent all values of the original type, the 788 // value is converted to an int; otherwise, it is converted to an 789 // unsigned int. These are called the integer promotions. All 790 // other types are unchanged by the integer promotions. 791 792 QualType PTy = Context.isPromotableBitField(E); 793 if (!PTy.isNull()) { 794 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 795 return E; 796 } 797 if (Ty->isPromotableIntegerType()) { 798 QualType PT = Context.getPromotedIntegerType(Ty); 799 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 800 return E; 801 } 802 } 803 return E; 804 } 805 806 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 807 /// do not have a prototype. Arguments that have type float or __fp16 808 /// are promoted to double. All other argument types are converted by 809 /// UsualUnaryConversions(). 810 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 811 QualType Ty = E->getType(); 812 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 813 814 ExprResult Res = UsualUnaryConversions(E); 815 if (Res.isInvalid()) 816 return ExprError(); 817 E = Res.get(); 818 819 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 820 // double. 821 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 822 if (BTy && (BTy->getKind() == BuiltinType::Half || 823 BTy->getKind() == BuiltinType::Float)) 824 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 825 826 // C++ performs lvalue-to-rvalue conversion as a default argument 827 // promotion, even on class types, but note: 828 // C++11 [conv.lval]p2: 829 // When an lvalue-to-rvalue conversion occurs in an unevaluated 830 // operand or a subexpression thereof the value contained in the 831 // referenced object is not accessed. Otherwise, if the glvalue 832 // has a class type, the conversion copy-initializes a temporary 833 // of type T from the glvalue and the result of the conversion 834 // is a prvalue for the temporary. 835 // FIXME: add some way to gate this entire thing for correctness in 836 // potentially potentially evaluated contexts. 837 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 838 ExprResult Temp = PerformCopyInitialization( 839 InitializedEntity::InitializeTemporary(E->getType()), 840 E->getExprLoc(), E); 841 if (Temp.isInvalid()) 842 return ExprError(); 843 E = Temp.get(); 844 } 845 846 return E; 847 } 848 849 /// Determine the degree of POD-ness for an expression. 850 /// Incomplete types are considered POD, since this check can be performed 851 /// when we're in an unevaluated context. 852 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 853 if (Ty->isIncompleteType()) { 854 // C++11 [expr.call]p7: 855 // After these conversions, if the argument does not have arithmetic, 856 // enumeration, pointer, pointer to member, or class type, the program 857 // is ill-formed. 858 // 859 // Since we've already performed array-to-pointer and function-to-pointer 860 // decay, the only such type in C++ is cv void. This also handles 861 // initializer lists as variadic arguments. 862 if (Ty->isVoidType()) 863 return VAK_Invalid; 864 865 if (Ty->isObjCObjectType()) 866 return VAK_Invalid; 867 return VAK_Valid; 868 } 869 870 if (Ty.isCXX98PODType(Context)) 871 return VAK_Valid; 872 873 // C++11 [expr.call]p7: 874 // Passing a potentially-evaluated argument of class type (Clause 9) 875 // having a non-trivial copy constructor, a non-trivial move constructor, 876 // or a non-trivial destructor, with no corresponding parameter, 877 // is conditionally-supported with implementation-defined semantics. 878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 880 if (!Record->hasNonTrivialCopyConstructor() && 881 !Record->hasNonTrivialMoveConstructor() && 882 !Record->hasNonTrivialDestructor()) 883 return VAK_ValidInCXX11; 884 885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 886 return VAK_Valid; 887 888 if (Ty->isObjCObjectType()) 889 return VAK_Invalid; 890 891 if (getLangOpts().MSVCCompat) 892 return VAK_MSVCUndefined; 893 894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 895 // permitted to reject them. We should consider doing so. 896 return VAK_Undefined; 897 } 898 899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 900 // Don't allow one to pass an Objective-C interface to a vararg. 901 const QualType &Ty = E->getType(); 902 VarArgKind VAK = isValidVarArgType(Ty); 903 904 // Complain about passing non-POD types through varargs. 905 switch (VAK) { 906 case VAK_ValidInCXX11: 907 DiagRuntimeBehavior( 908 E->getLocStart(), nullptr, 909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 910 << Ty << CT); 911 // Fall through. 912 case VAK_Valid: 913 if (Ty->isRecordType()) { 914 // This is unlikely to be what the user intended. If the class has a 915 // 'c_str' member function, the user probably meant to call that. 916 DiagRuntimeBehavior(E->getLocStart(), nullptr, 917 PDiag(diag::warn_pass_class_arg_to_vararg) 918 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 919 } 920 break; 921 922 case VAK_Undefined: 923 case VAK_MSVCUndefined: 924 DiagRuntimeBehavior( 925 E->getLocStart(), nullptr, 926 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 927 << getLangOpts().CPlusPlus11 << Ty << CT); 928 break; 929 930 case VAK_Invalid: 931 if (Ty->isObjCObjectType()) 932 DiagRuntimeBehavior( 933 E->getLocStart(), nullptr, 934 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 935 << Ty << CT); 936 else 937 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 938 << isa<InitListExpr>(E) << Ty << CT; 939 break; 940 } 941 } 942 943 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 944 /// will create a trap if the resulting type is not a POD type. 945 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 946 FunctionDecl *FDecl) { 947 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 948 // Strip the unbridged-cast placeholder expression off, if applicable. 949 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 950 (CT == VariadicMethod || 951 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 952 E = stripARCUnbridgedCast(E); 953 954 // Otherwise, do normal placeholder checking. 955 } else { 956 ExprResult ExprRes = CheckPlaceholderExpr(E); 957 if (ExprRes.isInvalid()) 958 return ExprError(); 959 E = ExprRes.get(); 960 } 961 } 962 963 ExprResult ExprRes = DefaultArgumentPromotion(E); 964 if (ExprRes.isInvalid()) 965 return ExprError(); 966 E = ExprRes.get(); 967 968 // Diagnostics regarding non-POD argument types are 969 // emitted along with format string checking in Sema::CheckFunctionCall(). 970 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 971 // Turn this into a trap. 972 CXXScopeSpec SS; 973 SourceLocation TemplateKWLoc; 974 UnqualifiedId Name; 975 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 976 E->getLocStart()); 977 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 978 Name, true, false); 979 if (TrapFn.isInvalid()) 980 return ExprError(); 981 982 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 983 E->getLocStart(), None, 984 E->getLocEnd()); 985 if (Call.isInvalid()) 986 return ExprError(); 987 988 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 989 Call.get(), E); 990 if (Comma.isInvalid()) 991 return ExprError(); 992 return Comma.get(); 993 } 994 995 if (!getLangOpts().CPlusPlus && 996 RequireCompleteType(E->getExprLoc(), E->getType(), 997 diag::err_call_incomplete_argument)) 998 return ExprError(); 999 1000 return E; 1001 } 1002 1003 /// \brief Converts an integer to complex float type. Helper function of 1004 /// UsualArithmeticConversions() 1005 /// 1006 /// \return false if the integer expression is an integer type and is 1007 /// successfully converted to the complex type. 1008 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1009 ExprResult &ComplexExpr, 1010 QualType IntTy, 1011 QualType ComplexTy, 1012 bool SkipCast) { 1013 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1014 if (SkipCast) return false; 1015 if (IntTy->isIntegerType()) { 1016 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1017 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1018 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1019 CK_FloatingRealToComplex); 1020 } else { 1021 assert(IntTy->isComplexIntegerType()); 1022 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1023 CK_IntegralComplexToFloatingComplex); 1024 } 1025 return false; 1026 } 1027 1028 /// \brief Handle arithmetic conversion with complex types. Helper function of 1029 /// UsualArithmeticConversions() 1030 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1031 ExprResult &RHS, QualType LHSType, 1032 QualType RHSType, 1033 bool IsCompAssign) { 1034 // if we have an integer operand, the result is the complex type. 1035 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1036 /*skipCast*/false)) 1037 return LHSType; 1038 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1039 /*skipCast*/IsCompAssign)) 1040 return RHSType; 1041 1042 // This handles complex/complex, complex/float, or float/complex. 1043 // When both operands are complex, the shorter operand is converted to the 1044 // type of the longer, and that is the type of the result. This corresponds 1045 // to what is done when combining two real floating-point operands. 1046 // The fun begins when size promotion occur across type domains. 1047 // From H&S 6.3.4: When one operand is complex and the other is a real 1048 // floating-point type, the less precise type is converted, within it's 1049 // real or complex domain, to the precision of the other type. For example, 1050 // when combining a "long double" with a "double _Complex", the 1051 // "double _Complex" is promoted to "long double _Complex". 1052 1053 // Compute the rank of the two types, regardless of whether they are complex. 1054 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1055 1056 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1057 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1058 QualType LHSElementType = 1059 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1060 QualType RHSElementType = 1061 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1062 1063 QualType ResultType = S.Context.getComplexType(LHSElementType); 1064 if (Order < 0) { 1065 // Promote the precision of the LHS if not an assignment. 1066 ResultType = S.Context.getComplexType(RHSElementType); 1067 if (!IsCompAssign) { 1068 if (LHSComplexType) 1069 LHS = 1070 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1071 else 1072 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1073 } 1074 } else if (Order > 0) { 1075 // Promote the precision of the RHS. 1076 if (RHSComplexType) 1077 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1078 else 1079 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1080 } 1081 return ResultType; 1082 } 1083 1084 /// \brief Hande arithmetic conversion from integer to float. Helper function 1085 /// of UsualArithmeticConversions() 1086 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1087 ExprResult &IntExpr, 1088 QualType FloatTy, QualType IntTy, 1089 bool ConvertFloat, bool ConvertInt) { 1090 if (IntTy->isIntegerType()) { 1091 if (ConvertInt) 1092 // Convert intExpr to the lhs floating point type. 1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1094 CK_IntegralToFloating); 1095 return FloatTy; 1096 } 1097 1098 // Convert both sides to the appropriate complex float. 1099 assert(IntTy->isComplexIntegerType()); 1100 QualType result = S.Context.getComplexType(FloatTy); 1101 1102 // _Complex int -> _Complex float 1103 if (ConvertInt) 1104 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1105 CK_IntegralComplexToFloatingComplex); 1106 1107 // float -> _Complex float 1108 if (ConvertFloat) 1109 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1110 CK_FloatingRealToComplex); 1111 1112 return result; 1113 } 1114 1115 /// \brief Handle arithmethic conversion with floating point types. Helper 1116 /// function of UsualArithmeticConversions() 1117 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1118 ExprResult &RHS, QualType LHSType, 1119 QualType RHSType, bool IsCompAssign) { 1120 bool LHSFloat = LHSType->isRealFloatingType(); 1121 bool RHSFloat = RHSType->isRealFloatingType(); 1122 1123 // If we have two real floating types, convert the smaller operand 1124 // to the bigger result. 1125 if (LHSFloat && RHSFloat) { 1126 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1127 if (order > 0) { 1128 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1129 return LHSType; 1130 } 1131 1132 assert(order < 0 && "illegal float comparison"); 1133 if (!IsCompAssign) 1134 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1135 return RHSType; 1136 } 1137 1138 if (LHSFloat) { 1139 // Half FP has to be promoted to float unless it is natively supported 1140 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1141 LHSType = S.Context.FloatTy; 1142 1143 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1144 /*convertFloat=*/!IsCompAssign, 1145 /*convertInt=*/ true); 1146 } 1147 assert(RHSFloat); 1148 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1149 /*convertInt=*/ true, 1150 /*convertFloat=*/!IsCompAssign); 1151 } 1152 1153 /// \brief Diagnose attempts to convert between __float128 and long double if 1154 /// there is no support for such conversion. Helper function of 1155 /// UsualArithmeticConversions(). 1156 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1157 QualType RHSType) { 1158 /* No issue converting if at least one of the types is not a floating point 1159 type or the two types have the same rank. 1160 */ 1161 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1162 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1163 return false; 1164 1165 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1166 "The remaining types must be floating point types."); 1167 1168 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1169 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1170 1171 QualType LHSElemType = LHSComplex ? 1172 LHSComplex->getElementType() : LHSType; 1173 QualType RHSElemType = RHSComplex ? 1174 RHSComplex->getElementType() : RHSType; 1175 1176 // No issue if the two types have the same representation 1177 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1178 &S.Context.getFloatTypeSemantics(RHSElemType)) 1179 return false; 1180 1181 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1182 RHSElemType == S.Context.LongDoubleTy); 1183 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1184 RHSElemType == S.Context.Float128Ty); 1185 1186 /* We've handled the situation where __float128 and long double have the same 1187 representation. The only other allowable conversion is if long double is 1188 really just double. 1189 */ 1190 return Float128AndLongDouble && 1191 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1192 &llvm::APFloat::IEEEdouble); 1193 } 1194 1195 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1196 1197 namespace { 1198 /// These helper callbacks are placed in an anonymous namespace to 1199 /// permit their use as function template parameters. 1200 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1201 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1202 } 1203 1204 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1205 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1206 CK_IntegralComplexCast); 1207 } 1208 } 1209 1210 /// \brief Handle integer arithmetic conversions. Helper function of 1211 /// UsualArithmeticConversions() 1212 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1213 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1214 ExprResult &RHS, QualType LHSType, 1215 QualType RHSType, bool IsCompAssign) { 1216 // The rules for this case are in C99 6.3.1.8 1217 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1218 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1219 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1220 if (LHSSigned == RHSSigned) { 1221 // Same signedness; use the higher-ranked type 1222 if (order >= 0) { 1223 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1224 return LHSType; 1225 } else if (!IsCompAssign) 1226 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1227 return RHSType; 1228 } else if (order != (LHSSigned ? 1 : -1)) { 1229 // The unsigned type has greater than or equal rank to the 1230 // signed type, so use the unsigned type 1231 if (RHSSigned) { 1232 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1233 return LHSType; 1234 } else if (!IsCompAssign) 1235 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1236 return RHSType; 1237 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1238 // The two types are different widths; if we are here, that 1239 // means the signed type is larger than the unsigned type, so 1240 // use the signed type. 1241 if (LHSSigned) { 1242 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1243 return LHSType; 1244 } else if (!IsCompAssign) 1245 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1246 return RHSType; 1247 } else { 1248 // The signed type is higher-ranked than the unsigned type, 1249 // but isn't actually any bigger (like unsigned int and long 1250 // on most 32-bit systems). Use the unsigned type corresponding 1251 // to the signed type. 1252 QualType result = 1253 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1254 RHS = (*doRHSCast)(S, RHS.get(), result); 1255 if (!IsCompAssign) 1256 LHS = (*doLHSCast)(S, LHS.get(), result); 1257 return result; 1258 } 1259 } 1260 1261 /// \brief Handle conversions with GCC complex int extension. Helper function 1262 /// of UsualArithmeticConversions() 1263 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1264 ExprResult &RHS, QualType LHSType, 1265 QualType RHSType, 1266 bool IsCompAssign) { 1267 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1268 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1269 1270 if (LHSComplexInt && RHSComplexInt) { 1271 QualType LHSEltType = LHSComplexInt->getElementType(); 1272 QualType RHSEltType = RHSComplexInt->getElementType(); 1273 QualType ScalarType = 1274 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1275 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1276 1277 return S.Context.getComplexType(ScalarType); 1278 } 1279 1280 if (LHSComplexInt) { 1281 QualType LHSEltType = LHSComplexInt->getElementType(); 1282 QualType ScalarType = 1283 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1284 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1285 QualType ComplexType = S.Context.getComplexType(ScalarType); 1286 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1287 CK_IntegralRealToComplex); 1288 1289 return ComplexType; 1290 } 1291 1292 assert(RHSComplexInt); 1293 1294 QualType RHSEltType = RHSComplexInt->getElementType(); 1295 QualType ScalarType = 1296 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1297 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1298 QualType ComplexType = S.Context.getComplexType(ScalarType); 1299 1300 if (!IsCompAssign) 1301 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1302 CK_IntegralRealToComplex); 1303 return ComplexType; 1304 } 1305 1306 /// UsualArithmeticConversions - Performs various conversions that are common to 1307 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1308 /// routine returns the first non-arithmetic type found. The client is 1309 /// responsible for emitting appropriate error diagnostics. 1310 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1311 bool IsCompAssign) { 1312 if (!IsCompAssign) { 1313 LHS = UsualUnaryConversions(LHS.get()); 1314 if (LHS.isInvalid()) 1315 return QualType(); 1316 } 1317 1318 RHS = UsualUnaryConversions(RHS.get()); 1319 if (RHS.isInvalid()) 1320 return QualType(); 1321 1322 // For conversion purposes, we ignore any qualifiers. 1323 // For example, "const float" and "float" are equivalent. 1324 QualType LHSType = 1325 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1326 QualType RHSType = 1327 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1328 1329 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1330 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1331 LHSType = AtomicLHS->getValueType(); 1332 1333 // If both types are identical, no conversion is needed. 1334 if (LHSType == RHSType) 1335 return LHSType; 1336 1337 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1338 // The caller can deal with this (e.g. pointer + int). 1339 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1340 return QualType(); 1341 1342 // Apply unary and bitfield promotions to the LHS's type. 1343 QualType LHSUnpromotedType = LHSType; 1344 if (LHSType->isPromotableIntegerType()) 1345 LHSType = Context.getPromotedIntegerType(LHSType); 1346 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1347 if (!LHSBitfieldPromoteTy.isNull()) 1348 LHSType = LHSBitfieldPromoteTy; 1349 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1350 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1351 1352 // If both types are identical, no conversion is needed. 1353 if (LHSType == RHSType) 1354 return LHSType; 1355 1356 // At this point, we have two different arithmetic types. 1357 1358 // Diagnose attempts to convert between __float128 and long double where 1359 // such conversions currently can't be handled. 1360 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1361 return QualType(); 1362 1363 // Handle complex types first (C99 6.3.1.8p1). 1364 if (LHSType->isComplexType() || RHSType->isComplexType()) 1365 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1366 IsCompAssign); 1367 1368 // Now handle "real" floating types (i.e. float, double, long double). 1369 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1370 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1371 IsCompAssign); 1372 1373 // Handle GCC complex int extension. 1374 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1375 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1376 IsCompAssign); 1377 1378 // Finally, we have two differing integer types. 1379 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1380 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1381 } 1382 1383 1384 //===----------------------------------------------------------------------===// 1385 // Semantic Analysis for various Expression Types 1386 //===----------------------------------------------------------------------===// 1387 1388 1389 ExprResult 1390 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1391 SourceLocation DefaultLoc, 1392 SourceLocation RParenLoc, 1393 Expr *ControllingExpr, 1394 ArrayRef<ParsedType> ArgTypes, 1395 ArrayRef<Expr *> ArgExprs) { 1396 unsigned NumAssocs = ArgTypes.size(); 1397 assert(NumAssocs == ArgExprs.size()); 1398 1399 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1400 for (unsigned i = 0; i < NumAssocs; ++i) { 1401 if (ArgTypes[i]) 1402 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1403 else 1404 Types[i] = nullptr; 1405 } 1406 1407 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1408 ControllingExpr, 1409 llvm::makeArrayRef(Types, NumAssocs), 1410 ArgExprs); 1411 delete [] Types; 1412 return ER; 1413 } 1414 1415 ExprResult 1416 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1417 SourceLocation DefaultLoc, 1418 SourceLocation RParenLoc, 1419 Expr *ControllingExpr, 1420 ArrayRef<TypeSourceInfo *> Types, 1421 ArrayRef<Expr *> Exprs) { 1422 unsigned NumAssocs = Types.size(); 1423 assert(NumAssocs == Exprs.size()); 1424 1425 // Decay and strip qualifiers for the controlling expression type, and handle 1426 // placeholder type replacement. See committee discussion from WG14 DR423. 1427 { 1428 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1429 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1430 if (R.isInvalid()) 1431 return ExprError(); 1432 ControllingExpr = R.get(); 1433 } 1434 1435 // The controlling expression is an unevaluated operand, so side effects are 1436 // likely unintended. 1437 if (ActiveTemplateInstantiations.empty() && 1438 ControllingExpr->HasSideEffects(Context, false)) 1439 Diag(ControllingExpr->getExprLoc(), 1440 diag::warn_side_effects_unevaluated_context); 1441 1442 bool TypeErrorFound = false, 1443 IsResultDependent = ControllingExpr->isTypeDependent(), 1444 ContainsUnexpandedParameterPack 1445 = ControllingExpr->containsUnexpandedParameterPack(); 1446 1447 for (unsigned i = 0; i < NumAssocs; ++i) { 1448 if (Exprs[i]->containsUnexpandedParameterPack()) 1449 ContainsUnexpandedParameterPack = true; 1450 1451 if (Types[i]) { 1452 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1453 ContainsUnexpandedParameterPack = true; 1454 1455 if (Types[i]->getType()->isDependentType()) { 1456 IsResultDependent = true; 1457 } else { 1458 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1459 // complete object type other than a variably modified type." 1460 unsigned D = 0; 1461 if (Types[i]->getType()->isIncompleteType()) 1462 D = diag::err_assoc_type_incomplete; 1463 else if (!Types[i]->getType()->isObjectType()) 1464 D = diag::err_assoc_type_nonobject; 1465 else if (Types[i]->getType()->isVariablyModifiedType()) 1466 D = diag::err_assoc_type_variably_modified; 1467 1468 if (D != 0) { 1469 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1470 << Types[i]->getTypeLoc().getSourceRange() 1471 << Types[i]->getType(); 1472 TypeErrorFound = true; 1473 } 1474 1475 // C11 6.5.1.1p2 "No two generic associations in the same generic 1476 // selection shall specify compatible types." 1477 for (unsigned j = i+1; j < NumAssocs; ++j) 1478 if (Types[j] && !Types[j]->getType()->isDependentType() && 1479 Context.typesAreCompatible(Types[i]->getType(), 1480 Types[j]->getType())) { 1481 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1482 diag::err_assoc_compatible_types) 1483 << Types[j]->getTypeLoc().getSourceRange() 1484 << Types[j]->getType() 1485 << Types[i]->getType(); 1486 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1487 diag::note_compat_assoc) 1488 << Types[i]->getTypeLoc().getSourceRange() 1489 << Types[i]->getType(); 1490 TypeErrorFound = true; 1491 } 1492 } 1493 } 1494 } 1495 if (TypeErrorFound) 1496 return ExprError(); 1497 1498 // If we determined that the generic selection is result-dependent, don't 1499 // try to compute the result expression. 1500 if (IsResultDependent) 1501 return new (Context) GenericSelectionExpr( 1502 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1503 ContainsUnexpandedParameterPack); 1504 1505 SmallVector<unsigned, 1> CompatIndices; 1506 unsigned DefaultIndex = -1U; 1507 for (unsigned i = 0; i < NumAssocs; ++i) { 1508 if (!Types[i]) 1509 DefaultIndex = i; 1510 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1511 Types[i]->getType())) 1512 CompatIndices.push_back(i); 1513 } 1514 1515 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1516 // type compatible with at most one of the types named in its generic 1517 // association list." 1518 if (CompatIndices.size() > 1) { 1519 // We strip parens here because the controlling expression is typically 1520 // parenthesized in macro definitions. 1521 ControllingExpr = ControllingExpr->IgnoreParens(); 1522 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1523 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1524 << (unsigned) CompatIndices.size(); 1525 for (unsigned I : CompatIndices) { 1526 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1527 diag::note_compat_assoc) 1528 << Types[I]->getTypeLoc().getSourceRange() 1529 << Types[I]->getType(); 1530 } 1531 return ExprError(); 1532 } 1533 1534 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1535 // its controlling expression shall have type compatible with exactly one of 1536 // the types named in its generic association list." 1537 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1538 // We strip parens here because the controlling expression is typically 1539 // parenthesized in macro definitions. 1540 ControllingExpr = ControllingExpr->IgnoreParens(); 1541 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1542 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1543 return ExprError(); 1544 } 1545 1546 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1547 // type name that is compatible with the type of the controlling expression, 1548 // then the result expression of the generic selection is the expression 1549 // in that generic association. Otherwise, the result expression of the 1550 // generic selection is the expression in the default generic association." 1551 unsigned ResultIndex = 1552 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1553 1554 return new (Context) GenericSelectionExpr( 1555 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1556 ContainsUnexpandedParameterPack, ResultIndex); 1557 } 1558 1559 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1560 /// location of the token and the offset of the ud-suffix within it. 1561 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1562 unsigned Offset) { 1563 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1564 S.getLangOpts()); 1565 } 1566 1567 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1568 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1569 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1570 IdentifierInfo *UDSuffix, 1571 SourceLocation UDSuffixLoc, 1572 ArrayRef<Expr*> Args, 1573 SourceLocation LitEndLoc) { 1574 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1575 1576 QualType ArgTy[2]; 1577 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1578 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1579 if (ArgTy[ArgIdx]->isArrayType()) 1580 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1581 } 1582 1583 DeclarationName OpName = 1584 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1585 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1586 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1587 1588 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1589 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1590 /*AllowRaw*/false, /*AllowTemplate*/false, 1591 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1592 return ExprError(); 1593 1594 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1595 } 1596 1597 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1598 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1599 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1600 /// multiple tokens. However, the common case is that StringToks points to one 1601 /// string. 1602 /// 1603 ExprResult 1604 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1605 assert(!StringToks.empty() && "Must have at least one string!"); 1606 1607 StringLiteralParser Literal(StringToks, PP); 1608 if (Literal.hadError) 1609 return ExprError(); 1610 1611 SmallVector<SourceLocation, 4> StringTokLocs; 1612 for (const Token &Tok : StringToks) 1613 StringTokLocs.push_back(Tok.getLocation()); 1614 1615 QualType CharTy = Context.CharTy; 1616 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1617 if (Literal.isWide()) { 1618 CharTy = Context.getWideCharType(); 1619 Kind = StringLiteral::Wide; 1620 } else if (Literal.isUTF8()) { 1621 Kind = StringLiteral::UTF8; 1622 } else if (Literal.isUTF16()) { 1623 CharTy = Context.Char16Ty; 1624 Kind = StringLiteral::UTF16; 1625 } else if (Literal.isUTF32()) { 1626 CharTy = Context.Char32Ty; 1627 Kind = StringLiteral::UTF32; 1628 } else if (Literal.isPascal()) { 1629 CharTy = Context.UnsignedCharTy; 1630 } 1631 1632 QualType CharTyConst = CharTy; 1633 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1634 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1635 CharTyConst.addConst(); 1636 1637 // Get an array type for the string, according to C99 6.4.5. This includes 1638 // the nul terminator character as well as the string length for pascal 1639 // strings. 1640 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1641 llvm::APInt(32, Literal.GetNumStringChars()+1), 1642 ArrayType::Normal, 0); 1643 1644 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1645 if (getLangOpts().OpenCL) { 1646 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1647 } 1648 1649 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1650 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1651 Kind, Literal.Pascal, StrTy, 1652 &StringTokLocs[0], 1653 StringTokLocs.size()); 1654 if (Literal.getUDSuffix().empty()) 1655 return Lit; 1656 1657 // We're building a user-defined literal. 1658 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1659 SourceLocation UDSuffixLoc = 1660 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1661 Literal.getUDSuffixOffset()); 1662 1663 // Make sure we're allowed user-defined literals here. 1664 if (!UDLScope) 1665 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1666 1667 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1668 // operator "" X (str, len) 1669 QualType SizeType = Context.getSizeType(); 1670 1671 DeclarationName OpName = 1672 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1673 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1674 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1675 1676 QualType ArgTy[] = { 1677 Context.getArrayDecayedType(StrTy), SizeType 1678 }; 1679 1680 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1681 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1682 /*AllowRaw*/false, /*AllowTemplate*/false, 1683 /*AllowStringTemplate*/true)) { 1684 1685 case LOLR_Cooked: { 1686 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1687 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1688 StringTokLocs[0]); 1689 Expr *Args[] = { Lit, LenArg }; 1690 1691 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1692 } 1693 1694 case LOLR_StringTemplate: { 1695 TemplateArgumentListInfo ExplicitArgs; 1696 1697 unsigned CharBits = Context.getIntWidth(CharTy); 1698 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1699 llvm::APSInt Value(CharBits, CharIsUnsigned); 1700 1701 TemplateArgument TypeArg(CharTy); 1702 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1703 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1704 1705 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1706 Value = Lit->getCodeUnit(I); 1707 TemplateArgument Arg(Context, Value, CharTy); 1708 TemplateArgumentLocInfo ArgInfo; 1709 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1710 } 1711 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1712 &ExplicitArgs); 1713 } 1714 case LOLR_Raw: 1715 case LOLR_Template: 1716 llvm_unreachable("unexpected literal operator lookup result"); 1717 case LOLR_Error: 1718 return ExprError(); 1719 } 1720 llvm_unreachable("unexpected literal operator lookup result"); 1721 } 1722 1723 ExprResult 1724 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1725 SourceLocation Loc, 1726 const CXXScopeSpec *SS) { 1727 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1728 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1729 } 1730 1731 /// BuildDeclRefExpr - Build an expression that references a 1732 /// declaration that does not require a closure capture. 1733 ExprResult 1734 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1735 const DeclarationNameInfo &NameInfo, 1736 const CXXScopeSpec *SS, NamedDecl *FoundD, 1737 const TemplateArgumentListInfo *TemplateArgs) { 1738 if (getLangOpts().CUDA) 1739 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1740 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1741 if (CheckCUDATarget(Caller, Callee)) { 1742 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1743 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1744 << IdentifyCUDATarget(Caller); 1745 Diag(D->getLocation(), diag::note_previous_decl) 1746 << D->getIdentifier(); 1747 return ExprError(); 1748 } 1749 } 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 return E; 1789 } 1790 1791 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1792 /// possibly a list of template arguments. 1793 /// 1794 /// If this produces template arguments, it is permitted to call 1795 /// DecomposeTemplateName. 1796 /// 1797 /// This actually loses a lot of source location information for 1798 /// non-standard name kinds; we should consider preserving that in 1799 /// some way. 1800 void 1801 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1802 TemplateArgumentListInfo &Buffer, 1803 DeclarationNameInfo &NameInfo, 1804 const TemplateArgumentListInfo *&TemplateArgs) { 1805 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1806 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1807 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1808 1809 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1810 Id.TemplateId->NumArgs); 1811 translateTemplateArguments(TemplateArgsPtr, Buffer); 1812 1813 TemplateName TName = Id.TemplateId->Template.get(); 1814 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1815 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1816 TemplateArgs = &Buffer; 1817 } else { 1818 NameInfo = GetNameFromUnqualifiedId(Id); 1819 TemplateArgs = nullptr; 1820 } 1821 } 1822 1823 static void emitEmptyLookupTypoDiagnostic( 1824 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1825 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1826 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1827 DeclContext *Ctx = 1828 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1829 if (!TC) { 1830 // Emit a special diagnostic for failed member lookups. 1831 // FIXME: computing the declaration context might fail here (?) 1832 if (Ctx) 1833 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1834 << SS.getRange(); 1835 else 1836 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1837 return; 1838 } 1839 1840 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1841 bool DroppedSpecifier = 1842 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1843 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1844 ? diag::note_implicit_param_decl 1845 : diag::note_previous_decl; 1846 if (!Ctx) 1847 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1848 SemaRef.PDiag(NoteID)); 1849 else 1850 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1851 << Typo << Ctx << DroppedSpecifier 1852 << SS.getRange(), 1853 SemaRef.PDiag(NoteID)); 1854 } 1855 1856 /// Diagnose an empty lookup. 1857 /// 1858 /// \return false if new lookup candidates were found 1859 bool 1860 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1861 std::unique_ptr<CorrectionCandidateCallback> CCC, 1862 TemplateArgumentListInfo *ExplicitTemplateArgs, 1863 ArrayRef<Expr *> Args, TypoExpr **Out) { 1864 DeclarationName Name = R.getLookupName(); 1865 1866 unsigned diagnostic = diag::err_undeclared_var_use; 1867 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1868 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1869 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1870 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1871 diagnostic = diag::err_undeclared_use; 1872 diagnostic_suggest = diag::err_undeclared_use_suggest; 1873 } 1874 1875 // If the original lookup was an unqualified lookup, fake an 1876 // unqualified lookup. This is useful when (for example) the 1877 // original lookup would not have found something because it was a 1878 // dependent name. 1879 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1880 while (DC) { 1881 if (isa<CXXRecordDecl>(DC)) { 1882 LookupQualifiedName(R, DC); 1883 1884 if (!R.empty()) { 1885 // Don't give errors about ambiguities in this lookup. 1886 R.suppressDiagnostics(); 1887 1888 // During a default argument instantiation the CurContext points 1889 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1890 // function parameter list, hence add an explicit check. 1891 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1892 ActiveTemplateInstantiations.back().Kind == 1893 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1894 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1895 bool isInstance = CurMethod && 1896 CurMethod->isInstance() && 1897 DC == CurMethod->getParent() && !isDefaultArgument; 1898 1899 // Give a code modification hint to insert 'this->'. 1900 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1901 // Actually quite difficult! 1902 if (getLangOpts().MSVCCompat) 1903 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1904 if (isInstance) { 1905 Diag(R.getNameLoc(), diagnostic) << Name 1906 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1907 CheckCXXThisCapture(R.getNameLoc()); 1908 } else { 1909 Diag(R.getNameLoc(), diagnostic) << Name; 1910 } 1911 1912 // Do we really want to note all of these? 1913 for (NamedDecl *D : R) 1914 Diag(D->getLocation(), diag::note_dependent_var_use); 1915 1916 // Return true if we are inside a default argument instantiation 1917 // and the found name refers to an instance member function, otherwise 1918 // the function calling DiagnoseEmptyLookup will try to create an 1919 // implicit member call and this is wrong for default argument. 1920 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1921 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1922 return true; 1923 } 1924 1925 // Tell the callee to try to recover. 1926 return false; 1927 } 1928 1929 R.clear(); 1930 } 1931 1932 // In Microsoft mode, if we are performing lookup from within a friend 1933 // function definition declared at class scope then we must set 1934 // DC to the lexical parent to be able to search into the parent 1935 // class. 1936 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1937 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1938 DC->getLexicalParent()->isRecord()) 1939 DC = DC->getLexicalParent(); 1940 else 1941 DC = DC->getParent(); 1942 } 1943 1944 // We didn't find anything, so try to correct for a typo. 1945 TypoCorrection Corrected; 1946 if (S && Out) { 1947 SourceLocation TypoLoc = R.getNameLoc(); 1948 assert(!ExplicitTemplateArgs && 1949 "Diagnosing an empty lookup with explicit template args!"); 1950 *Out = CorrectTypoDelayed( 1951 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1952 [=](const TypoCorrection &TC) { 1953 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1954 diagnostic, diagnostic_suggest); 1955 }, 1956 nullptr, CTK_ErrorRecovery); 1957 if (*Out) 1958 return true; 1959 } else if (S && (Corrected = 1960 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1961 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1962 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1963 bool DroppedSpecifier = 1964 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1965 R.setLookupName(Corrected.getCorrection()); 1966 1967 bool AcceptableWithRecovery = false; 1968 bool AcceptableWithoutRecovery = false; 1969 NamedDecl *ND = Corrected.getFoundDecl(); 1970 if (ND) { 1971 if (Corrected.isOverloaded()) { 1972 OverloadCandidateSet OCS(R.getNameLoc(), 1973 OverloadCandidateSet::CSK_Normal); 1974 OverloadCandidateSet::iterator Best; 1975 for (NamedDecl *CD : Corrected) { 1976 if (FunctionTemplateDecl *FTD = 1977 dyn_cast<FunctionTemplateDecl>(CD)) 1978 AddTemplateOverloadCandidate( 1979 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1980 Args, OCS); 1981 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1982 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1983 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1984 Args, OCS); 1985 } 1986 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1987 case OR_Success: 1988 ND = Best->FoundDecl; 1989 Corrected.setCorrectionDecl(ND); 1990 break; 1991 default: 1992 // FIXME: Arbitrarily pick the first declaration for the note. 1993 Corrected.setCorrectionDecl(ND); 1994 break; 1995 } 1996 } 1997 R.addDecl(ND); 1998 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1999 CXXRecordDecl *Record = nullptr; 2000 if (Corrected.getCorrectionSpecifier()) { 2001 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2002 Record = Ty->getAsCXXRecordDecl(); 2003 } 2004 if (!Record) 2005 Record = cast<CXXRecordDecl>( 2006 ND->getDeclContext()->getRedeclContext()); 2007 R.setNamingClass(Record); 2008 } 2009 2010 auto *UnderlyingND = ND->getUnderlyingDecl(); 2011 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2012 isa<FunctionTemplateDecl>(UnderlyingND); 2013 // FIXME: If we ended up with a typo for a type name or 2014 // Objective-C class name, we're in trouble because the parser 2015 // is in the wrong place to recover. Suggest the typo 2016 // correction, but don't make it a fix-it since we're not going 2017 // to recover well anyway. 2018 AcceptableWithoutRecovery = 2019 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2020 } else { 2021 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2022 // because we aren't able to recover. 2023 AcceptableWithoutRecovery = true; 2024 } 2025 2026 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2027 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2028 ? diag::note_implicit_param_decl 2029 : diag::note_previous_decl; 2030 if (SS.isEmpty()) 2031 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2032 PDiag(NoteID), AcceptableWithRecovery); 2033 else 2034 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2035 << Name << computeDeclContext(SS, false) 2036 << DroppedSpecifier << SS.getRange(), 2037 PDiag(NoteID), AcceptableWithRecovery); 2038 2039 // Tell the callee whether to try to recover. 2040 return !AcceptableWithRecovery; 2041 } 2042 } 2043 R.clear(); 2044 2045 // Emit a special diagnostic for failed member lookups. 2046 // FIXME: computing the declaration context might fail here (?) 2047 if (!SS.isEmpty()) { 2048 Diag(R.getNameLoc(), diag::err_no_member) 2049 << Name << computeDeclContext(SS, false) 2050 << SS.getRange(); 2051 return true; 2052 } 2053 2054 // Give up, we can't recover. 2055 Diag(R.getNameLoc(), diagnostic) << Name; 2056 return true; 2057 } 2058 2059 /// In Microsoft mode, if we are inside a template class whose parent class has 2060 /// dependent base classes, and we can't resolve an unqualified identifier, then 2061 /// assume the identifier is a member of a dependent base class. We can only 2062 /// recover successfully in static methods, instance methods, and other contexts 2063 /// where 'this' is available. This doesn't precisely match MSVC's 2064 /// instantiation model, but it's close enough. 2065 static Expr * 2066 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2067 DeclarationNameInfo &NameInfo, 2068 SourceLocation TemplateKWLoc, 2069 const TemplateArgumentListInfo *TemplateArgs) { 2070 // Only try to recover from lookup into dependent bases in static methods or 2071 // contexts where 'this' is available. 2072 QualType ThisType = S.getCurrentThisType(); 2073 const CXXRecordDecl *RD = nullptr; 2074 if (!ThisType.isNull()) 2075 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2076 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2077 RD = MD->getParent(); 2078 if (!RD || !RD->hasAnyDependentBases()) 2079 return nullptr; 2080 2081 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2082 // is available, suggest inserting 'this->' as a fixit. 2083 SourceLocation Loc = NameInfo.getLoc(); 2084 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2085 DB << NameInfo.getName() << RD; 2086 2087 if (!ThisType.isNull()) { 2088 DB << FixItHint::CreateInsertion(Loc, "this->"); 2089 return CXXDependentScopeMemberExpr::Create( 2090 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2091 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2092 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2093 } 2094 2095 // Synthesize a fake NNS that points to the derived class. This will 2096 // perform name lookup during template instantiation. 2097 CXXScopeSpec SS; 2098 auto *NNS = 2099 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2100 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2101 return DependentScopeDeclRefExpr::Create( 2102 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2103 TemplateArgs); 2104 } 2105 2106 ExprResult 2107 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2108 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2109 bool HasTrailingLParen, bool IsAddressOfOperand, 2110 std::unique_ptr<CorrectionCandidateCallback> CCC, 2111 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2112 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2113 "cannot be direct & operand and have a trailing lparen"); 2114 if (SS.isInvalid()) 2115 return ExprError(); 2116 2117 TemplateArgumentListInfo TemplateArgsBuffer; 2118 2119 // Decompose the UnqualifiedId into the following data. 2120 DeclarationNameInfo NameInfo; 2121 const TemplateArgumentListInfo *TemplateArgs; 2122 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2123 2124 DeclarationName Name = NameInfo.getName(); 2125 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2126 SourceLocation NameLoc = NameInfo.getLoc(); 2127 2128 // C++ [temp.dep.expr]p3: 2129 // An id-expression is type-dependent if it contains: 2130 // -- an identifier that was declared with a dependent type, 2131 // (note: handled after lookup) 2132 // -- a template-id that is dependent, 2133 // (note: handled in BuildTemplateIdExpr) 2134 // -- a conversion-function-id that specifies a dependent type, 2135 // -- a nested-name-specifier that contains a class-name that 2136 // names a dependent type. 2137 // Determine whether this is a member of an unknown specialization; 2138 // we need to handle these differently. 2139 bool DependentID = false; 2140 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2141 Name.getCXXNameType()->isDependentType()) { 2142 DependentID = true; 2143 } else if (SS.isSet()) { 2144 if (DeclContext *DC = computeDeclContext(SS, false)) { 2145 if (RequireCompleteDeclContext(SS, DC)) 2146 return ExprError(); 2147 } else { 2148 DependentID = true; 2149 } 2150 } 2151 2152 if (DependentID) 2153 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2154 IsAddressOfOperand, TemplateArgs); 2155 2156 // Perform the required lookup. 2157 LookupResult R(*this, NameInfo, 2158 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2159 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2160 if (TemplateArgs) { 2161 // Lookup the template name again to correctly establish the context in 2162 // which it was found. This is really unfortunate as we already did the 2163 // lookup to determine that it was a template name in the first place. If 2164 // this becomes a performance hit, we can work harder to preserve those 2165 // results until we get here but it's likely not worth it. 2166 bool MemberOfUnknownSpecialization; 2167 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2168 MemberOfUnknownSpecialization); 2169 2170 if (MemberOfUnknownSpecialization || 2171 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2172 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2173 IsAddressOfOperand, TemplateArgs); 2174 } else { 2175 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2176 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2177 2178 // If the result might be in a dependent base class, this is a dependent 2179 // id-expression. 2180 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2181 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2182 IsAddressOfOperand, TemplateArgs); 2183 2184 // If this reference is in an Objective-C method, then we need to do 2185 // some special Objective-C lookup, too. 2186 if (IvarLookupFollowUp) { 2187 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2188 if (E.isInvalid()) 2189 return ExprError(); 2190 2191 if (Expr *Ex = E.getAs<Expr>()) 2192 return Ex; 2193 } 2194 } 2195 2196 if (R.isAmbiguous()) 2197 return ExprError(); 2198 2199 // This could be an implicitly declared function reference (legal in C90, 2200 // extension in C99, forbidden in C++). 2201 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2202 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2203 if (D) R.addDecl(D); 2204 } 2205 2206 // Determine whether this name might be a candidate for 2207 // argument-dependent lookup. 2208 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2209 2210 if (R.empty() && !ADL) { 2211 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2212 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2213 TemplateKWLoc, TemplateArgs)) 2214 return E; 2215 } 2216 2217 // Don't diagnose an empty lookup for inline assembly. 2218 if (IsInlineAsmIdentifier) 2219 return ExprError(); 2220 2221 // If this name wasn't predeclared and if this is not a function 2222 // call, diagnose the problem. 2223 TypoExpr *TE = nullptr; 2224 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2225 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2226 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2227 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2228 "Typo correction callback misconfigured"); 2229 if (CCC) { 2230 // Make sure the callback knows what the typo being diagnosed is. 2231 CCC->setTypoName(II); 2232 if (SS.isValid()) 2233 CCC->setTypoNNS(SS.getScopeRep()); 2234 } 2235 if (DiagnoseEmptyLookup(S, SS, R, 2236 CCC ? std::move(CCC) : std::move(DefaultValidator), 2237 nullptr, None, &TE)) { 2238 if (TE && KeywordReplacement) { 2239 auto &State = getTypoExprState(TE); 2240 auto BestTC = State.Consumer->getNextCorrection(); 2241 if (BestTC.isKeyword()) { 2242 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2243 if (State.DiagHandler) 2244 State.DiagHandler(BestTC); 2245 KeywordReplacement->startToken(); 2246 KeywordReplacement->setKind(II->getTokenID()); 2247 KeywordReplacement->setIdentifierInfo(II); 2248 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2249 // Clean up the state associated with the TypoExpr, since it has 2250 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2251 clearDelayedTypo(TE); 2252 // Signal that a correction to a keyword was performed by returning a 2253 // valid-but-null ExprResult. 2254 return (Expr*)nullptr; 2255 } 2256 State.Consumer->resetCorrectionStream(); 2257 } 2258 return TE ? TE : ExprError(); 2259 } 2260 2261 assert(!R.empty() && 2262 "DiagnoseEmptyLookup returned false but added no results"); 2263 2264 // If we found an Objective-C instance variable, let 2265 // LookupInObjCMethod build the appropriate expression to 2266 // reference the ivar. 2267 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2268 R.clear(); 2269 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2270 // In a hopelessly buggy code, Objective-C instance variable 2271 // lookup fails and no expression will be built to reference it. 2272 if (!E.isInvalid() && !E.get()) 2273 return ExprError(); 2274 return E; 2275 } 2276 } 2277 2278 // This is guaranteed from this point on. 2279 assert(!R.empty() || ADL); 2280 2281 // Check whether this might be a C++ implicit instance member access. 2282 // C++ [class.mfct.non-static]p3: 2283 // When an id-expression that is not part of a class member access 2284 // syntax and not used to form a pointer to member is used in the 2285 // body of a non-static member function of class X, if name lookup 2286 // resolves the name in the id-expression to a non-static non-type 2287 // member of some class C, the id-expression is transformed into a 2288 // class member access expression using (*this) as the 2289 // postfix-expression to the left of the . operator. 2290 // 2291 // But we don't actually need to do this for '&' operands if R 2292 // resolved to a function or overloaded function set, because the 2293 // expression is ill-formed if it actually works out to be a 2294 // non-static member function: 2295 // 2296 // C++ [expr.ref]p4: 2297 // Otherwise, if E1.E2 refers to a non-static member function. . . 2298 // [t]he expression can be used only as the left-hand operand of a 2299 // member function call. 2300 // 2301 // There are other safeguards against such uses, but it's important 2302 // to get this right here so that we don't end up making a 2303 // spuriously dependent expression if we're inside a dependent 2304 // instance method. 2305 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2306 bool MightBeImplicitMember; 2307 if (!IsAddressOfOperand) 2308 MightBeImplicitMember = true; 2309 else if (!SS.isEmpty()) 2310 MightBeImplicitMember = false; 2311 else if (R.isOverloadedResult()) 2312 MightBeImplicitMember = false; 2313 else if (R.isUnresolvableResult()) 2314 MightBeImplicitMember = true; 2315 else 2316 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2317 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2318 isa<MSPropertyDecl>(R.getFoundDecl()); 2319 2320 if (MightBeImplicitMember) 2321 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2322 R, TemplateArgs, S); 2323 } 2324 2325 if (TemplateArgs || TemplateKWLoc.isValid()) { 2326 2327 // In C++1y, if this is a variable template id, then check it 2328 // in BuildTemplateIdExpr(). 2329 // The single lookup result must be a variable template declaration. 2330 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2331 Id.TemplateId->Kind == TNK_Var_template) { 2332 assert(R.getAsSingle<VarTemplateDecl>() && 2333 "There should only be one declaration found."); 2334 } 2335 2336 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2337 } 2338 2339 return BuildDeclarationNameExpr(SS, R, ADL); 2340 } 2341 2342 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2343 /// declaration name, generally during template instantiation. 2344 /// There's a large number of things which don't need to be done along 2345 /// this path. 2346 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2347 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2348 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2349 DeclContext *DC = computeDeclContext(SS, false); 2350 if (!DC) 2351 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2352 NameInfo, /*TemplateArgs=*/nullptr); 2353 2354 if (RequireCompleteDeclContext(SS, DC)) 2355 return ExprError(); 2356 2357 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2358 LookupQualifiedName(R, DC); 2359 2360 if (R.isAmbiguous()) 2361 return ExprError(); 2362 2363 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2364 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2365 NameInfo, /*TemplateArgs=*/nullptr); 2366 2367 if (R.empty()) { 2368 Diag(NameInfo.getLoc(), diag::err_no_member) 2369 << NameInfo.getName() << DC << SS.getRange(); 2370 return ExprError(); 2371 } 2372 2373 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2374 // Diagnose a missing typename if this resolved unambiguously to a type in 2375 // a dependent context. If we can recover with a type, downgrade this to 2376 // a warning in Microsoft compatibility mode. 2377 unsigned DiagID = diag::err_typename_missing; 2378 if (RecoveryTSI && getLangOpts().MSVCCompat) 2379 DiagID = diag::ext_typename_missing; 2380 SourceLocation Loc = SS.getBeginLoc(); 2381 auto D = Diag(Loc, DiagID); 2382 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2383 << SourceRange(Loc, NameInfo.getEndLoc()); 2384 2385 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2386 // context. 2387 if (!RecoveryTSI) 2388 return ExprError(); 2389 2390 // Only issue the fixit if we're prepared to recover. 2391 D << FixItHint::CreateInsertion(Loc, "typename "); 2392 2393 // Recover by pretending this was an elaborated type. 2394 QualType Ty = Context.getTypeDeclType(TD); 2395 TypeLocBuilder TLB; 2396 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2397 2398 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2399 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2400 QTL.setElaboratedKeywordLoc(SourceLocation()); 2401 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2402 2403 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2404 2405 return ExprEmpty(); 2406 } 2407 2408 // Defend against this resolving to an implicit member access. We usually 2409 // won't get here if this might be a legitimate a class member (we end up in 2410 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2411 // a pointer-to-member or in an unevaluated context in C++11. 2412 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2413 return BuildPossibleImplicitMemberExpr(SS, 2414 /*TemplateKWLoc=*/SourceLocation(), 2415 R, /*TemplateArgs=*/nullptr, S); 2416 2417 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2418 } 2419 2420 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2421 /// detected that we're currently inside an ObjC method. Perform some 2422 /// additional lookup. 2423 /// 2424 /// Ideally, most of this would be done by lookup, but there's 2425 /// actually quite a lot of extra work involved. 2426 /// 2427 /// Returns a null sentinel to indicate trivial success. 2428 ExprResult 2429 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2430 IdentifierInfo *II, bool AllowBuiltinCreation) { 2431 SourceLocation Loc = Lookup.getNameLoc(); 2432 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2433 2434 // Check for error condition which is already reported. 2435 if (!CurMethod) 2436 return ExprError(); 2437 2438 // There are two cases to handle here. 1) scoped lookup could have failed, 2439 // in which case we should look for an ivar. 2) scoped lookup could have 2440 // found a decl, but that decl is outside the current instance method (i.e. 2441 // a global variable). In these two cases, we do a lookup for an ivar with 2442 // this name, if the lookup sucedes, we replace it our current decl. 2443 2444 // If we're in a class method, we don't normally want to look for 2445 // ivars. But if we don't find anything else, and there's an 2446 // ivar, that's an error. 2447 bool IsClassMethod = CurMethod->isClassMethod(); 2448 2449 bool LookForIvars; 2450 if (Lookup.empty()) 2451 LookForIvars = true; 2452 else if (IsClassMethod) 2453 LookForIvars = false; 2454 else 2455 LookForIvars = (Lookup.isSingleResult() && 2456 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2457 ObjCInterfaceDecl *IFace = nullptr; 2458 if (LookForIvars) { 2459 IFace = CurMethod->getClassInterface(); 2460 ObjCInterfaceDecl *ClassDeclared; 2461 ObjCIvarDecl *IV = nullptr; 2462 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2463 // Diagnose using an ivar in a class method. 2464 if (IsClassMethod) 2465 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2466 << IV->getDeclName()); 2467 2468 // If we're referencing an invalid decl, just return this as a silent 2469 // error node. The error diagnostic was already emitted on the decl. 2470 if (IV->isInvalidDecl()) 2471 return ExprError(); 2472 2473 // Check if referencing a field with __attribute__((deprecated)). 2474 if (DiagnoseUseOfDecl(IV, Loc)) 2475 return ExprError(); 2476 2477 // Diagnose the use of an ivar outside of the declaring class. 2478 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2479 !declaresSameEntity(ClassDeclared, IFace) && 2480 !getLangOpts().DebuggerSupport) 2481 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2482 2483 // FIXME: This should use a new expr for a direct reference, don't 2484 // turn this into Self->ivar, just return a BareIVarExpr or something. 2485 IdentifierInfo &II = Context.Idents.get("self"); 2486 UnqualifiedId SelfName; 2487 SelfName.setIdentifier(&II, SourceLocation()); 2488 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2489 CXXScopeSpec SelfScopeSpec; 2490 SourceLocation TemplateKWLoc; 2491 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2492 SelfName, false, false); 2493 if (SelfExpr.isInvalid()) 2494 return ExprError(); 2495 2496 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2497 if (SelfExpr.isInvalid()) 2498 return ExprError(); 2499 2500 MarkAnyDeclReferenced(Loc, IV, true); 2501 2502 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2503 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2504 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2505 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2506 2507 ObjCIvarRefExpr *Result = new (Context) 2508 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2509 IV->getLocation(), SelfExpr.get(), true, true); 2510 2511 if (getLangOpts().ObjCAutoRefCount) { 2512 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2513 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2514 recordUseOfEvaluatedWeak(Result); 2515 } 2516 if (CurContext->isClosure()) 2517 Diag(Loc, diag::warn_implicitly_retains_self) 2518 << FixItHint::CreateInsertion(Loc, "self->"); 2519 } 2520 2521 return Result; 2522 } 2523 } else if (CurMethod->isInstanceMethod()) { 2524 // We should warn if a local variable hides an ivar. 2525 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2526 ObjCInterfaceDecl *ClassDeclared; 2527 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2528 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2529 declaresSameEntity(IFace, ClassDeclared)) 2530 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2531 } 2532 } 2533 } else if (Lookup.isSingleResult() && 2534 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2535 // If accessing a stand-alone ivar in a class method, this is an error. 2536 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2537 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2538 << IV->getDeclName()); 2539 } 2540 2541 if (Lookup.empty() && II && AllowBuiltinCreation) { 2542 // FIXME. Consolidate this with similar code in LookupName. 2543 if (unsigned BuiltinID = II->getBuiltinID()) { 2544 if (!(getLangOpts().CPlusPlus && 2545 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2546 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2547 S, Lookup.isForRedeclaration(), 2548 Lookup.getNameLoc()); 2549 if (D) Lookup.addDecl(D); 2550 } 2551 } 2552 } 2553 // Sentinel value saying that we didn't do anything special. 2554 return ExprResult((Expr *)nullptr); 2555 } 2556 2557 /// \brief Cast a base object to a member's actual type. 2558 /// 2559 /// Logically this happens in three phases: 2560 /// 2561 /// * First we cast from the base type to the naming class. 2562 /// The naming class is the class into which we were looking 2563 /// when we found the member; it's the qualifier type if a 2564 /// qualifier was provided, and otherwise it's the base type. 2565 /// 2566 /// * Next we cast from the naming class to the declaring class. 2567 /// If the member we found was brought into a class's scope by 2568 /// a using declaration, this is that class; otherwise it's 2569 /// the class declaring the member. 2570 /// 2571 /// * Finally we cast from the declaring class to the "true" 2572 /// declaring class of the member. This conversion does not 2573 /// obey access control. 2574 ExprResult 2575 Sema::PerformObjectMemberConversion(Expr *From, 2576 NestedNameSpecifier *Qualifier, 2577 NamedDecl *FoundDecl, 2578 NamedDecl *Member) { 2579 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2580 if (!RD) 2581 return From; 2582 2583 QualType DestRecordType; 2584 QualType DestType; 2585 QualType FromRecordType; 2586 QualType FromType = From->getType(); 2587 bool PointerConversions = false; 2588 if (isa<FieldDecl>(Member)) { 2589 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2590 2591 if (FromType->getAs<PointerType>()) { 2592 DestType = Context.getPointerType(DestRecordType); 2593 FromRecordType = FromType->getPointeeType(); 2594 PointerConversions = true; 2595 } else { 2596 DestType = DestRecordType; 2597 FromRecordType = FromType; 2598 } 2599 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2600 if (Method->isStatic()) 2601 return From; 2602 2603 DestType = Method->getThisType(Context); 2604 DestRecordType = DestType->getPointeeType(); 2605 2606 if (FromType->getAs<PointerType>()) { 2607 FromRecordType = FromType->getPointeeType(); 2608 PointerConversions = true; 2609 } else { 2610 FromRecordType = FromType; 2611 DestType = DestRecordType; 2612 } 2613 } else { 2614 // No conversion necessary. 2615 return From; 2616 } 2617 2618 if (DestType->isDependentType() || FromType->isDependentType()) 2619 return From; 2620 2621 // If the unqualified types are the same, no conversion is necessary. 2622 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2623 return From; 2624 2625 SourceRange FromRange = From->getSourceRange(); 2626 SourceLocation FromLoc = FromRange.getBegin(); 2627 2628 ExprValueKind VK = From->getValueKind(); 2629 2630 // C++ [class.member.lookup]p8: 2631 // [...] Ambiguities can often be resolved by qualifying a name with its 2632 // class name. 2633 // 2634 // If the member was a qualified name and the qualified referred to a 2635 // specific base subobject type, we'll cast to that intermediate type 2636 // first and then to the object in which the member is declared. That allows 2637 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2638 // 2639 // class Base { public: int x; }; 2640 // class Derived1 : public Base { }; 2641 // class Derived2 : public Base { }; 2642 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2643 // 2644 // void VeryDerived::f() { 2645 // x = 17; // error: ambiguous base subobjects 2646 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2647 // } 2648 if (Qualifier && Qualifier->getAsType()) { 2649 QualType QType = QualType(Qualifier->getAsType(), 0); 2650 assert(QType->isRecordType() && "lookup done with non-record type"); 2651 2652 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2653 2654 // In C++98, the qualifier type doesn't actually have to be a base 2655 // type of the object type, in which case we just ignore it. 2656 // Otherwise build the appropriate casts. 2657 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2658 CXXCastPath BasePath; 2659 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2660 FromLoc, FromRange, &BasePath)) 2661 return ExprError(); 2662 2663 if (PointerConversions) 2664 QType = Context.getPointerType(QType); 2665 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2666 VK, &BasePath).get(); 2667 2668 FromType = QType; 2669 FromRecordType = QRecordType; 2670 2671 // If the qualifier type was the same as the destination type, 2672 // we're done. 2673 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2674 return From; 2675 } 2676 } 2677 2678 bool IgnoreAccess = false; 2679 2680 // If we actually found the member through a using declaration, cast 2681 // down to the using declaration's type. 2682 // 2683 // Pointer equality is fine here because only one declaration of a 2684 // class ever has member declarations. 2685 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2686 assert(isa<UsingShadowDecl>(FoundDecl)); 2687 QualType URecordType = Context.getTypeDeclType( 2688 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2689 2690 // We only need to do this if the naming-class to declaring-class 2691 // conversion is non-trivial. 2692 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2693 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2694 CXXCastPath BasePath; 2695 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2696 FromLoc, FromRange, &BasePath)) 2697 return ExprError(); 2698 2699 QualType UType = URecordType; 2700 if (PointerConversions) 2701 UType = Context.getPointerType(UType); 2702 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2703 VK, &BasePath).get(); 2704 FromType = UType; 2705 FromRecordType = URecordType; 2706 } 2707 2708 // We don't do access control for the conversion from the 2709 // declaring class to the true declaring class. 2710 IgnoreAccess = true; 2711 } 2712 2713 CXXCastPath BasePath; 2714 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2715 FromLoc, FromRange, &BasePath, 2716 IgnoreAccess)) 2717 return ExprError(); 2718 2719 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2720 VK, &BasePath); 2721 } 2722 2723 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2724 const LookupResult &R, 2725 bool HasTrailingLParen) { 2726 // Only when used directly as the postfix-expression of a call. 2727 if (!HasTrailingLParen) 2728 return false; 2729 2730 // Never if a scope specifier was provided. 2731 if (SS.isSet()) 2732 return false; 2733 2734 // Only in C++ or ObjC++. 2735 if (!getLangOpts().CPlusPlus) 2736 return false; 2737 2738 // Turn off ADL when we find certain kinds of declarations during 2739 // normal lookup: 2740 for (NamedDecl *D : R) { 2741 // C++0x [basic.lookup.argdep]p3: 2742 // -- a declaration of a class member 2743 // Since using decls preserve this property, we check this on the 2744 // original decl. 2745 if (D->isCXXClassMember()) 2746 return false; 2747 2748 // C++0x [basic.lookup.argdep]p3: 2749 // -- a block-scope function declaration that is not a 2750 // using-declaration 2751 // NOTE: we also trigger this for function templates (in fact, we 2752 // don't check the decl type at all, since all other decl types 2753 // turn off ADL anyway). 2754 if (isa<UsingShadowDecl>(D)) 2755 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2756 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2757 return false; 2758 2759 // C++0x [basic.lookup.argdep]p3: 2760 // -- a declaration that is neither a function or a function 2761 // template 2762 // And also for builtin functions. 2763 if (isa<FunctionDecl>(D)) { 2764 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2765 2766 // But also builtin functions. 2767 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2768 return false; 2769 } else if (!isa<FunctionTemplateDecl>(D)) 2770 return false; 2771 } 2772 2773 return true; 2774 } 2775 2776 2777 /// Diagnoses obvious problems with the use of the given declaration 2778 /// as an expression. This is only actually called for lookups that 2779 /// were not overloaded, and it doesn't promise that the declaration 2780 /// will in fact be used. 2781 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2782 if (isa<TypedefNameDecl>(D)) { 2783 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2784 return true; 2785 } 2786 2787 if (isa<ObjCInterfaceDecl>(D)) { 2788 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2789 return true; 2790 } 2791 2792 if (isa<NamespaceDecl>(D)) { 2793 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2794 return true; 2795 } 2796 2797 return false; 2798 } 2799 2800 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2801 LookupResult &R, bool NeedsADL, 2802 bool AcceptInvalidDecl) { 2803 // If this is a single, fully-resolved result and we don't need ADL, 2804 // just build an ordinary singleton decl ref. 2805 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2806 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2807 R.getRepresentativeDecl(), nullptr, 2808 AcceptInvalidDecl); 2809 2810 // We only need to check the declaration if there's exactly one 2811 // result, because in the overloaded case the results can only be 2812 // functions and function templates. 2813 if (R.isSingleResult() && 2814 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2815 return ExprError(); 2816 2817 // Otherwise, just build an unresolved lookup expression. Suppress 2818 // any lookup-related diagnostics; we'll hash these out later, when 2819 // we've picked a target. 2820 R.suppressDiagnostics(); 2821 2822 UnresolvedLookupExpr *ULE 2823 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2824 SS.getWithLocInContext(Context), 2825 R.getLookupNameInfo(), 2826 NeedsADL, R.isOverloadedResult(), 2827 R.begin(), R.end()); 2828 2829 return ULE; 2830 } 2831 2832 /// \brief Complete semantic analysis for a reference to the given declaration. 2833 ExprResult Sema::BuildDeclarationNameExpr( 2834 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2835 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2836 bool AcceptInvalidDecl) { 2837 assert(D && "Cannot refer to a NULL declaration"); 2838 assert(!isa<FunctionTemplateDecl>(D) && 2839 "Cannot refer unambiguously to a function template"); 2840 2841 SourceLocation Loc = NameInfo.getLoc(); 2842 if (CheckDeclInExpr(*this, Loc, D)) 2843 return ExprError(); 2844 2845 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2846 // Specifically diagnose references to class templates that are missing 2847 // a template argument list. 2848 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2849 << Template << SS.getRange(); 2850 Diag(Template->getLocation(), diag::note_template_decl_here); 2851 return ExprError(); 2852 } 2853 2854 // Make sure that we're referring to a value. 2855 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2856 if (!VD) { 2857 Diag(Loc, diag::err_ref_non_value) 2858 << D << SS.getRange(); 2859 Diag(D->getLocation(), diag::note_declared_at); 2860 return ExprError(); 2861 } 2862 2863 // Check whether this declaration can be used. Note that we suppress 2864 // this check when we're going to perform argument-dependent lookup 2865 // on this function name, because this might not be the function 2866 // that overload resolution actually selects. 2867 if (DiagnoseUseOfDecl(VD, Loc)) 2868 return ExprError(); 2869 2870 // Only create DeclRefExpr's for valid Decl's. 2871 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2872 return ExprError(); 2873 2874 // Handle members of anonymous structs and unions. If we got here, 2875 // and the reference is to a class member indirect field, then this 2876 // must be the subject of a pointer-to-member expression. 2877 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2878 if (!indirectField->isCXXClassMember()) 2879 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2880 indirectField); 2881 2882 { 2883 QualType type = VD->getType(); 2884 ExprValueKind valueKind = VK_RValue; 2885 2886 switch (D->getKind()) { 2887 // Ignore all the non-ValueDecl kinds. 2888 #define ABSTRACT_DECL(kind) 2889 #define VALUE(type, base) 2890 #define DECL(type, base) \ 2891 case Decl::type: 2892 #include "clang/AST/DeclNodes.inc" 2893 llvm_unreachable("invalid value decl kind"); 2894 2895 // These shouldn't make it here. 2896 case Decl::ObjCAtDefsField: 2897 case Decl::ObjCIvar: 2898 llvm_unreachable("forming non-member reference to ivar?"); 2899 2900 // Enum constants are always r-values and never references. 2901 // Unresolved using declarations are dependent. 2902 case Decl::EnumConstant: 2903 case Decl::UnresolvedUsingValue: 2904 case Decl::OMPDeclareReduction: 2905 valueKind = VK_RValue; 2906 break; 2907 2908 // Fields and indirect fields that got here must be for 2909 // pointer-to-member expressions; we just call them l-values for 2910 // internal consistency, because this subexpression doesn't really 2911 // exist in the high-level semantics. 2912 case Decl::Field: 2913 case Decl::IndirectField: 2914 assert(getLangOpts().CPlusPlus && 2915 "building reference to field in C?"); 2916 2917 // These can't have reference type in well-formed programs, but 2918 // for internal consistency we do this anyway. 2919 type = type.getNonReferenceType(); 2920 valueKind = VK_LValue; 2921 break; 2922 2923 // Non-type template parameters are either l-values or r-values 2924 // depending on the type. 2925 case Decl::NonTypeTemplateParm: { 2926 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2927 type = reftype->getPointeeType(); 2928 valueKind = VK_LValue; // even if the parameter is an r-value reference 2929 break; 2930 } 2931 2932 // For non-references, we need to strip qualifiers just in case 2933 // the template parameter was declared as 'const int' or whatever. 2934 valueKind = VK_RValue; 2935 type = type.getUnqualifiedType(); 2936 break; 2937 } 2938 2939 case Decl::Var: 2940 case Decl::VarTemplateSpecialization: 2941 case Decl::VarTemplatePartialSpecialization: 2942 case Decl::OMPCapturedExpr: 2943 // In C, "extern void blah;" is valid and is an r-value. 2944 if (!getLangOpts().CPlusPlus && 2945 !type.hasQualifiers() && 2946 type->isVoidType()) { 2947 valueKind = VK_RValue; 2948 break; 2949 } 2950 // fallthrough 2951 2952 case Decl::ImplicitParam: 2953 case Decl::ParmVar: { 2954 // These are always l-values. 2955 valueKind = VK_LValue; 2956 type = type.getNonReferenceType(); 2957 2958 // FIXME: Does the addition of const really only apply in 2959 // potentially-evaluated contexts? Since the variable isn't actually 2960 // captured in an unevaluated context, it seems that the answer is no. 2961 if (!isUnevaluatedContext()) { 2962 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2963 if (!CapturedType.isNull()) 2964 type = CapturedType; 2965 } 2966 2967 break; 2968 } 2969 2970 case Decl::Function: { 2971 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2972 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2973 type = Context.BuiltinFnTy; 2974 valueKind = VK_RValue; 2975 break; 2976 } 2977 } 2978 2979 const FunctionType *fty = type->castAs<FunctionType>(); 2980 2981 // If we're referring to a function with an __unknown_anytype 2982 // result type, make the entire expression __unknown_anytype. 2983 if (fty->getReturnType() == Context.UnknownAnyTy) { 2984 type = Context.UnknownAnyTy; 2985 valueKind = VK_RValue; 2986 break; 2987 } 2988 2989 // Functions are l-values in C++. 2990 if (getLangOpts().CPlusPlus) { 2991 valueKind = VK_LValue; 2992 break; 2993 } 2994 2995 // C99 DR 316 says that, if a function type comes from a 2996 // function definition (without a prototype), that type is only 2997 // used for checking compatibility. Therefore, when referencing 2998 // the function, we pretend that we don't have the full function 2999 // type. 3000 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3001 isa<FunctionProtoType>(fty)) 3002 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3003 fty->getExtInfo()); 3004 3005 // Functions are r-values in C. 3006 valueKind = VK_RValue; 3007 break; 3008 } 3009 3010 case Decl::MSProperty: 3011 valueKind = VK_LValue; 3012 break; 3013 3014 case Decl::CXXMethod: 3015 // If we're referring to a method with an __unknown_anytype 3016 // result type, make the entire expression __unknown_anytype. 3017 // This should only be possible with a type written directly. 3018 if (const FunctionProtoType *proto 3019 = dyn_cast<FunctionProtoType>(VD->getType())) 3020 if (proto->getReturnType() == Context.UnknownAnyTy) { 3021 type = Context.UnknownAnyTy; 3022 valueKind = VK_RValue; 3023 break; 3024 } 3025 3026 // C++ methods are l-values if static, r-values if non-static. 3027 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3028 valueKind = VK_LValue; 3029 break; 3030 } 3031 // fallthrough 3032 3033 case Decl::CXXConversion: 3034 case Decl::CXXDestructor: 3035 case Decl::CXXConstructor: 3036 valueKind = VK_RValue; 3037 break; 3038 } 3039 3040 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3041 TemplateArgs); 3042 } 3043 } 3044 3045 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3046 SmallString<32> &Target) { 3047 Target.resize(CharByteWidth * (Source.size() + 1)); 3048 char *ResultPtr = &Target[0]; 3049 const UTF8 *ErrorPtr; 3050 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3051 (void)success; 3052 assert(success); 3053 Target.resize(ResultPtr - &Target[0]); 3054 } 3055 3056 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3057 PredefinedExpr::IdentType IT) { 3058 // Pick the current block, lambda, captured statement or function. 3059 Decl *currentDecl = nullptr; 3060 if (const BlockScopeInfo *BSI = getCurBlock()) 3061 currentDecl = BSI->TheDecl; 3062 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3063 currentDecl = LSI->CallOperator; 3064 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3065 currentDecl = CSI->TheCapturedDecl; 3066 else 3067 currentDecl = getCurFunctionOrMethodDecl(); 3068 3069 if (!currentDecl) { 3070 Diag(Loc, diag::ext_predef_outside_function); 3071 currentDecl = Context.getTranslationUnitDecl(); 3072 } 3073 3074 QualType ResTy; 3075 StringLiteral *SL = nullptr; 3076 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3077 ResTy = Context.DependentTy; 3078 else { 3079 // Pre-defined identifiers are of type char[x], where x is the length of 3080 // the string. 3081 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3082 unsigned Length = Str.length(); 3083 3084 llvm::APInt LengthI(32, Length + 1); 3085 if (IT == PredefinedExpr::LFunction) { 3086 ResTy = Context.WideCharTy.withConst(); 3087 SmallString<32> RawChars; 3088 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3089 Str, RawChars); 3090 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3091 /*IndexTypeQuals*/ 0); 3092 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3093 /*Pascal*/ false, ResTy, Loc); 3094 } else { 3095 ResTy = Context.CharTy.withConst(); 3096 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3097 /*IndexTypeQuals*/ 0); 3098 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3099 /*Pascal*/ false, ResTy, Loc); 3100 } 3101 } 3102 3103 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3104 } 3105 3106 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3107 PredefinedExpr::IdentType IT; 3108 3109 switch (Kind) { 3110 default: llvm_unreachable("Unknown simple primary expr!"); 3111 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3112 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3113 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3114 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3115 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3116 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3117 } 3118 3119 return BuildPredefinedExpr(Loc, IT); 3120 } 3121 3122 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3123 SmallString<16> CharBuffer; 3124 bool Invalid = false; 3125 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3126 if (Invalid) 3127 return ExprError(); 3128 3129 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3130 PP, Tok.getKind()); 3131 if (Literal.hadError()) 3132 return ExprError(); 3133 3134 QualType Ty; 3135 if (Literal.isWide()) 3136 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3137 else if (Literal.isUTF16()) 3138 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3139 else if (Literal.isUTF32()) 3140 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3141 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3142 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3143 else 3144 Ty = Context.CharTy; // 'x' -> char in C++ 3145 3146 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3147 if (Literal.isWide()) 3148 Kind = CharacterLiteral::Wide; 3149 else if (Literal.isUTF16()) 3150 Kind = CharacterLiteral::UTF16; 3151 else if (Literal.isUTF32()) 3152 Kind = CharacterLiteral::UTF32; 3153 else if (Literal.isUTF8()) 3154 Kind = CharacterLiteral::UTF8; 3155 3156 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3157 Tok.getLocation()); 3158 3159 if (Literal.getUDSuffix().empty()) 3160 return Lit; 3161 3162 // We're building a user-defined literal. 3163 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3164 SourceLocation UDSuffixLoc = 3165 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3166 3167 // Make sure we're allowed user-defined literals here. 3168 if (!UDLScope) 3169 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3170 3171 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3172 // operator "" X (ch) 3173 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3174 Lit, Tok.getLocation()); 3175 } 3176 3177 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3178 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3179 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3180 Context.IntTy, Loc); 3181 } 3182 3183 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3184 QualType Ty, SourceLocation Loc) { 3185 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3186 3187 using llvm::APFloat; 3188 APFloat Val(Format); 3189 3190 APFloat::opStatus result = Literal.GetFloatValue(Val); 3191 3192 // Overflow is always an error, but underflow is only an error if 3193 // we underflowed to zero (APFloat reports denormals as underflow). 3194 if ((result & APFloat::opOverflow) || 3195 ((result & APFloat::opUnderflow) && Val.isZero())) { 3196 unsigned diagnostic; 3197 SmallString<20> buffer; 3198 if (result & APFloat::opOverflow) { 3199 diagnostic = diag::warn_float_overflow; 3200 APFloat::getLargest(Format).toString(buffer); 3201 } else { 3202 diagnostic = diag::warn_float_underflow; 3203 APFloat::getSmallest(Format).toString(buffer); 3204 } 3205 3206 S.Diag(Loc, diagnostic) 3207 << Ty 3208 << StringRef(buffer.data(), buffer.size()); 3209 } 3210 3211 bool isExact = (result == APFloat::opOK); 3212 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3213 } 3214 3215 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3216 assert(E && "Invalid expression"); 3217 3218 if (E->isValueDependent()) 3219 return false; 3220 3221 QualType QT = E->getType(); 3222 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3223 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3224 return true; 3225 } 3226 3227 llvm::APSInt ValueAPS; 3228 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3229 3230 if (R.isInvalid()) 3231 return true; 3232 3233 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3234 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3235 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3236 << ValueAPS.toString(10) << ValueIsPositive; 3237 return true; 3238 } 3239 3240 return false; 3241 } 3242 3243 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3244 // Fast path for a single digit (which is quite common). A single digit 3245 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3246 if (Tok.getLength() == 1) { 3247 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3248 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3249 } 3250 3251 SmallString<128> SpellingBuffer; 3252 // NumericLiteralParser wants to overread by one character. Add padding to 3253 // the buffer in case the token is copied to the buffer. If getSpelling() 3254 // returns a StringRef to the memory buffer, it should have a null char at 3255 // the EOF, so it is also safe. 3256 SpellingBuffer.resize(Tok.getLength() + 1); 3257 3258 // Get the spelling of the token, which eliminates trigraphs, etc. 3259 bool Invalid = false; 3260 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3261 if (Invalid) 3262 return ExprError(); 3263 3264 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3265 if (Literal.hadError) 3266 return ExprError(); 3267 3268 if (Literal.hasUDSuffix()) { 3269 // We're building a user-defined literal. 3270 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3271 SourceLocation UDSuffixLoc = 3272 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3273 3274 // Make sure we're allowed user-defined literals here. 3275 if (!UDLScope) 3276 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3277 3278 QualType CookedTy; 3279 if (Literal.isFloatingLiteral()) { 3280 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3281 // long double, the literal is treated as a call of the form 3282 // operator "" X (f L) 3283 CookedTy = Context.LongDoubleTy; 3284 } else { 3285 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3286 // unsigned long long, the literal is treated as a call of the form 3287 // operator "" X (n ULL) 3288 CookedTy = Context.UnsignedLongLongTy; 3289 } 3290 3291 DeclarationName OpName = 3292 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3293 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3294 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3295 3296 SourceLocation TokLoc = Tok.getLocation(); 3297 3298 // Perform literal operator lookup to determine if we're building a raw 3299 // literal or a cooked one. 3300 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3301 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3302 /*AllowRaw*/true, /*AllowTemplate*/true, 3303 /*AllowStringTemplate*/false)) { 3304 case LOLR_Error: 3305 return ExprError(); 3306 3307 case LOLR_Cooked: { 3308 Expr *Lit; 3309 if (Literal.isFloatingLiteral()) { 3310 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3311 } else { 3312 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3313 if (Literal.GetIntegerValue(ResultVal)) 3314 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3315 << /* Unsigned */ 1; 3316 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3317 Tok.getLocation()); 3318 } 3319 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3320 } 3321 3322 case LOLR_Raw: { 3323 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3324 // literal is treated as a call of the form 3325 // operator "" X ("n") 3326 unsigned Length = Literal.getUDSuffixOffset(); 3327 QualType StrTy = Context.getConstantArrayType( 3328 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3329 ArrayType::Normal, 0); 3330 Expr *Lit = StringLiteral::Create( 3331 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3332 /*Pascal*/false, StrTy, &TokLoc, 1); 3333 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3334 } 3335 3336 case LOLR_Template: { 3337 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3338 // template), L is treated as a call fo the form 3339 // operator "" X <'c1', 'c2', ... 'ck'>() 3340 // where n is the source character sequence c1 c2 ... ck. 3341 TemplateArgumentListInfo ExplicitArgs; 3342 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3343 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3344 llvm::APSInt Value(CharBits, CharIsUnsigned); 3345 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3346 Value = TokSpelling[I]; 3347 TemplateArgument Arg(Context, Value, Context.CharTy); 3348 TemplateArgumentLocInfo ArgInfo; 3349 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3350 } 3351 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3352 &ExplicitArgs); 3353 } 3354 case LOLR_StringTemplate: 3355 llvm_unreachable("unexpected literal operator lookup result"); 3356 } 3357 } 3358 3359 Expr *Res; 3360 3361 if (Literal.isFloatingLiteral()) { 3362 QualType Ty; 3363 if (Literal.isHalf){ 3364 if (getOpenCLOptions().cl_khr_fp16) 3365 Ty = Context.HalfTy; 3366 else { 3367 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3368 return ExprError(); 3369 } 3370 } else if (Literal.isFloat) 3371 Ty = Context.FloatTy; 3372 else if (Literal.isLong) 3373 Ty = Context.LongDoubleTy; 3374 else if (Literal.isFloat128) 3375 Ty = Context.Float128Ty; 3376 else 3377 Ty = Context.DoubleTy; 3378 3379 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3380 3381 if (Ty == Context.DoubleTy) { 3382 if (getLangOpts().SinglePrecisionConstants) { 3383 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3384 } else if (getLangOpts().OpenCL && 3385 !((getLangOpts().OpenCLVersion >= 120) || 3386 getOpenCLOptions().cl_khr_fp64)) { 3387 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3388 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3389 } 3390 } 3391 } else if (!Literal.isIntegerLiteral()) { 3392 return ExprError(); 3393 } else { 3394 QualType Ty; 3395 3396 // 'long long' is a C99 or C++11 feature. 3397 if (!getLangOpts().C99 && Literal.isLongLong) { 3398 if (getLangOpts().CPlusPlus) 3399 Diag(Tok.getLocation(), 3400 getLangOpts().CPlusPlus11 ? 3401 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3402 else 3403 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3404 } 3405 3406 // Get the value in the widest-possible width. 3407 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3408 llvm::APInt ResultVal(MaxWidth, 0); 3409 3410 if (Literal.GetIntegerValue(ResultVal)) { 3411 // If this value didn't fit into uintmax_t, error and force to ull. 3412 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3413 << /* Unsigned */ 1; 3414 Ty = Context.UnsignedLongLongTy; 3415 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3416 "long long is not intmax_t?"); 3417 } else { 3418 // If this value fits into a ULL, try to figure out what else it fits into 3419 // according to the rules of C99 6.4.4.1p5. 3420 3421 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3422 // be an unsigned int. 3423 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3424 3425 // Check from smallest to largest, picking the smallest type we can. 3426 unsigned Width = 0; 3427 3428 // Microsoft specific integer suffixes are explicitly sized. 3429 if (Literal.MicrosoftInteger) { 3430 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3431 Width = 8; 3432 Ty = Context.CharTy; 3433 } else { 3434 Width = Literal.MicrosoftInteger; 3435 Ty = Context.getIntTypeForBitwidth(Width, 3436 /*Signed=*/!Literal.isUnsigned); 3437 } 3438 } 3439 3440 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3441 // Are int/unsigned possibilities? 3442 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3443 3444 // Does it fit in a unsigned int? 3445 if (ResultVal.isIntN(IntSize)) { 3446 // Does it fit in a signed int? 3447 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3448 Ty = Context.IntTy; 3449 else if (AllowUnsigned) 3450 Ty = Context.UnsignedIntTy; 3451 Width = IntSize; 3452 } 3453 } 3454 3455 // Are long/unsigned long possibilities? 3456 if (Ty.isNull() && !Literal.isLongLong) { 3457 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3458 3459 // Does it fit in a unsigned long? 3460 if (ResultVal.isIntN(LongSize)) { 3461 // Does it fit in a signed long? 3462 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3463 Ty = Context.LongTy; 3464 else if (AllowUnsigned) 3465 Ty = Context.UnsignedLongTy; 3466 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3467 // is compatible. 3468 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3469 const unsigned LongLongSize = 3470 Context.getTargetInfo().getLongLongWidth(); 3471 Diag(Tok.getLocation(), 3472 getLangOpts().CPlusPlus 3473 ? Literal.isLong 3474 ? diag::warn_old_implicitly_unsigned_long_cxx 3475 : /*C++98 UB*/ diag:: 3476 ext_old_implicitly_unsigned_long_cxx 3477 : diag::warn_old_implicitly_unsigned_long) 3478 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3479 : /*will be ill-formed*/ 1); 3480 Ty = Context.UnsignedLongTy; 3481 } 3482 Width = LongSize; 3483 } 3484 } 3485 3486 // Check long long if needed. 3487 if (Ty.isNull()) { 3488 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3489 3490 // Does it fit in a unsigned long long? 3491 if (ResultVal.isIntN(LongLongSize)) { 3492 // Does it fit in a signed long long? 3493 // To be compatible with MSVC, hex integer literals ending with the 3494 // LL or i64 suffix are always signed in Microsoft mode. 3495 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3496 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3497 Ty = Context.LongLongTy; 3498 else if (AllowUnsigned) 3499 Ty = Context.UnsignedLongLongTy; 3500 Width = LongLongSize; 3501 } 3502 } 3503 3504 // If we still couldn't decide a type, we probably have something that 3505 // does not fit in a signed long long, but has no U suffix. 3506 if (Ty.isNull()) { 3507 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3508 Ty = Context.UnsignedLongLongTy; 3509 Width = Context.getTargetInfo().getLongLongWidth(); 3510 } 3511 3512 if (ResultVal.getBitWidth() != Width) 3513 ResultVal = ResultVal.trunc(Width); 3514 } 3515 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3516 } 3517 3518 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3519 if (Literal.isImaginary) 3520 Res = new (Context) ImaginaryLiteral(Res, 3521 Context.getComplexType(Res->getType())); 3522 3523 return Res; 3524 } 3525 3526 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3527 assert(E && "ActOnParenExpr() missing expr"); 3528 return new (Context) ParenExpr(L, R, E); 3529 } 3530 3531 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3532 SourceLocation Loc, 3533 SourceRange ArgRange) { 3534 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3535 // scalar or vector data type argument..." 3536 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3537 // type (C99 6.2.5p18) or void. 3538 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3539 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3540 << T << ArgRange; 3541 return true; 3542 } 3543 3544 assert((T->isVoidType() || !T->isIncompleteType()) && 3545 "Scalar types should always be complete"); 3546 return false; 3547 } 3548 3549 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3550 SourceLocation Loc, 3551 SourceRange ArgRange, 3552 UnaryExprOrTypeTrait TraitKind) { 3553 // Invalid types must be hard errors for SFINAE in C++. 3554 if (S.LangOpts.CPlusPlus) 3555 return true; 3556 3557 // C99 6.5.3.4p1: 3558 if (T->isFunctionType() && 3559 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3560 // sizeof(function)/alignof(function) is allowed as an extension. 3561 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3562 << TraitKind << ArgRange; 3563 return false; 3564 } 3565 3566 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3567 // this is an error (OpenCL v1.1 s6.3.k) 3568 if (T->isVoidType()) { 3569 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3570 : diag::ext_sizeof_alignof_void_type; 3571 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3572 return false; 3573 } 3574 3575 return true; 3576 } 3577 3578 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3579 SourceLocation Loc, 3580 SourceRange ArgRange, 3581 UnaryExprOrTypeTrait TraitKind) { 3582 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3583 // runtime doesn't allow it. 3584 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3585 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3586 << T << (TraitKind == UETT_SizeOf) 3587 << ArgRange; 3588 return true; 3589 } 3590 3591 return false; 3592 } 3593 3594 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3595 /// pointer type is equal to T) and emit a warning if it is. 3596 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3597 Expr *E) { 3598 // Don't warn if the operation changed the type. 3599 if (T != E->getType()) 3600 return; 3601 3602 // Now look for array decays. 3603 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3604 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3605 return; 3606 3607 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3608 << ICE->getType() 3609 << ICE->getSubExpr()->getType(); 3610 } 3611 3612 /// \brief Check the constraints on expression operands to unary type expression 3613 /// and type traits. 3614 /// 3615 /// Completes any types necessary and validates the constraints on the operand 3616 /// expression. The logic mostly mirrors the type-based overload, but may modify 3617 /// the expression as it completes the type for that expression through template 3618 /// instantiation, etc. 3619 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3620 UnaryExprOrTypeTrait ExprKind) { 3621 QualType ExprTy = E->getType(); 3622 assert(!ExprTy->isReferenceType()); 3623 3624 if (ExprKind == UETT_VecStep) 3625 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3626 E->getSourceRange()); 3627 3628 // Whitelist some types as extensions 3629 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3630 E->getSourceRange(), ExprKind)) 3631 return false; 3632 3633 // 'alignof' applied to an expression only requires the base element type of 3634 // the expression to be complete. 'sizeof' requires the expression's type to 3635 // be complete (and will attempt to complete it if it's an array of unknown 3636 // bound). 3637 if (ExprKind == UETT_AlignOf) { 3638 if (RequireCompleteType(E->getExprLoc(), 3639 Context.getBaseElementType(E->getType()), 3640 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3641 E->getSourceRange())) 3642 return true; 3643 } else { 3644 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3645 ExprKind, E->getSourceRange())) 3646 return true; 3647 } 3648 3649 // Completing the expression's type may have changed it. 3650 ExprTy = E->getType(); 3651 assert(!ExprTy->isReferenceType()); 3652 3653 if (ExprTy->isFunctionType()) { 3654 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3655 << ExprKind << E->getSourceRange(); 3656 return true; 3657 } 3658 3659 // The operand for sizeof and alignof is in an unevaluated expression context, 3660 // so side effects could result in unintended consequences. 3661 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3662 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3663 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3664 3665 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3666 E->getSourceRange(), ExprKind)) 3667 return true; 3668 3669 if (ExprKind == UETT_SizeOf) { 3670 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3671 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3672 QualType OType = PVD->getOriginalType(); 3673 QualType Type = PVD->getType(); 3674 if (Type->isPointerType() && OType->isArrayType()) { 3675 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3676 << Type << OType; 3677 Diag(PVD->getLocation(), diag::note_declared_at); 3678 } 3679 } 3680 } 3681 3682 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3683 // decays into a pointer and returns an unintended result. This is most 3684 // likely a typo for "sizeof(array) op x". 3685 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3686 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3687 BO->getLHS()); 3688 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3689 BO->getRHS()); 3690 } 3691 } 3692 3693 return false; 3694 } 3695 3696 /// \brief Check the constraints on operands to unary expression and type 3697 /// traits. 3698 /// 3699 /// This will complete any types necessary, and validate the various constraints 3700 /// on those operands. 3701 /// 3702 /// The UsualUnaryConversions() function is *not* called by this routine. 3703 /// C99 6.3.2.1p[2-4] all state: 3704 /// Except when it is the operand of the sizeof operator ... 3705 /// 3706 /// C++ [expr.sizeof]p4 3707 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3708 /// standard conversions are not applied to the operand of sizeof. 3709 /// 3710 /// This policy is followed for all of the unary trait expressions. 3711 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3712 SourceLocation OpLoc, 3713 SourceRange ExprRange, 3714 UnaryExprOrTypeTrait ExprKind) { 3715 if (ExprType->isDependentType()) 3716 return false; 3717 3718 // C++ [expr.sizeof]p2: 3719 // When applied to a reference or a reference type, the result 3720 // is the size of the referenced type. 3721 // C++11 [expr.alignof]p3: 3722 // When alignof is applied to a reference type, the result 3723 // shall be the alignment of the referenced type. 3724 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3725 ExprType = Ref->getPointeeType(); 3726 3727 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3728 // When alignof or _Alignof is applied to an array type, the result 3729 // is the alignment of the element type. 3730 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3731 ExprType = Context.getBaseElementType(ExprType); 3732 3733 if (ExprKind == UETT_VecStep) 3734 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3735 3736 // Whitelist some types as extensions 3737 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3738 ExprKind)) 3739 return false; 3740 3741 if (RequireCompleteType(OpLoc, ExprType, 3742 diag::err_sizeof_alignof_incomplete_type, 3743 ExprKind, ExprRange)) 3744 return true; 3745 3746 if (ExprType->isFunctionType()) { 3747 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3748 << ExprKind << ExprRange; 3749 return true; 3750 } 3751 3752 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3753 ExprKind)) 3754 return true; 3755 3756 return false; 3757 } 3758 3759 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3760 E = E->IgnoreParens(); 3761 3762 // Cannot know anything else if the expression is dependent. 3763 if (E->isTypeDependent()) 3764 return false; 3765 3766 if (E->getObjectKind() == OK_BitField) { 3767 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3768 << 1 << E->getSourceRange(); 3769 return true; 3770 } 3771 3772 ValueDecl *D = nullptr; 3773 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3774 D = DRE->getDecl(); 3775 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3776 D = ME->getMemberDecl(); 3777 } 3778 3779 // If it's a field, require the containing struct to have a 3780 // complete definition so that we can compute the layout. 3781 // 3782 // This can happen in C++11 onwards, either by naming the member 3783 // in a way that is not transformed into a member access expression 3784 // (in an unevaluated operand, for instance), or by naming the member 3785 // in a trailing-return-type. 3786 // 3787 // For the record, since __alignof__ on expressions is a GCC 3788 // extension, GCC seems to permit this but always gives the 3789 // nonsensical answer 0. 3790 // 3791 // We don't really need the layout here --- we could instead just 3792 // directly check for all the appropriate alignment-lowing 3793 // attributes --- but that would require duplicating a lot of 3794 // logic that just isn't worth duplicating for such a marginal 3795 // use-case. 3796 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3797 // Fast path this check, since we at least know the record has a 3798 // definition if we can find a member of it. 3799 if (!FD->getParent()->isCompleteDefinition()) { 3800 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3801 << E->getSourceRange(); 3802 return true; 3803 } 3804 3805 // Otherwise, if it's a field, and the field doesn't have 3806 // reference type, then it must have a complete type (or be a 3807 // flexible array member, which we explicitly want to 3808 // white-list anyway), which makes the following checks trivial. 3809 if (!FD->getType()->isReferenceType()) 3810 return false; 3811 } 3812 3813 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3814 } 3815 3816 bool Sema::CheckVecStepExpr(Expr *E) { 3817 E = E->IgnoreParens(); 3818 3819 // Cannot know anything else if the expression is dependent. 3820 if (E->isTypeDependent()) 3821 return false; 3822 3823 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3824 } 3825 3826 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3827 CapturingScopeInfo *CSI) { 3828 assert(T->isVariablyModifiedType()); 3829 assert(CSI != nullptr); 3830 3831 // We're going to walk down into the type and look for VLA expressions. 3832 do { 3833 const Type *Ty = T.getTypePtr(); 3834 switch (Ty->getTypeClass()) { 3835 #define TYPE(Class, Base) 3836 #define ABSTRACT_TYPE(Class, Base) 3837 #define NON_CANONICAL_TYPE(Class, Base) 3838 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3839 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3840 #include "clang/AST/TypeNodes.def" 3841 T = QualType(); 3842 break; 3843 // These types are never variably-modified. 3844 case Type::Builtin: 3845 case Type::Complex: 3846 case Type::Vector: 3847 case Type::ExtVector: 3848 case Type::Record: 3849 case Type::Enum: 3850 case Type::Elaborated: 3851 case Type::TemplateSpecialization: 3852 case Type::ObjCObject: 3853 case Type::ObjCInterface: 3854 case Type::ObjCObjectPointer: 3855 case Type::Pipe: 3856 llvm_unreachable("type class is never variably-modified!"); 3857 case Type::Adjusted: 3858 T = cast<AdjustedType>(Ty)->getOriginalType(); 3859 break; 3860 case Type::Decayed: 3861 T = cast<DecayedType>(Ty)->getPointeeType(); 3862 break; 3863 case Type::Pointer: 3864 T = cast<PointerType>(Ty)->getPointeeType(); 3865 break; 3866 case Type::BlockPointer: 3867 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3868 break; 3869 case Type::LValueReference: 3870 case Type::RValueReference: 3871 T = cast<ReferenceType>(Ty)->getPointeeType(); 3872 break; 3873 case Type::MemberPointer: 3874 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3875 break; 3876 case Type::ConstantArray: 3877 case Type::IncompleteArray: 3878 // Losing element qualification here is fine. 3879 T = cast<ArrayType>(Ty)->getElementType(); 3880 break; 3881 case Type::VariableArray: { 3882 // Losing element qualification here is fine. 3883 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3884 3885 // Unknown size indication requires no size computation. 3886 // Otherwise, evaluate and record it. 3887 if (auto Size = VAT->getSizeExpr()) { 3888 if (!CSI->isVLATypeCaptured(VAT)) { 3889 RecordDecl *CapRecord = nullptr; 3890 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3891 CapRecord = LSI->Lambda; 3892 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3893 CapRecord = CRSI->TheRecordDecl; 3894 } 3895 if (CapRecord) { 3896 auto ExprLoc = Size->getExprLoc(); 3897 auto SizeType = Context.getSizeType(); 3898 // Build the non-static data member. 3899 auto Field = 3900 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3901 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3902 /*BW*/ nullptr, /*Mutable*/ false, 3903 /*InitStyle*/ ICIS_NoInit); 3904 Field->setImplicit(true); 3905 Field->setAccess(AS_private); 3906 Field->setCapturedVLAType(VAT); 3907 CapRecord->addDecl(Field); 3908 3909 CSI->addVLATypeCapture(ExprLoc, SizeType); 3910 } 3911 } 3912 } 3913 T = VAT->getElementType(); 3914 break; 3915 } 3916 case Type::FunctionProto: 3917 case Type::FunctionNoProto: 3918 T = cast<FunctionType>(Ty)->getReturnType(); 3919 break; 3920 case Type::Paren: 3921 case Type::TypeOf: 3922 case Type::UnaryTransform: 3923 case Type::Attributed: 3924 case Type::SubstTemplateTypeParm: 3925 case Type::PackExpansion: 3926 // Keep walking after single level desugaring. 3927 T = T.getSingleStepDesugaredType(Context); 3928 break; 3929 case Type::Typedef: 3930 T = cast<TypedefType>(Ty)->desugar(); 3931 break; 3932 case Type::Decltype: 3933 T = cast<DecltypeType>(Ty)->desugar(); 3934 break; 3935 case Type::Auto: 3936 T = cast<AutoType>(Ty)->getDeducedType(); 3937 break; 3938 case Type::TypeOfExpr: 3939 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3940 break; 3941 case Type::Atomic: 3942 T = cast<AtomicType>(Ty)->getValueType(); 3943 break; 3944 } 3945 } while (!T.isNull() && T->isVariablyModifiedType()); 3946 } 3947 3948 /// \brief Build a sizeof or alignof expression given a type operand. 3949 ExprResult 3950 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3951 SourceLocation OpLoc, 3952 UnaryExprOrTypeTrait ExprKind, 3953 SourceRange R) { 3954 if (!TInfo) 3955 return ExprError(); 3956 3957 QualType T = TInfo->getType(); 3958 3959 if (!T->isDependentType() && 3960 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3961 return ExprError(); 3962 3963 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3964 if (auto *TT = T->getAs<TypedefType>()) { 3965 for (auto I = FunctionScopes.rbegin(), 3966 E = std::prev(FunctionScopes.rend()); 3967 I != E; ++I) { 3968 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3969 if (CSI == nullptr) 3970 break; 3971 DeclContext *DC = nullptr; 3972 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3973 DC = LSI->CallOperator; 3974 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3975 DC = CRSI->TheCapturedDecl; 3976 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3977 DC = BSI->TheDecl; 3978 if (DC) { 3979 if (DC->containsDecl(TT->getDecl())) 3980 break; 3981 captureVariablyModifiedType(Context, T, CSI); 3982 } 3983 } 3984 } 3985 } 3986 3987 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3988 return new (Context) UnaryExprOrTypeTraitExpr( 3989 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3990 } 3991 3992 /// \brief Build a sizeof or alignof expression given an expression 3993 /// operand. 3994 ExprResult 3995 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3996 UnaryExprOrTypeTrait ExprKind) { 3997 ExprResult PE = CheckPlaceholderExpr(E); 3998 if (PE.isInvalid()) 3999 return ExprError(); 4000 4001 E = PE.get(); 4002 4003 // Verify that the operand is valid. 4004 bool isInvalid = false; 4005 if (E->isTypeDependent()) { 4006 // Delay type-checking for type-dependent expressions. 4007 } else if (ExprKind == UETT_AlignOf) { 4008 isInvalid = CheckAlignOfExpr(*this, E); 4009 } else if (ExprKind == UETT_VecStep) { 4010 isInvalid = CheckVecStepExpr(E); 4011 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4012 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4013 isInvalid = true; 4014 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4015 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4016 isInvalid = true; 4017 } else { 4018 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4019 } 4020 4021 if (isInvalid) 4022 return ExprError(); 4023 4024 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4025 PE = TransformToPotentiallyEvaluated(E); 4026 if (PE.isInvalid()) return ExprError(); 4027 E = PE.get(); 4028 } 4029 4030 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4031 return new (Context) UnaryExprOrTypeTraitExpr( 4032 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4033 } 4034 4035 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4036 /// expr and the same for @c alignof and @c __alignof 4037 /// Note that the ArgRange is invalid if isType is false. 4038 ExprResult 4039 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4040 UnaryExprOrTypeTrait ExprKind, bool IsType, 4041 void *TyOrEx, SourceRange ArgRange) { 4042 // If error parsing type, ignore. 4043 if (!TyOrEx) return ExprError(); 4044 4045 if (IsType) { 4046 TypeSourceInfo *TInfo; 4047 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4048 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4049 } 4050 4051 Expr *ArgEx = (Expr *)TyOrEx; 4052 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4053 return Result; 4054 } 4055 4056 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4057 bool IsReal) { 4058 if (V.get()->isTypeDependent()) 4059 return S.Context.DependentTy; 4060 4061 // _Real and _Imag are only l-values for normal l-values. 4062 if (V.get()->getObjectKind() != OK_Ordinary) { 4063 V = S.DefaultLvalueConversion(V.get()); 4064 if (V.isInvalid()) 4065 return QualType(); 4066 } 4067 4068 // These operators return the element type of a complex type. 4069 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4070 return CT->getElementType(); 4071 4072 // Otherwise they pass through real integer and floating point types here. 4073 if (V.get()->getType()->isArithmeticType()) 4074 return V.get()->getType(); 4075 4076 // Test for placeholders. 4077 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4078 if (PR.isInvalid()) return QualType(); 4079 if (PR.get() != V.get()) { 4080 V = PR; 4081 return CheckRealImagOperand(S, V, Loc, IsReal); 4082 } 4083 4084 // Reject anything else. 4085 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4086 << (IsReal ? "__real" : "__imag"); 4087 return QualType(); 4088 } 4089 4090 4091 4092 ExprResult 4093 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4094 tok::TokenKind Kind, Expr *Input) { 4095 UnaryOperatorKind Opc; 4096 switch (Kind) { 4097 default: llvm_unreachable("Unknown unary op!"); 4098 case tok::plusplus: Opc = UO_PostInc; break; 4099 case tok::minusminus: Opc = UO_PostDec; break; 4100 } 4101 4102 // Since this might is a postfix expression, get rid of ParenListExprs. 4103 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4104 if (Result.isInvalid()) return ExprError(); 4105 Input = Result.get(); 4106 4107 return BuildUnaryOp(S, OpLoc, Opc, Input); 4108 } 4109 4110 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4111 /// 4112 /// \return true on error 4113 static bool checkArithmeticOnObjCPointer(Sema &S, 4114 SourceLocation opLoc, 4115 Expr *op) { 4116 assert(op->getType()->isObjCObjectPointerType()); 4117 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4118 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4119 return false; 4120 4121 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4122 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4123 << op->getSourceRange(); 4124 return true; 4125 } 4126 4127 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4128 auto *BaseNoParens = Base->IgnoreParens(); 4129 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4130 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4131 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4132 } 4133 4134 ExprResult 4135 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4136 Expr *idx, SourceLocation rbLoc) { 4137 if (base && !base->getType().isNull() && 4138 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4139 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4140 /*Length=*/nullptr, rbLoc); 4141 4142 // Since this might be a postfix expression, get rid of ParenListExprs. 4143 if (isa<ParenListExpr>(base)) { 4144 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4145 if (result.isInvalid()) return ExprError(); 4146 base = result.get(); 4147 } 4148 4149 // Handle any non-overload placeholder types in the base and index 4150 // expressions. We can't handle overloads here because the other 4151 // operand might be an overloadable type, in which case the overload 4152 // resolution for the operator overload should get the first crack 4153 // at the overload. 4154 bool IsMSPropertySubscript = false; 4155 if (base->getType()->isNonOverloadPlaceholderType()) { 4156 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4157 if (!IsMSPropertySubscript) { 4158 ExprResult result = CheckPlaceholderExpr(base); 4159 if (result.isInvalid()) 4160 return ExprError(); 4161 base = result.get(); 4162 } 4163 } 4164 if (idx->getType()->isNonOverloadPlaceholderType()) { 4165 ExprResult result = CheckPlaceholderExpr(idx); 4166 if (result.isInvalid()) return ExprError(); 4167 idx = result.get(); 4168 } 4169 4170 // Build an unanalyzed expression if either operand is type-dependent. 4171 if (getLangOpts().CPlusPlus && 4172 (base->isTypeDependent() || idx->isTypeDependent())) { 4173 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4174 VK_LValue, OK_Ordinary, rbLoc); 4175 } 4176 4177 // MSDN, property (C++) 4178 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4179 // This attribute can also be used in the declaration of an empty array in a 4180 // class or structure definition. For example: 4181 // __declspec(property(get=GetX, put=PutX)) int x[]; 4182 // The above statement indicates that x[] can be used with one or more array 4183 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4184 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4185 if (IsMSPropertySubscript) { 4186 // Build MS property subscript expression if base is MS property reference 4187 // or MS property subscript. 4188 return new (Context) MSPropertySubscriptExpr( 4189 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4190 } 4191 4192 // Use C++ overloaded-operator rules if either operand has record 4193 // type. The spec says to do this if either type is *overloadable*, 4194 // but enum types can't declare subscript operators or conversion 4195 // operators, so there's nothing interesting for overload resolution 4196 // to do if there aren't any record types involved. 4197 // 4198 // ObjC pointers have their own subscripting logic that is not tied 4199 // to overload resolution and so should not take this path. 4200 if (getLangOpts().CPlusPlus && 4201 (base->getType()->isRecordType() || 4202 (!base->getType()->isObjCObjectPointerType() && 4203 idx->getType()->isRecordType()))) { 4204 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4205 } 4206 4207 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4208 } 4209 4210 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4211 Expr *LowerBound, 4212 SourceLocation ColonLoc, Expr *Length, 4213 SourceLocation RBLoc) { 4214 if (Base->getType()->isPlaceholderType() && 4215 !Base->getType()->isSpecificPlaceholderType( 4216 BuiltinType::OMPArraySection)) { 4217 ExprResult Result = CheckPlaceholderExpr(Base); 4218 if (Result.isInvalid()) 4219 return ExprError(); 4220 Base = Result.get(); 4221 } 4222 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4223 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4224 if (Result.isInvalid()) 4225 return ExprError(); 4226 Result = DefaultLvalueConversion(Result.get()); 4227 if (Result.isInvalid()) 4228 return ExprError(); 4229 LowerBound = Result.get(); 4230 } 4231 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4232 ExprResult Result = CheckPlaceholderExpr(Length); 4233 if (Result.isInvalid()) 4234 return ExprError(); 4235 Result = DefaultLvalueConversion(Result.get()); 4236 if (Result.isInvalid()) 4237 return ExprError(); 4238 Length = Result.get(); 4239 } 4240 4241 // Build an unanalyzed expression if either operand is type-dependent. 4242 if (Base->isTypeDependent() || 4243 (LowerBound && 4244 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4245 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4246 return new (Context) 4247 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4248 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4249 } 4250 4251 // Perform default conversions. 4252 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4253 QualType ResultTy; 4254 if (OriginalTy->isAnyPointerType()) { 4255 ResultTy = OriginalTy->getPointeeType(); 4256 } else if (OriginalTy->isArrayType()) { 4257 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4258 } else { 4259 return ExprError( 4260 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4261 << Base->getSourceRange()); 4262 } 4263 // C99 6.5.2.1p1 4264 if (LowerBound) { 4265 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4266 LowerBound); 4267 if (Res.isInvalid()) 4268 return ExprError(Diag(LowerBound->getExprLoc(), 4269 diag::err_omp_typecheck_section_not_integer) 4270 << 0 << LowerBound->getSourceRange()); 4271 LowerBound = Res.get(); 4272 4273 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4274 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4275 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4276 << 0 << LowerBound->getSourceRange(); 4277 } 4278 if (Length) { 4279 auto Res = 4280 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4281 if (Res.isInvalid()) 4282 return ExprError(Diag(Length->getExprLoc(), 4283 diag::err_omp_typecheck_section_not_integer) 4284 << 1 << Length->getSourceRange()); 4285 Length = Res.get(); 4286 4287 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4288 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4289 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4290 << 1 << Length->getSourceRange(); 4291 } 4292 4293 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4294 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4295 // type. Note that functions are not objects, and that (in C99 parlance) 4296 // incomplete types are not object types. 4297 if (ResultTy->isFunctionType()) { 4298 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4299 << ResultTy << Base->getSourceRange(); 4300 return ExprError(); 4301 } 4302 4303 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4304 diag::err_omp_section_incomplete_type, Base)) 4305 return ExprError(); 4306 4307 if (LowerBound) { 4308 llvm::APSInt LowerBoundValue; 4309 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4310 // OpenMP 4.0, [2.4 Array Sections] 4311 // The lower-bound and length must evaluate to non-negative integers. 4312 if (LowerBoundValue.isNegative()) { 4313 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4314 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4315 << LowerBound->getSourceRange(); 4316 return ExprError(); 4317 } 4318 } 4319 } 4320 4321 if (Length) { 4322 llvm::APSInt LengthValue; 4323 if (Length->EvaluateAsInt(LengthValue, Context)) { 4324 // OpenMP 4.0, [2.4 Array Sections] 4325 // The lower-bound and length must evaluate to non-negative integers. 4326 if (LengthValue.isNegative()) { 4327 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4328 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4329 << Length->getSourceRange(); 4330 return ExprError(); 4331 } 4332 } 4333 } else if (ColonLoc.isValid() && 4334 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4335 !OriginalTy->isVariableArrayType()))) { 4336 // OpenMP 4.0, [2.4 Array Sections] 4337 // When the size of the array dimension is not known, the length must be 4338 // specified explicitly. 4339 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4340 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4341 return ExprError(); 4342 } 4343 4344 if (!Base->getType()->isSpecificPlaceholderType( 4345 BuiltinType::OMPArraySection)) { 4346 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4347 if (Result.isInvalid()) 4348 return ExprError(); 4349 Base = Result.get(); 4350 } 4351 return new (Context) 4352 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4353 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4354 } 4355 4356 ExprResult 4357 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4358 Expr *Idx, SourceLocation RLoc) { 4359 Expr *LHSExp = Base; 4360 Expr *RHSExp = Idx; 4361 4362 // Perform default conversions. 4363 if (!LHSExp->getType()->getAs<VectorType>()) { 4364 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4365 if (Result.isInvalid()) 4366 return ExprError(); 4367 LHSExp = Result.get(); 4368 } 4369 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4370 if (Result.isInvalid()) 4371 return ExprError(); 4372 RHSExp = Result.get(); 4373 4374 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4375 ExprValueKind VK = VK_LValue; 4376 ExprObjectKind OK = OK_Ordinary; 4377 4378 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4379 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4380 // in the subscript position. As a result, we need to derive the array base 4381 // and index from the expression types. 4382 Expr *BaseExpr, *IndexExpr; 4383 QualType ResultType; 4384 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4385 BaseExpr = LHSExp; 4386 IndexExpr = RHSExp; 4387 ResultType = Context.DependentTy; 4388 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4389 BaseExpr = LHSExp; 4390 IndexExpr = RHSExp; 4391 ResultType = PTy->getPointeeType(); 4392 } else if (const ObjCObjectPointerType *PTy = 4393 LHSTy->getAs<ObjCObjectPointerType>()) { 4394 BaseExpr = LHSExp; 4395 IndexExpr = RHSExp; 4396 4397 // Use custom logic if this should be the pseudo-object subscript 4398 // expression. 4399 if (!LangOpts.isSubscriptPointerArithmetic()) 4400 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4401 nullptr); 4402 4403 ResultType = PTy->getPointeeType(); 4404 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4405 // Handle the uncommon case of "123[Ptr]". 4406 BaseExpr = RHSExp; 4407 IndexExpr = LHSExp; 4408 ResultType = PTy->getPointeeType(); 4409 } else if (const ObjCObjectPointerType *PTy = 4410 RHSTy->getAs<ObjCObjectPointerType>()) { 4411 // Handle the uncommon case of "123[Ptr]". 4412 BaseExpr = RHSExp; 4413 IndexExpr = LHSExp; 4414 ResultType = PTy->getPointeeType(); 4415 if (!LangOpts.isSubscriptPointerArithmetic()) { 4416 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4417 << ResultType << BaseExpr->getSourceRange(); 4418 return ExprError(); 4419 } 4420 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4421 BaseExpr = LHSExp; // vectors: V[123] 4422 IndexExpr = RHSExp; 4423 VK = LHSExp->getValueKind(); 4424 if (VK != VK_RValue) 4425 OK = OK_VectorComponent; 4426 4427 // FIXME: need to deal with const... 4428 ResultType = VTy->getElementType(); 4429 } else if (LHSTy->isArrayType()) { 4430 // If we see an array that wasn't promoted by 4431 // DefaultFunctionArrayLvalueConversion, it must be an array that 4432 // wasn't promoted because of the C90 rule that doesn't 4433 // allow promoting non-lvalue arrays. Warn, then 4434 // force the promotion here. 4435 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4436 LHSExp->getSourceRange(); 4437 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4438 CK_ArrayToPointerDecay).get(); 4439 LHSTy = LHSExp->getType(); 4440 4441 BaseExpr = LHSExp; 4442 IndexExpr = RHSExp; 4443 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4444 } else if (RHSTy->isArrayType()) { 4445 // Same as previous, except for 123[f().a] case 4446 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4447 RHSExp->getSourceRange(); 4448 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4449 CK_ArrayToPointerDecay).get(); 4450 RHSTy = RHSExp->getType(); 4451 4452 BaseExpr = RHSExp; 4453 IndexExpr = LHSExp; 4454 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4455 } else { 4456 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4457 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4458 } 4459 // C99 6.5.2.1p1 4460 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4461 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4462 << IndexExpr->getSourceRange()); 4463 4464 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4465 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4466 && !IndexExpr->isTypeDependent()) 4467 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4468 4469 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4470 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4471 // type. Note that Functions are not objects, and that (in C99 parlance) 4472 // incomplete types are not object types. 4473 if (ResultType->isFunctionType()) { 4474 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4475 << ResultType << BaseExpr->getSourceRange(); 4476 return ExprError(); 4477 } 4478 4479 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4480 // GNU extension: subscripting on pointer to void 4481 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4482 << BaseExpr->getSourceRange(); 4483 4484 // C forbids expressions of unqualified void type from being l-values. 4485 // See IsCForbiddenLValueType. 4486 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4487 } else if (!ResultType->isDependentType() && 4488 RequireCompleteType(LLoc, ResultType, 4489 diag::err_subscript_incomplete_type, BaseExpr)) 4490 return ExprError(); 4491 4492 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4493 !ResultType.isCForbiddenLValueType()); 4494 4495 return new (Context) 4496 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4497 } 4498 4499 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4500 FunctionDecl *FD, 4501 ParmVarDecl *Param) { 4502 if (Param->hasUnparsedDefaultArg()) { 4503 Diag(CallLoc, 4504 diag::err_use_of_default_argument_to_function_declared_later) << 4505 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4506 Diag(UnparsedDefaultArgLocs[Param], 4507 diag::note_default_argument_declared_here); 4508 return ExprError(); 4509 } 4510 4511 if (Param->hasUninstantiatedDefaultArg()) { 4512 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4513 4514 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4515 Param); 4516 4517 // Instantiate the expression. 4518 MultiLevelTemplateArgumentList MutiLevelArgList 4519 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4520 4521 InstantiatingTemplate Inst(*this, CallLoc, Param, 4522 MutiLevelArgList.getInnermost()); 4523 if (Inst.isInvalid()) 4524 return ExprError(); 4525 4526 ExprResult Result; 4527 { 4528 // C++ [dcl.fct.default]p5: 4529 // The names in the [default argument] expression are bound, and 4530 // the semantic constraints are checked, at the point where the 4531 // default argument expression appears. 4532 ContextRAII SavedContext(*this, FD); 4533 LocalInstantiationScope Local(*this); 4534 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4535 } 4536 if (Result.isInvalid()) 4537 return ExprError(); 4538 4539 // Check the expression as an initializer for the parameter. 4540 InitializedEntity Entity 4541 = InitializedEntity::InitializeParameter(Context, Param); 4542 InitializationKind Kind 4543 = InitializationKind::CreateCopy(Param->getLocation(), 4544 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4545 Expr *ResultE = Result.getAs<Expr>(); 4546 4547 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4548 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4549 if (Result.isInvalid()) 4550 return ExprError(); 4551 4552 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4553 Param->getOuterLocStart()); 4554 if (Result.isInvalid()) 4555 return ExprError(); 4556 4557 // Remember the instantiated default argument. 4558 Param->setDefaultArg(Result.getAs<Expr>()); 4559 if (ASTMutationListener *L = getASTMutationListener()) { 4560 L->DefaultArgumentInstantiated(Param); 4561 } 4562 } 4563 4564 // If the default argument expression is not set yet, we are building it now. 4565 if (!Param->hasInit()) { 4566 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4567 Param->setInvalidDecl(); 4568 return ExprError(); 4569 } 4570 4571 // If the default expression creates temporaries, we need to 4572 // push them to the current stack of expression temporaries so they'll 4573 // be properly destroyed. 4574 // FIXME: We should really be rebuilding the default argument with new 4575 // bound temporaries; see the comment in PR5810. 4576 // We don't need to do that with block decls, though, because 4577 // blocks in default argument expression can never capture anything. 4578 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4579 // Set the "needs cleanups" bit regardless of whether there are 4580 // any explicit objects. 4581 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4582 4583 // Append all the objects to the cleanup list. Right now, this 4584 // should always be a no-op, because blocks in default argument 4585 // expressions should never be able to capture anything. 4586 assert(!Init->getNumObjects() && 4587 "default argument expression has capturing blocks?"); 4588 } 4589 4590 // We already type-checked the argument, so we know it works. 4591 // Just mark all of the declarations in this potentially-evaluated expression 4592 // as being "referenced". 4593 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4594 /*SkipLocalVariables=*/true); 4595 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4596 } 4597 4598 4599 Sema::VariadicCallType 4600 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4601 Expr *Fn) { 4602 if (Proto && Proto->isVariadic()) { 4603 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4604 return VariadicConstructor; 4605 else if (Fn && Fn->getType()->isBlockPointerType()) 4606 return VariadicBlock; 4607 else if (FDecl) { 4608 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4609 if (Method->isInstance()) 4610 return VariadicMethod; 4611 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4612 return VariadicMethod; 4613 return VariadicFunction; 4614 } 4615 return VariadicDoesNotApply; 4616 } 4617 4618 namespace { 4619 class FunctionCallCCC : public FunctionCallFilterCCC { 4620 public: 4621 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4622 unsigned NumArgs, MemberExpr *ME) 4623 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4624 FunctionName(FuncName) {} 4625 4626 bool ValidateCandidate(const TypoCorrection &candidate) override { 4627 if (!candidate.getCorrectionSpecifier() || 4628 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4629 return false; 4630 } 4631 4632 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4633 } 4634 4635 private: 4636 const IdentifierInfo *const FunctionName; 4637 }; 4638 } 4639 4640 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4641 FunctionDecl *FDecl, 4642 ArrayRef<Expr *> Args) { 4643 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4644 DeclarationName FuncName = FDecl->getDeclName(); 4645 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4646 4647 if (TypoCorrection Corrected = S.CorrectTypo( 4648 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4649 S.getScopeForContext(S.CurContext), nullptr, 4650 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4651 Args.size(), ME), 4652 Sema::CTK_ErrorRecovery)) { 4653 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4654 if (Corrected.isOverloaded()) { 4655 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4656 OverloadCandidateSet::iterator Best; 4657 for (NamedDecl *CD : Corrected) { 4658 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4659 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4660 OCS); 4661 } 4662 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4663 case OR_Success: 4664 ND = Best->FoundDecl; 4665 Corrected.setCorrectionDecl(ND); 4666 break; 4667 default: 4668 break; 4669 } 4670 } 4671 ND = ND->getUnderlyingDecl(); 4672 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4673 return Corrected; 4674 } 4675 } 4676 return TypoCorrection(); 4677 } 4678 4679 /// ConvertArgumentsForCall - Converts the arguments specified in 4680 /// Args/NumArgs to the parameter types of the function FDecl with 4681 /// function prototype Proto. Call is the call expression itself, and 4682 /// Fn is the function expression. For a C++ member function, this 4683 /// routine does not attempt to convert the object argument. Returns 4684 /// true if the call is ill-formed. 4685 bool 4686 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4687 FunctionDecl *FDecl, 4688 const FunctionProtoType *Proto, 4689 ArrayRef<Expr *> Args, 4690 SourceLocation RParenLoc, 4691 bool IsExecConfig) { 4692 // Bail out early if calling a builtin with custom typechecking. 4693 if (FDecl) 4694 if (unsigned ID = FDecl->getBuiltinID()) 4695 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4696 return false; 4697 4698 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4699 // assignment, to the types of the corresponding parameter, ... 4700 unsigned NumParams = Proto->getNumParams(); 4701 bool Invalid = false; 4702 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4703 unsigned FnKind = Fn->getType()->isBlockPointerType() 4704 ? 1 /* block */ 4705 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4706 : 0 /* function */); 4707 4708 // If too few arguments are available (and we don't have default 4709 // arguments for the remaining parameters), don't make the call. 4710 if (Args.size() < NumParams) { 4711 if (Args.size() < MinArgs) { 4712 TypoCorrection TC; 4713 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4714 unsigned diag_id = 4715 MinArgs == NumParams && !Proto->isVariadic() 4716 ? diag::err_typecheck_call_too_few_args_suggest 4717 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4718 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4719 << static_cast<unsigned>(Args.size()) 4720 << TC.getCorrectionRange()); 4721 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4722 Diag(RParenLoc, 4723 MinArgs == NumParams && !Proto->isVariadic() 4724 ? diag::err_typecheck_call_too_few_args_one 4725 : diag::err_typecheck_call_too_few_args_at_least_one) 4726 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4727 else 4728 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4729 ? diag::err_typecheck_call_too_few_args 4730 : diag::err_typecheck_call_too_few_args_at_least) 4731 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4732 << Fn->getSourceRange(); 4733 4734 // Emit the location of the prototype. 4735 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4736 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4737 << FDecl; 4738 4739 return true; 4740 } 4741 Call->setNumArgs(Context, NumParams); 4742 } 4743 4744 // If too many are passed and not variadic, error on the extras and drop 4745 // them. 4746 if (Args.size() > NumParams) { 4747 if (!Proto->isVariadic()) { 4748 TypoCorrection TC; 4749 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4750 unsigned diag_id = 4751 MinArgs == NumParams && !Proto->isVariadic() 4752 ? diag::err_typecheck_call_too_many_args_suggest 4753 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4754 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4755 << static_cast<unsigned>(Args.size()) 4756 << TC.getCorrectionRange()); 4757 } else if (NumParams == 1 && FDecl && 4758 FDecl->getParamDecl(0)->getDeclName()) 4759 Diag(Args[NumParams]->getLocStart(), 4760 MinArgs == NumParams 4761 ? diag::err_typecheck_call_too_many_args_one 4762 : diag::err_typecheck_call_too_many_args_at_most_one) 4763 << FnKind << FDecl->getParamDecl(0) 4764 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4765 << SourceRange(Args[NumParams]->getLocStart(), 4766 Args.back()->getLocEnd()); 4767 else 4768 Diag(Args[NumParams]->getLocStart(), 4769 MinArgs == NumParams 4770 ? diag::err_typecheck_call_too_many_args 4771 : diag::err_typecheck_call_too_many_args_at_most) 4772 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4773 << Fn->getSourceRange() 4774 << SourceRange(Args[NumParams]->getLocStart(), 4775 Args.back()->getLocEnd()); 4776 4777 // Emit the location of the prototype. 4778 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4779 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4780 << FDecl; 4781 4782 // This deletes the extra arguments. 4783 Call->setNumArgs(Context, NumParams); 4784 return true; 4785 } 4786 } 4787 SmallVector<Expr *, 8> AllArgs; 4788 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4789 4790 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4791 Proto, 0, Args, AllArgs, CallType); 4792 if (Invalid) 4793 return true; 4794 unsigned TotalNumArgs = AllArgs.size(); 4795 for (unsigned i = 0; i < TotalNumArgs; ++i) 4796 Call->setArg(i, AllArgs[i]); 4797 4798 return false; 4799 } 4800 4801 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4802 const FunctionProtoType *Proto, 4803 unsigned FirstParam, ArrayRef<Expr *> Args, 4804 SmallVectorImpl<Expr *> &AllArgs, 4805 VariadicCallType CallType, bool AllowExplicit, 4806 bool IsListInitialization) { 4807 unsigned NumParams = Proto->getNumParams(); 4808 bool Invalid = false; 4809 size_t ArgIx = 0; 4810 // Continue to check argument types (even if we have too few/many args). 4811 for (unsigned i = FirstParam; i < NumParams; i++) { 4812 QualType ProtoArgType = Proto->getParamType(i); 4813 4814 Expr *Arg; 4815 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4816 if (ArgIx < Args.size()) { 4817 Arg = Args[ArgIx++]; 4818 4819 if (RequireCompleteType(Arg->getLocStart(), 4820 ProtoArgType, 4821 diag::err_call_incomplete_argument, Arg)) 4822 return true; 4823 4824 // Strip the unbridged-cast placeholder expression off, if applicable. 4825 bool CFAudited = false; 4826 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4827 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4828 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4829 Arg = stripARCUnbridgedCast(Arg); 4830 else if (getLangOpts().ObjCAutoRefCount && 4831 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4832 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4833 CFAudited = true; 4834 4835 InitializedEntity Entity = 4836 Param ? InitializedEntity::InitializeParameter(Context, Param, 4837 ProtoArgType) 4838 : InitializedEntity::InitializeParameter( 4839 Context, ProtoArgType, Proto->isParamConsumed(i)); 4840 4841 // Remember that parameter belongs to a CF audited API. 4842 if (CFAudited) 4843 Entity.setParameterCFAudited(); 4844 4845 ExprResult ArgE = PerformCopyInitialization( 4846 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4847 if (ArgE.isInvalid()) 4848 return true; 4849 4850 Arg = ArgE.getAs<Expr>(); 4851 } else { 4852 assert(Param && "can't use default arguments without a known callee"); 4853 4854 ExprResult ArgExpr = 4855 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4856 if (ArgExpr.isInvalid()) 4857 return true; 4858 4859 Arg = ArgExpr.getAs<Expr>(); 4860 } 4861 4862 // Check for array bounds violations for each argument to the call. This 4863 // check only triggers warnings when the argument isn't a more complex Expr 4864 // with its own checking, such as a BinaryOperator. 4865 CheckArrayAccess(Arg); 4866 4867 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4868 CheckStaticArrayArgument(CallLoc, Param, Arg); 4869 4870 AllArgs.push_back(Arg); 4871 } 4872 4873 // If this is a variadic call, handle args passed through "...". 4874 if (CallType != VariadicDoesNotApply) { 4875 // Assume that extern "C" functions with variadic arguments that 4876 // return __unknown_anytype aren't *really* variadic. 4877 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4878 FDecl->isExternC()) { 4879 for (Expr *A : Args.slice(ArgIx)) { 4880 QualType paramType; // ignored 4881 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4882 Invalid |= arg.isInvalid(); 4883 AllArgs.push_back(arg.get()); 4884 } 4885 4886 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4887 } else { 4888 for (Expr *A : Args.slice(ArgIx)) { 4889 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4890 Invalid |= Arg.isInvalid(); 4891 AllArgs.push_back(Arg.get()); 4892 } 4893 } 4894 4895 // Check for array bounds violations. 4896 for (Expr *A : Args.slice(ArgIx)) 4897 CheckArrayAccess(A); 4898 } 4899 return Invalid; 4900 } 4901 4902 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4903 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4904 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4905 TL = DTL.getOriginalLoc(); 4906 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4907 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4908 << ATL.getLocalSourceRange(); 4909 } 4910 4911 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4912 /// array parameter, check that it is non-null, and that if it is formed by 4913 /// array-to-pointer decay, the underlying array is sufficiently large. 4914 /// 4915 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4916 /// array type derivation, then for each call to the function, the value of the 4917 /// corresponding actual argument shall provide access to the first element of 4918 /// an array with at least as many elements as specified by the size expression. 4919 void 4920 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4921 ParmVarDecl *Param, 4922 const Expr *ArgExpr) { 4923 // Static array parameters are not supported in C++. 4924 if (!Param || getLangOpts().CPlusPlus) 4925 return; 4926 4927 QualType OrigTy = Param->getOriginalType(); 4928 4929 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4930 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4931 return; 4932 4933 if (ArgExpr->isNullPointerConstant(Context, 4934 Expr::NPC_NeverValueDependent)) { 4935 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4936 DiagnoseCalleeStaticArrayParam(*this, Param); 4937 return; 4938 } 4939 4940 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4941 if (!CAT) 4942 return; 4943 4944 const ConstantArrayType *ArgCAT = 4945 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4946 if (!ArgCAT) 4947 return; 4948 4949 if (ArgCAT->getSize().ult(CAT->getSize())) { 4950 Diag(CallLoc, diag::warn_static_array_too_small) 4951 << ArgExpr->getSourceRange() 4952 << (unsigned) ArgCAT->getSize().getZExtValue() 4953 << (unsigned) CAT->getSize().getZExtValue(); 4954 DiagnoseCalleeStaticArrayParam(*this, Param); 4955 } 4956 } 4957 4958 /// Given a function expression of unknown-any type, try to rebuild it 4959 /// to have a function type. 4960 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4961 4962 /// Is the given type a placeholder that we need to lower out 4963 /// immediately during argument processing? 4964 static bool isPlaceholderToRemoveAsArg(QualType type) { 4965 // Placeholders are never sugared. 4966 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4967 if (!placeholder) return false; 4968 4969 switch (placeholder->getKind()) { 4970 // Ignore all the non-placeholder types. 4971 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4972 case BuiltinType::Id: 4973 #include "clang/Basic/OpenCLImageTypes.def" 4974 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4975 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4976 #include "clang/AST/BuiltinTypes.def" 4977 return false; 4978 4979 // We cannot lower out overload sets; they might validly be resolved 4980 // by the call machinery. 4981 case BuiltinType::Overload: 4982 return false; 4983 4984 // Unbridged casts in ARC can be handled in some call positions and 4985 // should be left in place. 4986 case BuiltinType::ARCUnbridgedCast: 4987 return false; 4988 4989 // Pseudo-objects should be converted as soon as possible. 4990 case BuiltinType::PseudoObject: 4991 return true; 4992 4993 // The debugger mode could theoretically but currently does not try 4994 // to resolve unknown-typed arguments based on known parameter types. 4995 case BuiltinType::UnknownAny: 4996 return true; 4997 4998 // These are always invalid as call arguments and should be reported. 4999 case BuiltinType::BoundMember: 5000 case BuiltinType::BuiltinFn: 5001 case BuiltinType::OMPArraySection: 5002 return true; 5003 5004 } 5005 llvm_unreachable("bad builtin type kind"); 5006 } 5007 5008 /// Check an argument list for placeholders that we won't try to 5009 /// handle later. 5010 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5011 // Apply this processing to all the arguments at once instead of 5012 // dying at the first failure. 5013 bool hasInvalid = false; 5014 for (size_t i = 0, e = args.size(); i != e; i++) { 5015 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5016 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5017 if (result.isInvalid()) hasInvalid = true; 5018 else args[i] = result.get(); 5019 } else if (hasInvalid) { 5020 (void)S.CorrectDelayedTyposInExpr(args[i]); 5021 } 5022 } 5023 return hasInvalid; 5024 } 5025 5026 /// If a builtin function has a pointer argument with no explicit address 5027 /// space, then it should be able to accept a pointer to any address 5028 /// space as input. In order to do this, we need to replace the 5029 /// standard builtin declaration with one that uses the same address space 5030 /// as the call. 5031 /// 5032 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5033 /// it does not contain any pointer arguments without 5034 /// an address space qualifer. Otherwise the rewritten 5035 /// FunctionDecl is returned. 5036 /// TODO: Handle pointer return types. 5037 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5038 const FunctionDecl *FDecl, 5039 MultiExprArg ArgExprs) { 5040 5041 QualType DeclType = FDecl->getType(); 5042 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5043 5044 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5045 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5046 return nullptr; 5047 5048 bool NeedsNewDecl = false; 5049 unsigned i = 0; 5050 SmallVector<QualType, 8> OverloadParams; 5051 5052 for (QualType ParamType : FT->param_types()) { 5053 5054 // Convert array arguments to pointer to simplify type lookup. 5055 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 5056 QualType ArgType = Arg->getType(); 5057 if (!ParamType->isPointerType() || 5058 ParamType.getQualifiers().hasAddressSpace() || 5059 !ArgType->isPointerType() || 5060 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5061 OverloadParams.push_back(ParamType); 5062 continue; 5063 } 5064 5065 NeedsNewDecl = true; 5066 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5067 5068 QualType PointeeType = ParamType->getPointeeType(); 5069 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5070 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5071 } 5072 5073 if (!NeedsNewDecl) 5074 return nullptr; 5075 5076 FunctionProtoType::ExtProtoInfo EPI; 5077 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5078 OverloadParams, EPI); 5079 DeclContext *Parent = Context.getTranslationUnitDecl(); 5080 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5081 FDecl->getLocation(), 5082 FDecl->getLocation(), 5083 FDecl->getIdentifier(), 5084 OverloadTy, 5085 /*TInfo=*/nullptr, 5086 SC_Extern, false, 5087 /*hasPrototype=*/true); 5088 SmallVector<ParmVarDecl*, 16> Params; 5089 FT = cast<FunctionProtoType>(OverloadTy); 5090 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5091 QualType ParamType = FT->getParamType(i); 5092 ParmVarDecl *Parm = 5093 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5094 SourceLocation(), nullptr, ParamType, 5095 /*TInfo=*/nullptr, SC_None, nullptr); 5096 Parm->setScopeInfo(0, i); 5097 Params.push_back(Parm); 5098 } 5099 OverloadDecl->setParams(Params); 5100 return OverloadDecl; 5101 } 5102 5103 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5104 std::size_t NumArgs) { 5105 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5106 /*PartialOverloading=*/false)) 5107 return Callee->isVariadic(); 5108 return Callee->getMinRequiredArguments() <= NumArgs; 5109 } 5110 5111 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5112 /// This provides the location of the left/right parens and a list of comma 5113 /// locations. 5114 ExprResult 5115 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5116 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5117 Expr *ExecConfig, bool IsExecConfig) { 5118 // Since this might be a postfix expression, get rid of ParenListExprs. 5119 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 5120 if (Result.isInvalid()) return ExprError(); 5121 Fn = Result.get(); 5122 5123 if (checkArgsForPlaceholders(*this, ArgExprs)) 5124 return ExprError(); 5125 5126 if (getLangOpts().CPlusPlus) { 5127 // If this is a pseudo-destructor expression, build the call immediately. 5128 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5129 if (!ArgExprs.empty()) { 5130 // Pseudo-destructor calls should not have any arguments. 5131 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5132 << FixItHint::CreateRemoval( 5133 SourceRange(ArgExprs.front()->getLocStart(), 5134 ArgExprs.back()->getLocEnd())); 5135 } 5136 5137 return new (Context) 5138 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5139 } 5140 if (Fn->getType() == Context.PseudoObjectTy) { 5141 ExprResult result = CheckPlaceholderExpr(Fn); 5142 if (result.isInvalid()) return ExprError(); 5143 Fn = result.get(); 5144 } 5145 5146 // Determine whether this is a dependent call inside a C++ template, 5147 // in which case we won't do any semantic analysis now. 5148 bool Dependent = false; 5149 if (Fn->isTypeDependent()) 5150 Dependent = true; 5151 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5152 Dependent = true; 5153 5154 if (Dependent) { 5155 if (ExecConfig) { 5156 return new (Context) CUDAKernelCallExpr( 5157 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5158 Context.DependentTy, VK_RValue, RParenLoc); 5159 } else { 5160 return new (Context) CallExpr( 5161 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5162 } 5163 } 5164 5165 // Determine whether this is a call to an object (C++ [over.call.object]). 5166 if (Fn->getType()->isRecordType()) 5167 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 5168 RParenLoc); 5169 5170 if (Fn->getType() == Context.UnknownAnyTy) { 5171 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5172 if (result.isInvalid()) return ExprError(); 5173 Fn = result.get(); 5174 } 5175 5176 if (Fn->getType() == Context.BoundMemberTy) { 5177 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5178 } 5179 } 5180 5181 // Check for overloaded calls. This can happen even in C due to extensions. 5182 if (Fn->getType() == Context.OverloadTy) { 5183 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5184 5185 // We aren't supposed to apply this logic for if there's an '&' involved. 5186 if (!find.HasFormOfMemberPointer) { 5187 OverloadExpr *ovl = find.Expression; 5188 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5189 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 5190 RParenLoc, ExecConfig, 5191 /*AllowTypoCorrection=*/true, 5192 find.IsAddressOfOperand); 5193 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5194 } 5195 } 5196 5197 // If we're directly calling a function, get the appropriate declaration. 5198 if (Fn->getType() == Context.UnknownAnyTy) { 5199 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5200 if (result.isInvalid()) return ExprError(); 5201 Fn = result.get(); 5202 } 5203 5204 Expr *NakedFn = Fn->IgnoreParens(); 5205 5206 bool CallingNDeclIndirectly = false; 5207 NamedDecl *NDecl = nullptr; 5208 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5209 if (UnOp->getOpcode() == UO_AddrOf) { 5210 CallingNDeclIndirectly = true; 5211 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5212 } 5213 } 5214 5215 if (isa<DeclRefExpr>(NakedFn)) { 5216 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5217 5218 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5219 if (FDecl && FDecl->getBuiltinID()) { 5220 // Rewrite the function decl for this builtin by replacing parameters 5221 // with no explicit address space with the address space of the arguments 5222 // in ArgExprs. 5223 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5224 NDecl = FDecl; 5225 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 5226 SourceLocation(), FDecl, false, 5227 SourceLocation(), FDecl->getType(), 5228 Fn->getValueKind(), FDecl); 5229 } 5230 } 5231 } else if (isa<MemberExpr>(NakedFn)) 5232 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5233 5234 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5235 if (CallingNDeclIndirectly && 5236 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5237 Fn->getLocStart())) 5238 return ExprError(); 5239 5240 // CheckEnableIf assumes that the we're passing in a sane number of args for 5241 // FD, but that doesn't always hold true here. This is because, in some 5242 // cases, we'll emit a diag about an ill-formed function call, but then 5243 // we'll continue on as if the function call wasn't ill-formed. So, if the 5244 // number of args looks incorrect, don't do enable_if checks; we should've 5245 // already emitted an error about the bad call. 5246 if (FD->hasAttr<EnableIfAttr>() && 5247 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5248 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5249 Diag(Fn->getLocStart(), 5250 isa<CXXMethodDecl>(FD) ? 5251 diag::err_ovl_no_viable_member_function_in_call : 5252 diag::err_ovl_no_viable_function_in_call) 5253 << FD << FD->getSourceRange(); 5254 Diag(FD->getLocation(), 5255 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5256 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5257 } 5258 } 5259 } 5260 5261 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5262 ExecConfig, IsExecConfig); 5263 } 5264 5265 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5266 /// 5267 /// __builtin_astype( value, dst type ) 5268 /// 5269 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5270 SourceLocation BuiltinLoc, 5271 SourceLocation RParenLoc) { 5272 ExprValueKind VK = VK_RValue; 5273 ExprObjectKind OK = OK_Ordinary; 5274 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5275 QualType SrcTy = E->getType(); 5276 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5277 return ExprError(Diag(BuiltinLoc, 5278 diag::err_invalid_astype_of_different_size) 5279 << DstTy 5280 << SrcTy 5281 << E->getSourceRange()); 5282 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5283 } 5284 5285 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5286 /// provided arguments. 5287 /// 5288 /// __builtin_convertvector( value, dst type ) 5289 /// 5290 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5291 SourceLocation BuiltinLoc, 5292 SourceLocation RParenLoc) { 5293 TypeSourceInfo *TInfo; 5294 GetTypeFromParser(ParsedDestTy, &TInfo); 5295 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5296 } 5297 5298 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5299 /// i.e. an expression not of \p OverloadTy. The expression should 5300 /// unary-convert to an expression of function-pointer or 5301 /// block-pointer type. 5302 /// 5303 /// \param NDecl the declaration being called, if available 5304 ExprResult 5305 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5306 SourceLocation LParenLoc, 5307 ArrayRef<Expr *> Args, 5308 SourceLocation RParenLoc, 5309 Expr *Config, bool IsExecConfig) { 5310 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5311 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5312 5313 // Functions with 'interrupt' attribute cannot be called directly. 5314 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5315 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5316 return ExprError(); 5317 } 5318 5319 // Promote the function operand. 5320 // We special-case function promotion here because we only allow promoting 5321 // builtin functions to function pointers in the callee of a call. 5322 ExprResult Result; 5323 if (BuiltinID && 5324 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5325 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5326 CK_BuiltinFnToFnPtr).get(); 5327 } else { 5328 Result = CallExprUnaryConversions(Fn); 5329 } 5330 if (Result.isInvalid()) 5331 return ExprError(); 5332 Fn = Result.get(); 5333 5334 // Make the call expr early, before semantic checks. This guarantees cleanup 5335 // of arguments and function on error. 5336 CallExpr *TheCall; 5337 if (Config) 5338 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5339 cast<CallExpr>(Config), Args, 5340 Context.BoolTy, VK_RValue, 5341 RParenLoc); 5342 else 5343 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5344 VK_RValue, RParenLoc); 5345 5346 if (!getLangOpts().CPlusPlus) { 5347 // C cannot always handle TypoExpr nodes in builtin calls and direct 5348 // function calls as their argument checking don't necessarily handle 5349 // dependent types properly, so make sure any TypoExprs have been 5350 // dealt with. 5351 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5352 if (!Result.isUsable()) return ExprError(); 5353 TheCall = dyn_cast<CallExpr>(Result.get()); 5354 if (!TheCall) return Result; 5355 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5356 } 5357 5358 // Bail out early if calling a builtin with custom typechecking. 5359 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5360 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5361 5362 retry: 5363 const FunctionType *FuncT; 5364 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5365 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5366 // have type pointer to function". 5367 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5368 if (!FuncT) 5369 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5370 << Fn->getType() << Fn->getSourceRange()); 5371 } else if (const BlockPointerType *BPT = 5372 Fn->getType()->getAs<BlockPointerType>()) { 5373 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5374 } else { 5375 // Handle calls to expressions of unknown-any type. 5376 if (Fn->getType() == Context.UnknownAnyTy) { 5377 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5378 if (rewrite.isInvalid()) return ExprError(); 5379 Fn = rewrite.get(); 5380 TheCall->setCallee(Fn); 5381 goto retry; 5382 } 5383 5384 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5385 << Fn->getType() << Fn->getSourceRange()); 5386 } 5387 5388 if (getLangOpts().CUDA) { 5389 if (Config) { 5390 // CUDA: Kernel calls must be to global functions 5391 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5392 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5393 << FDecl->getName() << Fn->getSourceRange()); 5394 5395 // CUDA: Kernel function must have 'void' return type 5396 if (!FuncT->getReturnType()->isVoidType()) 5397 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5398 << Fn->getType() << Fn->getSourceRange()); 5399 } else { 5400 // CUDA: Calls to global functions must be configured 5401 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5402 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5403 << FDecl->getName() << Fn->getSourceRange()); 5404 } 5405 } 5406 5407 // Check for a valid return type 5408 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5409 FDecl)) 5410 return ExprError(); 5411 5412 // We know the result type of the call, set it. 5413 TheCall->setType(FuncT->getCallResultType(Context)); 5414 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5415 5416 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5417 if (Proto) { 5418 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5419 IsExecConfig)) 5420 return ExprError(); 5421 } else { 5422 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5423 5424 if (FDecl) { 5425 // Check if we have too few/too many template arguments, based 5426 // on our knowledge of the function definition. 5427 const FunctionDecl *Def = nullptr; 5428 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5429 Proto = Def->getType()->getAs<FunctionProtoType>(); 5430 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5431 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5432 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5433 } 5434 5435 // If the function we're calling isn't a function prototype, but we have 5436 // a function prototype from a prior declaratiom, use that prototype. 5437 if (!FDecl->hasPrototype()) 5438 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5439 } 5440 5441 // Promote the arguments (C99 6.5.2.2p6). 5442 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5443 Expr *Arg = Args[i]; 5444 5445 if (Proto && i < Proto->getNumParams()) { 5446 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5447 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5448 ExprResult ArgE = 5449 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5450 if (ArgE.isInvalid()) 5451 return true; 5452 5453 Arg = ArgE.getAs<Expr>(); 5454 5455 } else { 5456 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5457 5458 if (ArgE.isInvalid()) 5459 return true; 5460 5461 Arg = ArgE.getAs<Expr>(); 5462 } 5463 5464 if (RequireCompleteType(Arg->getLocStart(), 5465 Arg->getType(), 5466 diag::err_call_incomplete_argument, Arg)) 5467 return ExprError(); 5468 5469 TheCall->setArg(i, Arg); 5470 } 5471 } 5472 5473 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5474 if (!Method->isStatic()) 5475 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5476 << Fn->getSourceRange()); 5477 5478 // Check for sentinels 5479 if (NDecl) 5480 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5481 5482 // Do special checking on direct calls to functions. 5483 if (FDecl) { 5484 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5485 return ExprError(); 5486 5487 if (BuiltinID) 5488 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5489 } else if (NDecl) { 5490 if (CheckPointerCall(NDecl, TheCall, Proto)) 5491 return ExprError(); 5492 } else { 5493 if (CheckOtherCall(TheCall, Proto)) 5494 return ExprError(); 5495 } 5496 5497 return MaybeBindToTemporary(TheCall); 5498 } 5499 5500 ExprResult 5501 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5502 SourceLocation RParenLoc, Expr *InitExpr) { 5503 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5504 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5505 5506 TypeSourceInfo *TInfo; 5507 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5508 if (!TInfo) 5509 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5510 5511 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5512 } 5513 5514 ExprResult 5515 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5516 SourceLocation RParenLoc, Expr *LiteralExpr) { 5517 QualType literalType = TInfo->getType(); 5518 5519 if (literalType->isArrayType()) { 5520 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5521 diag::err_illegal_decl_array_incomplete_type, 5522 SourceRange(LParenLoc, 5523 LiteralExpr->getSourceRange().getEnd()))) 5524 return ExprError(); 5525 if (literalType->isVariableArrayType()) 5526 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5527 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5528 } else if (!literalType->isDependentType() && 5529 RequireCompleteType(LParenLoc, literalType, 5530 diag::err_typecheck_decl_incomplete_type, 5531 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5532 return ExprError(); 5533 5534 InitializedEntity Entity 5535 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5536 InitializationKind Kind 5537 = InitializationKind::CreateCStyleCast(LParenLoc, 5538 SourceRange(LParenLoc, RParenLoc), 5539 /*InitList=*/true); 5540 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5541 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5542 &literalType); 5543 if (Result.isInvalid()) 5544 return ExprError(); 5545 LiteralExpr = Result.get(); 5546 5547 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5548 if (isFileScope && 5549 !LiteralExpr->isTypeDependent() && 5550 !LiteralExpr->isValueDependent() && 5551 !literalType->isDependentType()) { // 6.5.2.5p3 5552 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5553 return ExprError(); 5554 } 5555 5556 // In C, compound literals are l-values for some reason. 5557 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5558 5559 return MaybeBindToTemporary( 5560 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5561 VK, LiteralExpr, isFileScope)); 5562 } 5563 5564 ExprResult 5565 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5566 SourceLocation RBraceLoc) { 5567 // Immediately handle non-overload placeholders. Overloads can be 5568 // resolved contextually, but everything else here can't. 5569 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5570 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5571 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5572 5573 // Ignore failures; dropping the entire initializer list because 5574 // of one failure would be terrible for indexing/etc. 5575 if (result.isInvalid()) continue; 5576 5577 InitArgList[I] = result.get(); 5578 } 5579 } 5580 5581 // Semantic analysis for initializers is done by ActOnDeclarator() and 5582 // CheckInitializer() - it requires knowledge of the object being intialized. 5583 5584 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5585 RBraceLoc); 5586 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5587 return E; 5588 } 5589 5590 /// Do an explicit extend of the given block pointer if we're in ARC. 5591 void Sema::maybeExtendBlockObject(ExprResult &E) { 5592 assert(E.get()->getType()->isBlockPointerType()); 5593 assert(E.get()->isRValue()); 5594 5595 // Only do this in an r-value context. 5596 if (!getLangOpts().ObjCAutoRefCount) return; 5597 5598 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5599 CK_ARCExtendBlockObject, E.get(), 5600 /*base path*/ nullptr, VK_RValue); 5601 Cleanup.setExprNeedsCleanups(true); 5602 } 5603 5604 /// Prepare a conversion of the given expression to an ObjC object 5605 /// pointer type. 5606 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5607 QualType type = E.get()->getType(); 5608 if (type->isObjCObjectPointerType()) { 5609 return CK_BitCast; 5610 } else if (type->isBlockPointerType()) { 5611 maybeExtendBlockObject(E); 5612 return CK_BlockPointerToObjCPointerCast; 5613 } else { 5614 assert(type->isPointerType()); 5615 return CK_CPointerToObjCPointerCast; 5616 } 5617 } 5618 5619 /// Prepares for a scalar cast, performing all the necessary stages 5620 /// except the final cast and returning the kind required. 5621 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5622 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5623 // Also, callers should have filtered out the invalid cases with 5624 // pointers. Everything else should be possible. 5625 5626 QualType SrcTy = Src.get()->getType(); 5627 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5628 return CK_NoOp; 5629 5630 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5631 case Type::STK_MemberPointer: 5632 llvm_unreachable("member pointer type in C"); 5633 5634 case Type::STK_CPointer: 5635 case Type::STK_BlockPointer: 5636 case Type::STK_ObjCObjectPointer: 5637 switch (DestTy->getScalarTypeKind()) { 5638 case Type::STK_CPointer: { 5639 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5640 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5641 if (SrcAS != DestAS) 5642 return CK_AddressSpaceConversion; 5643 return CK_BitCast; 5644 } 5645 case Type::STK_BlockPointer: 5646 return (SrcKind == Type::STK_BlockPointer 5647 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5648 case Type::STK_ObjCObjectPointer: 5649 if (SrcKind == Type::STK_ObjCObjectPointer) 5650 return CK_BitCast; 5651 if (SrcKind == Type::STK_CPointer) 5652 return CK_CPointerToObjCPointerCast; 5653 maybeExtendBlockObject(Src); 5654 return CK_BlockPointerToObjCPointerCast; 5655 case Type::STK_Bool: 5656 return CK_PointerToBoolean; 5657 case Type::STK_Integral: 5658 return CK_PointerToIntegral; 5659 case Type::STK_Floating: 5660 case Type::STK_FloatingComplex: 5661 case Type::STK_IntegralComplex: 5662 case Type::STK_MemberPointer: 5663 llvm_unreachable("illegal cast from pointer"); 5664 } 5665 llvm_unreachable("Should have returned before this"); 5666 5667 case Type::STK_Bool: // casting from bool is like casting from an integer 5668 case Type::STK_Integral: 5669 switch (DestTy->getScalarTypeKind()) { 5670 case Type::STK_CPointer: 5671 case Type::STK_ObjCObjectPointer: 5672 case Type::STK_BlockPointer: 5673 if (Src.get()->isNullPointerConstant(Context, 5674 Expr::NPC_ValueDependentIsNull)) 5675 return CK_NullToPointer; 5676 return CK_IntegralToPointer; 5677 case Type::STK_Bool: 5678 return CK_IntegralToBoolean; 5679 case Type::STK_Integral: 5680 return CK_IntegralCast; 5681 case Type::STK_Floating: 5682 return CK_IntegralToFloating; 5683 case Type::STK_IntegralComplex: 5684 Src = ImpCastExprToType(Src.get(), 5685 DestTy->castAs<ComplexType>()->getElementType(), 5686 CK_IntegralCast); 5687 return CK_IntegralRealToComplex; 5688 case Type::STK_FloatingComplex: 5689 Src = ImpCastExprToType(Src.get(), 5690 DestTy->castAs<ComplexType>()->getElementType(), 5691 CK_IntegralToFloating); 5692 return CK_FloatingRealToComplex; 5693 case Type::STK_MemberPointer: 5694 llvm_unreachable("member pointer type in C"); 5695 } 5696 llvm_unreachable("Should have returned before this"); 5697 5698 case Type::STK_Floating: 5699 switch (DestTy->getScalarTypeKind()) { 5700 case Type::STK_Floating: 5701 return CK_FloatingCast; 5702 case Type::STK_Bool: 5703 return CK_FloatingToBoolean; 5704 case Type::STK_Integral: 5705 return CK_FloatingToIntegral; 5706 case Type::STK_FloatingComplex: 5707 Src = ImpCastExprToType(Src.get(), 5708 DestTy->castAs<ComplexType>()->getElementType(), 5709 CK_FloatingCast); 5710 return CK_FloatingRealToComplex; 5711 case Type::STK_IntegralComplex: 5712 Src = ImpCastExprToType(Src.get(), 5713 DestTy->castAs<ComplexType>()->getElementType(), 5714 CK_FloatingToIntegral); 5715 return CK_IntegralRealToComplex; 5716 case Type::STK_CPointer: 5717 case Type::STK_ObjCObjectPointer: 5718 case Type::STK_BlockPointer: 5719 llvm_unreachable("valid float->pointer cast?"); 5720 case Type::STK_MemberPointer: 5721 llvm_unreachable("member pointer type in C"); 5722 } 5723 llvm_unreachable("Should have returned before this"); 5724 5725 case Type::STK_FloatingComplex: 5726 switch (DestTy->getScalarTypeKind()) { 5727 case Type::STK_FloatingComplex: 5728 return CK_FloatingComplexCast; 5729 case Type::STK_IntegralComplex: 5730 return CK_FloatingComplexToIntegralComplex; 5731 case Type::STK_Floating: { 5732 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5733 if (Context.hasSameType(ET, DestTy)) 5734 return CK_FloatingComplexToReal; 5735 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5736 return CK_FloatingCast; 5737 } 5738 case Type::STK_Bool: 5739 return CK_FloatingComplexToBoolean; 5740 case Type::STK_Integral: 5741 Src = ImpCastExprToType(Src.get(), 5742 SrcTy->castAs<ComplexType>()->getElementType(), 5743 CK_FloatingComplexToReal); 5744 return CK_FloatingToIntegral; 5745 case Type::STK_CPointer: 5746 case Type::STK_ObjCObjectPointer: 5747 case Type::STK_BlockPointer: 5748 llvm_unreachable("valid complex float->pointer cast?"); 5749 case Type::STK_MemberPointer: 5750 llvm_unreachable("member pointer type in C"); 5751 } 5752 llvm_unreachable("Should have returned before this"); 5753 5754 case Type::STK_IntegralComplex: 5755 switch (DestTy->getScalarTypeKind()) { 5756 case Type::STK_FloatingComplex: 5757 return CK_IntegralComplexToFloatingComplex; 5758 case Type::STK_IntegralComplex: 5759 return CK_IntegralComplexCast; 5760 case Type::STK_Integral: { 5761 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5762 if (Context.hasSameType(ET, DestTy)) 5763 return CK_IntegralComplexToReal; 5764 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5765 return CK_IntegralCast; 5766 } 5767 case Type::STK_Bool: 5768 return CK_IntegralComplexToBoolean; 5769 case Type::STK_Floating: 5770 Src = ImpCastExprToType(Src.get(), 5771 SrcTy->castAs<ComplexType>()->getElementType(), 5772 CK_IntegralComplexToReal); 5773 return CK_IntegralToFloating; 5774 case Type::STK_CPointer: 5775 case Type::STK_ObjCObjectPointer: 5776 case Type::STK_BlockPointer: 5777 llvm_unreachable("valid complex int->pointer cast?"); 5778 case Type::STK_MemberPointer: 5779 llvm_unreachable("member pointer type in C"); 5780 } 5781 llvm_unreachable("Should have returned before this"); 5782 } 5783 5784 llvm_unreachable("Unhandled scalar cast"); 5785 } 5786 5787 static bool breakDownVectorType(QualType type, uint64_t &len, 5788 QualType &eltType) { 5789 // Vectors are simple. 5790 if (const VectorType *vecType = type->getAs<VectorType>()) { 5791 len = vecType->getNumElements(); 5792 eltType = vecType->getElementType(); 5793 assert(eltType->isScalarType()); 5794 return true; 5795 } 5796 5797 // We allow lax conversion to and from non-vector types, but only if 5798 // they're real types (i.e. non-complex, non-pointer scalar types). 5799 if (!type->isRealType()) return false; 5800 5801 len = 1; 5802 eltType = type; 5803 return true; 5804 } 5805 5806 /// Are the two types lax-compatible vector types? That is, given 5807 /// that one of them is a vector, do they have equal storage sizes, 5808 /// where the storage size is the number of elements times the element 5809 /// size? 5810 /// 5811 /// This will also return false if either of the types is neither a 5812 /// vector nor a real type. 5813 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5814 assert(destTy->isVectorType() || srcTy->isVectorType()); 5815 5816 // Disallow lax conversions between scalars and ExtVectors (these 5817 // conversions are allowed for other vector types because common headers 5818 // depend on them). Most scalar OP ExtVector cases are handled by the 5819 // splat path anyway, which does what we want (convert, not bitcast). 5820 // What this rules out for ExtVectors is crazy things like char4*float. 5821 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5822 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5823 5824 uint64_t srcLen, destLen; 5825 QualType srcEltTy, destEltTy; 5826 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5827 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5828 5829 // ASTContext::getTypeSize will return the size rounded up to a 5830 // power of 2, so instead of using that, we need to use the raw 5831 // element size multiplied by the element count. 5832 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5833 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5834 5835 return (srcLen * srcEltSize == destLen * destEltSize); 5836 } 5837 5838 /// Is this a legal conversion between two types, one of which is 5839 /// known to be a vector type? 5840 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5841 assert(destTy->isVectorType() || srcTy->isVectorType()); 5842 5843 if (!Context.getLangOpts().LaxVectorConversions) 5844 return false; 5845 return areLaxCompatibleVectorTypes(srcTy, destTy); 5846 } 5847 5848 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5849 CastKind &Kind) { 5850 assert(VectorTy->isVectorType() && "Not a vector type!"); 5851 5852 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5853 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5854 return Diag(R.getBegin(), 5855 Ty->isVectorType() ? 5856 diag::err_invalid_conversion_between_vectors : 5857 diag::err_invalid_conversion_between_vector_and_integer) 5858 << VectorTy << Ty << R; 5859 } else 5860 return Diag(R.getBegin(), 5861 diag::err_invalid_conversion_between_vector_and_scalar) 5862 << VectorTy << Ty << R; 5863 5864 Kind = CK_BitCast; 5865 return false; 5866 } 5867 5868 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5869 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5870 5871 if (DestElemTy == SplattedExpr->getType()) 5872 return SplattedExpr; 5873 5874 assert(DestElemTy->isFloatingType() || 5875 DestElemTy->isIntegralOrEnumerationType()); 5876 5877 CastKind CK; 5878 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5879 // OpenCL requires that we convert `true` boolean expressions to -1, but 5880 // only when splatting vectors. 5881 if (DestElemTy->isFloatingType()) { 5882 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5883 // in two steps: boolean to signed integral, then to floating. 5884 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5885 CK_BooleanToSignedIntegral); 5886 SplattedExpr = CastExprRes.get(); 5887 CK = CK_IntegralToFloating; 5888 } else { 5889 CK = CK_BooleanToSignedIntegral; 5890 } 5891 } else { 5892 ExprResult CastExprRes = SplattedExpr; 5893 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5894 if (CastExprRes.isInvalid()) 5895 return ExprError(); 5896 SplattedExpr = CastExprRes.get(); 5897 } 5898 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5899 } 5900 5901 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5902 Expr *CastExpr, CastKind &Kind) { 5903 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5904 5905 QualType SrcTy = CastExpr->getType(); 5906 5907 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5908 // an ExtVectorType. 5909 // In OpenCL, casts between vectors of different types are not allowed. 5910 // (See OpenCL 6.2). 5911 if (SrcTy->isVectorType()) { 5912 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5913 || (getLangOpts().OpenCL && 5914 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5915 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5916 << DestTy << SrcTy << R; 5917 return ExprError(); 5918 } 5919 Kind = CK_BitCast; 5920 return CastExpr; 5921 } 5922 5923 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5924 // conversion will take place first from scalar to elt type, and then 5925 // splat from elt type to vector. 5926 if (SrcTy->isPointerType()) 5927 return Diag(R.getBegin(), 5928 diag::err_invalid_conversion_between_vector_and_scalar) 5929 << DestTy << SrcTy << R; 5930 5931 Kind = CK_VectorSplat; 5932 return prepareVectorSplat(DestTy, CastExpr); 5933 } 5934 5935 ExprResult 5936 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5937 Declarator &D, ParsedType &Ty, 5938 SourceLocation RParenLoc, Expr *CastExpr) { 5939 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5940 "ActOnCastExpr(): missing type or expr"); 5941 5942 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5943 if (D.isInvalidType()) 5944 return ExprError(); 5945 5946 if (getLangOpts().CPlusPlus) { 5947 // Check that there are no default arguments (C++ only). 5948 CheckExtraCXXDefaultArguments(D); 5949 } else { 5950 // Make sure any TypoExprs have been dealt with. 5951 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5952 if (!Res.isUsable()) 5953 return ExprError(); 5954 CastExpr = Res.get(); 5955 } 5956 5957 checkUnusedDeclAttributes(D); 5958 5959 QualType castType = castTInfo->getType(); 5960 Ty = CreateParsedType(castType, castTInfo); 5961 5962 bool isVectorLiteral = false; 5963 5964 // Check for an altivec or OpenCL literal, 5965 // i.e. all the elements are integer constants. 5966 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5967 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5968 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5969 && castType->isVectorType() && (PE || PLE)) { 5970 if (PLE && PLE->getNumExprs() == 0) { 5971 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5972 return ExprError(); 5973 } 5974 if (PE || PLE->getNumExprs() == 1) { 5975 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5976 if (!E->getType()->isVectorType()) 5977 isVectorLiteral = true; 5978 } 5979 else 5980 isVectorLiteral = true; 5981 } 5982 5983 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5984 // then handle it as such. 5985 if (isVectorLiteral) 5986 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5987 5988 // If the Expr being casted is a ParenListExpr, handle it specially. 5989 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5990 // sequence of BinOp comma operators. 5991 if (isa<ParenListExpr>(CastExpr)) { 5992 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5993 if (Result.isInvalid()) return ExprError(); 5994 CastExpr = Result.get(); 5995 } 5996 5997 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5998 !getSourceManager().isInSystemMacro(LParenLoc)) 5999 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6000 6001 CheckTollFreeBridgeCast(castType, CastExpr); 6002 6003 CheckObjCBridgeRelatedCast(castType, CastExpr); 6004 6005 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6006 } 6007 6008 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6009 SourceLocation RParenLoc, Expr *E, 6010 TypeSourceInfo *TInfo) { 6011 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6012 "Expected paren or paren list expression"); 6013 6014 Expr **exprs; 6015 unsigned numExprs; 6016 Expr *subExpr; 6017 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6018 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6019 LiteralLParenLoc = PE->getLParenLoc(); 6020 LiteralRParenLoc = PE->getRParenLoc(); 6021 exprs = PE->getExprs(); 6022 numExprs = PE->getNumExprs(); 6023 } else { // isa<ParenExpr> by assertion at function entrance 6024 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6025 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6026 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6027 exprs = &subExpr; 6028 numExprs = 1; 6029 } 6030 6031 QualType Ty = TInfo->getType(); 6032 assert(Ty->isVectorType() && "Expected vector type"); 6033 6034 SmallVector<Expr *, 8> initExprs; 6035 const VectorType *VTy = Ty->getAs<VectorType>(); 6036 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6037 6038 // '(...)' form of vector initialization in AltiVec: the number of 6039 // initializers must be one or must match the size of the vector. 6040 // If a single value is specified in the initializer then it will be 6041 // replicated to all the components of the vector 6042 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6043 // The number of initializers must be one or must match the size of the 6044 // vector. If a single value is specified in the initializer then it will 6045 // be replicated to all the components of the vector 6046 if (numExprs == 1) { 6047 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6048 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6049 if (Literal.isInvalid()) 6050 return ExprError(); 6051 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6052 PrepareScalarCast(Literal, ElemTy)); 6053 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6054 } 6055 else if (numExprs < numElems) { 6056 Diag(E->getExprLoc(), 6057 diag::err_incorrect_number_of_vector_initializers); 6058 return ExprError(); 6059 } 6060 else 6061 initExprs.append(exprs, exprs + numExprs); 6062 } 6063 else { 6064 // For OpenCL, when the number of initializers is a single value, 6065 // it will be replicated to all components of the vector. 6066 if (getLangOpts().OpenCL && 6067 VTy->getVectorKind() == VectorType::GenericVector && 6068 numExprs == 1) { 6069 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6070 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6071 if (Literal.isInvalid()) 6072 return ExprError(); 6073 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6074 PrepareScalarCast(Literal, ElemTy)); 6075 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6076 } 6077 6078 initExprs.append(exprs, exprs + numExprs); 6079 } 6080 // FIXME: This means that pretty-printing the final AST will produce curly 6081 // braces instead of the original commas. 6082 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6083 initExprs, LiteralRParenLoc); 6084 initE->setType(Ty); 6085 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6086 } 6087 6088 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6089 /// the ParenListExpr into a sequence of comma binary operators. 6090 ExprResult 6091 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6092 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6093 if (!E) 6094 return OrigExpr; 6095 6096 ExprResult Result(E->getExpr(0)); 6097 6098 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6099 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6100 E->getExpr(i)); 6101 6102 if (Result.isInvalid()) return ExprError(); 6103 6104 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6105 } 6106 6107 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6108 SourceLocation R, 6109 MultiExprArg Val) { 6110 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6111 return expr; 6112 } 6113 6114 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6115 /// constant and the other is not a pointer. Returns true if a diagnostic is 6116 /// emitted. 6117 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6118 SourceLocation QuestionLoc) { 6119 Expr *NullExpr = LHSExpr; 6120 Expr *NonPointerExpr = RHSExpr; 6121 Expr::NullPointerConstantKind NullKind = 6122 NullExpr->isNullPointerConstant(Context, 6123 Expr::NPC_ValueDependentIsNotNull); 6124 6125 if (NullKind == Expr::NPCK_NotNull) { 6126 NullExpr = RHSExpr; 6127 NonPointerExpr = LHSExpr; 6128 NullKind = 6129 NullExpr->isNullPointerConstant(Context, 6130 Expr::NPC_ValueDependentIsNotNull); 6131 } 6132 6133 if (NullKind == Expr::NPCK_NotNull) 6134 return false; 6135 6136 if (NullKind == Expr::NPCK_ZeroExpression) 6137 return false; 6138 6139 if (NullKind == Expr::NPCK_ZeroLiteral) { 6140 // In this case, check to make sure that we got here from a "NULL" 6141 // string in the source code. 6142 NullExpr = NullExpr->IgnoreParenImpCasts(); 6143 SourceLocation loc = NullExpr->getExprLoc(); 6144 if (!findMacroSpelling(loc, "NULL")) 6145 return false; 6146 } 6147 6148 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6149 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6150 << NonPointerExpr->getType() << DiagType 6151 << NonPointerExpr->getSourceRange(); 6152 return true; 6153 } 6154 6155 /// \brief Return false if the condition expression is valid, true otherwise. 6156 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6157 QualType CondTy = Cond->getType(); 6158 6159 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6160 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6161 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6162 << CondTy << Cond->getSourceRange(); 6163 return true; 6164 } 6165 6166 // C99 6.5.15p2 6167 if (CondTy->isScalarType()) return false; 6168 6169 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6170 << CondTy << Cond->getSourceRange(); 6171 return true; 6172 } 6173 6174 /// \brief Handle when one or both operands are void type. 6175 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6176 ExprResult &RHS) { 6177 Expr *LHSExpr = LHS.get(); 6178 Expr *RHSExpr = RHS.get(); 6179 6180 if (!LHSExpr->getType()->isVoidType()) 6181 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6182 << RHSExpr->getSourceRange(); 6183 if (!RHSExpr->getType()->isVoidType()) 6184 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6185 << LHSExpr->getSourceRange(); 6186 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6187 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6188 return S.Context.VoidTy; 6189 } 6190 6191 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6192 /// true otherwise. 6193 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6194 QualType PointerTy) { 6195 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6196 !NullExpr.get()->isNullPointerConstant(S.Context, 6197 Expr::NPC_ValueDependentIsNull)) 6198 return true; 6199 6200 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6201 return false; 6202 } 6203 6204 /// \brief Checks compatibility between two pointers and return the resulting 6205 /// type. 6206 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6207 ExprResult &RHS, 6208 SourceLocation Loc) { 6209 QualType LHSTy = LHS.get()->getType(); 6210 QualType RHSTy = RHS.get()->getType(); 6211 6212 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6213 // Two identical pointers types are always compatible. 6214 return LHSTy; 6215 } 6216 6217 QualType lhptee, rhptee; 6218 6219 // Get the pointee types. 6220 bool IsBlockPointer = false; 6221 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6222 lhptee = LHSBTy->getPointeeType(); 6223 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6224 IsBlockPointer = true; 6225 } else { 6226 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6227 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6228 } 6229 6230 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6231 // differently qualified versions of compatible types, the result type is 6232 // a pointer to an appropriately qualified version of the composite 6233 // type. 6234 6235 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6236 // clause doesn't make sense for our extensions. E.g. address space 2 should 6237 // be incompatible with address space 3: they may live on different devices or 6238 // anything. 6239 Qualifiers lhQual = lhptee.getQualifiers(); 6240 Qualifiers rhQual = rhptee.getQualifiers(); 6241 6242 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6243 lhQual.removeCVRQualifiers(); 6244 rhQual.removeCVRQualifiers(); 6245 6246 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6247 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6248 6249 // For OpenCL: 6250 // 1. If LHS and RHS types match exactly and: 6251 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6252 // (b) AS overlap => generate addrspacecast 6253 // (c) AS don't overlap => give an error 6254 // 2. if LHS and RHS types don't match: 6255 // (a) AS match => use standard C rules, generate bitcast 6256 // (b) AS overlap => generate addrspacecast instead of bitcast 6257 // (c) AS don't overlap => give an error 6258 6259 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6260 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6261 6262 // OpenCL cases 1c, 2a, 2b, and 2c. 6263 if (CompositeTy.isNull()) { 6264 // In this situation, we assume void* type. No especially good 6265 // reason, but this is what gcc does, and we do have to pick 6266 // to get a consistent AST. 6267 QualType incompatTy; 6268 if (S.getLangOpts().OpenCL) { 6269 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6270 // spaces is disallowed. 6271 unsigned ResultAddrSpace; 6272 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6273 // Cases 2a and 2b. 6274 ResultAddrSpace = lhQual.getAddressSpace(); 6275 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6276 // Cases 2a and 2b. 6277 ResultAddrSpace = rhQual.getAddressSpace(); 6278 } else { 6279 // Cases 1c and 2c. 6280 S.Diag(Loc, 6281 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6282 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6283 << RHS.get()->getSourceRange(); 6284 return QualType(); 6285 } 6286 6287 // Continue handling cases 2a and 2b. 6288 incompatTy = S.Context.getPointerType( 6289 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6290 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6291 (lhQual.getAddressSpace() != ResultAddrSpace) 6292 ? CK_AddressSpaceConversion /* 2b */ 6293 : CK_BitCast /* 2a */); 6294 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6295 (rhQual.getAddressSpace() != ResultAddrSpace) 6296 ? CK_AddressSpaceConversion /* 2b */ 6297 : CK_BitCast /* 2a */); 6298 } else { 6299 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6300 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6301 << RHS.get()->getSourceRange(); 6302 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6303 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6304 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6305 } 6306 return incompatTy; 6307 } 6308 6309 // The pointer types are compatible. 6310 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6311 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6312 if (IsBlockPointer) 6313 ResultTy = S.Context.getBlockPointerType(ResultTy); 6314 else { 6315 // Cases 1a and 1b for OpenCL. 6316 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6317 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6318 ? CK_BitCast /* 1a */ 6319 : CK_AddressSpaceConversion /* 1b */; 6320 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6321 ? CK_BitCast /* 1a */ 6322 : CK_AddressSpaceConversion /* 1b */; 6323 ResultTy = S.Context.getPointerType(ResultTy); 6324 } 6325 6326 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6327 // if the target type does not change. 6328 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6329 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6330 return ResultTy; 6331 } 6332 6333 /// \brief Return the resulting type when the operands are both block pointers. 6334 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6335 ExprResult &LHS, 6336 ExprResult &RHS, 6337 SourceLocation Loc) { 6338 QualType LHSTy = LHS.get()->getType(); 6339 QualType RHSTy = RHS.get()->getType(); 6340 6341 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6342 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6343 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6344 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6345 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6346 return destType; 6347 } 6348 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6349 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6350 << RHS.get()->getSourceRange(); 6351 return QualType(); 6352 } 6353 6354 // We have 2 block pointer types. 6355 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6356 } 6357 6358 /// \brief Return the resulting type when the operands are both pointers. 6359 static QualType 6360 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6361 ExprResult &RHS, 6362 SourceLocation Loc) { 6363 // get the pointer types 6364 QualType LHSTy = LHS.get()->getType(); 6365 QualType RHSTy = RHS.get()->getType(); 6366 6367 // get the "pointed to" types 6368 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6369 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6370 6371 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6372 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6373 // Figure out necessary qualifiers (C99 6.5.15p6) 6374 QualType destPointee 6375 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6376 QualType destType = S.Context.getPointerType(destPointee); 6377 // Add qualifiers if necessary. 6378 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6379 // Promote to void*. 6380 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6381 return destType; 6382 } 6383 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6384 QualType destPointee 6385 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6386 QualType destType = S.Context.getPointerType(destPointee); 6387 // Add qualifiers if necessary. 6388 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6389 // Promote to void*. 6390 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6391 return destType; 6392 } 6393 6394 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6395 } 6396 6397 /// \brief Return false if the first expression is not an integer and the second 6398 /// expression is not a pointer, true otherwise. 6399 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6400 Expr* PointerExpr, SourceLocation Loc, 6401 bool IsIntFirstExpr) { 6402 if (!PointerExpr->getType()->isPointerType() || 6403 !Int.get()->getType()->isIntegerType()) 6404 return false; 6405 6406 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6407 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6408 6409 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6410 << Expr1->getType() << Expr2->getType() 6411 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6412 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6413 CK_IntegralToPointer); 6414 return true; 6415 } 6416 6417 /// \brief Simple conversion between integer and floating point types. 6418 /// 6419 /// Used when handling the OpenCL conditional operator where the 6420 /// condition is a vector while the other operands are scalar. 6421 /// 6422 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6423 /// types are either integer or floating type. Between the two 6424 /// operands, the type with the higher rank is defined as the "result 6425 /// type". The other operand needs to be promoted to the same type. No 6426 /// other type promotion is allowed. We cannot use 6427 /// UsualArithmeticConversions() for this purpose, since it always 6428 /// promotes promotable types. 6429 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6430 ExprResult &RHS, 6431 SourceLocation QuestionLoc) { 6432 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6433 if (LHS.isInvalid()) 6434 return QualType(); 6435 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6436 if (RHS.isInvalid()) 6437 return QualType(); 6438 6439 // For conversion purposes, we ignore any qualifiers. 6440 // For example, "const float" and "float" are equivalent. 6441 QualType LHSType = 6442 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6443 QualType RHSType = 6444 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6445 6446 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6447 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6448 << LHSType << LHS.get()->getSourceRange(); 6449 return QualType(); 6450 } 6451 6452 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6453 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6454 << RHSType << RHS.get()->getSourceRange(); 6455 return QualType(); 6456 } 6457 6458 // If both types are identical, no conversion is needed. 6459 if (LHSType == RHSType) 6460 return LHSType; 6461 6462 // Now handle "real" floating types (i.e. float, double, long double). 6463 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6464 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6465 /*IsCompAssign = */ false); 6466 6467 // Finally, we have two differing integer types. 6468 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6469 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6470 } 6471 6472 /// \brief Convert scalar operands to a vector that matches the 6473 /// condition in length. 6474 /// 6475 /// Used when handling the OpenCL conditional operator where the 6476 /// condition is a vector while the other operands are scalar. 6477 /// 6478 /// We first compute the "result type" for the scalar operands 6479 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6480 /// into a vector of that type where the length matches the condition 6481 /// vector type. s6.11.6 requires that the element types of the result 6482 /// and the condition must have the same number of bits. 6483 static QualType 6484 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6485 QualType CondTy, SourceLocation QuestionLoc) { 6486 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6487 if (ResTy.isNull()) return QualType(); 6488 6489 const VectorType *CV = CondTy->getAs<VectorType>(); 6490 assert(CV); 6491 6492 // Determine the vector result type 6493 unsigned NumElements = CV->getNumElements(); 6494 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6495 6496 // Ensure that all types have the same number of bits 6497 if (S.Context.getTypeSize(CV->getElementType()) 6498 != S.Context.getTypeSize(ResTy)) { 6499 // Since VectorTy is created internally, it does not pretty print 6500 // with an OpenCL name. Instead, we just print a description. 6501 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6502 SmallString<64> Str; 6503 llvm::raw_svector_ostream OS(Str); 6504 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6505 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6506 << CondTy << OS.str(); 6507 return QualType(); 6508 } 6509 6510 // Convert operands to the vector result type 6511 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6512 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6513 6514 return VectorTy; 6515 } 6516 6517 /// \brief Return false if this is a valid OpenCL condition vector 6518 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6519 SourceLocation QuestionLoc) { 6520 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6521 // integral type. 6522 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6523 assert(CondTy); 6524 QualType EleTy = CondTy->getElementType(); 6525 if (EleTy->isIntegerType()) return false; 6526 6527 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6528 << Cond->getType() << Cond->getSourceRange(); 6529 return true; 6530 } 6531 6532 /// \brief Return false if the vector condition type and the vector 6533 /// result type are compatible. 6534 /// 6535 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6536 /// number of elements, and their element types have the same number 6537 /// of bits. 6538 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6539 SourceLocation QuestionLoc) { 6540 const VectorType *CV = CondTy->getAs<VectorType>(); 6541 const VectorType *RV = VecResTy->getAs<VectorType>(); 6542 assert(CV && RV); 6543 6544 if (CV->getNumElements() != RV->getNumElements()) { 6545 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6546 << CondTy << VecResTy; 6547 return true; 6548 } 6549 6550 QualType CVE = CV->getElementType(); 6551 QualType RVE = RV->getElementType(); 6552 6553 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6554 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6555 << CondTy << VecResTy; 6556 return true; 6557 } 6558 6559 return false; 6560 } 6561 6562 /// \brief Return the resulting type for the conditional operator in 6563 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6564 /// s6.3.i) when the condition is a vector type. 6565 static QualType 6566 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6567 ExprResult &LHS, ExprResult &RHS, 6568 SourceLocation QuestionLoc) { 6569 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6570 if (Cond.isInvalid()) 6571 return QualType(); 6572 QualType CondTy = Cond.get()->getType(); 6573 6574 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6575 return QualType(); 6576 6577 // If either operand is a vector then find the vector type of the 6578 // result as specified in OpenCL v1.1 s6.3.i. 6579 if (LHS.get()->getType()->isVectorType() || 6580 RHS.get()->getType()->isVectorType()) { 6581 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6582 /*isCompAssign*/false, 6583 /*AllowBothBool*/true, 6584 /*AllowBoolConversions*/false); 6585 if (VecResTy.isNull()) return QualType(); 6586 // The result type must match the condition type as specified in 6587 // OpenCL v1.1 s6.11.6. 6588 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6589 return QualType(); 6590 return VecResTy; 6591 } 6592 6593 // Both operands are scalar. 6594 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6595 } 6596 6597 /// \brief Return true if the Expr is block type 6598 static bool checkBlockType(Sema &S, const Expr *E) { 6599 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6600 QualType Ty = CE->getCallee()->getType(); 6601 if (Ty->isBlockPointerType()) { 6602 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6603 return true; 6604 } 6605 } 6606 return false; 6607 } 6608 6609 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6610 /// In that case, LHS = cond. 6611 /// C99 6.5.15 6612 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6613 ExprResult &RHS, ExprValueKind &VK, 6614 ExprObjectKind &OK, 6615 SourceLocation QuestionLoc) { 6616 6617 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6618 if (!LHSResult.isUsable()) return QualType(); 6619 LHS = LHSResult; 6620 6621 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6622 if (!RHSResult.isUsable()) return QualType(); 6623 RHS = RHSResult; 6624 6625 // C++ is sufficiently different to merit its own checker. 6626 if (getLangOpts().CPlusPlus) 6627 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6628 6629 VK = VK_RValue; 6630 OK = OK_Ordinary; 6631 6632 // The OpenCL operator with a vector condition is sufficiently 6633 // different to merit its own checker. 6634 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6635 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6636 6637 // First, check the condition. 6638 Cond = UsualUnaryConversions(Cond.get()); 6639 if (Cond.isInvalid()) 6640 return QualType(); 6641 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6642 return QualType(); 6643 6644 // Now check the two expressions. 6645 if (LHS.get()->getType()->isVectorType() || 6646 RHS.get()->getType()->isVectorType()) 6647 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6648 /*AllowBothBool*/true, 6649 /*AllowBoolConversions*/false); 6650 6651 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6652 if (LHS.isInvalid() || RHS.isInvalid()) 6653 return QualType(); 6654 6655 QualType LHSTy = LHS.get()->getType(); 6656 QualType RHSTy = RHS.get()->getType(); 6657 6658 // Diagnose attempts to convert between __float128 and long double where 6659 // such conversions currently can't be handled. 6660 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6661 Diag(QuestionLoc, 6662 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6663 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6664 return QualType(); 6665 } 6666 6667 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6668 // selection operator (?:). 6669 if (getLangOpts().OpenCL && 6670 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6671 return QualType(); 6672 } 6673 6674 // If both operands have arithmetic type, do the usual arithmetic conversions 6675 // to find a common type: C99 6.5.15p3,5. 6676 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6677 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6678 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6679 6680 return ResTy; 6681 } 6682 6683 // If both operands are the same structure or union type, the result is that 6684 // type. 6685 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6686 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6687 if (LHSRT->getDecl() == RHSRT->getDecl()) 6688 // "If both the operands have structure or union type, the result has 6689 // that type." This implies that CV qualifiers are dropped. 6690 return LHSTy.getUnqualifiedType(); 6691 // FIXME: Type of conditional expression must be complete in C mode. 6692 } 6693 6694 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6695 // The following || allows only one side to be void (a GCC-ism). 6696 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6697 return checkConditionalVoidType(*this, LHS, RHS); 6698 } 6699 6700 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6701 // the type of the other operand." 6702 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6703 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6704 6705 // All objective-c pointer type analysis is done here. 6706 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6707 QuestionLoc); 6708 if (LHS.isInvalid() || RHS.isInvalid()) 6709 return QualType(); 6710 if (!compositeType.isNull()) 6711 return compositeType; 6712 6713 6714 // Handle block pointer types. 6715 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6716 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6717 QuestionLoc); 6718 6719 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6720 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6721 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6722 QuestionLoc); 6723 6724 // GCC compatibility: soften pointer/integer mismatch. Note that 6725 // null pointers have been filtered out by this point. 6726 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6727 /*isIntFirstExpr=*/true)) 6728 return RHSTy; 6729 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6730 /*isIntFirstExpr=*/false)) 6731 return LHSTy; 6732 6733 // Emit a better diagnostic if one of the expressions is a null pointer 6734 // constant and the other is not a pointer type. In this case, the user most 6735 // likely forgot to take the address of the other expression. 6736 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6737 return QualType(); 6738 6739 // Otherwise, the operands are not compatible. 6740 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6741 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6742 << RHS.get()->getSourceRange(); 6743 return QualType(); 6744 } 6745 6746 /// FindCompositeObjCPointerType - Helper method to find composite type of 6747 /// two objective-c pointer types of the two input expressions. 6748 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6749 SourceLocation QuestionLoc) { 6750 QualType LHSTy = LHS.get()->getType(); 6751 QualType RHSTy = RHS.get()->getType(); 6752 6753 // Handle things like Class and struct objc_class*. Here we case the result 6754 // to the pseudo-builtin, because that will be implicitly cast back to the 6755 // redefinition type if an attempt is made to access its fields. 6756 if (LHSTy->isObjCClassType() && 6757 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6758 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6759 return LHSTy; 6760 } 6761 if (RHSTy->isObjCClassType() && 6762 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6763 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6764 return RHSTy; 6765 } 6766 // And the same for struct objc_object* / id 6767 if (LHSTy->isObjCIdType() && 6768 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6769 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6770 return LHSTy; 6771 } 6772 if (RHSTy->isObjCIdType() && 6773 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6774 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6775 return RHSTy; 6776 } 6777 // And the same for struct objc_selector* / SEL 6778 if (Context.isObjCSelType(LHSTy) && 6779 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6780 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6781 return LHSTy; 6782 } 6783 if (Context.isObjCSelType(RHSTy) && 6784 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6785 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6786 return RHSTy; 6787 } 6788 // Check constraints for Objective-C object pointers types. 6789 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6790 6791 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6792 // Two identical object pointer types are always compatible. 6793 return LHSTy; 6794 } 6795 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6796 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6797 QualType compositeType = LHSTy; 6798 6799 // If both operands are interfaces and either operand can be 6800 // assigned to the other, use that type as the composite 6801 // type. This allows 6802 // xxx ? (A*) a : (B*) b 6803 // where B is a subclass of A. 6804 // 6805 // Additionally, as for assignment, if either type is 'id' 6806 // allow silent coercion. Finally, if the types are 6807 // incompatible then make sure to use 'id' as the composite 6808 // type so the result is acceptable for sending messages to. 6809 6810 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6811 // It could return the composite type. 6812 if (!(compositeType = 6813 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6814 // Nothing more to do. 6815 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6816 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6817 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6818 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6819 } else if ((LHSTy->isObjCQualifiedIdType() || 6820 RHSTy->isObjCQualifiedIdType()) && 6821 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6822 // Need to handle "id<xx>" explicitly. 6823 // GCC allows qualified id and any Objective-C type to devolve to 6824 // id. Currently localizing to here until clear this should be 6825 // part of ObjCQualifiedIdTypesAreCompatible. 6826 compositeType = Context.getObjCIdType(); 6827 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6828 compositeType = Context.getObjCIdType(); 6829 } else { 6830 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6831 << LHSTy << RHSTy 6832 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6833 QualType incompatTy = Context.getObjCIdType(); 6834 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6835 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6836 return incompatTy; 6837 } 6838 // The object pointer types are compatible. 6839 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6840 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6841 return compositeType; 6842 } 6843 // Check Objective-C object pointer types and 'void *' 6844 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6845 if (getLangOpts().ObjCAutoRefCount) { 6846 // ARC forbids the implicit conversion of object pointers to 'void *', 6847 // so these types are not compatible. 6848 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6849 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6850 LHS = RHS = true; 6851 return QualType(); 6852 } 6853 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6854 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6855 QualType destPointee 6856 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6857 QualType destType = Context.getPointerType(destPointee); 6858 // Add qualifiers if necessary. 6859 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6860 // Promote to void*. 6861 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6862 return destType; 6863 } 6864 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6865 if (getLangOpts().ObjCAutoRefCount) { 6866 // ARC forbids the implicit conversion of object pointers to 'void *', 6867 // so these types are not compatible. 6868 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6869 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6870 LHS = RHS = true; 6871 return QualType(); 6872 } 6873 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6874 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6875 QualType destPointee 6876 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6877 QualType destType = Context.getPointerType(destPointee); 6878 // Add qualifiers if necessary. 6879 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6880 // Promote to void*. 6881 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6882 return destType; 6883 } 6884 return QualType(); 6885 } 6886 6887 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6888 /// ParenRange in parentheses. 6889 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6890 const PartialDiagnostic &Note, 6891 SourceRange ParenRange) { 6892 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6893 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6894 EndLoc.isValid()) { 6895 Self.Diag(Loc, Note) 6896 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6897 << FixItHint::CreateInsertion(EndLoc, ")"); 6898 } else { 6899 // We can't display the parentheses, so just show the bare note. 6900 Self.Diag(Loc, Note) << ParenRange; 6901 } 6902 } 6903 6904 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6905 return BinaryOperator::isAdditiveOp(Opc) || 6906 BinaryOperator::isMultiplicativeOp(Opc) || 6907 BinaryOperator::isShiftOp(Opc); 6908 } 6909 6910 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6911 /// expression, either using a built-in or overloaded operator, 6912 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6913 /// expression. 6914 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6915 Expr **RHSExprs) { 6916 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6917 E = E->IgnoreImpCasts(); 6918 E = E->IgnoreConversionOperator(); 6919 E = E->IgnoreImpCasts(); 6920 6921 // Built-in binary operator. 6922 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6923 if (IsArithmeticOp(OP->getOpcode())) { 6924 *Opcode = OP->getOpcode(); 6925 *RHSExprs = OP->getRHS(); 6926 return true; 6927 } 6928 } 6929 6930 // Overloaded operator. 6931 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6932 if (Call->getNumArgs() != 2) 6933 return false; 6934 6935 // Make sure this is really a binary operator that is safe to pass into 6936 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6937 OverloadedOperatorKind OO = Call->getOperator(); 6938 if (OO < OO_Plus || OO > OO_Arrow || 6939 OO == OO_PlusPlus || OO == OO_MinusMinus) 6940 return false; 6941 6942 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6943 if (IsArithmeticOp(OpKind)) { 6944 *Opcode = OpKind; 6945 *RHSExprs = Call->getArg(1); 6946 return true; 6947 } 6948 } 6949 6950 return false; 6951 } 6952 6953 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6954 /// or is a logical expression such as (x==y) which has int type, but is 6955 /// commonly interpreted as boolean. 6956 static bool ExprLooksBoolean(Expr *E) { 6957 E = E->IgnoreParenImpCasts(); 6958 6959 if (E->getType()->isBooleanType()) 6960 return true; 6961 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6962 return OP->isComparisonOp() || OP->isLogicalOp(); 6963 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6964 return OP->getOpcode() == UO_LNot; 6965 if (E->getType()->isPointerType()) 6966 return true; 6967 6968 return false; 6969 } 6970 6971 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6972 /// and binary operator are mixed in a way that suggests the programmer assumed 6973 /// the conditional operator has higher precedence, for example: 6974 /// "int x = a + someBinaryCondition ? 1 : 2". 6975 static void DiagnoseConditionalPrecedence(Sema &Self, 6976 SourceLocation OpLoc, 6977 Expr *Condition, 6978 Expr *LHSExpr, 6979 Expr *RHSExpr) { 6980 BinaryOperatorKind CondOpcode; 6981 Expr *CondRHS; 6982 6983 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6984 return; 6985 if (!ExprLooksBoolean(CondRHS)) 6986 return; 6987 6988 // The condition is an arithmetic binary expression, with a right- 6989 // hand side that looks boolean, so warn. 6990 6991 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6992 << Condition->getSourceRange() 6993 << BinaryOperator::getOpcodeStr(CondOpcode); 6994 6995 SuggestParentheses(Self, OpLoc, 6996 Self.PDiag(diag::note_precedence_silence) 6997 << BinaryOperator::getOpcodeStr(CondOpcode), 6998 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6999 7000 SuggestParentheses(Self, OpLoc, 7001 Self.PDiag(diag::note_precedence_conditional_first), 7002 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7003 } 7004 7005 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7006 /// in the case of a the GNU conditional expr extension. 7007 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7008 SourceLocation ColonLoc, 7009 Expr *CondExpr, Expr *LHSExpr, 7010 Expr *RHSExpr) { 7011 if (!getLangOpts().CPlusPlus) { 7012 // C cannot handle TypoExpr nodes in the condition because it 7013 // doesn't handle dependent types properly, so make sure any TypoExprs have 7014 // been dealt with before checking the operands. 7015 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7016 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7017 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7018 7019 if (!CondResult.isUsable()) 7020 return ExprError(); 7021 7022 if (LHSExpr) { 7023 if (!LHSResult.isUsable()) 7024 return ExprError(); 7025 } 7026 7027 if (!RHSResult.isUsable()) 7028 return ExprError(); 7029 7030 CondExpr = CondResult.get(); 7031 LHSExpr = LHSResult.get(); 7032 RHSExpr = RHSResult.get(); 7033 } 7034 7035 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7036 // was the condition. 7037 OpaqueValueExpr *opaqueValue = nullptr; 7038 Expr *commonExpr = nullptr; 7039 if (!LHSExpr) { 7040 commonExpr = CondExpr; 7041 // Lower out placeholder types first. This is important so that we don't 7042 // try to capture a placeholder. This happens in few cases in C++; such 7043 // as Objective-C++'s dictionary subscripting syntax. 7044 if (commonExpr->hasPlaceholderType()) { 7045 ExprResult result = CheckPlaceholderExpr(commonExpr); 7046 if (!result.isUsable()) return ExprError(); 7047 commonExpr = result.get(); 7048 } 7049 // We usually want to apply unary conversions *before* saving, except 7050 // in the special case of a C++ l-value conditional. 7051 if (!(getLangOpts().CPlusPlus 7052 && !commonExpr->isTypeDependent() 7053 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7054 && commonExpr->isGLValue() 7055 && commonExpr->isOrdinaryOrBitFieldObject() 7056 && RHSExpr->isOrdinaryOrBitFieldObject() 7057 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7058 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7059 if (commonRes.isInvalid()) 7060 return ExprError(); 7061 commonExpr = commonRes.get(); 7062 } 7063 7064 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7065 commonExpr->getType(), 7066 commonExpr->getValueKind(), 7067 commonExpr->getObjectKind(), 7068 commonExpr); 7069 LHSExpr = CondExpr = opaqueValue; 7070 } 7071 7072 ExprValueKind VK = VK_RValue; 7073 ExprObjectKind OK = OK_Ordinary; 7074 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7075 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7076 VK, OK, QuestionLoc); 7077 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7078 RHS.isInvalid()) 7079 return ExprError(); 7080 7081 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7082 RHS.get()); 7083 7084 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7085 7086 if (!commonExpr) 7087 return new (Context) 7088 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7089 RHS.get(), result, VK, OK); 7090 7091 return new (Context) BinaryConditionalOperator( 7092 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7093 ColonLoc, result, VK, OK); 7094 } 7095 7096 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7097 // being closely modeled after the C99 spec:-). The odd characteristic of this 7098 // routine is it effectively iqnores the qualifiers on the top level pointee. 7099 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7100 // FIXME: add a couple examples in this comment. 7101 static Sema::AssignConvertType 7102 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7103 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7104 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7105 7106 // get the "pointed to" type (ignoring qualifiers at the top level) 7107 const Type *lhptee, *rhptee; 7108 Qualifiers lhq, rhq; 7109 std::tie(lhptee, lhq) = 7110 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7111 std::tie(rhptee, rhq) = 7112 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7113 7114 Sema::AssignConvertType ConvTy = Sema::Compatible; 7115 7116 // C99 6.5.16.1p1: This following citation is common to constraints 7117 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7118 // qualifiers of the type *pointed to* by the right; 7119 7120 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7121 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7122 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7123 // Ignore lifetime for further calculation. 7124 lhq.removeObjCLifetime(); 7125 rhq.removeObjCLifetime(); 7126 } 7127 7128 if (!lhq.compatiblyIncludes(rhq)) { 7129 // Treat address-space mismatches as fatal. TODO: address subspaces 7130 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7131 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7132 7133 // It's okay to add or remove GC or lifetime qualifiers when converting to 7134 // and from void*. 7135 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7136 .compatiblyIncludes( 7137 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7138 && (lhptee->isVoidType() || rhptee->isVoidType())) 7139 ; // keep old 7140 7141 // Treat lifetime mismatches as fatal. 7142 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7143 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7144 7145 // For GCC/MS compatibility, other qualifier mismatches are treated 7146 // as still compatible in C. 7147 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7148 } 7149 7150 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7151 // incomplete type and the other is a pointer to a qualified or unqualified 7152 // version of void... 7153 if (lhptee->isVoidType()) { 7154 if (rhptee->isIncompleteOrObjectType()) 7155 return ConvTy; 7156 7157 // As an extension, we allow cast to/from void* to function pointer. 7158 assert(rhptee->isFunctionType()); 7159 return Sema::FunctionVoidPointer; 7160 } 7161 7162 if (rhptee->isVoidType()) { 7163 if (lhptee->isIncompleteOrObjectType()) 7164 return ConvTy; 7165 7166 // As an extension, we allow cast to/from void* to function pointer. 7167 assert(lhptee->isFunctionType()); 7168 return Sema::FunctionVoidPointer; 7169 } 7170 7171 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7172 // unqualified versions of compatible types, ... 7173 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7174 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7175 // Check if the pointee types are compatible ignoring the sign. 7176 // We explicitly check for char so that we catch "char" vs 7177 // "unsigned char" on systems where "char" is unsigned. 7178 if (lhptee->isCharType()) 7179 ltrans = S.Context.UnsignedCharTy; 7180 else if (lhptee->hasSignedIntegerRepresentation()) 7181 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7182 7183 if (rhptee->isCharType()) 7184 rtrans = S.Context.UnsignedCharTy; 7185 else if (rhptee->hasSignedIntegerRepresentation()) 7186 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7187 7188 if (ltrans == rtrans) { 7189 // Types are compatible ignoring the sign. Qualifier incompatibility 7190 // takes priority over sign incompatibility because the sign 7191 // warning can be disabled. 7192 if (ConvTy != Sema::Compatible) 7193 return ConvTy; 7194 7195 return Sema::IncompatiblePointerSign; 7196 } 7197 7198 // If we are a multi-level pointer, it's possible that our issue is simply 7199 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7200 // the eventual target type is the same and the pointers have the same 7201 // level of indirection, this must be the issue. 7202 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7203 do { 7204 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7205 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7206 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7207 7208 if (lhptee == rhptee) 7209 return Sema::IncompatibleNestedPointerQualifiers; 7210 } 7211 7212 // General pointer incompatibility takes priority over qualifiers. 7213 return Sema::IncompatiblePointer; 7214 } 7215 if (!S.getLangOpts().CPlusPlus && 7216 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7217 return Sema::IncompatiblePointer; 7218 return ConvTy; 7219 } 7220 7221 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7222 /// block pointer types are compatible or whether a block and normal pointer 7223 /// are compatible. It is more restrict than comparing two function pointer 7224 // types. 7225 static Sema::AssignConvertType 7226 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7227 QualType RHSType) { 7228 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7229 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7230 7231 QualType lhptee, rhptee; 7232 7233 // get the "pointed to" type (ignoring qualifiers at the top level) 7234 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7235 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7236 7237 // In C++, the types have to match exactly. 7238 if (S.getLangOpts().CPlusPlus) 7239 return Sema::IncompatibleBlockPointer; 7240 7241 Sema::AssignConvertType ConvTy = Sema::Compatible; 7242 7243 // For blocks we enforce that qualifiers are identical. 7244 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7245 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7246 7247 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7248 return Sema::IncompatibleBlockPointer; 7249 7250 return ConvTy; 7251 } 7252 7253 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7254 /// for assignment compatibility. 7255 static Sema::AssignConvertType 7256 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7257 QualType RHSType) { 7258 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7259 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7260 7261 if (LHSType->isObjCBuiltinType()) { 7262 // Class is not compatible with ObjC object pointers. 7263 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7264 !RHSType->isObjCQualifiedClassType()) 7265 return Sema::IncompatiblePointer; 7266 return Sema::Compatible; 7267 } 7268 if (RHSType->isObjCBuiltinType()) { 7269 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7270 !LHSType->isObjCQualifiedClassType()) 7271 return Sema::IncompatiblePointer; 7272 return Sema::Compatible; 7273 } 7274 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7275 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7276 7277 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7278 // make an exception for id<P> 7279 !LHSType->isObjCQualifiedIdType()) 7280 return Sema::CompatiblePointerDiscardsQualifiers; 7281 7282 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7283 return Sema::Compatible; 7284 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7285 return Sema::IncompatibleObjCQualifiedId; 7286 return Sema::IncompatiblePointer; 7287 } 7288 7289 Sema::AssignConvertType 7290 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7291 QualType LHSType, QualType RHSType) { 7292 // Fake up an opaque expression. We don't actually care about what 7293 // cast operations are required, so if CheckAssignmentConstraints 7294 // adds casts to this they'll be wasted, but fortunately that doesn't 7295 // usually happen on valid code. 7296 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7297 ExprResult RHSPtr = &RHSExpr; 7298 CastKind K = CK_Invalid; 7299 7300 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7301 } 7302 7303 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7304 /// has code to accommodate several GCC extensions when type checking 7305 /// pointers. Here are some objectionable examples that GCC considers warnings: 7306 /// 7307 /// int a, *pint; 7308 /// short *pshort; 7309 /// struct foo *pfoo; 7310 /// 7311 /// pint = pshort; // warning: assignment from incompatible pointer type 7312 /// a = pint; // warning: assignment makes integer from pointer without a cast 7313 /// pint = a; // warning: assignment makes pointer from integer without a cast 7314 /// pint = pfoo; // warning: assignment from incompatible pointer type 7315 /// 7316 /// As a result, the code for dealing with pointers is more complex than the 7317 /// C99 spec dictates. 7318 /// 7319 /// Sets 'Kind' for any result kind except Incompatible. 7320 Sema::AssignConvertType 7321 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7322 CastKind &Kind, bool ConvertRHS) { 7323 QualType RHSType = RHS.get()->getType(); 7324 QualType OrigLHSType = LHSType; 7325 7326 // Get canonical types. We're not formatting these types, just comparing 7327 // them. 7328 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7329 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7330 7331 // Common case: no conversion required. 7332 if (LHSType == RHSType) { 7333 Kind = CK_NoOp; 7334 return Compatible; 7335 } 7336 7337 // If we have an atomic type, try a non-atomic assignment, then just add an 7338 // atomic qualification step. 7339 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7340 Sema::AssignConvertType result = 7341 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7342 if (result != Compatible) 7343 return result; 7344 if (Kind != CK_NoOp && ConvertRHS) 7345 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7346 Kind = CK_NonAtomicToAtomic; 7347 return Compatible; 7348 } 7349 7350 // If the left-hand side is a reference type, then we are in a 7351 // (rare!) case where we've allowed the use of references in C, 7352 // e.g., as a parameter type in a built-in function. In this case, 7353 // just make sure that the type referenced is compatible with the 7354 // right-hand side type. The caller is responsible for adjusting 7355 // LHSType so that the resulting expression does not have reference 7356 // type. 7357 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7358 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7359 Kind = CK_LValueBitCast; 7360 return Compatible; 7361 } 7362 return Incompatible; 7363 } 7364 7365 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7366 // to the same ExtVector type. 7367 if (LHSType->isExtVectorType()) { 7368 if (RHSType->isExtVectorType()) 7369 return Incompatible; 7370 if (RHSType->isArithmeticType()) { 7371 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7372 if (ConvertRHS) 7373 RHS = prepareVectorSplat(LHSType, RHS.get()); 7374 Kind = CK_VectorSplat; 7375 return Compatible; 7376 } 7377 } 7378 7379 // Conversions to or from vector type. 7380 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7381 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7382 // Allow assignments of an AltiVec vector type to an equivalent GCC 7383 // vector type and vice versa 7384 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7385 Kind = CK_BitCast; 7386 return Compatible; 7387 } 7388 7389 // If we are allowing lax vector conversions, and LHS and RHS are both 7390 // vectors, the total size only needs to be the same. This is a bitcast; 7391 // no bits are changed but the result type is different. 7392 if (isLaxVectorConversion(RHSType, LHSType)) { 7393 Kind = CK_BitCast; 7394 return IncompatibleVectors; 7395 } 7396 } 7397 return Incompatible; 7398 } 7399 7400 // Diagnose attempts to convert between __float128 and long double where 7401 // such conversions currently can't be handled. 7402 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7403 return Incompatible; 7404 7405 // Arithmetic conversions. 7406 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7407 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7408 if (ConvertRHS) 7409 Kind = PrepareScalarCast(RHS, LHSType); 7410 return Compatible; 7411 } 7412 7413 // Conversions to normal pointers. 7414 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7415 // U* -> T* 7416 if (isa<PointerType>(RHSType)) { 7417 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7418 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7419 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7420 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7421 } 7422 7423 // int -> T* 7424 if (RHSType->isIntegerType()) { 7425 Kind = CK_IntegralToPointer; // FIXME: null? 7426 return IntToPointer; 7427 } 7428 7429 // C pointers are not compatible with ObjC object pointers, 7430 // with two exceptions: 7431 if (isa<ObjCObjectPointerType>(RHSType)) { 7432 // - conversions to void* 7433 if (LHSPointer->getPointeeType()->isVoidType()) { 7434 Kind = CK_BitCast; 7435 return Compatible; 7436 } 7437 7438 // - conversions from 'Class' to the redefinition type 7439 if (RHSType->isObjCClassType() && 7440 Context.hasSameType(LHSType, 7441 Context.getObjCClassRedefinitionType())) { 7442 Kind = CK_BitCast; 7443 return Compatible; 7444 } 7445 7446 Kind = CK_BitCast; 7447 return IncompatiblePointer; 7448 } 7449 7450 // U^ -> void* 7451 if (RHSType->getAs<BlockPointerType>()) { 7452 if (LHSPointer->getPointeeType()->isVoidType()) { 7453 Kind = CK_BitCast; 7454 return Compatible; 7455 } 7456 } 7457 7458 return Incompatible; 7459 } 7460 7461 // Conversions to block pointers. 7462 if (isa<BlockPointerType>(LHSType)) { 7463 // U^ -> T^ 7464 if (RHSType->isBlockPointerType()) { 7465 Kind = CK_BitCast; 7466 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7467 } 7468 7469 // int or null -> T^ 7470 if (RHSType->isIntegerType()) { 7471 Kind = CK_IntegralToPointer; // FIXME: null 7472 return IntToBlockPointer; 7473 } 7474 7475 // id -> T^ 7476 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7477 Kind = CK_AnyPointerToBlockPointerCast; 7478 return Compatible; 7479 } 7480 7481 // void* -> T^ 7482 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7483 if (RHSPT->getPointeeType()->isVoidType()) { 7484 Kind = CK_AnyPointerToBlockPointerCast; 7485 return Compatible; 7486 } 7487 7488 return Incompatible; 7489 } 7490 7491 // Conversions to Objective-C pointers. 7492 if (isa<ObjCObjectPointerType>(LHSType)) { 7493 // A* -> B* 7494 if (RHSType->isObjCObjectPointerType()) { 7495 Kind = CK_BitCast; 7496 Sema::AssignConvertType result = 7497 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7498 if (getLangOpts().ObjCAutoRefCount && 7499 result == Compatible && 7500 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7501 result = IncompatibleObjCWeakRef; 7502 return result; 7503 } 7504 7505 // int or null -> A* 7506 if (RHSType->isIntegerType()) { 7507 Kind = CK_IntegralToPointer; // FIXME: null 7508 return IntToPointer; 7509 } 7510 7511 // In general, C pointers are not compatible with ObjC object pointers, 7512 // with two exceptions: 7513 if (isa<PointerType>(RHSType)) { 7514 Kind = CK_CPointerToObjCPointerCast; 7515 7516 // - conversions from 'void*' 7517 if (RHSType->isVoidPointerType()) { 7518 return Compatible; 7519 } 7520 7521 // - conversions to 'Class' from its redefinition type 7522 if (LHSType->isObjCClassType() && 7523 Context.hasSameType(RHSType, 7524 Context.getObjCClassRedefinitionType())) { 7525 return Compatible; 7526 } 7527 7528 return IncompatiblePointer; 7529 } 7530 7531 // Only under strict condition T^ is compatible with an Objective-C pointer. 7532 if (RHSType->isBlockPointerType() && 7533 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7534 if (ConvertRHS) 7535 maybeExtendBlockObject(RHS); 7536 Kind = CK_BlockPointerToObjCPointerCast; 7537 return Compatible; 7538 } 7539 7540 return Incompatible; 7541 } 7542 7543 // Conversions from pointers that are not covered by the above. 7544 if (isa<PointerType>(RHSType)) { 7545 // T* -> _Bool 7546 if (LHSType == Context.BoolTy) { 7547 Kind = CK_PointerToBoolean; 7548 return Compatible; 7549 } 7550 7551 // T* -> int 7552 if (LHSType->isIntegerType()) { 7553 Kind = CK_PointerToIntegral; 7554 return PointerToInt; 7555 } 7556 7557 return Incompatible; 7558 } 7559 7560 // Conversions from Objective-C pointers that are not covered by the above. 7561 if (isa<ObjCObjectPointerType>(RHSType)) { 7562 // T* -> _Bool 7563 if (LHSType == Context.BoolTy) { 7564 Kind = CK_PointerToBoolean; 7565 return Compatible; 7566 } 7567 7568 // T* -> int 7569 if (LHSType->isIntegerType()) { 7570 Kind = CK_PointerToIntegral; 7571 return PointerToInt; 7572 } 7573 7574 return Incompatible; 7575 } 7576 7577 // struct A -> struct B 7578 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7579 if (Context.typesAreCompatible(LHSType, RHSType)) { 7580 Kind = CK_NoOp; 7581 return Compatible; 7582 } 7583 } 7584 7585 return Incompatible; 7586 } 7587 7588 /// \brief Constructs a transparent union from an expression that is 7589 /// used to initialize the transparent union. 7590 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7591 ExprResult &EResult, QualType UnionType, 7592 FieldDecl *Field) { 7593 // Build an initializer list that designates the appropriate member 7594 // of the transparent union. 7595 Expr *E = EResult.get(); 7596 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7597 E, SourceLocation()); 7598 Initializer->setType(UnionType); 7599 Initializer->setInitializedFieldInUnion(Field); 7600 7601 // Build a compound literal constructing a value of the transparent 7602 // union type from this initializer list. 7603 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7604 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7605 VK_RValue, Initializer, false); 7606 } 7607 7608 Sema::AssignConvertType 7609 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7610 ExprResult &RHS) { 7611 QualType RHSType = RHS.get()->getType(); 7612 7613 // If the ArgType is a Union type, we want to handle a potential 7614 // transparent_union GCC extension. 7615 const RecordType *UT = ArgType->getAsUnionType(); 7616 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7617 return Incompatible; 7618 7619 // The field to initialize within the transparent union. 7620 RecordDecl *UD = UT->getDecl(); 7621 FieldDecl *InitField = nullptr; 7622 // It's compatible if the expression matches any of the fields. 7623 for (auto *it : UD->fields()) { 7624 if (it->getType()->isPointerType()) { 7625 // If the transparent union contains a pointer type, we allow: 7626 // 1) void pointer 7627 // 2) null pointer constant 7628 if (RHSType->isPointerType()) 7629 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7630 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7631 InitField = it; 7632 break; 7633 } 7634 7635 if (RHS.get()->isNullPointerConstant(Context, 7636 Expr::NPC_ValueDependentIsNull)) { 7637 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7638 CK_NullToPointer); 7639 InitField = it; 7640 break; 7641 } 7642 } 7643 7644 CastKind Kind = CK_Invalid; 7645 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7646 == Compatible) { 7647 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7648 InitField = it; 7649 break; 7650 } 7651 } 7652 7653 if (!InitField) 7654 return Incompatible; 7655 7656 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7657 return Compatible; 7658 } 7659 7660 Sema::AssignConvertType 7661 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7662 bool Diagnose, 7663 bool DiagnoseCFAudited, 7664 bool ConvertRHS) { 7665 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7666 // we can't avoid *all* modifications at the moment, so we need some somewhere 7667 // to put the updated value. 7668 ExprResult LocalRHS = CallerRHS; 7669 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7670 7671 if (getLangOpts().CPlusPlus) { 7672 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7673 // C++ 5.17p3: If the left operand is not of class type, the 7674 // expression is implicitly converted (C++ 4) to the 7675 // cv-unqualified type of the left operand. 7676 ExprResult Res; 7677 if (Diagnose) { 7678 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7679 AA_Assigning); 7680 } else { 7681 ImplicitConversionSequence ICS = 7682 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7683 /*SuppressUserConversions=*/false, 7684 /*AllowExplicit=*/false, 7685 /*InOverloadResolution=*/false, 7686 /*CStyle=*/false, 7687 /*AllowObjCWritebackConversion=*/false); 7688 if (ICS.isFailure()) 7689 return Incompatible; 7690 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7691 ICS, AA_Assigning); 7692 } 7693 if (Res.isInvalid()) 7694 return Incompatible; 7695 Sema::AssignConvertType result = Compatible; 7696 if (getLangOpts().ObjCAutoRefCount && 7697 !CheckObjCARCUnavailableWeakConversion(LHSType, 7698 RHS.get()->getType())) 7699 result = IncompatibleObjCWeakRef; 7700 RHS = Res; 7701 return result; 7702 } 7703 7704 // FIXME: Currently, we fall through and treat C++ classes like C 7705 // structures. 7706 // FIXME: We also fall through for atomics; not sure what should 7707 // happen there, though. 7708 } else if (RHS.get()->getType() == Context.OverloadTy) { 7709 // As a set of extensions to C, we support overloading on functions. These 7710 // functions need to be resolved here. 7711 DeclAccessPair DAP; 7712 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7713 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7714 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7715 else 7716 return Incompatible; 7717 } 7718 7719 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7720 // a null pointer constant. 7721 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7722 LHSType->isBlockPointerType()) && 7723 RHS.get()->isNullPointerConstant(Context, 7724 Expr::NPC_ValueDependentIsNull)) { 7725 if (Diagnose || ConvertRHS) { 7726 CastKind Kind; 7727 CXXCastPath Path; 7728 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7729 /*IgnoreBaseAccess=*/false, Diagnose); 7730 if (ConvertRHS) 7731 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7732 } 7733 return Compatible; 7734 } 7735 7736 // This check seems unnatural, however it is necessary to ensure the proper 7737 // conversion of functions/arrays. If the conversion were done for all 7738 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7739 // expressions that suppress this implicit conversion (&, sizeof). 7740 // 7741 // Suppress this for references: C++ 8.5.3p5. 7742 if (!LHSType->isReferenceType()) { 7743 // FIXME: We potentially allocate here even if ConvertRHS is false. 7744 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7745 if (RHS.isInvalid()) 7746 return Incompatible; 7747 } 7748 7749 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7750 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7751 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7752 if (PDecl && !PDecl->hasDefinition()) { 7753 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7754 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7755 } 7756 } 7757 7758 CastKind Kind = CK_Invalid; 7759 Sema::AssignConvertType result = 7760 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7761 7762 // C99 6.5.16.1p2: The value of the right operand is converted to the 7763 // type of the assignment expression. 7764 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7765 // so that we can use references in built-in functions even in C. 7766 // The getNonReferenceType() call makes sure that the resulting expression 7767 // does not have reference type. 7768 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7769 QualType Ty = LHSType.getNonLValueExprType(Context); 7770 Expr *E = RHS.get(); 7771 7772 // Check for various Objective-C errors. If we are not reporting 7773 // diagnostics and just checking for errors, e.g., during overload 7774 // resolution, return Incompatible to indicate the failure. 7775 if (getLangOpts().ObjCAutoRefCount && 7776 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7777 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7778 if (!Diagnose) 7779 return Incompatible; 7780 } 7781 if (getLangOpts().ObjC1 && 7782 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7783 E->getType(), E, Diagnose) || 7784 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7785 if (!Diagnose) 7786 return Incompatible; 7787 // Replace the expression with a corrected version and continue so we 7788 // can find further errors. 7789 RHS = E; 7790 return Compatible; 7791 } 7792 7793 if (ConvertRHS) 7794 RHS = ImpCastExprToType(E, Ty, Kind); 7795 } 7796 return result; 7797 } 7798 7799 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7800 ExprResult &RHS) { 7801 Diag(Loc, diag::err_typecheck_invalid_operands) 7802 << LHS.get()->getType() << RHS.get()->getType() 7803 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7804 return QualType(); 7805 } 7806 7807 /// Try to convert a value of non-vector type to a vector type by converting 7808 /// the type to the element type of the vector and then performing a splat. 7809 /// If the language is OpenCL, we only use conversions that promote scalar 7810 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7811 /// for float->int. 7812 /// 7813 /// \param scalar - if non-null, actually perform the conversions 7814 /// \return true if the operation fails (but without diagnosing the failure) 7815 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7816 QualType scalarTy, 7817 QualType vectorEltTy, 7818 QualType vectorTy) { 7819 // The conversion to apply to the scalar before splatting it, 7820 // if necessary. 7821 CastKind scalarCast = CK_Invalid; 7822 7823 if (vectorEltTy->isIntegralType(S.Context)) { 7824 if (!scalarTy->isIntegralType(S.Context)) 7825 return true; 7826 if (S.getLangOpts().OpenCL && 7827 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7828 return true; 7829 scalarCast = CK_IntegralCast; 7830 } else if (vectorEltTy->isRealFloatingType()) { 7831 if (scalarTy->isRealFloatingType()) { 7832 if (S.getLangOpts().OpenCL && 7833 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7834 return true; 7835 scalarCast = CK_FloatingCast; 7836 } 7837 else if (scalarTy->isIntegralType(S.Context)) 7838 scalarCast = CK_IntegralToFloating; 7839 else 7840 return true; 7841 } else { 7842 return true; 7843 } 7844 7845 // Adjust scalar if desired. 7846 if (scalar) { 7847 if (scalarCast != CK_Invalid) 7848 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7849 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7850 } 7851 return false; 7852 } 7853 7854 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7855 SourceLocation Loc, bool IsCompAssign, 7856 bool AllowBothBool, 7857 bool AllowBoolConversions) { 7858 if (!IsCompAssign) { 7859 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7860 if (LHS.isInvalid()) 7861 return QualType(); 7862 } 7863 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7864 if (RHS.isInvalid()) 7865 return QualType(); 7866 7867 // For conversion purposes, we ignore any qualifiers. 7868 // For example, "const float" and "float" are equivalent. 7869 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7870 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7871 7872 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7873 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7874 assert(LHSVecType || RHSVecType); 7875 7876 // AltiVec-style "vector bool op vector bool" combinations are allowed 7877 // for some operators but not others. 7878 if (!AllowBothBool && 7879 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7880 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7881 return InvalidOperands(Loc, LHS, RHS); 7882 7883 // If the vector types are identical, return. 7884 if (Context.hasSameType(LHSType, RHSType)) 7885 return LHSType; 7886 7887 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7888 if (LHSVecType && RHSVecType && 7889 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7890 if (isa<ExtVectorType>(LHSVecType)) { 7891 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7892 return LHSType; 7893 } 7894 7895 if (!IsCompAssign) 7896 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7897 return RHSType; 7898 } 7899 7900 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7901 // can be mixed, with the result being the non-bool type. The non-bool 7902 // operand must have integer element type. 7903 if (AllowBoolConversions && LHSVecType && RHSVecType && 7904 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7905 (Context.getTypeSize(LHSVecType->getElementType()) == 7906 Context.getTypeSize(RHSVecType->getElementType()))) { 7907 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7908 LHSVecType->getElementType()->isIntegerType() && 7909 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7910 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7911 return LHSType; 7912 } 7913 if (!IsCompAssign && 7914 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7915 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7916 RHSVecType->getElementType()->isIntegerType()) { 7917 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7918 return RHSType; 7919 } 7920 } 7921 7922 // If there's an ext-vector type and a scalar, try to convert the scalar to 7923 // the vector element type and splat. 7924 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7925 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7926 LHSVecType->getElementType(), LHSType)) 7927 return LHSType; 7928 } 7929 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7930 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7931 LHSType, RHSVecType->getElementType(), 7932 RHSType)) 7933 return RHSType; 7934 } 7935 7936 // If we're allowing lax vector conversions, only the total (data) size needs 7937 // to be the same. If one of the types is scalar, the result is always the 7938 // vector type. Don't allow this if the scalar operand is an lvalue. 7939 QualType VecType = LHSVecType ? LHSType : RHSType; 7940 QualType ScalarType = LHSVecType ? RHSType : LHSType; 7941 ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS; 7942 if (isLaxVectorConversion(ScalarType, VecType) && 7943 !ScalarExpr->get()->isLValue()) { 7944 *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast); 7945 return VecType; 7946 } 7947 7948 // Okay, the expression is invalid. 7949 7950 // If there's a non-vector, non-real operand, diagnose that. 7951 if ((!RHSVecType && !RHSType->isRealType()) || 7952 (!LHSVecType && !LHSType->isRealType())) { 7953 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7954 << LHSType << RHSType 7955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7956 return QualType(); 7957 } 7958 7959 // OpenCL V1.1 6.2.6.p1: 7960 // If the operands are of more than one vector type, then an error shall 7961 // occur. Implicit conversions between vector types are not permitted, per 7962 // section 6.2.1. 7963 if (getLangOpts().OpenCL && 7964 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7965 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7966 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7967 << RHSType; 7968 return QualType(); 7969 } 7970 7971 // Otherwise, use the generic diagnostic. 7972 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7973 << LHSType << RHSType 7974 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7975 return QualType(); 7976 } 7977 7978 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7979 // expression. These are mainly cases where the null pointer is used as an 7980 // integer instead of a pointer. 7981 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7982 SourceLocation Loc, bool IsCompare) { 7983 // The canonical way to check for a GNU null is with isNullPointerConstant, 7984 // but we use a bit of a hack here for speed; this is a relatively 7985 // hot path, and isNullPointerConstant is slow. 7986 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7987 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7988 7989 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7990 7991 // Avoid analyzing cases where the result will either be invalid (and 7992 // diagnosed as such) or entirely valid and not something to warn about. 7993 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7994 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7995 return; 7996 7997 // Comparison operations would not make sense with a null pointer no matter 7998 // what the other expression is. 7999 if (!IsCompare) { 8000 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8001 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8002 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8003 return; 8004 } 8005 8006 // The rest of the operations only make sense with a null pointer 8007 // if the other expression is a pointer. 8008 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8009 NonNullType->canDecayToPointerType()) 8010 return; 8011 8012 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8013 << LHSNull /* LHS is NULL */ << NonNullType 8014 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8015 } 8016 8017 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8018 ExprResult &RHS, 8019 SourceLocation Loc, bool IsDiv) { 8020 // Check for division/remainder by zero. 8021 llvm::APSInt RHSValue; 8022 if (!RHS.get()->isValueDependent() && 8023 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8024 S.DiagRuntimeBehavior(Loc, RHS.get(), 8025 S.PDiag(diag::warn_remainder_division_by_zero) 8026 << IsDiv << RHS.get()->getSourceRange()); 8027 } 8028 8029 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8030 SourceLocation Loc, 8031 bool IsCompAssign, bool IsDiv) { 8032 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8033 8034 if (LHS.get()->getType()->isVectorType() || 8035 RHS.get()->getType()->isVectorType()) 8036 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8037 /*AllowBothBool*/getLangOpts().AltiVec, 8038 /*AllowBoolConversions*/false); 8039 8040 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8041 if (LHS.isInvalid() || RHS.isInvalid()) 8042 return QualType(); 8043 8044 8045 if (compType.isNull() || !compType->isArithmeticType()) 8046 return InvalidOperands(Loc, LHS, RHS); 8047 if (IsDiv) 8048 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8049 return compType; 8050 } 8051 8052 QualType Sema::CheckRemainderOperands( 8053 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8054 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8055 8056 if (LHS.get()->getType()->isVectorType() || 8057 RHS.get()->getType()->isVectorType()) { 8058 if (LHS.get()->getType()->hasIntegerRepresentation() && 8059 RHS.get()->getType()->hasIntegerRepresentation()) 8060 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8061 /*AllowBothBool*/getLangOpts().AltiVec, 8062 /*AllowBoolConversions*/false); 8063 return InvalidOperands(Loc, LHS, RHS); 8064 } 8065 8066 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8067 if (LHS.isInvalid() || RHS.isInvalid()) 8068 return QualType(); 8069 8070 if (compType.isNull() || !compType->isIntegerType()) 8071 return InvalidOperands(Loc, LHS, RHS); 8072 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8073 return compType; 8074 } 8075 8076 /// \brief Diagnose invalid arithmetic on two void pointers. 8077 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8078 Expr *LHSExpr, Expr *RHSExpr) { 8079 S.Diag(Loc, S.getLangOpts().CPlusPlus 8080 ? diag::err_typecheck_pointer_arith_void_type 8081 : diag::ext_gnu_void_ptr) 8082 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8083 << RHSExpr->getSourceRange(); 8084 } 8085 8086 /// \brief Diagnose invalid arithmetic on a void pointer. 8087 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8088 Expr *Pointer) { 8089 S.Diag(Loc, S.getLangOpts().CPlusPlus 8090 ? diag::err_typecheck_pointer_arith_void_type 8091 : diag::ext_gnu_void_ptr) 8092 << 0 /* one pointer */ << Pointer->getSourceRange(); 8093 } 8094 8095 /// \brief Diagnose invalid arithmetic on two function pointers. 8096 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8097 Expr *LHS, Expr *RHS) { 8098 assert(LHS->getType()->isAnyPointerType()); 8099 assert(RHS->getType()->isAnyPointerType()); 8100 S.Diag(Loc, S.getLangOpts().CPlusPlus 8101 ? diag::err_typecheck_pointer_arith_function_type 8102 : diag::ext_gnu_ptr_func_arith) 8103 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8104 // We only show the second type if it differs from the first. 8105 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8106 RHS->getType()) 8107 << RHS->getType()->getPointeeType() 8108 << LHS->getSourceRange() << RHS->getSourceRange(); 8109 } 8110 8111 /// \brief Diagnose invalid arithmetic on a function pointer. 8112 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8113 Expr *Pointer) { 8114 assert(Pointer->getType()->isAnyPointerType()); 8115 S.Diag(Loc, S.getLangOpts().CPlusPlus 8116 ? diag::err_typecheck_pointer_arith_function_type 8117 : diag::ext_gnu_ptr_func_arith) 8118 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8119 << 0 /* one pointer, so only one type */ 8120 << Pointer->getSourceRange(); 8121 } 8122 8123 /// \brief Emit error if Operand is incomplete pointer type 8124 /// 8125 /// \returns True if pointer has incomplete type 8126 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8127 Expr *Operand) { 8128 QualType ResType = Operand->getType(); 8129 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8130 ResType = ResAtomicType->getValueType(); 8131 8132 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8133 QualType PointeeTy = ResType->getPointeeType(); 8134 return S.RequireCompleteType(Loc, PointeeTy, 8135 diag::err_typecheck_arithmetic_incomplete_type, 8136 PointeeTy, Operand->getSourceRange()); 8137 } 8138 8139 /// \brief Check the validity of an arithmetic pointer operand. 8140 /// 8141 /// If the operand has pointer type, this code will check for pointer types 8142 /// which are invalid in arithmetic operations. These will be diagnosed 8143 /// appropriately, including whether or not the use is supported as an 8144 /// extension. 8145 /// 8146 /// \returns True when the operand is valid to use (even if as an extension). 8147 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8148 Expr *Operand) { 8149 QualType ResType = Operand->getType(); 8150 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8151 ResType = ResAtomicType->getValueType(); 8152 8153 if (!ResType->isAnyPointerType()) return true; 8154 8155 QualType PointeeTy = ResType->getPointeeType(); 8156 if (PointeeTy->isVoidType()) { 8157 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8158 return !S.getLangOpts().CPlusPlus; 8159 } 8160 if (PointeeTy->isFunctionType()) { 8161 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8162 return !S.getLangOpts().CPlusPlus; 8163 } 8164 8165 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8166 8167 return true; 8168 } 8169 8170 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8171 /// operands. 8172 /// 8173 /// This routine will diagnose any invalid arithmetic on pointer operands much 8174 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8175 /// for emitting a single diagnostic even for operations where both LHS and RHS 8176 /// are (potentially problematic) pointers. 8177 /// 8178 /// \returns True when the operand is valid to use (even if as an extension). 8179 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8180 Expr *LHSExpr, Expr *RHSExpr) { 8181 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8182 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8183 if (!isLHSPointer && !isRHSPointer) return true; 8184 8185 QualType LHSPointeeTy, RHSPointeeTy; 8186 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8187 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8188 8189 // if both are pointers check if operation is valid wrt address spaces 8190 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8191 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8192 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8193 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8194 S.Diag(Loc, 8195 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8196 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8197 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8198 return false; 8199 } 8200 } 8201 8202 // Check for arithmetic on pointers to incomplete types. 8203 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8204 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8205 if (isLHSVoidPtr || isRHSVoidPtr) { 8206 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8207 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8208 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8209 8210 return !S.getLangOpts().CPlusPlus; 8211 } 8212 8213 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8214 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8215 if (isLHSFuncPtr || isRHSFuncPtr) { 8216 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8217 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8218 RHSExpr); 8219 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8220 8221 return !S.getLangOpts().CPlusPlus; 8222 } 8223 8224 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8225 return false; 8226 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8227 return false; 8228 8229 return true; 8230 } 8231 8232 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8233 /// literal. 8234 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8235 Expr *LHSExpr, Expr *RHSExpr) { 8236 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8237 Expr* IndexExpr = RHSExpr; 8238 if (!StrExpr) { 8239 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8240 IndexExpr = LHSExpr; 8241 } 8242 8243 bool IsStringPlusInt = StrExpr && 8244 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8245 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8246 return; 8247 8248 llvm::APSInt index; 8249 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8250 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8251 if (index.isNonNegative() && 8252 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8253 index.isUnsigned())) 8254 return; 8255 } 8256 8257 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8258 Self.Diag(OpLoc, diag::warn_string_plus_int) 8259 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8260 8261 // Only print a fixit for "str" + int, not for int + "str". 8262 if (IndexExpr == RHSExpr) { 8263 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8264 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8265 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8266 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8267 << FixItHint::CreateInsertion(EndLoc, "]"); 8268 } else 8269 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8270 } 8271 8272 /// \brief Emit a warning when adding a char literal to a string. 8273 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8274 Expr *LHSExpr, Expr *RHSExpr) { 8275 const Expr *StringRefExpr = LHSExpr; 8276 const CharacterLiteral *CharExpr = 8277 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8278 8279 if (!CharExpr) { 8280 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8281 StringRefExpr = RHSExpr; 8282 } 8283 8284 if (!CharExpr || !StringRefExpr) 8285 return; 8286 8287 const QualType StringType = StringRefExpr->getType(); 8288 8289 // Return if not a PointerType. 8290 if (!StringType->isAnyPointerType()) 8291 return; 8292 8293 // Return if not a CharacterType. 8294 if (!StringType->getPointeeType()->isAnyCharacterType()) 8295 return; 8296 8297 ASTContext &Ctx = Self.getASTContext(); 8298 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8299 8300 const QualType CharType = CharExpr->getType(); 8301 if (!CharType->isAnyCharacterType() && 8302 CharType->isIntegerType() && 8303 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8304 Self.Diag(OpLoc, diag::warn_string_plus_char) 8305 << DiagRange << Ctx.CharTy; 8306 } else { 8307 Self.Diag(OpLoc, diag::warn_string_plus_char) 8308 << DiagRange << CharExpr->getType(); 8309 } 8310 8311 // Only print a fixit for str + char, not for char + str. 8312 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8313 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8314 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8315 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8316 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8317 << FixItHint::CreateInsertion(EndLoc, "]"); 8318 } else { 8319 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8320 } 8321 } 8322 8323 /// \brief Emit error when two pointers are incompatible. 8324 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8325 Expr *LHSExpr, Expr *RHSExpr) { 8326 assert(LHSExpr->getType()->isAnyPointerType()); 8327 assert(RHSExpr->getType()->isAnyPointerType()); 8328 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8329 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8330 << RHSExpr->getSourceRange(); 8331 } 8332 8333 // C99 6.5.6 8334 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8335 SourceLocation Loc, BinaryOperatorKind Opc, 8336 QualType* CompLHSTy) { 8337 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8338 8339 if (LHS.get()->getType()->isVectorType() || 8340 RHS.get()->getType()->isVectorType()) { 8341 QualType compType = CheckVectorOperands( 8342 LHS, RHS, Loc, CompLHSTy, 8343 /*AllowBothBool*/getLangOpts().AltiVec, 8344 /*AllowBoolConversions*/getLangOpts().ZVector); 8345 if (CompLHSTy) *CompLHSTy = compType; 8346 return compType; 8347 } 8348 8349 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8350 if (LHS.isInvalid() || RHS.isInvalid()) 8351 return QualType(); 8352 8353 // Diagnose "string literal" '+' int and string '+' "char literal". 8354 if (Opc == BO_Add) { 8355 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8356 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8357 } 8358 8359 // handle the common case first (both operands are arithmetic). 8360 if (!compType.isNull() && compType->isArithmeticType()) { 8361 if (CompLHSTy) *CompLHSTy = compType; 8362 return compType; 8363 } 8364 8365 // Type-checking. Ultimately the pointer's going to be in PExp; 8366 // note that we bias towards the LHS being the pointer. 8367 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8368 8369 bool isObjCPointer; 8370 if (PExp->getType()->isPointerType()) { 8371 isObjCPointer = false; 8372 } else if (PExp->getType()->isObjCObjectPointerType()) { 8373 isObjCPointer = true; 8374 } else { 8375 std::swap(PExp, IExp); 8376 if (PExp->getType()->isPointerType()) { 8377 isObjCPointer = false; 8378 } else if (PExp->getType()->isObjCObjectPointerType()) { 8379 isObjCPointer = true; 8380 } else { 8381 return InvalidOperands(Loc, LHS, RHS); 8382 } 8383 } 8384 assert(PExp->getType()->isAnyPointerType()); 8385 8386 if (!IExp->getType()->isIntegerType()) 8387 return InvalidOperands(Loc, LHS, RHS); 8388 8389 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8390 return QualType(); 8391 8392 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8393 return QualType(); 8394 8395 // Check array bounds for pointer arithemtic 8396 CheckArrayAccess(PExp, IExp); 8397 8398 if (CompLHSTy) { 8399 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8400 if (LHSTy.isNull()) { 8401 LHSTy = LHS.get()->getType(); 8402 if (LHSTy->isPromotableIntegerType()) 8403 LHSTy = Context.getPromotedIntegerType(LHSTy); 8404 } 8405 *CompLHSTy = LHSTy; 8406 } 8407 8408 return PExp->getType(); 8409 } 8410 8411 // C99 6.5.6 8412 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8413 SourceLocation Loc, 8414 QualType* CompLHSTy) { 8415 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8416 8417 if (LHS.get()->getType()->isVectorType() || 8418 RHS.get()->getType()->isVectorType()) { 8419 QualType compType = CheckVectorOperands( 8420 LHS, RHS, Loc, CompLHSTy, 8421 /*AllowBothBool*/getLangOpts().AltiVec, 8422 /*AllowBoolConversions*/getLangOpts().ZVector); 8423 if (CompLHSTy) *CompLHSTy = compType; 8424 return compType; 8425 } 8426 8427 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8428 if (LHS.isInvalid() || RHS.isInvalid()) 8429 return QualType(); 8430 8431 // Enforce type constraints: C99 6.5.6p3. 8432 8433 // Handle the common case first (both operands are arithmetic). 8434 if (!compType.isNull() && compType->isArithmeticType()) { 8435 if (CompLHSTy) *CompLHSTy = compType; 8436 return compType; 8437 } 8438 8439 // Either ptr - int or ptr - ptr. 8440 if (LHS.get()->getType()->isAnyPointerType()) { 8441 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8442 8443 // Diagnose bad cases where we step over interface counts. 8444 if (LHS.get()->getType()->isObjCObjectPointerType() && 8445 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8446 return QualType(); 8447 8448 // The result type of a pointer-int computation is the pointer type. 8449 if (RHS.get()->getType()->isIntegerType()) { 8450 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8451 return QualType(); 8452 8453 // Check array bounds for pointer arithemtic 8454 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8455 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8456 8457 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8458 return LHS.get()->getType(); 8459 } 8460 8461 // Handle pointer-pointer subtractions. 8462 if (const PointerType *RHSPTy 8463 = RHS.get()->getType()->getAs<PointerType>()) { 8464 QualType rpointee = RHSPTy->getPointeeType(); 8465 8466 if (getLangOpts().CPlusPlus) { 8467 // Pointee types must be the same: C++ [expr.add] 8468 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8469 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8470 } 8471 } else { 8472 // Pointee types must be compatible C99 6.5.6p3 8473 if (!Context.typesAreCompatible( 8474 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8475 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8476 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8477 return QualType(); 8478 } 8479 } 8480 8481 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8482 LHS.get(), RHS.get())) 8483 return QualType(); 8484 8485 // The pointee type may have zero size. As an extension, a structure or 8486 // union may have zero size or an array may have zero length. In this 8487 // case subtraction does not make sense. 8488 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8489 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8490 if (ElementSize.isZero()) { 8491 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8492 << rpointee.getUnqualifiedType() 8493 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8494 } 8495 } 8496 8497 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8498 return Context.getPointerDiffType(); 8499 } 8500 } 8501 8502 return InvalidOperands(Loc, LHS, RHS); 8503 } 8504 8505 static bool isScopedEnumerationType(QualType T) { 8506 if (const EnumType *ET = T->getAs<EnumType>()) 8507 return ET->getDecl()->isScoped(); 8508 return false; 8509 } 8510 8511 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8512 SourceLocation Loc, BinaryOperatorKind Opc, 8513 QualType LHSType) { 8514 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8515 // so skip remaining warnings as we don't want to modify values within Sema. 8516 if (S.getLangOpts().OpenCL) 8517 return; 8518 8519 llvm::APSInt Right; 8520 // Check right/shifter operand 8521 if (RHS.get()->isValueDependent() || 8522 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8523 return; 8524 8525 if (Right.isNegative()) { 8526 S.DiagRuntimeBehavior(Loc, RHS.get(), 8527 S.PDiag(diag::warn_shift_negative) 8528 << RHS.get()->getSourceRange()); 8529 return; 8530 } 8531 llvm::APInt LeftBits(Right.getBitWidth(), 8532 S.Context.getTypeSize(LHS.get()->getType())); 8533 if (Right.uge(LeftBits)) { 8534 S.DiagRuntimeBehavior(Loc, RHS.get(), 8535 S.PDiag(diag::warn_shift_gt_typewidth) 8536 << RHS.get()->getSourceRange()); 8537 return; 8538 } 8539 if (Opc != BO_Shl) 8540 return; 8541 8542 // When left shifting an ICE which is signed, we can check for overflow which 8543 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8544 // integers have defined behavior modulo one more than the maximum value 8545 // representable in the result type, so never warn for those. 8546 llvm::APSInt Left; 8547 if (LHS.get()->isValueDependent() || 8548 LHSType->hasUnsignedIntegerRepresentation() || 8549 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8550 return; 8551 8552 // If LHS does not have a signed type and non-negative value 8553 // then, the behavior is undefined. Warn about it. 8554 if (Left.isNegative()) { 8555 S.DiagRuntimeBehavior(Loc, LHS.get(), 8556 S.PDiag(diag::warn_shift_lhs_negative) 8557 << LHS.get()->getSourceRange()); 8558 return; 8559 } 8560 8561 llvm::APInt ResultBits = 8562 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8563 if (LeftBits.uge(ResultBits)) 8564 return; 8565 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8566 Result = Result.shl(Right); 8567 8568 // Print the bit representation of the signed integer as an unsigned 8569 // hexadecimal number. 8570 SmallString<40> HexResult; 8571 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8572 8573 // If we are only missing a sign bit, this is less likely to result in actual 8574 // bugs -- if the result is cast back to an unsigned type, it will have the 8575 // expected value. Thus we place this behind a different warning that can be 8576 // turned off separately if needed. 8577 if (LeftBits == ResultBits - 1) { 8578 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8579 << HexResult << LHSType 8580 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8581 return; 8582 } 8583 8584 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8585 << HexResult.str() << Result.getMinSignedBits() << LHSType 8586 << Left.getBitWidth() << LHS.get()->getSourceRange() 8587 << RHS.get()->getSourceRange(); 8588 } 8589 8590 /// \brief Return the resulting type when an OpenCL vector is shifted 8591 /// by a scalar or vector shift amount. 8592 static QualType checkOpenCLVectorShift(Sema &S, 8593 ExprResult &LHS, ExprResult &RHS, 8594 SourceLocation Loc, bool IsCompAssign) { 8595 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8596 if (!LHS.get()->getType()->isVectorType()) { 8597 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8598 << RHS.get()->getType() << LHS.get()->getType() 8599 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8600 return QualType(); 8601 } 8602 8603 if (!IsCompAssign) { 8604 LHS = S.UsualUnaryConversions(LHS.get()); 8605 if (LHS.isInvalid()) return QualType(); 8606 } 8607 8608 RHS = S.UsualUnaryConversions(RHS.get()); 8609 if (RHS.isInvalid()) return QualType(); 8610 8611 QualType LHSType = LHS.get()->getType(); 8612 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8613 QualType LHSEleType = LHSVecTy->getElementType(); 8614 8615 // Note that RHS might not be a vector. 8616 QualType RHSType = RHS.get()->getType(); 8617 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8618 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8619 8620 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8621 if (!LHSEleType->isIntegerType()) { 8622 S.Diag(Loc, diag::err_typecheck_expect_int) 8623 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8624 return QualType(); 8625 } 8626 8627 if (!RHSEleType->isIntegerType()) { 8628 S.Diag(Loc, diag::err_typecheck_expect_int) 8629 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8630 return QualType(); 8631 } 8632 8633 if (RHSVecTy) { 8634 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8635 // are applied component-wise. So if RHS is a vector, then ensure 8636 // that the number of elements is the same as LHS... 8637 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8638 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8639 << LHS.get()->getType() << RHS.get()->getType() 8640 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8641 return QualType(); 8642 } 8643 } else { 8644 // ...else expand RHS to match the number of elements in LHS. 8645 QualType VecTy = 8646 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8647 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8648 } 8649 8650 return LHSType; 8651 } 8652 8653 // C99 6.5.7 8654 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8655 SourceLocation Loc, BinaryOperatorKind Opc, 8656 bool IsCompAssign) { 8657 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8658 8659 // Vector shifts promote their scalar inputs to vector type. 8660 if (LHS.get()->getType()->isVectorType() || 8661 RHS.get()->getType()->isVectorType()) { 8662 if (LangOpts.OpenCL) 8663 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8664 if (LangOpts.ZVector) { 8665 // The shift operators for the z vector extensions work basically 8666 // like OpenCL shifts, except that neither the LHS nor the RHS is 8667 // allowed to be a "vector bool". 8668 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8669 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8670 return InvalidOperands(Loc, LHS, RHS); 8671 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8672 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8673 return InvalidOperands(Loc, LHS, RHS); 8674 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8675 } 8676 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8677 /*AllowBothBool*/true, 8678 /*AllowBoolConversions*/false); 8679 } 8680 8681 // Shifts don't perform usual arithmetic conversions, they just do integer 8682 // promotions on each operand. C99 6.5.7p3 8683 8684 // For the LHS, do usual unary conversions, but then reset them away 8685 // if this is a compound assignment. 8686 ExprResult OldLHS = LHS; 8687 LHS = UsualUnaryConversions(LHS.get()); 8688 if (LHS.isInvalid()) 8689 return QualType(); 8690 QualType LHSType = LHS.get()->getType(); 8691 if (IsCompAssign) LHS = OldLHS; 8692 8693 // The RHS is simpler. 8694 RHS = UsualUnaryConversions(RHS.get()); 8695 if (RHS.isInvalid()) 8696 return QualType(); 8697 QualType RHSType = RHS.get()->getType(); 8698 8699 // C99 6.5.7p2: Each of the operands shall have integer type. 8700 if (!LHSType->hasIntegerRepresentation() || 8701 !RHSType->hasIntegerRepresentation()) 8702 return InvalidOperands(Loc, LHS, RHS); 8703 8704 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8705 // hasIntegerRepresentation() above instead of this. 8706 if (isScopedEnumerationType(LHSType) || 8707 isScopedEnumerationType(RHSType)) { 8708 return InvalidOperands(Loc, LHS, RHS); 8709 } 8710 // Sanity-check shift operands 8711 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8712 8713 // "The type of the result is that of the promoted left operand." 8714 return LHSType; 8715 } 8716 8717 static bool IsWithinTemplateSpecialization(Decl *D) { 8718 if (DeclContext *DC = D->getDeclContext()) { 8719 if (isa<ClassTemplateSpecializationDecl>(DC)) 8720 return true; 8721 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8722 return FD->isFunctionTemplateSpecialization(); 8723 } 8724 return false; 8725 } 8726 8727 /// If two different enums are compared, raise a warning. 8728 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8729 Expr *RHS) { 8730 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8731 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8732 8733 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8734 if (!LHSEnumType) 8735 return; 8736 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8737 if (!RHSEnumType) 8738 return; 8739 8740 // Ignore anonymous enums. 8741 if (!LHSEnumType->getDecl()->getIdentifier()) 8742 return; 8743 if (!RHSEnumType->getDecl()->getIdentifier()) 8744 return; 8745 8746 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8747 return; 8748 8749 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8750 << LHSStrippedType << RHSStrippedType 8751 << LHS->getSourceRange() << RHS->getSourceRange(); 8752 } 8753 8754 /// \brief Diagnose bad pointer comparisons. 8755 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8756 ExprResult &LHS, ExprResult &RHS, 8757 bool IsError) { 8758 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8759 : diag::ext_typecheck_comparison_of_distinct_pointers) 8760 << LHS.get()->getType() << RHS.get()->getType() 8761 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8762 } 8763 8764 /// \brief Returns false if the pointers are converted to a composite type, 8765 /// true otherwise. 8766 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8767 ExprResult &LHS, ExprResult &RHS) { 8768 // C++ [expr.rel]p2: 8769 // [...] Pointer conversions (4.10) and qualification 8770 // conversions (4.4) are performed on pointer operands (or on 8771 // a pointer operand and a null pointer constant) to bring 8772 // them to their composite pointer type. [...] 8773 // 8774 // C++ [expr.eq]p1 uses the same notion for (in)equality 8775 // comparisons of pointers. 8776 8777 // C++ [expr.eq]p2: 8778 // In addition, pointers to members can be compared, or a pointer to 8779 // member and a null pointer constant. Pointer to member conversions 8780 // (4.11) and qualification conversions (4.4) are performed to bring 8781 // them to a common type. If one operand is a null pointer constant, 8782 // the common type is the type of the other operand. Otherwise, the 8783 // common type is a pointer to member type similar (4.4) to the type 8784 // of one of the operands, with a cv-qualification signature (4.4) 8785 // that is the union of the cv-qualification signatures of the operand 8786 // types. 8787 8788 QualType LHSType = LHS.get()->getType(); 8789 QualType RHSType = RHS.get()->getType(); 8790 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8791 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8792 8793 bool NonStandardCompositeType = false; 8794 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8795 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8796 if (T.isNull()) { 8797 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8798 return true; 8799 } 8800 8801 if (NonStandardCompositeType) 8802 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8803 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8804 << RHS.get()->getSourceRange(); 8805 8806 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8807 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8808 return false; 8809 } 8810 8811 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8812 ExprResult &LHS, 8813 ExprResult &RHS, 8814 bool IsError) { 8815 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8816 : diag::ext_typecheck_comparison_of_fptr_to_void) 8817 << LHS.get()->getType() << RHS.get()->getType() 8818 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8819 } 8820 8821 static bool isObjCObjectLiteral(ExprResult &E) { 8822 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8823 case Stmt::ObjCArrayLiteralClass: 8824 case Stmt::ObjCDictionaryLiteralClass: 8825 case Stmt::ObjCStringLiteralClass: 8826 case Stmt::ObjCBoxedExprClass: 8827 return true; 8828 default: 8829 // Note that ObjCBoolLiteral is NOT an object literal! 8830 return false; 8831 } 8832 } 8833 8834 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8835 const ObjCObjectPointerType *Type = 8836 LHS->getType()->getAs<ObjCObjectPointerType>(); 8837 8838 // If this is not actually an Objective-C object, bail out. 8839 if (!Type) 8840 return false; 8841 8842 // Get the LHS object's interface type. 8843 QualType InterfaceType = Type->getPointeeType(); 8844 8845 // If the RHS isn't an Objective-C object, bail out. 8846 if (!RHS->getType()->isObjCObjectPointerType()) 8847 return false; 8848 8849 // Try to find the -isEqual: method. 8850 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8851 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8852 InterfaceType, 8853 /*instance=*/true); 8854 if (!Method) { 8855 if (Type->isObjCIdType()) { 8856 // For 'id', just check the global pool. 8857 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8858 /*receiverId=*/true); 8859 } else { 8860 // Check protocols. 8861 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8862 /*instance=*/true); 8863 } 8864 } 8865 8866 if (!Method) 8867 return false; 8868 8869 QualType T = Method->parameters()[0]->getType(); 8870 if (!T->isObjCObjectPointerType()) 8871 return false; 8872 8873 QualType R = Method->getReturnType(); 8874 if (!R->isScalarType()) 8875 return false; 8876 8877 return true; 8878 } 8879 8880 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8881 FromE = FromE->IgnoreParenImpCasts(); 8882 switch (FromE->getStmtClass()) { 8883 default: 8884 break; 8885 case Stmt::ObjCStringLiteralClass: 8886 // "string literal" 8887 return LK_String; 8888 case Stmt::ObjCArrayLiteralClass: 8889 // "array literal" 8890 return LK_Array; 8891 case Stmt::ObjCDictionaryLiteralClass: 8892 // "dictionary literal" 8893 return LK_Dictionary; 8894 case Stmt::BlockExprClass: 8895 return LK_Block; 8896 case Stmt::ObjCBoxedExprClass: { 8897 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8898 switch (Inner->getStmtClass()) { 8899 case Stmt::IntegerLiteralClass: 8900 case Stmt::FloatingLiteralClass: 8901 case Stmt::CharacterLiteralClass: 8902 case Stmt::ObjCBoolLiteralExprClass: 8903 case Stmt::CXXBoolLiteralExprClass: 8904 // "numeric literal" 8905 return LK_Numeric; 8906 case Stmt::ImplicitCastExprClass: { 8907 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8908 // Boolean literals can be represented by implicit casts. 8909 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8910 return LK_Numeric; 8911 break; 8912 } 8913 default: 8914 break; 8915 } 8916 return LK_Boxed; 8917 } 8918 } 8919 return LK_None; 8920 } 8921 8922 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8923 ExprResult &LHS, ExprResult &RHS, 8924 BinaryOperator::Opcode Opc){ 8925 Expr *Literal; 8926 Expr *Other; 8927 if (isObjCObjectLiteral(LHS)) { 8928 Literal = LHS.get(); 8929 Other = RHS.get(); 8930 } else { 8931 Literal = RHS.get(); 8932 Other = LHS.get(); 8933 } 8934 8935 // Don't warn on comparisons against nil. 8936 Other = Other->IgnoreParenCasts(); 8937 if (Other->isNullPointerConstant(S.getASTContext(), 8938 Expr::NPC_ValueDependentIsNotNull)) 8939 return; 8940 8941 // This should be kept in sync with warn_objc_literal_comparison. 8942 // LK_String should always be after the other literals, since it has its own 8943 // warning flag. 8944 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8945 assert(LiteralKind != Sema::LK_Block); 8946 if (LiteralKind == Sema::LK_None) { 8947 llvm_unreachable("Unknown Objective-C object literal kind"); 8948 } 8949 8950 if (LiteralKind == Sema::LK_String) 8951 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8952 << Literal->getSourceRange(); 8953 else 8954 S.Diag(Loc, diag::warn_objc_literal_comparison) 8955 << LiteralKind << Literal->getSourceRange(); 8956 8957 if (BinaryOperator::isEqualityOp(Opc) && 8958 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8959 SourceLocation Start = LHS.get()->getLocStart(); 8960 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 8961 CharSourceRange OpRange = 8962 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 8963 8964 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8965 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8966 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8967 << FixItHint::CreateInsertion(End, "]"); 8968 } 8969 } 8970 8971 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8972 ExprResult &RHS, 8973 SourceLocation Loc, 8974 BinaryOperatorKind Opc) { 8975 // Check that left hand side is !something. 8976 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8977 if (!UO || UO->getOpcode() != UO_LNot) return; 8978 8979 // Only check if the right hand side is non-bool arithmetic type. 8980 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8981 8982 // Make sure that the something in !something is not bool. 8983 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8984 if (SubExpr->isKnownToHaveBooleanValue()) return; 8985 8986 // Emit warning. 8987 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8988 << Loc; 8989 8990 // First note suggest !(x < y) 8991 SourceLocation FirstOpen = SubExpr->getLocStart(); 8992 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8993 FirstClose = S.getLocForEndOfToken(FirstClose); 8994 if (FirstClose.isInvalid()) 8995 FirstOpen = SourceLocation(); 8996 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8997 << FixItHint::CreateInsertion(FirstOpen, "(") 8998 << FixItHint::CreateInsertion(FirstClose, ")"); 8999 9000 // Second note suggests (!x) < y 9001 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9002 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9003 SecondClose = S.getLocForEndOfToken(SecondClose); 9004 if (SecondClose.isInvalid()) 9005 SecondOpen = SourceLocation(); 9006 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9007 << FixItHint::CreateInsertion(SecondOpen, "(") 9008 << FixItHint::CreateInsertion(SecondClose, ")"); 9009 } 9010 9011 // Get the decl for a simple expression: a reference to a variable, 9012 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9013 static ValueDecl *getCompareDecl(Expr *E) { 9014 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9015 return DR->getDecl(); 9016 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9017 if (Ivar->isFreeIvar()) 9018 return Ivar->getDecl(); 9019 } 9020 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9021 if (Mem->isImplicitAccess()) 9022 return Mem->getMemberDecl(); 9023 } 9024 return nullptr; 9025 } 9026 9027 // C99 6.5.8, C++ [expr.rel] 9028 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9029 SourceLocation Loc, BinaryOperatorKind Opc, 9030 bool IsRelational) { 9031 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9032 9033 // Handle vector comparisons separately. 9034 if (LHS.get()->getType()->isVectorType() || 9035 RHS.get()->getType()->isVectorType()) 9036 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9037 9038 QualType LHSType = LHS.get()->getType(); 9039 QualType RHSType = RHS.get()->getType(); 9040 9041 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9042 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9043 9044 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9045 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9046 9047 if (!LHSType->hasFloatingRepresentation() && 9048 !(LHSType->isBlockPointerType() && IsRelational) && 9049 !LHS.get()->getLocStart().isMacroID() && 9050 !RHS.get()->getLocStart().isMacroID() && 9051 ActiveTemplateInstantiations.empty()) { 9052 // For non-floating point types, check for self-comparisons of the form 9053 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9054 // often indicate logic errors in the program. 9055 // 9056 // NOTE: Don't warn about comparison expressions resulting from macro 9057 // expansion. Also don't warn about comparisons which are only self 9058 // comparisons within a template specialization. The warnings should catch 9059 // obvious cases in the definition of the template anyways. The idea is to 9060 // warn when the typed comparison operator will always evaluate to the same 9061 // result. 9062 ValueDecl *DL = getCompareDecl(LHSStripped); 9063 ValueDecl *DR = getCompareDecl(RHSStripped); 9064 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9065 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9066 << 0 // self- 9067 << (Opc == BO_EQ 9068 || Opc == BO_LE 9069 || Opc == BO_GE)); 9070 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9071 !DL->getType()->isReferenceType() && 9072 !DR->getType()->isReferenceType()) { 9073 // what is it always going to eval to? 9074 char always_evals_to; 9075 switch(Opc) { 9076 case BO_EQ: // e.g. array1 == array2 9077 always_evals_to = 0; // false 9078 break; 9079 case BO_NE: // e.g. array1 != array2 9080 always_evals_to = 1; // true 9081 break; 9082 default: 9083 // best we can say is 'a constant' 9084 always_evals_to = 2; // e.g. array1 <= array2 9085 break; 9086 } 9087 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9088 << 1 // array 9089 << always_evals_to); 9090 } 9091 9092 if (isa<CastExpr>(LHSStripped)) 9093 LHSStripped = LHSStripped->IgnoreParenCasts(); 9094 if (isa<CastExpr>(RHSStripped)) 9095 RHSStripped = RHSStripped->IgnoreParenCasts(); 9096 9097 // Warn about comparisons against a string constant (unless the other 9098 // operand is null), the user probably wants strcmp. 9099 Expr *literalString = nullptr; 9100 Expr *literalStringStripped = nullptr; 9101 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9102 !RHSStripped->isNullPointerConstant(Context, 9103 Expr::NPC_ValueDependentIsNull)) { 9104 literalString = LHS.get(); 9105 literalStringStripped = LHSStripped; 9106 } else if ((isa<StringLiteral>(RHSStripped) || 9107 isa<ObjCEncodeExpr>(RHSStripped)) && 9108 !LHSStripped->isNullPointerConstant(Context, 9109 Expr::NPC_ValueDependentIsNull)) { 9110 literalString = RHS.get(); 9111 literalStringStripped = RHSStripped; 9112 } 9113 9114 if (literalString) { 9115 DiagRuntimeBehavior(Loc, nullptr, 9116 PDiag(diag::warn_stringcompare) 9117 << isa<ObjCEncodeExpr>(literalStringStripped) 9118 << literalString->getSourceRange()); 9119 } 9120 } 9121 9122 // C99 6.5.8p3 / C99 6.5.9p4 9123 UsualArithmeticConversions(LHS, RHS); 9124 if (LHS.isInvalid() || RHS.isInvalid()) 9125 return QualType(); 9126 9127 LHSType = LHS.get()->getType(); 9128 RHSType = RHS.get()->getType(); 9129 9130 // The result of comparisons is 'bool' in C++, 'int' in C. 9131 QualType ResultTy = Context.getLogicalOperationType(); 9132 9133 if (IsRelational) { 9134 if (LHSType->isRealType() && RHSType->isRealType()) 9135 return ResultTy; 9136 } else { 9137 // Check for comparisons of floating point operands using != and ==. 9138 if (LHSType->hasFloatingRepresentation()) 9139 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9140 9141 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9142 return ResultTy; 9143 } 9144 9145 const Expr::NullPointerConstantKind LHSNullKind = 9146 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9147 const Expr::NullPointerConstantKind RHSNullKind = 9148 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9149 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9150 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9151 9152 if (!IsRelational && LHSIsNull != RHSIsNull) { 9153 bool IsEquality = Opc == BO_EQ; 9154 if (RHSIsNull) 9155 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9156 RHS.get()->getSourceRange()); 9157 else 9158 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9159 LHS.get()->getSourceRange()); 9160 } 9161 9162 // All of the following pointer-related warnings are GCC extensions, except 9163 // when handling null pointer constants. 9164 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9165 QualType LCanPointeeTy = 9166 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9167 QualType RCanPointeeTy = 9168 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9169 9170 if (getLangOpts().CPlusPlus) { 9171 if (LCanPointeeTy == RCanPointeeTy) 9172 return ResultTy; 9173 if (!IsRelational && 9174 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9175 // Valid unless comparison between non-null pointer and function pointer 9176 // This is a gcc extension compatibility comparison. 9177 // In a SFINAE context, we treat this as a hard error to maintain 9178 // conformance with the C++ standard. 9179 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9180 && !LHSIsNull && !RHSIsNull) { 9181 diagnoseFunctionPointerToVoidComparison( 9182 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9183 9184 if (isSFINAEContext()) 9185 return QualType(); 9186 9187 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9188 return ResultTy; 9189 } 9190 } 9191 9192 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9193 return QualType(); 9194 else 9195 return ResultTy; 9196 } 9197 // C99 6.5.9p2 and C99 6.5.8p2 9198 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9199 RCanPointeeTy.getUnqualifiedType())) { 9200 // Valid unless a relational comparison of function pointers 9201 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9202 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9203 << LHSType << RHSType << LHS.get()->getSourceRange() 9204 << RHS.get()->getSourceRange(); 9205 } 9206 } else if (!IsRelational && 9207 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9208 // Valid unless comparison between non-null pointer and function pointer 9209 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9210 && !LHSIsNull && !RHSIsNull) 9211 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9212 /*isError*/false); 9213 } else { 9214 // Invalid 9215 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9216 } 9217 if (LCanPointeeTy != RCanPointeeTy) { 9218 // Treat NULL constant as a special case in OpenCL. 9219 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9220 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9221 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9222 Diag(Loc, 9223 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9224 << LHSType << RHSType << 0 /* comparison */ 9225 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9226 } 9227 } 9228 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9229 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9230 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9231 : CK_BitCast; 9232 if (LHSIsNull && !RHSIsNull) 9233 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9234 else 9235 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9236 } 9237 return ResultTy; 9238 } 9239 9240 if (getLangOpts().CPlusPlus) { 9241 // Comparison of nullptr_t with itself. 9242 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9243 return ResultTy; 9244 9245 // Comparison of pointers with null pointer constants and equality 9246 // comparisons of member pointers to null pointer constants. 9247 if (RHSIsNull && 9248 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9249 (!IsRelational && 9250 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9251 RHS = ImpCastExprToType(RHS.get(), LHSType, 9252 LHSType->isMemberPointerType() 9253 ? CK_NullToMemberPointer 9254 : CK_NullToPointer); 9255 return ResultTy; 9256 } 9257 if (LHSIsNull && 9258 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9259 (!IsRelational && 9260 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9261 LHS = ImpCastExprToType(LHS.get(), RHSType, 9262 RHSType->isMemberPointerType() 9263 ? CK_NullToMemberPointer 9264 : CK_NullToPointer); 9265 return ResultTy; 9266 } 9267 9268 // Comparison of member pointers. 9269 if (!IsRelational && 9270 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9271 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9272 return QualType(); 9273 else 9274 return ResultTy; 9275 } 9276 9277 // Handle scoped enumeration types specifically, since they don't promote 9278 // to integers. 9279 if (LHS.get()->getType()->isEnumeralType() && 9280 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9281 RHS.get()->getType())) 9282 return ResultTy; 9283 } 9284 9285 // Handle block pointer types. 9286 if (!IsRelational && LHSType->isBlockPointerType() && 9287 RHSType->isBlockPointerType()) { 9288 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9289 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9290 9291 if (!LHSIsNull && !RHSIsNull && 9292 !Context.typesAreCompatible(lpointee, rpointee)) { 9293 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9294 << LHSType << RHSType << LHS.get()->getSourceRange() 9295 << RHS.get()->getSourceRange(); 9296 } 9297 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9298 return ResultTy; 9299 } 9300 9301 // Allow block pointers to be compared with null pointer constants. 9302 if (!IsRelational 9303 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9304 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9305 if (!LHSIsNull && !RHSIsNull) { 9306 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9307 ->getPointeeType()->isVoidType()) 9308 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9309 ->getPointeeType()->isVoidType()))) 9310 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9311 << LHSType << RHSType << LHS.get()->getSourceRange() 9312 << RHS.get()->getSourceRange(); 9313 } 9314 if (LHSIsNull && !RHSIsNull) 9315 LHS = ImpCastExprToType(LHS.get(), RHSType, 9316 RHSType->isPointerType() ? CK_BitCast 9317 : CK_AnyPointerToBlockPointerCast); 9318 else 9319 RHS = ImpCastExprToType(RHS.get(), LHSType, 9320 LHSType->isPointerType() ? CK_BitCast 9321 : CK_AnyPointerToBlockPointerCast); 9322 return ResultTy; 9323 } 9324 9325 if (LHSType->isObjCObjectPointerType() || 9326 RHSType->isObjCObjectPointerType()) { 9327 const PointerType *LPT = LHSType->getAs<PointerType>(); 9328 const PointerType *RPT = RHSType->getAs<PointerType>(); 9329 if (LPT || RPT) { 9330 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9331 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9332 9333 if (!LPtrToVoid && !RPtrToVoid && 9334 !Context.typesAreCompatible(LHSType, RHSType)) { 9335 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9336 /*isError*/false); 9337 } 9338 if (LHSIsNull && !RHSIsNull) { 9339 Expr *E = LHS.get(); 9340 if (getLangOpts().ObjCAutoRefCount) 9341 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9342 LHS = ImpCastExprToType(E, RHSType, 9343 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9344 } 9345 else { 9346 Expr *E = RHS.get(); 9347 if (getLangOpts().ObjCAutoRefCount) 9348 CheckObjCARCConversion(SourceRange(), LHSType, E, 9349 CCK_ImplicitConversion, /*Diagnose=*/true, 9350 /*DiagnoseCFAudited=*/false, Opc); 9351 RHS = ImpCastExprToType(E, LHSType, 9352 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9353 } 9354 return ResultTy; 9355 } 9356 if (LHSType->isObjCObjectPointerType() && 9357 RHSType->isObjCObjectPointerType()) { 9358 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9359 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9360 /*isError*/false); 9361 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9362 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9363 9364 if (LHSIsNull && !RHSIsNull) 9365 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9366 else 9367 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9368 return ResultTy; 9369 } 9370 } 9371 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9372 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9373 unsigned DiagID = 0; 9374 bool isError = false; 9375 if (LangOpts.DebuggerSupport) { 9376 // Under a debugger, allow the comparison of pointers to integers, 9377 // since users tend to want to compare addresses. 9378 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9379 (RHSIsNull && RHSType->isIntegerType())) { 9380 if (IsRelational && !getLangOpts().CPlusPlus) 9381 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9382 } else if (IsRelational && !getLangOpts().CPlusPlus) 9383 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9384 else if (getLangOpts().CPlusPlus) { 9385 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9386 isError = true; 9387 } else 9388 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9389 9390 if (DiagID) { 9391 Diag(Loc, DiagID) 9392 << LHSType << RHSType << LHS.get()->getSourceRange() 9393 << RHS.get()->getSourceRange(); 9394 if (isError) 9395 return QualType(); 9396 } 9397 9398 if (LHSType->isIntegerType()) 9399 LHS = ImpCastExprToType(LHS.get(), RHSType, 9400 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9401 else 9402 RHS = ImpCastExprToType(RHS.get(), LHSType, 9403 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9404 return ResultTy; 9405 } 9406 9407 // Handle block pointers. 9408 if (!IsRelational && RHSIsNull 9409 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9410 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9411 return ResultTy; 9412 } 9413 if (!IsRelational && LHSIsNull 9414 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9415 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9416 return ResultTy; 9417 } 9418 9419 return InvalidOperands(Loc, LHS, RHS); 9420 } 9421 9422 9423 // Return a signed type that is of identical size and number of elements. 9424 // For floating point vectors, return an integer type of identical size 9425 // and number of elements. 9426 QualType Sema::GetSignedVectorType(QualType V) { 9427 const VectorType *VTy = V->getAs<VectorType>(); 9428 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9429 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9430 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9431 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9432 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9433 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9434 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9435 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9436 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9437 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9438 "Unhandled vector element size in vector compare"); 9439 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9440 } 9441 9442 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9443 /// operates on extended vector types. Instead of producing an IntTy result, 9444 /// like a scalar comparison, a vector comparison produces a vector of integer 9445 /// types. 9446 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9447 SourceLocation Loc, 9448 bool IsRelational) { 9449 // Check to make sure we're operating on vectors of the same type and width, 9450 // Allowing one side to be a scalar of element type. 9451 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9452 /*AllowBothBool*/true, 9453 /*AllowBoolConversions*/getLangOpts().ZVector); 9454 if (vType.isNull()) 9455 return vType; 9456 9457 QualType LHSType = LHS.get()->getType(); 9458 9459 // If AltiVec, the comparison results in a numeric type, i.e. 9460 // bool for C++, int for C 9461 if (getLangOpts().AltiVec && 9462 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9463 return Context.getLogicalOperationType(); 9464 9465 // For non-floating point types, check for self-comparisons of the form 9466 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9467 // often indicate logic errors in the program. 9468 if (!LHSType->hasFloatingRepresentation() && 9469 ActiveTemplateInstantiations.empty()) { 9470 if (DeclRefExpr* DRL 9471 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9472 if (DeclRefExpr* DRR 9473 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9474 if (DRL->getDecl() == DRR->getDecl()) 9475 DiagRuntimeBehavior(Loc, nullptr, 9476 PDiag(diag::warn_comparison_always) 9477 << 0 // self- 9478 << 2 // "a constant" 9479 ); 9480 } 9481 9482 // Check for comparisons of floating point operands using != and ==. 9483 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9484 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9485 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9486 } 9487 9488 // Return a signed type for the vector. 9489 return GetSignedVectorType(vType); 9490 } 9491 9492 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9493 SourceLocation Loc) { 9494 // Ensure that either both operands are of the same vector type, or 9495 // one operand is of a vector type and the other is of its element type. 9496 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9497 /*AllowBothBool*/true, 9498 /*AllowBoolConversions*/false); 9499 if (vType.isNull()) 9500 return InvalidOperands(Loc, LHS, RHS); 9501 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9502 vType->hasFloatingRepresentation()) 9503 return InvalidOperands(Loc, LHS, RHS); 9504 9505 return GetSignedVectorType(LHS.get()->getType()); 9506 } 9507 9508 inline QualType Sema::CheckBitwiseOperands( 9509 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9510 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9511 9512 if (LHS.get()->getType()->isVectorType() || 9513 RHS.get()->getType()->isVectorType()) { 9514 if (LHS.get()->getType()->hasIntegerRepresentation() && 9515 RHS.get()->getType()->hasIntegerRepresentation()) 9516 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9517 /*AllowBothBool*/true, 9518 /*AllowBoolConversions*/getLangOpts().ZVector); 9519 return InvalidOperands(Loc, LHS, RHS); 9520 } 9521 9522 ExprResult LHSResult = LHS, RHSResult = RHS; 9523 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9524 IsCompAssign); 9525 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9526 return QualType(); 9527 LHS = LHSResult.get(); 9528 RHS = RHSResult.get(); 9529 9530 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9531 return compType; 9532 return InvalidOperands(Loc, LHS, RHS); 9533 } 9534 9535 // C99 6.5.[13,14] 9536 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9537 SourceLocation Loc, 9538 BinaryOperatorKind Opc) { 9539 // Check vector operands differently. 9540 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9541 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9542 9543 // Diagnose cases where the user write a logical and/or but probably meant a 9544 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9545 // is a constant. 9546 if (LHS.get()->getType()->isIntegerType() && 9547 !LHS.get()->getType()->isBooleanType() && 9548 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9549 // Don't warn in macros or template instantiations. 9550 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9551 // If the RHS can be constant folded, and if it constant folds to something 9552 // that isn't 0 or 1 (which indicate a potential logical operation that 9553 // happened to fold to true/false) then warn. 9554 // Parens on the RHS are ignored. 9555 llvm::APSInt Result; 9556 if (RHS.get()->EvaluateAsInt(Result, Context)) 9557 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9558 !RHS.get()->getExprLoc().isMacroID()) || 9559 (Result != 0 && Result != 1)) { 9560 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9561 << RHS.get()->getSourceRange() 9562 << (Opc == BO_LAnd ? "&&" : "||"); 9563 // Suggest replacing the logical operator with the bitwise version 9564 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9565 << (Opc == BO_LAnd ? "&" : "|") 9566 << FixItHint::CreateReplacement(SourceRange( 9567 Loc, getLocForEndOfToken(Loc)), 9568 Opc == BO_LAnd ? "&" : "|"); 9569 if (Opc == BO_LAnd) 9570 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9571 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9572 << FixItHint::CreateRemoval( 9573 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9574 RHS.get()->getLocEnd())); 9575 } 9576 } 9577 9578 if (!Context.getLangOpts().CPlusPlus) { 9579 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9580 // not operate on the built-in scalar and vector float types. 9581 if (Context.getLangOpts().OpenCL && 9582 Context.getLangOpts().OpenCLVersion < 120) { 9583 if (LHS.get()->getType()->isFloatingType() || 9584 RHS.get()->getType()->isFloatingType()) 9585 return InvalidOperands(Loc, LHS, RHS); 9586 } 9587 9588 LHS = UsualUnaryConversions(LHS.get()); 9589 if (LHS.isInvalid()) 9590 return QualType(); 9591 9592 RHS = UsualUnaryConversions(RHS.get()); 9593 if (RHS.isInvalid()) 9594 return QualType(); 9595 9596 if (!LHS.get()->getType()->isScalarType() || 9597 !RHS.get()->getType()->isScalarType()) 9598 return InvalidOperands(Loc, LHS, RHS); 9599 9600 return Context.IntTy; 9601 } 9602 9603 // The following is safe because we only use this method for 9604 // non-overloadable operands. 9605 9606 // C++ [expr.log.and]p1 9607 // C++ [expr.log.or]p1 9608 // The operands are both contextually converted to type bool. 9609 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9610 if (LHSRes.isInvalid()) 9611 return InvalidOperands(Loc, LHS, RHS); 9612 LHS = LHSRes; 9613 9614 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9615 if (RHSRes.isInvalid()) 9616 return InvalidOperands(Loc, LHS, RHS); 9617 RHS = RHSRes; 9618 9619 // C++ [expr.log.and]p2 9620 // C++ [expr.log.or]p2 9621 // The result is a bool. 9622 return Context.BoolTy; 9623 } 9624 9625 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9626 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9627 if (!ME) return false; 9628 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9629 ObjCMessageExpr *Base = 9630 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9631 if (!Base) return false; 9632 return Base->getMethodDecl() != nullptr; 9633 } 9634 9635 /// Is the given expression (which must be 'const') a reference to a 9636 /// variable which was originally non-const, but which has become 9637 /// 'const' due to being captured within a block? 9638 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9639 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9640 assert(E->isLValue() && E->getType().isConstQualified()); 9641 E = E->IgnoreParens(); 9642 9643 // Must be a reference to a declaration from an enclosing scope. 9644 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9645 if (!DRE) return NCCK_None; 9646 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9647 9648 // The declaration must be a variable which is not declared 'const'. 9649 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9650 if (!var) return NCCK_None; 9651 if (var->getType().isConstQualified()) return NCCK_None; 9652 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9653 9654 // Decide whether the first capture was for a block or a lambda. 9655 DeclContext *DC = S.CurContext, *Prev = nullptr; 9656 // Decide whether the first capture was for a block or a lambda. 9657 while (DC) { 9658 // For init-capture, it is possible that the variable belongs to the 9659 // template pattern of the current context. 9660 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9661 if (var->isInitCapture() && 9662 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9663 break; 9664 if (DC == var->getDeclContext()) 9665 break; 9666 Prev = DC; 9667 DC = DC->getParent(); 9668 } 9669 // Unless we have an init-capture, we've gone one step too far. 9670 if (!var->isInitCapture()) 9671 DC = Prev; 9672 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9673 } 9674 9675 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9676 Ty = Ty.getNonReferenceType(); 9677 if (IsDereference && Ty->isPointerType()) 9678 Ty = Ty->getPointeeType(); 9679 return !Ty.isConstQualified(); 9680 } 9681 9682 /// Emit the "read-only variable not assignable" error and print notes to give 9683 /// more information about why the variable is not assignable, such as pointing 9684 /// to the declaration of a const variable, showing that a method is const, or 9685 /// that the function is returning a const reference. 9686 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9687 SourceLocation Loc) { 9688 // Update err_typecheck_assign_const and note_typecheck_assign_const 9689 // when this enum is changed. 9690 enum { 9691 ConstFunction, 9692 ConstVariable, 9693 ConstMember, 9694 ConstMethod, 9695 ConstUnknown, // Keep as last element 9696 }; 9697 9698 SourceRange ExprRange = E->getSourceRange(); 9699 9700 // Only emit one error on the first const found. All other consts will emit 9701 // a note to the error. 9702 bool DiagnosticEmitted = false; 9703 9704 // Track if the current expression is the result of a derefence, and if the 9705 // next checked expression is the result of a derefence. 9706 bool IsDereference = false; 9707 bool NextIsDereference = false; 9708 9709 // Loop to process MemberExpr chains. 9710 while (true) { 9711 IsDereference = NextIsDereference; 9712 NextIsDereference = false; 9713 9714 E = E->IgnoreParenImpCasts(); 9715 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9716 NextIsDereference = ME->isArrow(); 9717 const ValueDecl *VD = ME->getMemberDecl(); 9718 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9719 // Mutable fields can be modified even if the class is const. 9720 if (Field->isMutable()) { 9721 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9722 break; 9723 } 9724 9725 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9726 if (!DiagnosticEmitted) { 9727 S.Diag(Loc, diag::err_typecheck_assign_const) 9728 << ExprRange << ConstMember << false /*static*/ << Field 9729 << Field->getType(); 9730 DiagnosticEmitted = true; 9731 } 9732 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9733 << ConstMember << false /*static*/ << Field << Field->getType() 9734 << Field->getSourceRange(); 9735 } 9736 E = ME->getBase(); 9737 continue; 9738 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9739 if (VDecl->getType().isConstQualified()) { 9740 if (!DiagnosticEmitted) { 9741 S.Diag(Loc, diag::err_typecheck_assign_const) 9742 << ExprRange << ConstMember << true /*static*/ << VDecl 9743 << VDecl->getType(); 9744 DiagnosticEmitted = true; 9745 } 9746 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9747 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9748 << VDecl->getSourceRange(); 9749 } 9750 // Static fields do not inherit constness from parents. 9751 break; 9752 } 9753 break; 9754 } // End MemberExpr 9755 break; 9756 } 9757 9758 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9759 // Function calls 9760 const FunctionDecl *FD = CE->getDirectCallee(); 9761 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9762 if (!DiagnosticEmitted) { 9763 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9764 << ConstFunction << FD; 9765 DiagnosticEmitted = true; 9766 } 9767 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9768 diag::note_typecheck_assign_const) 9769 << ConstFunction << FD << FD->getReturnType() 9770 << FD->getReturnTypeSourceRange(); 9771 } 9772 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9773 // Point to variable declaration. 9774 if (const ValueDecl *VD = DRE->getDecl()) { 9775 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9776 if (!DiagnosticEmitted) { 9777 S.Diag(Loc, diag::err_typecheck_assign_const) 9778 << ExprRange << ConstVariable << VD << VD->getType(); 9779 DiagnosticEmitted = true; 9780 } 9781 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9782 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9783 } 9784 } 9785 } else if (isa<CXXThisExpr>(E)) { 9786 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9787 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9788 if (MD->isConst()) { 9789 if (!DiagnosticEmitted) { 9790 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9791 << ConstMethod << MD; 9792 DiagnosticEmitted = true; 9793 } 9794 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9795 << ConstMethod << MD << MD->getSourceRange(); 9796 } 9797 } 9798 } 9799 } 9800 9801 if (DiagnosticEmitted) 9802 return; 9803 9804 // Can't determine a more specific message, so display the generic error. 9805 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9806 } 9807 9808 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9809 /// emit an error and return true. If so, return false. 9810 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9811 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9812 9813 S.CheckShadowingDeclModification(E, Loc); 9814 9815 SourceLocation OrigLoc = Loc; 9816 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9817 &Loc); 9818 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9819 IsLV = Expr::MLV_InvalidMessageExpression; 9820 if (IsLV == Expr::MLV_Valid) 9821 return false; 9822 9823 unsigned DiagID = 0; 9824 bool NeedType = false; 9825 switch (IsLV) { // C99 6.5.16p2 9826 case Expr::MLV_ConstQualified: 9827 // Use a specialized diagnostic when we're assigning to an object 9828 // from an enclosing function or block. 9829 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9830 if (NCCK == NCCK_Block) 9831 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9832 else 9833 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9834 break; 9835 } 9836 9837 // In ARC, use some specialized diagnostics for occasions where we 9838 // infer 'const'. These are always pseudo-strong variables. 9839 if (S.getLangOpts().ObjCAutoRefCount) { 9840 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9841 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9842 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9843 9844 // Use the normal diagnostic if it's pseudo-__strong but the 9845 // user actually wrote 'const'. 9846 if (var->isARCPseudoStrong() && 9847 (!var->getTypeSourceInfo() || 9848 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9849 // There are two pseudo-strong cases: 9850 // - self 9851 ObjCMethodDecl *method = S.getCurMethodDecl(); 9852 if (method && var == method->getSelfDecl()) 9853 DiagID = method->isClassMethod() 9854 ? diag::err_typecheck_arc_assign_self_class_method 9855 : diag::err_typecheck_arc_assign_self; 9856 9857 // - fast enumeration variables 9858 else 9859 DiagID = diag::err_typecheck_arr_assign_enumeration; 9860 9861 SourceRange Assign; 9862 if (Loc != OrigLoc) 9863 Assign = SourceRange(OrigLoc, OrigLoc); 9864 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9865 // We need to preserve the AST regardless, so migration tool 9866 // can do its job. 9867 return false; 9868 } 9869 } 9870 } 9871 9872 // If none of the special cases above are triggered, then this is a 9873 // simple const assignment. 9874 if (DiagID == 0) { 9875 DiagnoseConstAssignment(S, E, Loc); 9876 return true; 9877 } 9878 9879 break; 9880 case Expr::MLV_ConstAddrSpace: 9881 DiagnoseConstAssignment(S, E, Loc); 9882 return true; 9883 case Expr::MLV_ArrayType: 9884 case Expr::MLV_ArrayTemporary: 9885 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9886 NeedType = true; 9887 break; 9888 case Expr::MLV_NotObjectType: 9889 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9890 NeedType = true; 9891 break; 9892 case Expr::MLV_LValueCast: 9893 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9894 break; 9895 case Expr::MLV_Valid: 9896 llvm_unreachable("did not take early return for MLV_Valid"); 9897 case Expr::MLV_InvalidExpression: 9898 case Expr::MLV_MemberFunction: 9899 case Expr::MLV_ClassTemporary: 9900 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9901 break; 9902 case Expr::MLV_IncompleteType: 9903 case Expr::MLV_IncompleteVoidType: 9904 return S.RequireCompleteType(Loc, E->getType(), 9905 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9906 case Expr::MLV_DuplicateVectorComponents: 9907 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9908 break; 9909 case Expr::MLV_NoSetterProperty: 9910 llvm_unreachable("readonly properties should be processed differently"); 9911 case Expr::MLV_InvalidMessageExpression: 9912 DiagID = diag::error_readonly_message_assignment; 9913 break; 9914 case Expr::MLV_SubObjCPropertySetting: 9915 DiagID = diag::error_no_subobject_property_setting; 9916 break; 9917 } 9918 9919 SourceRange Assign; 9920 if (Loc != OrigLoc) 9921 Assign = SourceRange(OrigLoc, OrigLoc); 9922 if (NeedType) 9923 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9924 else 9925 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9926 return true; 9927 } 9928 9929 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9930 SourceLocation Loc, 9931 Sema &Sema) { 9932 // C / C++ fields 9933 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9934 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9935 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9936 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9937 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9938 } 9939 9940 // Objective-C instance variables 9941 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9942 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9943 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9944 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9945 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9946 if (RL && RR && RL->getDecl() == RR->getDecl()) 9947 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9948 } 9949 } 9950 9951 // C99 6.5.16.1 9952 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9953 SourceLocation Loc, 9954 QualType CompoundType) { 9955 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9956 9957 // Verify that LHS is a modifiable lvalue, and emit error if not. 9958 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9959 return QualType(); 9960 9961 QualType LHSType = LHSExpr->getType(); 9962 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9963 CompoundType; 9964 AssignConvertType ConvTy; 9965 if (CompoundType.isNull()) { 9966 Expr *RHSCheck = RHS.get(); 9967 9968 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9969 9970 QualType LHSTy(LHSType); 9971 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9972 if (RHS.isInvalid()) 9973 return QualType(); 9974 // Special case of NSObject attributes on c-style pointer types. 9975 if (ConvTy == IncompatiblePointer && 9976 ((Context.isObjCNSObjectType(LHSType) && 9977 RHSType->isObjCObjectPointerType()) || 9978 (Context.isObjCNSObjectType(RHSType) && 9979 LHSType->isObjCObjectPointerType()))) 9980 ConvTy = Compatible; 9981 9982 if (ConvTy == Compatible && 9983 LHSType->isObjCObjectType()) 9984 Diag(Loc, diag::err_objc_object_assignment) 9985 << LHSType; 9986 9987 // If the RHS is a unary plus or minus, check to see if they = and + are 9988 // right next to each other. If so, the user may have typo'd "x =+ 4" 9989 // instead of "x += 4". 9990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9991 RHSCheck = ICE->getSubExpr(); 9992 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9993 if ((UO->getOpcode() == UO_Plus || 9994 UO->getOpcode() == UO_Minus) && 9995 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9996 // Only if the two operators are exactly adjacent. 9997 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9998 // And there is a space or other character before the subexpr of the 9999 // unary +/-. We don't want to warn on "x=-1". 10000 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10001 UO->getSubExpr()->getLocStart().isFileID()) { 10002 Diag(Loc, diag::warn_not_compound_assign) 10003 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10004 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10005 } 10006 } 10007 10008 if (ConvTy == Compatible) { 10009 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10010 // Warn about retain cycles where a block captures the LHS, but 10011 // not if the LHS is a simple variable into which the block is 10012 // being stored...unless that variable can be captured by reference! 10013 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10014 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10015 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10016 checkRetainCycles(LHSExpr, RHS.get()); 10017 10018 // It is safe to assign a weak reference into a strong variable. 10019 // Although this code can still have problems: 10020 // id x = self.weakProp; 10021 // id y = self.weakProp; 10022 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10023 // paths through the function. This should be revisited if 10024 // -Wrepeated-use-of-weak is made flow-sensitive. 10025 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10026 RHS.get()->getLocStart())) 10027 getCurFunction()->markSafeWeakUse(RHS.get()); 10028 10029 } else if (getLangOpts().ObjCAutoRefCount) { 10030 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10031 } 10032 } 10033 } else { 10034 // Compound assignment "x += y" 10035 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10036 } 10037 10038 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10039 RHS.get(), AA_Assigning)) 10040 return QualType(); 10041 10042 CheckForNullPointerDereference(*this, LHSExpr); 10043 10044 // C99 6.5.16p3: The type of an assignment expression is the type of the 10045 // left operand unless the left operand has qualified type, in which case 10046 // it is the unqualified version of the type of the left operand. 10047 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10048 // is converted to the type of the assignment expression (above). 10049 // C++ 5.17p1: the type of the assignment expression is that of its left 10050 // operand. 10051 return (getLangOpts().CPlusPlus 10052 ? LHSType : LHSType.getUnqualifiedType()); 10053 } 10054 10055 // Only ignore explicit casts to void. 10056 static bool IgnoreCommaOperand(const Expr *E) { 10057 E = E->IgnoreParens(); 10058 10059 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10060 if (CE->getCastKind() == CK_ToVoid) { 10061 return true; 10062 } 10063 } 10064 10065 return false; 10066 } 10067 10068 // Look for instances where it is likely the comma operator is confused with 10069 // another operator. There is a whitelist of acceptable expressions for the 10070 // left hand side of the comma operator, otherwise emit a warning. 10071 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10072 // No warnings in macros 10073 if (Loc.isMacroID()) 10074 return; 10075 10076 // Don't warn in template instantiations. 10077 if (!ActiveTemplateInstantiations.empty()) 10078 return; 10079 10080 // Scope isn't fine-grained enough to whitelist the specific cases, so 10081 // instead, skip more than needed, then call back into here with the 10082 // CommaVisitor in SemaStmt.cpp. 10083 // The whitelisted locations are the initialization and increment portions 10084 // of a for loop. The additional checks are on the condition of 10085 // if statements, do/while loops, and for loops. 10086 const unsigned ForIncrementFlags = 10087 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10088 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10089 const unsigned ScopeFlags = getCurScope()->getFlags(); 10090 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10091 (ScopeFlags & ForInitFlags) == ForInitFlags) 10092 return; 10093 10094 // If there are multiple comma operators used together, get the RHS of the 10095 // of the comma operator as the LHS. 10096 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10097 if (BO->getOpcode() != BO_Comma) 10098 break; 10099 LHS = BO->getRHS(); 10100 } 10101 10102 // Only allow some expressions on LHS to not warn. 10103 if (IgnoreCommaOperand(LHS)) 10104 return; 10105 10106 Diag(Loc, diag::warn_comma_operator); 10107 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10108 << LHS->getSourceRange() 10109 << FixItHint::CreateInsertion(LHS->getLocStart(), 10110 LangOpts.CPlusPlus ? "static_cast<void>(" 10111 : "(void)(") 10112 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10113 ")"); 10114 } 10115 10116 // C99 6.5.17 10117 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10118 SourceLocation Loc) { 10119 LHS = S.CheckPlaceholderExpr(LHS.get()); 10120 RHS = S.CheckPlaceholderExpr(RHS.get()); 10121 if (LHS.isInvalid() || RHS.isInvalid()) 10122 return QualType(); 10123 10124 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10125 // operands, but not unary promotions. 10126 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10127 10128 // So we treat the LHS as a ignored value, and in C++ we allow the 10129 // containing site to determine what should be done with the RHS. 10130 LHS = S.IgnoredValueConversions(LHS.get()); 10131 if (LHS.isInvalid()) 10132 return QualType(); 10133 10134 S.DiagnoseUnusedExprResult(LHS.get()); 10135 10136 if (!S.getLangOpts().CPlusPlus) { 10137 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10138 if (RHS.isInvalid()) 10139 return QualType(); 10140 if (!RHS.get()->getType()->isVoidType()) 10141 S.RequireCompleteType(Loc, RHS.get()->getType(), 10142 diag::err_incomplete_type); 10143 } 10144 10145 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10146 S.DiagnoseCommaOperator(LHS.get(), Loc); 10147 10148 return RHS.get()->getType(); 10149 } 10150 10151 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10152 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10153 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10154 ExprValueKind &VK, 10155 ExprObjectKind &OK, 10156 SourceLocation OpLoc, 10157 bool IsInc, bool IsPrefix) { 10158 if (Op->isTypeDependent()) 10159 return S.Context.DependentTy; 10160 10161 QualType ResType = Op->getType(); 10162 // Atomic types can be used for increment / decrement where the non-atomic 10163 // versions can, so ignore the _Atomic() specifier for the purpose of 10164 // checking. 10165 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10166 ResType = ResAtomicType->getValueType(); 10167 10168 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10169 10170 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10171 // Decrement of bool is not allowed. 10172 if (!IsInc) { 10173 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10174 return QualType(); 10175 } 10176 // Increment of bool sets it to true, but is deprecated. 10177 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10178 : diag::warn_increment_bool) 10179 << Op->getSourceRange(); 10180 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10181 // Error on enum increments and decrements in C++ mode 10182 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10183 return QualType(); 10184 } else if (ResType->isRealType()) { 10185 // OK! 10186 } else if (ResType->isPointerType()) { 10187 // C99 6.5.2.4p2, 6.5.6p2 10188 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10189 return QualType(); 10190 } else if (ResType->isObjCObjectPointerType()) { 10191 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10192 // Otherwise, we just need a complete type. 10193 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10194 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10195 return QualType(); 10196 } else if (ResType->isAnyComplexType()) { 10197 // C99 does not support ++/-- on complex types, we allow as an extension. 10198 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10199 << ResType << Op->getSourceRange(); 10200 } else if (ResType->isPlaceholderType()) { 10201 ExprResult PR = S.CheckPlaceholderExpr(Op); 10202 if (PR.isInvalid()) return QualType(); 10203 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10204 IsInc, IsPrefix); 10205 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10206 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10207 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10208 (ResType->getAs<VectorType>()->getVectorKind() != 10209 VectorType::AltiVecBool)) { 10210 // The z vector extensions allow ++ and -- for non-bool vectors. 10211 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10212 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10213 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10214 } else { 10215 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10216 << ResType << int(IsInc) << Op->getSourceRange(); 10217 return QualType(); 10218 } 10219 // At this point, we know we have a real, complex or pointer type. 10220 // Now make sure the operand is a modifiable lvalue. 10221 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10222 return QualType(); 10223 // In C++, a prefix increment is the same type as the operand. Otherwise 10224 // (in C or with postfix), the increment is the unqualified type of the 10225 // operand. 10226 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10227 VK = VK_LValue; 10228 OK = Op->getObjectKind(); 10229 return ResType; 10230 } else { 10231 VK = VK_RValue; 10232 return ResType.getUnqualifiedType(); 10233 } 10234 } 10235 10236 10237 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10238 /// This routine allows us to typecheck complex/recursive expressions 10239 /// where the declaration is needed for type checking. We only need to 10240 /// handle cases when the expression references a function designator 10241 /// or is an lvalue. Here are some examples: 10242 /// - &(x) => x 10243 /// - &*****f => f for f a function designator. 10244 /// - &s.xx => s 10245 /// - &s.zz[1].yy -> s, if zz is an array 10246 /// - *(x + 1) -> x, if x is an array 10247 /// - &"123"[2] -> 0 10248 /// - & __real__ x -> x 10249 static ValueDecl *getPrimaryDecl(Expr *E) { 10250 switch (E->getStmtClass()) { 10251 case Stmt::DeclRefExprClass: 10252 return cast<DeclRefExpr>(E)->getDecl(); 10253 case Stmt::MemberExprClass: 10254 // If this is an arrow operator, the address is an offset from 10255 // the base's value, so the object the base refers to is 10256 // irrelevant. 10257 if (cast<MemberExpr>(E)->isArrow()) 10258 return nullptr; 10259 // Otherwise, the expression refers to a part of the base 10260 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10261 case Stmt::ArraySubscriptExprClass: { 10262 // FIXME: This code shouldn't be necessary! We should catch the implicit 10263 // promotion of register arrays earlier. 10264 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10265 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10266 if (ICE->getSubExpr()->getType()->isArrayType()) 10267 return getPrimaryDecl(ICE->getSubExpr()); 10268 } 10269 return nullptr; 10270 } 10271 case Stmt::UnaryOperatorClass: { 10272 UnaryOperator *UO = cast<UnaryOperator>(E); 10273 10274 switch(UO->getOpcode()) { 10275 case UO_Real: 10276 case UO_Imag: 10277 case UO_Extension: 10278 return getPrimaryDecl(UO->getSubExpr()); 10279 default: 10280 return nullptr; 10281 } 10282 } 10283 case Stmt::ParenExprClass: 10284 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10285 case Stmt::ImplicitCastExprClass: 10286 // If the result of an implicit cast is an l-value, we care about 10287 // the sub-expression; otherwise, the result here doesn't matter. 10288 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10289 default: 10290 return nullptr; 10291 } 10292 } 10293 10294 namespace { 10295 enum { 10296 AO_Bit_Field = 0, 10297 AO_Vector_Element = 1, 10298 AO_Property_Expansion = 2, 10299 AO_Register_Variable = 3, 10300 AO_No_Error = 4 10301 }; 10302 } 10303 /// \brief Diagnose invalid operand for address of operations. 10304 /// 10305 /// \param Type The type of operand which cannot have its address taken. 10306 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10307 Expr *E, unsigned Type) { 10308 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10309 } 10310 10311 /// CheckAddressOfOperand - The operand of & must be either a function 10312 /// designator or an lvalue designating an object. If it is an lvalue, the 10313 /// object cannot be declared with storage class register or be a bit field. 10314 /// Note: The usual conversions are *not* applied to the operand of the & 10315 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10316 /// In C++, the operand might be an overloaded function name, in which case 10317 /// we allow the '&' but retain the overloaded-function type. 10318 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10319 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10320 if (PTy->getKind() == BuiltinType::Overload) { 10321 Expr *E = OrigOp.get()->IgnoreParens(); 10322 if (!isa<OverloadExpr>(E)) { 10323 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10324 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10325 << OrigOp.get()->getSourceRange(); 10326 return QualType(); 10327 } 10328 10329 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10330 if (isa<UnresolvedMemberExpr>(Ovl)) 10331 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10332 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10333 << OrigOp.get()->getSourceRange(); 10334 return QualType(); 10335 } 10336 10337 return Context.OverloadTy; 10338 } 10339 10340 if (PTy->getKind() == BuiltinType::UnknownAny) 10341 return Context.UnknownAnyTy; 10342 10343 if (PTy->getKind() == BuiltinType::BoundMember) { 10344 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10345 << OrigOp.get()->getSourceRange(); 10346 return QualType(); 10347 } 10348 10349 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10350 if (OrigOp.isInvalid()) return QualType(); 10351 } 10352 10353 if (OrigOp.get()->isTypeDependent()) 10354 return Context.DependentTy; 10355 10356 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10357 10358 // Make sure to ignore parentheses in subsequent checks 10359 Expr *op = OrigOp.get()->IgnoreParens(); 10360 10361 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10362 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10363 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10364 return QualType(); 10365 } 10366 10367 if (getLangOpts().C99) { 10368 // Implement C99-only parts of addressof rules. 10369 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10370 if (uOp->getOpcode() == UO_Deref) 10371 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10372 // (assuming the deref expression is valid). 10373 return uOp->getSubExpr()->getType(); 10374 } 10375 // Technically, there should be a check for array subscript 10376 // expressions here, but the result of one is always an lvalue anyway. 10377 } 10378 ValueDecl *dcl = getPrimaryDecl(op); 10379 10380 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10381 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10382 op->getLocStart())) 10383 return QualType(); 10384 10385 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10386 unsigned AddressOfError = AO_No_Error; 10387 10388 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10389 bool sfinae = (bool)isSFINAEContext(); 10390 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10391 : diag::ext_typecheck_addrof_temporary) 10392 << op->getType() << op->getSourceRange(); 10393 if (sfinae) 10394 return QualType(); 10395 // Materialize the temporary as an lvalue so that we can take its address. 10396 OrigOp = op = 10397 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10398 } else if (isa<ObjCSelectorExpr>(op)) { 10399 return Context.getPointerType(op->getType()); 10400 } else if (lval == Expr::LV_MemberFunction) { 10401 // If it's an instance method, make a member pointer. 10402 // The expression must have exactly the form &A::foo. 10403 10404 // If the underlying expression isn't a decl ref, give up. 10405 if (!isa<DeclRefExpr>(op)) { 10406 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10407 << OrigOp.get()->getSourceRange(); 10408 return QualType(); 10409 } 10410 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10411 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10412 10413 // The id-expression was parenthesized. 10414 if (OrigOp.get() != DRE) { 10415 Diag(OpLoc, diag::err_parens_pointer_member_function) 10416 << OrigOp.get()->getSourceRange(); 10417 10418 // The method was named without a qualifier. 10419 } else if (!DRE->getQualifier()) { 10420 if (MD->getParent()->getName().empty()) 10421 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10422 << op->getSourceRange(); 10423 else { 10424 SmallString<32> Str; 10425 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10426 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10427 << op->getSourceRange() 10428 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10429 } 10430 } 10431 10432 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10433 if (isa<CXXDestructorDecl>(MD)) 10434 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10435 10436 QualType MPTy = Context.getMemberPointerType( 10437 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10438 // Under the MS ABI, lock down the inheritance model now. 10439 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10440 (void)isCompleteType(OpLoc, MPTy); 10441 return MPTy; 10442 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10443 // C99 6.5.3.2p1 10444 // The operand must be either an l-value or a function designator 10445 if (!op->getType()->isFunctionType()) { 10446 // Use a special diagnostic for loads from property references. 10447 if (isa<PseudoObjectExpr>(op)) { 10448 AddressOfError = AO_Property_Expansion; 10449 } else { 10450 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10451 << op->getType() << op->getSourceRange(); 10452 return QualType(); 10453 } 10454 } 10455 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10456 // The operand cannot be a bit-field 10457 AddressOfError = AO_Bit_Field; 10458 } else if (op->getObjectKind() == OK_VectorComponent) { 10459 // The operand cannot be an element of a vector 10460 AddressOfError = AO_Vector_Element; 10461 } else if (dcl) { // C99 6.5.3.2p1 10462 // We have an lvalue with a decl. Make sure the decl is not declared 10463 // with the register storage-class specifier. 10464 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10465 // in C++ it is not error to take address of a register 10466 // variable (c++03 7.1.1P3) 10467 if (vd->getStorageClass() == SC_Register && 10468 !getLangOpts().CPlusPlus) { 10469 AddressOfError = AO_Register_Variable; 10470 } 10471 } else if (isa<MSPropertyDecl>(dcl)) { 10472 AddressOfError = AO_Property_Expansion; 10473 } else if (isa<FunctionTemplateDecl>(dcl)) { 10474 return Context.OverloadTy; 10475 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10476 // Okay: we can take the address of a field. 10477 // Could be a pointer to member, though, if there is an explicit 10478 // scope qualifier for the class. 10479 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10480 DeclContext *Ctx = dcl->getDeclContext(); 10481 if (Ctx && Ctx->isRecord()) { 10482 if (dcl->getType()->isReferenceType()) { 10483 Diag(OpLoc, 10484 diag::err_cannot_form_pointer_to_member_of_reference_type) 10485 << dcl->getDeclName() << dcl->getType(); 10486 return QualType(); 10487 } 10488 10489 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10490 Ctx = Ctx->getParent(); 10491 10492 QualType MPTy = Context.getMemberPointerType( 10493 op->getType(), 10494 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10495 // Under the MS ABI, lock down the inheritance model now. 10496 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10497 (void)isCompleteType(OpLoc, MPTy); 10498 return MPTy; 10499 } 10500 } 10501 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10502 llvm_unreachable("Unknown/unexpected decl type"); 10503 } 10504 10505 if (AddressOfError != AO_No_Error) { 10506 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10507 return QualType(); 10508 } 10509 10510 if (lval == Expr::LV_IncompleteVoidType) { 10511 // Taking the address of a void variable is technically illegal, but we 10512 // allow it in cases which are otherwise valid. 10513 // Example: "extern void x; void* y = &x;". 10514 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10515 } 10516 10517 // If the operand has type "type", the result has type "pointer to type". 10518 if (op->getType()->isObjCObjectType()) 10519 return Context.getObjCObjectPointerType(op->getType()); 10520 10521 // OpenCL v2.0 s6.12.5 - The unary operators & cannot be used with a block. 10522 if (getLangOpts().OpenCL && OrigOp.get()->getType()->isBlockPointerType()) { 10523 Diag(OpLoc, diag::err_typecheck_unary_expr) << OrigOp.get()->getType() 10524 << op->getSourceRange(); 10525 return QualType(); 10526 } 10527 10528 return Context.getPointerType(op->getType()); 10529 } 10530 10531 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10532 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10533 if (!DRE) 10534 return; 10535 const Decl *D = DRE->getDecl(); 10536 if (!D) 10537 return; 10538 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10539 if (!Param) 10540 return; 10541 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10542 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10543 return; 10544 if (FunctionScopeInfo *FD = S.getCurFunction()) 10545 if (!FD->ModifiedNonNullParams.count(Param)) 10546 FD->ModifiedNonNullParams.insert(Param); 10547 } 10548 10549 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10550 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10551 SourceLocation OpLoc) { 10552 if (Op->isTypeDependent()) 10553 return S.Context.DependentTy; 10554 10555 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10556 if (ConvResult.isInvalid()) 10557 return QualType(); 10558 Op = ConvResult.get(); 10559 QualType OpTy = Op->getType(); 10560 QualType Result; 10561 10562 if (isa<CXXReinterpretCastExpr>(Op)) { 10563 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10564 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10565 Op->getSourceRange()); 10566 } 10567 10568 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10569 { 10570 Result = PT->getPointeeType(); 10571 // OpenCL v2.0 s6.12.5 - The unary operators * cannot be used with a block. 10572 if (S.getLangOpts().OpenCLVersion >= 200 && Result->isBlockPointerType()) { 10573 S.Diag(OpLoc, diag::err_opencl_dereferencing) << OpTy 10574 << Op->getSourceRange(); 10575 return QualType(); 10576 } 10577 } 10578 else if (const ObjCObjectPointerType *OPT = 10579 OpTy->getAs<ObjCObjectPointerType>()) 10580 Result = OPT->getPointeeType(); 10581 else { 10582 ExprResult PR = S.CheckPlaceholderExpr(Op); 10583 if (PR.isInvalid()) return QualType(); 10584 if (PR.get() != Op) 10585 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10586 } 10587 10588 if (Result.isNull()) { 10589 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10590 << OpTy << Op->getSourceRange(); 10591 return QualType(); 10592 } 10593 10594 // Note that per both C89 and C99, indirection is always legal, even if Result 10595 // is an incomplete type or void. It would be possible to warn about 10596 // dereferencing a void pointer, but it's completely well-defined, and such a 10597 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10598 // for pointers to 'void' but is fine for any other pointer type: 10599 // 10600 // C++ [expr.unary.op]p1: 10601 // [...] the expression to which [the unary * operator] is applied shall 10602 // be a pointer to an object type, or a pointer to a function type 10603 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10604 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10605 << OpTy << Op->getSourceRange(); 10606 10607 // Dereferences are usually l-values... 10608 VK = VK_LValue; 10609 10610 // ...except that certain expressions are never l-values in C. 10611 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10612 VK = VK_RValue; 10613 10614 return Result; 10615 } 10616 10617 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10618 BinaryOperatorKind Opc; 10619 switch (Kind) { 10620 default: llvm_unreachable("Unknown binop!"); 10621 case tok::periodstar: Opc = BO_PtrMemD; break; 10622 case tok::arrowstar: Opc = BO_PtrMemI; break; 10623 case tok::star: Opc = BO_Mul; break; 10624 case tok::slash: Opc = BO_Div; break; 10625 case tok::percent: Opc = BO_Rem; break; 10626 case tok::plus: Opc = BO_Add; break; 10627 case tok::minus: Opc = BO_Sub; break; 10628 case tok::lessless: Opc = BO_Shl; break; 10629 case tok::greatergreater: Opc = BO_Shr; break; 10630 case tok::lessequal: Opc = BO_LE; break; 10631 case tok::less: Opc = BO_LT; break; 10632 case tok::greaterequal: Opc = BO_GE; break; 10633 case tok::greater: Opc = BO_GT; break; 10634 case tok::exclaimequal: Opc = BO_NE; break; 10635 case tok::equalequal: Opc = BO_EQ; break; 10636 case tok::amp: Opc = BO_And; break; 10637 case tok::caret: Opc = BO_Xor; break; 10638 case tok::pipe: Opc = BO_Or; break; 10639 case tok::ampamp: Opc = BO_LAnd; break; 10640 case tok::pipepipe: Opc = BO_LOr; break; 10641 case tok::equal: Opc = BO_Assign; break; 10642 case tok::starequal: Opc = BO_MulAssign; break; 10643 case tok::slashequal: Opc = BO_DivAssign; break; 10644 case tok::percentequal: Opc = BO_RemAssign; break; 10645 case tok::plusequal: Opc = BO_AddAssign; break; 10646 case tok::minusequal: Opc = BO_SubAssign; break; 10647 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10648 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10649 case tok::ampequal: Opc = BO_AndAssign; break; 10650 case tok::caretequal: Opc = BO_XorAssign; break; 10651 case tok::pipeequal: Opc = BO_OrAssign; break; 10652 case tok::comma: Opc = BO_Comma; break; 10653 } 10654 return Opc; 10655 } 10656 10657 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10658 tok::TokenKind Kind) { 10659 UnaryOperatorKind Opc; 10660 switch (Kind) { 10661 default: llvm_unreachable("Unknown unary op!"); 10662 case tok::plusplus: Opc = UO_PreInc; break; 10663 case tok::minusminus: Opc = UO_PreDec; break; 10664 case tok::amp: Opc = UO_AddrOf; break; 10665 case tok::star: Opc = UO_Deref; break; 10666 case tok::plus: Opc = UO_Plus; break; 10667 case tok::minus: Opc = UO_Minus; break; 10668 case tok::tilde: Opc = UO_Not; break; 10669 case tok::exclaim: Opc = UO_LNot; break; 10670 case tok::kw___real: Opc = UO_Real; break; 10671 case tok::kw___imag: Opc = UO_Imag; break; 10672 case tok::kw___extension__: Opc = UO_Extension; break; 10673 } 10674 return Opc; 10675 } 10676 10677 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10678 /// This warning is only emitted for builtin assignment operations. It is also 10679 /// suppressed in the event of macro expansions. 10680 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10681 SourceLocation OpLoc) { 10682 if (!S.ActiveTemplateInstantiations.empty()) 10683 return; 10684 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10685 return; 10686 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10687 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10688 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10689 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10690 if (!LHSDeclRef || !RHSDeclRef || 10691 LHSDeclRef->getLocation().isMacroID() || 10692 RHSDeclRef->getLocation().isMacroID()) 10693 return; 10694 const ValueDecl *LHSDecl = 10695 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10696 const ValueDecl *RHSDecl = 10697 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10698 if (LHSDecl != RHSDecl) 10699 return; 10700 if (LHSDecl->getType().isVolatileQualified()) 10701 return; 10702 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10703 if (RefTy->getPointeeType().isVolatileQualified()) 10704 return; 10705 10706 S.Diag(OpLoc, diag::warn_self_assignment) 10707 << LHSDeclRef->getType() 10708 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10709 } 10710 10711 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10712 /// is usually indicative of introspection within the Objective-C pointer. 10713 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10714 SourceLocation OpLoc) { 10715 if (!S.getLangOpts().ObjC1) 10716 return; 10717 10718 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10719 const Expr *LHS = L.get(); 10720 const Expr *RHS = R.get(); 10721 10722 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10723 ObjCPointerExpr = LHS; 10724 OtherExpr = RHS; 10725 } 10726 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10727 ObjCPointerExpr = RHS; 10728 OtherExpr = LHS; 10729 } 10730 10731 // This warning is deliberately made very specific to reduce false 10732 // positives with logic that uses '&' for hashing. This logic mainly 10733 // looks for code trying to introspect into tagged pointers, which 10734 // code should generally never do. 10735 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10736 unsigned Diag = diag::warn_objc_pointer_masking; 10737 // Determine if we are introspecting the result of performSelectorXXX. 10738 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10739 // Special case messages to -performSelector and friends, which 10740 // can return non-pointer values boxed in a pointer value. 10741 // Some clients may wish to silence warnings in this subcase. 10742 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10743 Selector S = ME->getSelector(); 10744 StringRef SelArg0 = S.getNameForSlot(0); 10745 if (SelArg0.startswith("performSelector")) 10746 Diag = diag::warn_objc_pointer_masking_performSelector; 10747 } 10748 10749 S.Diag(OpLoc, Diag) 10750 << ObjCPointerExpr->getSourceRange(); 10751 } 10752 } 10753 10754 static NamedDecl *getDeclFromExpr(Expr *E) { 10755 if (!E) 10756 return nullptr; 10757 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10758 return DRE->getDecl(); 10759 if (auto *ME = dyn_cast<MemberExpr>(E)) 10760 return ME->getMemberDecl(); 10761 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10762 return IRE->getDecl(); 10763 return nullptr; 10764 } 10765 10766 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10767 /// operator @p Opc at location @c TokLoc. This routine only supports 10768 /// built-in operations; ActOnBinOp handles overloaded operators. 10769 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10770 BinaryOperatorKind Opc, 10771 Expr *LHSExpr, Expr *RHSExpr) { 10772 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10773 // The syntax only allows initializer lists on the RHS of assignment, 10774 // so we don't need to worry about accepting invalid code for 10775 // non-assignment operators. 10776 // C++11 5.17p9: 10777 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10778 // of x = {} is x = T(). 10779 InitializationKind Kind = 10780 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10781 InitializedEntity Entity = 10782 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10783 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10784 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10785 if (Init.isInvalid()) 10786 return Init; 10787 RHSExpr = Init.get(); 10788 } 10789 10790 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10791 QualType ResultTy; // Result type of the binary operator. 10792 // The following two variables are used for compound assignment operators 10793 QualType CompLHSTy; // Type of LHS after promotions for computation 10794 QualType CompResultTy; // Type of computation result 10795 ExprValueKind VK = VK_RValue; 10796 ExprObjectKind OK = OK_Ordinary; 10797 10798 if (!getLangOpts().CPlusPlus) { 10799 // C cannot handle TypoExpr nodes on either side of a binop because it 10800 // doesn't handle dependent types properly, so make sure any TypoExprs have 10801 // been dealt with before checking the operands. 10802 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10803 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10804 if (Opc != BO_Assign) 10805 return ExprResult(E); 10806 // Avoid correcting the RHS to the same Expr as the LHS. 10807 Decl *D = getDeclFromExpr(E); 10808 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10809 }); 10810 if (!LHS.isUsable() || !RHS.isUsable()) 10811 return ExprError(); 10812 } 10813 10814 if (getLangOpts().OpenCL) { 10815 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10816 // the ATOMIC_VAR_INIT macro. 10817 if (LHSExpr->getType()->isAtomicType() || 10818 RHSExpr->getType()->isAtomicType()) { 10819 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10820 if (BO_Assign == Opc) 10821 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10822 else 10823 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10824 return ExprError(); 10825 } 10826 } 10827 10828 switch (Opc) { 10829 case BO_Assign: 10830 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10831 if (getLangOpts().CPlusPlus && 10832 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10833 VK = LHS.get()->getValueKind(); 10834 OK = LHS.get()->getObjectKind(); 10835 } 10836 if (!ResultTy.isNull()) { 10837 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10838 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10839 } 10840 RecordModifiableNonNullParam(*this, LHS.get()); 10841 break; 10842 case BO_PtrMemD: 10843 case BO_PtrMemI: 10844 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10845 Opc == BO_PtrMemI); 10846 break; 10847 case BO_Mul: 10848 case BO_Div: 10849 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10850 Opc == BO_Div); 10851 break; 10852 case BO_Rem: 10853 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10854 break; 10855 case BO_Add: 10856 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10857 break; 10858 case BO_Sub: 10859 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10860 break; 10861 case BO_Shl: 10862 case BO_Shr: 10863 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10864 break; 10865 case BO_LE: 10866 case BO_LT: 10867 case BO_GE: 10868 case BO_GT: 10869 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10870 break; 10871 case BO_EQ: 10872 case BO_NE: 10873 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10874 break; 10875 case BO_And: 10876 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10877 case BO_Xor: 10878 case BO_Or: 10879 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10880 break; 10881 case BO_LAnd: 10882 case BO_LOr: 10883 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10884 break; 10885 case BO_MulAssign: 10886 case BO_DivAssign: 10887 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10888 Opc == BO_DivAssign); 10889 CompLHSTy = CompResultTy; 10890 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10891 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10892 break; 10893 case BO_RemAssign: 10894 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10895 CompLHSTy = CompResultTy; 10896 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10897 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10898 break; 10899 case BO_AddAssign: 10900 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10901 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10902 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10903 break; 10904 case BO_SubAssign: 10905 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10906 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10907 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10908 break; 10909 case BO_ShlAssign: 10910 case BO_ShrAssign: 10911 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10912 CompLHSTy = CompResultTy; 10913 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10914 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10915 break; 10916 case BO_AndAssign: 10917 case BO_OrAssign: // fallthrough 10918 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10919 case BO_XorAssign: 10920 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10921 CompLHSTy = CompResultTy; 10922 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10923 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10924 break; 10925 case BO_Comma: 10926 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10927 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10928 VK = RHS.get()->getValueKind(); 10929 OK = RHS.get()->getObjectKind(); 10930 } 10931 break; 10932 } 10933 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10934 return ExprError(); 10935 10936 // Check for array bounds violations for both sides of the BinaryOperator 10937 CheckArrayAccess(LHS.get()); 10938 CheckArrayAccess(RHS.get()); 10939 10940 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10941 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10942 &Context.Idents.get("object_setClass"), 10943 SourceLocation(), LookupOrdinaryName); 10944 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10945 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 10946 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10947 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10948 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10949 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10950 } 10951 else 10952 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10953 } 10954 else if (const ObjCIvarRefExpr *OIRE = 10955 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10956 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10957 10958 if (CompResultTy.isNull()) 10959 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10960 OK, OpLoc, FPFeatures.fp_contract); 10961 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10962 OK_ObjCProperty) { 10963 VK = VK_LValue; 10964 OK = LHS.get()->getObjectKind(); 10965 } 10966 return new (Context) CompoundAssignOperator( 10967 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10968 OpLoc, FPFeatures.fp_contract); 10969 } 10970 10971 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10972 /// operators are mixed in a way that suggests that the programmer forgot that 10973 /// comparison operators have higher precedence. The most typical example of 10974 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10975 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10976 SourceLocation OpLoc, Expr *LHSExpr, 10977 Expr *RHSExpr) { 10978 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10979 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10980 10981 // Check that one of the sides is a comparison operator and the other isn't. 10982 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10983 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10984 if (isLeftComp == isRightComp) 10985 return; 10986 10987 // Bitwise operations are sometimes used as eager logical ops. 10988 // Don't diagnose this. 10989 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10990 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10991 if (isLeftBitwise || isRightBitwise) 10992 return; 10993 10994 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10995 OpLoc) 10996 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10997 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10998 SourceRange ParensRange = isLeftComp ? 10999 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11000 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11001 11002 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11003 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11004 SuggestParentheses(Self, OpLoc, 11005 Self.PDiag(diag::note_precedence_silence) << OpStr, 11006 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11007 SuggestParentheses(Self, OpLoc, 11008 Self.PDiag(diag::note_precedence_bitwise_first) 11009 << BinaryOperator::getOpcodeStr(Opc), 11010 ParensRange); 11011 } 11012 11013 /// \brief It accepts a '&&' expr that is inside a '||' one. 11014 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11015 /// in parentheses. 11016 static void 11017 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11018 BinaryOperator *Bop) { 11019 assert(Bop->getOpcode() == BO_LAnd); 11020 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11021 << Bop->getSourceRange() << OpLoc; 11022 SuggestParentheses(Self, Bop->getOperatorLoc(), 11023 Self.PDiag(diag::note_precedence_silence) 11024 << Bop->getOpcodeStr(), 11025 Bop->getSourceRange()); 11026 } 11027 11028 /// \brief Returns true if the given expression can be evaluated as a constant 11029 /// 'true'. 11030 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11031 bool Res; 11032 return !E->isValueDependent() && 11033 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11034 } 11035 11036 /// \brief Returns true if the given expression can be evaluated as a constant 11037 /// 'false'. 11038 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11039 bool Res; 11040 return !E->isValueDependent() && 11041 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11042 } 11043 11044 /// \brief Look for '&&' in the left hand of a '||' expr. 11045 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11046 Expr *LHSExpr, Expr *RHSExpr) { 11047 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11048 if (Bop->getOpcode() == BO_LAnd) { 11049 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11050 if (EvaluatesAsFalse(S, RHSExpr)) 11051 return; 11052 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11053 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11054 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11055 } else if (Bop->getOpcode() == BO_LOr) { 11056 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11057 // If it's "a || b && 1 || c" we didn't warn earlier for 11058 // "a || b && 1", but warn now. 11059 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11060 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11061 } 11062 } 11063 } 11064 } 11065 11066 /// \brief Look for '&&' in the right hand of a '||' expr. 11067 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11068 Expr *LHSExpr, Expr *RHSExpr) { 11069 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11070 if (Bop->getOpcode() == BO_LAnd) { 11071 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11072 if (EvaluatesAsFalse(S, LHSExpr)) 11073 return; 11074 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11075 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11076 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11077 } 11078 } 11079 } 11080 11081 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11082 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11083 /// the '&' expression in parentheses. 11084 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11085 SourceLocation OpLoc, Expr *SubExpr) { 11086 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11087 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11088 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11089 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11090 << Bop->getSourceRange() << OpLoc; 11091 SuggestParentheses(S, Bop->getOperatorLoc(), 11092 S.PDiag(diag::note_precedence_silence) 11093 << Bop->getOpcodeStr(), 11094 Bop->getSourceRange()); 11095 } 11096 } 11097 } 11098 11099 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11100 Expr *SubExpr, StringRef Shift) { 11101 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11102 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11103 StringRef Op = Bop->getOpcodeStr(); 11104 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11105 << Bop->getSourceRange() << OpLoc << Shift << Op; 11106 SuggestParentheses(S, Bop->getOperatorLoc(), 11107 S.PDiag(diag::note_precedence_silence) << Op, 11108 Bop->getSourceRange()); 11109 } 11110 } 11111 } 11112 11113 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11114 Expr *LHSExpr, Expr *RHSExpr) { 11115 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11116 if (!OCE) 11117 return; 11118 11119 FunctionDecl *FD = OCE->getDirectCallee(); 11120 if (!FD || !FD->isOverloadedOperator()) 11121 return; 11122 11123 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11124 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11125 return; 11126 11127 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11128 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11129 << (Kind == OO_LessLess); 11130 SuggestParentheses(S, OCE->getOperatorLoc(), 11131 S.PDiag(diag::note_precedence_silence) 11132 << (Kind == OO_LessLess ? "<<" : ">>"), 11133 OCE->getSourceRange()); 11134 SuggestParentheses(S, OpLoc, 11135 S.PDiag(diag::note_evaluate_comparison_first), 11136 SourceRange(OCE->getArg(1)->getLocStart(), 11137 RHSExpr->getLocEnd())); 11138 } 11139 11140 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11141 /// precedence. 11142 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11143 SourceLocation OpLoc, Expr *LHSExpr, 11144 Expr *RHSExpr){ 11145 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11146 if (BinaryOperator::isBitwiseOp(Opc)) 11147 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11148 11149 // Diagnose "arg1 & arg2 | arg3" 11150 if ((Opc == BO_Or || Opc == BO_Xor) && 11151 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11152 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11153 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11154 } 11155 11156 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11157 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11158 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11159 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11160 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11161 } 11162 11163 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11164 || Opc == BO_Shr) { 11165 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11166 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11167 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11168 } 11169 11170 // Warn on overloaded shift operators and comparisons, such as: 11171 // cout << 5 == 4; 11172 if (BinaryOperator::isComparisonOp(Opc)) 11173 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11174 } 11175 11176 // Binary Operators. 'Tok' is the token for the operator. 11177 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11178 tok::TokenKind Kind, 11179 Expr *LHSExpr, Expr *RHSExpr) { 11180 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11181 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11182 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11183 11184 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11185 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11186 11187 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11188 } 11189 11190 /// Build an overloaded binary operator expression in the given scope. 11191 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11192 BinaryOperatorKind Opc, 11193 Expr *LHS, Expr *RHS) { 11194 // Find all of the overloaded operators visible from this 11195 // point. We perform both an operator-name lookup from the local 11196 // scope and an argument-dependent lookup based on the types of 11197 // the arguments. 11198 UnresolvedSet<16> Functions; 11199 OverloadedOperatorKind OverOp 11200 = BinaryOperator::getOverloadedOperator(Opc); 11201 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11202 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11203 RHS->getType(), Functions); 11204 11205 // Build the (potentially-overloaded, potentially-dependent) 11206 // binary operation. 11207 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11208 } 11209 11210 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11211 BinaryOperatorKind Opc, 11212 Expr *LHSExpr, Expr *RHSExpr) { 11213 // We want to end up calling one of checkPseudoObjectAssignment 11214 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11215 // both expressions are overloadable or either is type-dependent), 11216 // or CreateBuiltinBinOp (in any other case). We also want to get 11217 // any placeholder types out of the way. 11218 11219 // Handle pseudo-objects in the LHS. 11220 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11221 // Assignments with a pseudo-object l-value need special analysis. 11222 if (pty->getKind() == BuiltinType::PseudoObject && 11223 BinaryOperator::isAssignmentOp(Opc)) 11224 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11225 11226 // Don't resolve overloads if the other type is overloadable. 11227 if (pty->getKind() == BuiltinType::Overload) { 11228 // We can't actually test that if we still have a placeholder, 11229 // though. Fortunately, none of the exceptions we see in that 11230 // code below are valid when the LHS is an overload set. Note 11231 // that an overload set can be dependently-typed, but it never 11232 // instantiates to having an overloadable type. 11233 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11234 if (resolvedRHS.isInvalid()) return ExprError(); 11235 RHSExpr = resolvedRHS.get(); 11236 11237 if (RHSExpr->isTypeDependent() || 11238 RHSExpr->getType()->isOverloadableType()) 11239 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11240 } 11241 11242 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11243 if (LHS.isInvalid()) return ExprError(); 11244 LHSExpr = LHS.get(); 11245 } 11246 11247 // Handle pseudo-objects in the RHS. 11248 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11249 // An overload in the RHS can potentially be resolved by the type 11250 // being assigned to. 11251 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11252 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11253 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11254 11255 if (LHSExpr->getType()->isOverloadableType()) 11256 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11257 11258 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11259 } 11260 11261 // Don't resolve overloads if the other type is overloadable. 11262 if (pty->getKind() == BuiltinType::Overload && 11263 LHSExpr->getType()->isOverloadableType()) 11264 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11265 11266 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11267 if (!resolvedRHS.isUsable()) return ExprError(); 11268 RHSExpr = resolvedRHS.get(); 11269 } 11270 11271 if (getLangOpts().CPlusPlus) { 11272 // If either expression is type-dependent, always build an 11273 // overloaded op. 11274 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11275 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11276 11277 // Otherwise, build an overloaded op if either expression has an 11278 // overloadable type. 11279 if (LHSExpr->getType()->isOverloadableType() || 11280 RHSExpr->getType()->isOverloadableType()) 11281 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11282 } 11283 11284 // Build a built-in binary operation. 11285 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11286 } 11287 11288 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11289 UnaryOperatorKind Opc, 11290 Expr *InputExpr) { 11291 ExprResult Input = InputExpr; 11292 ExprValueKind VK = VK_RValue; 11293 ExprObjectKind OK = OK_Ordinary; 11294 QualType resultType; 11295 if (getLangOpts().OpenCL) { 11296 // The only legal unary operation for atomics is '&'. 11297 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 11298 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11299 << InputExpr->getType() 11300 << Input.get()->getSourceRange()); 11301 } 11302 } 11303 switch (Opc) { 11304 case UO_PreInc: 11305 case UO_PreDec: 11306 case UO_PostInc: 11307 case UO_PostDec: 11308 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11309 OpLoc, 11310 Opc == UO_PreInc || 11311 Opc == UO_PostInc, 11312 Opc == UO_PreInc || 11313 Opc == UO_PreDec); 11314 break; 11315 case UO_AddrOf: 11316 resultType = CheckAddressOfOperand(Input, OpLoc); 11317 RecordModifiableNonNullParam(*this, InputExpr); 11318 break; 11319 case UO_Deref: { 11320 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11321 if (Input.isInvalid()) return ExprError(); 11322 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11323 break; 11324 } 11325 case UO_Plus: 11326 case UO_Minus: 11327 Input = UsualUnaryConversions(Input.get()); 11328 if (Input.isInvalid()) return ExprError(); 11329 resultType = Input.get()->getType(); 11330 if (resultType->isDependentType()) 11331 break; 11332 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11333 break; 11334 else if (resultType->isVectorType() && 11335 // The z vector extensions don't allow + or - with bool vectors. 11336 (!Context.getLangOpts().ZVector || 11337 resultType->getAs<VectorType>()->getVectorKind() != 11338 VectorType::AltiVecBool)) 11339 break; 11340 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11341 Opc == UO_Plus && 11342 resultType->isPointerType()) 11343 break; 11344 11345 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11346 << resultType << Input.get()->getSourceRange()); 11347 11348 case UO_Not: // bitwise complement 11349 Input = UsualUnaryConversions(Input.get()); 11350 if (Input.isInvalid()) 11351 return ExprError(); 11352 resultType = Input.get()->getType(); 11353 if (resultType->isDependentType()) 11354 break; 11355 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11356 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11357 // C99 does not support '~' for complex conjugation. 11358 Diag(OpLoc, diag::ext_integer_complement_complex) 11359 << resultType << Input.get()->getSourceRange(); 11360 else if (resultType->hasIntegerRepresentation()) 11361 break; 11362 else if (resultType->isExtVectorType()) { 11363 if (Context.getLangOpts().OpenCL) { 11364 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11365 // on vector float types. 11366 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11367 if (!T->isIntegerType()) 11368 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11369 << resultType << Input.get()->getSourceRange()); 11370 } 11371 break; 11372 } else { 11373 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11374 << resultType << Input.get()->getSourceRange()); 11375 } 11376 break; 11377 11378 case UO_LNot: // logical negation 11379 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11380 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11381 if (Input.isInvalid()) return ExprError(); 11382 resultType = Input.get()->getType(); 11383 11384 // Though we still have to promote half FP to float... 11385 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11386 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11387 resultType = Context.FloatTy; 11388 } 11389 11390 if (resultType->isDependentType()) 11391 break; 11392 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11393 // C99 6.5.3.3p1: ok, fallthrough; 11394 if (Context.getLangOpts().CPlusPlus) { 11395 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11396 // operand contextually converted to bool. 11397 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11398 ScalarTypeToBooleanCastKind(resultType)); 11399 } else if (Context.getLangOpts().OpenCL && 11400 Context.getLangOpts().OpenCLVersion < 120) { 11401 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11402 // operate on scalar float types. 11403 if (!resultType->isIntegerType()) 11404 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11405 << resultType << Input.get()->getSourceRange()); 11406 } 11407 } else if (resultType->isExtVectorType()) { 11408 if (Context.getLangOpts().OpenCL && 11409 Context.getLangOpts().OpenCLVersion < 120) { 11410 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11411 // operate on vector float types. 11412 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11413 if (!T->isIntegerType()) 11414 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11415 << resultType << Input.get()->getSourceRange()); 11416 } 11417 // Vector logical not returns the signed variant of the operand type. 11418 resultType = GetSignedVectorType(resultType); 11419 break; 11420 } else { 11421 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11422 << resultType << Input.get()->getSourceRange()); 11423 } 11424 11425 // LNot always has type int. C99 6.5.3.3p5. 11426 // In C++, it's bool. C++ 5.3.1p8 11427 resultType = Context.getLogicalOperationType(); 11428 break; 11429 case UO_Real: 11430 case UO_Imag: 11431 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11432 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11433 // complex l-values to ordinary l-values and all other values to r-values. 11434 if (Input.isInvalid()) return ExprError(); 11435 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11436 if (Input.get()->getValueKind() != VK_RValue && 11437 Input.get()->getObjectKind() == OK_Ordinary) 11438 VK = Input.get()->getValueKind(); 11439 } else if (!getLangOpts().CPlusPlus) { 11440 // In C, a volatile scalar is read by __imag. In C++, it is not. 11441 Input = DefaultLvalueConversion(Input.get()); 11442 } 11443 break; 11444 case UO_Extension: 11445 case UO_Coawait: 11446 resultType = Input.get()->getType(); 11447 VK = Input.get()->getValueKind(); 11448 OK = Input.get()->getObjectKind(); 11449 break; 11450 } 11451 if (resultType.isNull() || Input.isInvalid()) 11452 return ExprError(); 11453 11454 // Check for array bounds violations in the operand of the UnaryOperator, 11455 // except for the '*' and '&' operators that have to be handled specially 11456 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11457 // that are explicitly defined as valid by the standard). 11458 if (Opc != UO_AddrOf && Opc != UO_Deref) 11459 CheckArrayAccess(Input.get()); 11460 11461 return new (Context) 11462 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11463 } 11464 11465 /// \brief Determine whether the given expression is a qualified member 11466 /// access expression, of a form that could be turned into a pointer to member 11467 /// with the address-of operator. 11468 static bool isQualifiedMemberAccess(Expr *E) { 11469 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11470 if (!DRE->getQualifier()) 11471 return false; 11472 11473 ValueDecl *VD = DRE->getDecl(); 11474 if (!VD->isCXXClassMember()) 11475 return false; 11476 11477 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11478 return true; 11479 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11480 return Method->isInstance(); 11481 11482 return false; 11483 } 11484 11485 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11486 if (!ULE->getQualifier()) 11487 return false; 11488 11489 for (NamedDecl *D : ULE->decls()) { 11490 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11491 if (Method->isInstance()) 11492 return true; 11493 } else { 11494 // Overload set does not contain methods. 11495 break; 11496 } 11497 } 11498 11499 return false; 11500 } 11501 11502 return false; 11503 } 11504 11505 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11506 UnaryOperatorKind Opc, Expr *Input) { 11507 // First things first: handle placeholders so that the 11508 // overloaded-operator check considers the right type. 11509 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11510 // Increment and decrement of pseudo-object references. 11511 if (pty->getKind() == BuiltinType::PseudoObject && 11512 UnaryOperator::isIncrementDecrementOp(Opc)) 11513 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11514 11515 // extension is always a builtin operator. 11516 if (Opc == UO_Extension) 11517 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11518 11519 // & gets special logic for several kinds of placeholder. 11520 // The builtin code knows what to do. 11521 if (Opc == UO_AddrOf && 11522 (pty->getKind() == BuiltinType::Overload || 11523 pty->getKind() == BuiltinType::UnknownAny || 11524 pty->getKind() == BuiltinType::BoundMember)) 11525 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11526 11527 // Anything else needs to be handled now. 11528 ExprResult Result = CheckPlaceholderExpr(Input); 11529 if (Result.isInvalid()) return ExprError(); 11530 Input = Result.get(); 11531 } 11532 11533 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11534 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11535 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11536 // Find all of the overloaded operators visible from this 11537 // point. We perform both an operator-name lookup from the local 11538 // scope and an argument-dependent lookup based on the types of 11539 // the arguments. 11540 UnresolvedSet<16> Functions; 11541 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11542 if (S && OverOp != OO_None) 11543 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11544 Functions); 11545 11546 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11547 } 11548 11549 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11550 } 11551 11552 // Unary Operators. 'Tok' is the token for the operator. 11553 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11554 tok::TokenKind Op, Expr *Input) { 11555 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11556 } 11557 11558 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11559 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11560 LabelDecl *TheDecl) { 11561 TheDecl->markUsed(Context); 11562 // Create the AST node. The address of a label always has type 'void*'. 11563 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11564 Context.getPointerType(Context.VoidTy)); 11565 } 11566 11567 /// Given the last statement in a statement-expression, check whether 11568 /// the result is a producing expression (like a call to an 11569 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11570 /// release out of the full-expression. Otherwise, return null. 11571 /// Cannot fail. 11572 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11573 // Should always be wrapped with one of these. 11574 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11575 if (!cleanups) return nullptr; 11576 11577 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11578 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11579 return nullptr; 11580 11581 // Splice out the cast. This shouldn't modify any interesting 11582 // features of the statement. 11583 Expr *producer = cast->getSubExpr(); 11584 assert(producer->getType() == cast->getType()); 11585 assert(producer->getValueKind() == cast->getValueKind()); 11586 cleanups->setSubExpr(producer); 11587 return cleanups; 11588 } 11589 11590 void Sema::ActOnStartStmtExpr() { 11591 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11592 } 11593 11594 void Sema::ActOnStmtExprError() { 11595 // Note that function is also called by TreeTransform when leaving a 11596 // StmtExpr scope without rebuilding anything. 11597 11598 DiscardCleanupsInEvaluationContext(); 11599 PopExpressionEvaluationContext(); 11600 } 11601 11602 ExprResult 11603 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11604 SourceLocation RPLoc) { // "({..})" 11605 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11606 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11607 11608 if (hasAnyUnrecoverableErrorsInThisFunction()) 11609 DiscardCleanupsInEvaluationContext(); 11610 assert(!Cleanup.exprNeedsCleanups() && 11611 "cleanups within StmtExpr not correctly bound!"); 11612 PopExpressionEvaluationContext(); 11613 11614 // FIXME: there are a variety of strange constraints to enforce here, for 11615 // example, it is not possible to goto into a stmt expression apparently. 11616 // More semantic analysis is needed. 11617 11618 // If there are sub-stmts in the compound stmt, take the type of the last one 11619 // as the type of the stmtexpr. 11620 QualType Ty = Context.VoidTy; 11621 bool StmtExprMayBindToTemp = false; 11622 if (!Compound->body_empty()) { 11623 Stmt *LastStmt = Compound->body_back(); 11624 LabelStmt *LastLabelStmt = nullptr; 11625 // If LastStmt is a label, skip down through into the body. 11626 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11627 LastLabelStmt = Label; 11628 LastStmt = Label->getSubStmt(); 11629 } 11630 11631 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11632 // Do function/array conversion on the last expression, but not 11633 // lvalue-to-rvalue. However, initialize an unqualified type. 11634 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11635 if (LastExpr.isInvalid()) 11636 return ExprError(); 11637 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11638 11639 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11640 // In ARC, if the final expression ends in a consume, splice 11641 // the consume out and bind it later. In the alternate case 11642 // (when dealing with a retainable type), the result 11643 // initialization will create a produce. In both cases the 11644 // result will be +1, and we'll need to balance that out with 11645 // a bind. 11646 if (Expr *rebuiltLastStmt 11647 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11648 LastExpr = rebuiltLastStmt; 11649 } else { 11650 LastExpr = PerformCopyInitialization( 11651 InitializedEntity::InitializeResult(LPLoc, 11652 Ty, 11653 false), 11654 SourceLocation(), 11655 LastExpr); 11656 } 11657 11658 if (LastExpr.isInvalid()) 11659 return ExprError(); 11660 if (LastExpr.get() != nullptr) { 11661 if (!LastLabelStmt) 11662 Compound->setLastStmt(LastExpr.get()); 11663 else 11664 LastLabelStmt->setSubStmt(LastExpr.get()); 11665 StmtExprMayBindToTemp = true; 11666 } 11667 } 11668 } 11669 } 11670 11671 // FIXME: Check that expression type is complete/non-abstract; statement 11672 // expressions are not lvalues. 11673 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11674 if (StmtExprMayBindToTemp) 11675 return MaybeBindToTemporary(ResStmtExpr); 11676 return ResStmtExpr; 11677 } 11678 11679 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11680 TypeSourceInfo *TInfo, 11681 ArrayRef<OffsetOfComponent> Components, 11682 SourceLocation RParenLoc) { 11683 QualType ArgTy = TInfo->getType(); 11684 bool Dependent = ArgTy->isDependentType(); 11685 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11686 11687 // We must have at least one component that refers to the type, and the first 11688 // one is known to be a field designator. Verify that the ArgTy represents 11689 // a struct/union/class. 11690 if (!Dependent && !ArgTy->isRecordType()) 11691 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11692 << ArgTy << TypeRange); 11693 11694 // Type must be complete per C99 7.17p3 because a declaring a variable 11695 // with an incomplete type would be ill-formed. 11696 if (!Dependent 11697 && RequireCompleteType(BuiltinLoc, ArgTy, 11698 diag::err_offsetof_incomplete_type, TypeRange)) 11699 return ExprError(); 11700 11701 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11702 // GCC extension, diagnose them. 11703 // FIXME: This diagnostic isn't actually visible because the location is in 11704 // a system header! 11705 if (Components.size() != 1) 11706 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11707 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11708 11709 bool DidWarnAboutNonPOD = false; 11710 QualType CurrentType = ArgTy; 11711 SmallVector<OffsetOfNode, 4> Comps; 11712 SmallVector<Expr*, 4> Exprs; 11713 for (const OffsetOfComponent &OC : Components) { 11714 if (OC.isBrackets) { 11715 // Offset of an array sub-field. TODO: Should we allow vector elements? 11716 if (!CurrentType->isDependentType()) { 11717 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11718 if(!AT) 11719 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11720 << CurrentType); 11721 CurrentType = AT->getElementType(); 11722 } else 11723 CurrentType = Context.DependentTy; 11724 11725 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11726 if (IdxRval.isInvalid()) 11727 return ExprError(); 11728 Expr *Idx = IdxRval.get(); 11729 11730 // The expression must be an integral expression. 11731 // FIXME: An integral constant expression? 11732 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11733 !Idx->getType()->isIntegerType()) 11734 return ExprError(Diag(Idx->getLocStart(), 11735 diag::err_typecheck_subscript_not_integer) 11736 << Idx->getSourceRange()); 11737 11738 // Record this array index. 11739 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11740 Exprs.push_back(Idx); 11741 continue; 11742 } 11743 11744 // Offset of a field. 11745 if (CurrentType->isDependentType()) { 11746 // We have the offset of a field, but we can't look into the dependent 11747 // type. Just record the identifier of the field. 11748 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11749 CurrentType = Context.DependentTy; 11750 continue; 11751 } 11752 11753 // We need to have a complete type to look into. 11754 if (RequireCompleteType(OC.LocStart, CurrentType, 11755 diag::err_offsetof_incomplete_type)) 11756 return ExprError(); 11757 11758 // Look for the designated field. 11759 const RecordType *RC = CurrentType->getAs<RecordType>(); 11760 if (!RC) 11761 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11762 << CurrentType); 11763 RecordDecl *RD = RC->getDecl(); 11764 11765 // C++ [lib.support.types]p5: 11766 // The macro offsetof accepts a restricted set of type arguments in this 11767 // International Standard. type shall be a POD structure or a POD union 11768 // (clause 9). 11769 // C++11 [support.types]p4: 11770 // If type is not a standard-layout class (Clause 9), the results are 11771 // undefined. 11772 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11773 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11774 unsigned DiagID = 11775 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11776 : diag::ext_offsetof_non_pod_type; 11777 11778 if (!IsSafe && !DidWarnAboutNonPOD && 11779 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11780 PDiag(DiagID) 11781 << SourceRange(Components[0].LocStart, OC.LocEnd) 11782 << CurrentType)) 11783 DidWarnAboutNonPOD = true; 11784 } 11785 11786 // Look for the field. 11787 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11788 LookupQualifiedName(R, RD); 11789 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11790 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11791 if (!MemberDecl) { 11792 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11793 MemberDecl = IndirectMemberDecl->getAnonField(); 11794 } 11795 11796 if (!MemberDecl) 11797 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11798 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11799 OC.LocEnd)); 11800 11801 // C99 7.17p3: 11802 // (If the specified member is a bit-field, the behavior is undefined.) 11803 // 11804 // We diagnose this as an error. 11805 if (MemberDecl->isBitField()) { 11806 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11807 << MemberDecl->getDeclName() 11808 << SourceRange(BuiltinLoc, RParenLoc); 11809 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11810 return ExprError(); 11811 } 11812 11813 RecordDecl *Parent = MemberDecl->getParent(); 11814 if (IndirectMemberDecl) 11815 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11816 11817 // If the member was found in a base class, introduce OffsetOfNodes for 11818 // the base class indirections. 11819 CXXBasePaths Paths; 11820 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11821 Paths)) { 11822 if (Paths.getDetectedVirtual()) { 11823 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11824 << MemberDecl->getDeclName() 11825 << SourceRange(BuiltinLoc, RParenLoc); 11826 return ExprError(); 11827 } 11828 11829 CXXBasePath &Path = Paths.front(); 11830 for (const CXXBasePathElement &B : Path) 11831 Comps.push_back(OffsetOfNode(B.Base)); 11832 } 11833 11834 if (IndirectMemberDecl) { 11835 for (auto *FI : IndirectMemberDecl->chain()) { 11836 assert(isa<FieldDecl>(FI)); 11837 Comps.push_back(OffsetOfNode(OC.LocStart, 11838 cast<FieldDecl>(FI), OC.LocEnd)); 11839 } 11840 } else 11841 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11842 11843 CurrentType = MemberDecl->getType().getNonReferenceType(); 11844 } 11845 11846 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11847 Comps, Exprs, RParenLoc); 11848 } 11849 11850 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11851 SourceLocation BuiltinLoc, 11852 SourceLocation TypeLoc, 11853 ParsedType ParsedArgTy, 11854 ArrayRef<OffsetOfComponent> Components, 11855 SourceLocation RParenLoc) { 11856 11857 TypeSourceInfo *ArgTInfo; 11858 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11859 if (ArgTy.isNull()) 11860 return ExprError(); 11861 11862 if (!ArgTInfo) 11863 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11864 11865 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11866 } 11867 11868 11869 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11870 Expr *CondExpr, 11871 Expr *LHSExpr, Expr *RHSExpr, 11872 SourceLocation RPLoc) { 11873 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11874 11875 ExprValueKind VK = VK_RValue; 11876 ExprObjectKind OK = OK_Ordinary; 11877 QualType resType; 11878 bool ValueDependent = false; 11879 bool CondIsTrue = false; 11880 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11881 resType = Context.DependentTy; 11882 ValueDependent = true; 11883 } else { 11884 // The conditional expression is required to be a constant expression. 11885 llvm::APSInt condEval(32); 11886 ExprResult CondICE 11887 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11888 diag::err_typecheck_choose_expr_requires_constant, false); 11889 if (CondICE.isInvalid()) 11890 return ExprError(); 11891 CondExpr = CondICE.get(); 11892 CondIsTrue = condEval.getZExtValue(); 11893 11894 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11895 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11896 11897 resType = ActiveExpr->getType(); 11898 ValueDependent = ActiveExpr->isValueDependent(); 11899 VK = ActiveExpr->getValueKind(); 11900 OK = ActiveExpr->getObjectKind(); 11901 } 11902 11903 return new (Context) 11904 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11905 CondIsTrue, resType->isDependentType(), ValueDependent); 11906 } 11907 11908 //===----------------------------------------------------------------------===// 11909 // Clang Extensions. 11910 //===----------------------------------------------------------------------===// 11911 11912 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11913 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11914 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11915 11916 if (LangOpts.CPlusPlus) { 11917 Decl *ManglingContextDecl; 11918 if (MangleNumberingContext *MCtx = 11919 getCurrentMangleNumberContext(Block->getDeclContext(), 11920 ManglingContextDecl)) { 11921 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11922 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11923 } 11924 } 11925 11926 PushBlockScope(CurScope, Block); 11927 CurContext->addDecl(Block); 11928 if (CurScope) 11929 PushDeclContext(CurScope, Block); 11930 else 11931 CurContext = Block; 11932 11933 getCurBlock()->HasImplicitReturnType = true; 11934 11935 // Enter a new evaluation context to insulate the block from any 11936 // cleanups from the enclosing full-expression. 11937 PushExpressionEvaluationContext(PotentiallyEvaluated); 11938 } 11939 11940 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11941 Scope *CurScope) { 11942 assert(ParamInfo.getIdentifier() == nullptr && 11943 "block-id should have no identifier!"); 11944 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11945 BlockScopeInfo *CurBlock = getCurBlock(); 11946 11947 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11948 QualType T = Sig->getType(); 11949 11950 // FIXME: We should allow unexpanded parameter packs here, but that would, 11951 // in turn, make the block expression contain unexpanded parameter packs. 11952 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11953 // Drop the parameters. 11954 FunctionProtoType::ExtProtoInfo EPI; 11955 EPI.HasTrailingReturn = false; 11956 EPI.TypeQuals |= DeclSpec::TQ_const; 11957 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11958 Sig = Context.getTrivialTypeSourceInfo(T); 11959 } 11960 11961 // GetTypeForDeclarator always produces a function type for a block 11962 // literal signature. Furthermore, it is always a FunctionProtoType 11963 // unless the function was written with a typedef. 11964 assert(T->isFunctionType() && 11965 "GetTypeForDeclarator made a non-function block signature"); 11966 11967 // Look for an explicit signature in that function type. 11968 FunctionProtoTypeLoc ExplicitSignature; 11969 11970 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11971 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11972 11973 // Check whether that explicit signature was synthesized by 11974 // GetTypeForDeclarator. If so, don't save that as part of the 11975 // written signature. 11976 if (ExplicitSignature.getLocalRangeBegin() == 11977 ExplicitSignature.getLocalRangeEnd()) { 11978 // This would be much cheaper if we stored TypeLocs instead of 11979 // TypeSourceInfos. 11980 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11981 unsigned Size = Result.getFullDataSize(); 11982 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11983 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11984 11985 ExplicitSignature = FunctionProtoTypeLoc(); 11986 } 11987 } 11988 11989 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11990 CurBlock->FunctionType = T; 11991 11992 const FunctionType *Fn = T->getAs<FunctionType>(); 11993 QualType RetTy = Fn->getReturnType(); 11994 bool isVariadic = 11995 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11996 11997 CurBlock->TheDecl->setIsVariadic(isVariadic); 11998 11999 // Context.DependentTy is used as a placeholder for a missing block 12000 // return type. TODO: what should we do with declarators like: 12001 // ^ * { ... } 12002 // If the answer is "apply template argument deduction".... 12003 if (RetTy != Context.DependentTy) { 12004 CurBlock->ReturnType = RetTy; 12005 CurBlock->TheDecl->setBlockMissingReturnType(false); 12006 CurBlock->HasImplicitReturnType = false; 12007 } 12008 12009 // Push block parameters from the declarator if we had them. 12010 SmallVector<ParmVarDecl*, 8> Params; 12011 if (ExplicitSignature) { 12012 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12013 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12014 if (Param->getIdentifier() == nullptr && 12015 !Param->isImplicit() && 12016 !Param->isInvalidDecl() && 12017 !getLangOpts().CPlusPlus) 12018 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12019 Params.push_back(Param); 12020 } 12021 12022 // Fake up parameter variables if we have a typedef, like 12023 // ^ fntype { ... } 12024 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12025 for (const auto &I : Fn->param_types()) { 12026 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12027 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12028 Params.push_back(Param); 12029 } 12030 } 12031 12032 // Set the parameters on the block decl. 12033 if (!Params.empty()) { 12034 CurBlock->TheDecl->setParams(Params); 12035 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12036 /*CheckParameterNames=*/false); 12037 } 12038 12039 // Finally we can process decl attributes. 12040 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12041 12042 // Put the parameter variables in scope. 12043 for (auto AI : CurBlock->TheDecl->parameters()) { 12044 AI->setOwningFunction(CurBlock->TheDecl); 12045 12046 // If this has an identifier, add it to the scope stack. 12047 if (AI->getIdentifier()) { 12048 CheckShadow(CurBlock->TheScope, AI); 12049 12050 PushOnScopeChains(AI, CurBlock->TheScope); 12051 } 12052 } 12053 } 12054 12055 /// ActOnBlockError - If there is an error parsing a block, this callback 12056 /// is invoked to pop the information about the block from the action impl. 12057 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12058 // Leave the expression-evaluation context. 12059 DiscardCleanupsInEvaluationContext(); 12060 PopExpressionEvaluationContext(); 12061 12062 // Pop off CurBlock, handle nested blocks. 12063 PopDeclContext(); 12064 PopFunctionScopeInfo(); 12065 } 12066 12067 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12068 /// literal was successfully completed. ^(int x){...} 12069 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12070 Stmt *Body, Scope *CurScope) { 12071 // If blocks are disabled, emit an error. 12072 if (!LangOpts.Blocks) 12073 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12074 12075 // Leave the expression-evaluation context. 12076 if (hasAnyUnrecoverableErrorsInThisFunction()) 12077 DiscardCleanupsInEvaluationContext(); 12078 assert(!Cleanup.exprNeedsCleanups() && 12079 "cleanups within block not correctly bound!"); 12080 PopExpressionEvaluationContext(); 12081 12082 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12083 12084 if (BSI->HasImplicitReturnType) 12085 deduceClosureReturnType(*BSI); 12086 12087 PopDeclContext(); 12088 12089 QualType RetTy = Context.VoidTy; 12090 if (!BSI->ReturnType.isNull()) 12091 RetTy = BSI->ReturnType; 12092 12093 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12094 QualType BlockTy; 12095 12096 // Set the captured variables on the block. 12097 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12098 SmallVector<BlockDecl::Capture, 4> Captures; 12099 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12100 if (Cap.isThisCapture()) 12101 continue; 12102 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12103 Cap.isNested(), Cap.getInitExpr()); 12104 Captures.push_back(NewCap); 12105 } 12106 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12107 12108 // If the user wrote a function type in some form, try to use that. 12109 if (!BSI->FunctionType.isNull()) { 12110 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12111 12112 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12113 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12114 12115 // Turn protoless block types into nullary block types. 12116 if (isa<FunctionNoProtoType>(FTy)) { 12117 FunctionProtoType::ExtProtoInfo EPI; 12118 EPI.ExtInfo = Ext; 12119 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12120 12121 // Otherwise, if we don't need to change anything about the function type, 12122 // preserve its sugar structure. 12123 } else if (FTy->getReturnType() == RetTy && 12124 (!NoReturn || FTy->getNoReturnAttr())) { 12125 BlockTy = BSI->FunctionType; 12126 12127 // Otherwise, make the minimal modifications to the function type. 12128 } else { 12129 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12130 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12131 EPI.TypeQuals = 0; // FIXME: silently? 12132 EPI.ExtInfo = Ext; 12133 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12134 } 12135 12136 // If we don't have a function type, just build one from nothing. 12137 } else { 12138 FunctionProtoType::ExtProtoInfo EPI; 12139 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12140 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12141 } 12142 12143 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12144 BlockTy = Context.getBlockPointerType(BlockTy); 12145 12146 // If needed, diagnose invalid gotos and switches in the block. 12147 if (getCurFunction()->NeedsScopeChecking() && 12148 !PP.isCodeCompletionEnabled()) 12149 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12150 12151 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12152 12153 // Try to apply the named return value optimization. We have to check again 12154 // if we can do this, though, because blocks keep return statements around 12155 // to deduce an implicit return type. 12156 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12157 !BSI->TheDecl->isDependentContext()) 12158 computeNRVO(Body, BSI); 12159 12160 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12161 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12162 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12163 12164 // If the block isn't obviously global, i.e. it captures anything at 12165 // all, then we need to do a few things in the surrounding context: 12166 if (Result->getBlockDecl()->hasCaptures()) { 12167 // First, this expression has a new cleanup object. 12168 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12169 Cleanup.setExprNeedsCleanups(true); 12170 12171 // It also gets a branch-protected scope if any of the captured 12172 // variables needs destruction. 12173 for (const auto &CI : Result->getBlockDecl()->captures()) { 12174 const VarDecl *var = CI.getVariable(); 12175 if (var->getType().isDestructedType() != QualType::DK_none) { 12176 getCurFunction()->setHasBranchProtectedScope(); 12177 break; 12178 } 12179 } 12180 } 12181 12182 return Result; 12183 } 12184 12185 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12186 SourceLocation RPLoc) { 12187 TypeSourceInfo *TInfo; 12188 GetTypeFromParser(Ty, &TInfo); 12189 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12190 } 12191 12192 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12193 Expr *E, TypeSourceInfo *TInfo, 12194 SourceLocation RPLoc) { 12195 Expr *OrigExpr = E; 12196 bool IsMS = false; 12197 12198 // CUDA device code does not support varargs. 12199 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12200 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12201 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12202 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12203 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12204 } 12205 } 12206 12207 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12208 // as Microsoft ABI on an actual Microsoft platform, where 12209 // __builtin_ms_va_list and __builtin_va_list are the same.) 12210 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12211 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12212 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12213 if (Context.hasSameType(MSVaListType, E->getType())) { 12214 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12215 return ExprError(); 12216 IsMS = true; 12217 } 12218 } 12219 12220 // Get the va_list type 12221 QualType VaListType = Context.getBuiltinVaListType(); 12222 if (!IsMS) { 12223 if (VaListType->isArrayType()) { 12224 // Deal with implicit array decay; for example, on x86-64, 12225 // va_list is an array, but it's supposed to decay to 12226 // a pointer for va_arg. 12227 VaListType = Context.getArrayDecayedType(VaListType); 12228 // Make sure the input expression also decays appropriately. 12229 ExprResult Result = UsualUnaryConversions(E); 12230 if (Result.isInvalid()) 12231 return ExprError(); 12232 E = Result.get(); 12233 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12234 // If va_list is a record type and we are compiling in C++ mode, 12235 // check the argument using reference binding. 12236 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12237 Context, Context.getLValueReferenceType(VaListType), false); 12238 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12239 if (Init.isInvalid()) 12240 return ExprError(); 12241 E = Init.getAs<Expr>(); 12242 } else { 12243 // Otherwise, the va_list argument must be an l-value because 12244 // it is modified by va_arg. 12245 if (!E->isTypeDependent() && 12246 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12247 return ExprError(); 12248 } 12249 } 12250 12251 if (!IsMS && !E->isTypeDependent() && 12252 !Context.hasSameType(VaListType, E->getType())) 12253 return ExprError(Diag(E->getLocStart(), 12254 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12255 << OrigExpr->getType() << E->getSourceRange()); 12256 12257 if (!TInfo->getType()->isDependentType()) { 12258 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12259 diag::err_second_parameter_to_va_arg_incomplete, 12260 TInfo->getTypeLoc())) 12261 return ExprError(); 12262 12263 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12264 TInfo->getType(), 12265 diag::err_second_parameter_to_va_arg_abstract, 12266 TInfo->getTypeLoc())) 12267 return ExprError(); 12268 12269 if (!TInfo->getType().isPODType(Context)) { 12270 Diag(TInfo->getTypeLoc().getBeginLoc(), 12271 TInfo->getType()->isObjCLifetimeType() 12272 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12273 : diag::warn_second_parameter_to_va_arg_not_pod) 12274 << TInfo->getType() 12275 << TInfo->getTypeLoc().getSourceRange(); 12276 } 12277 12278 // Check for va_arg where arguments of the given type will be promoted 12279 // (i.e. this va_arg is guaranteed to have undefined behavior). 12280 QualType PromoteType; 12281 if (TInfo->getType()->isPromotableIntegerType()) { 12282 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12283 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12284 PromoteType = QualType(); 12285 } 12286 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12287 PromoteType = Context.DoubleTy; 12288 if (!PromoteType.isNull()) 12289 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12290 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12291 << TInfo->getType() 12292 << PromoteType 12293 << TInfo->getTypeLoc().getSourceRange()); 12294 } 12295 12296 QualType T = TInfo->getType().getNonLValueExprType(Context); 12297 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12298 } 12299 12300 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12301 // The type of __null will be int or long, depending on the size of 12302 // pointers on the target. 12303 QualType Ty; 12304 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12305 if (pw == Context.getTargetInfo().getIntWidth()) 12306 Ty = Context.IntTy; 12307 else if (pw == Context.getTargetInfo().getLongWidth()) 12308 Ty = Context.LongTy; 12309 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12310 Ty = Context.LongLongTy; 12311 else { 12312 llvm_unreachable("I don't know size of pointer!"); 12313 } 12314 12315 return new (Context) GNUNullExpr(Ty, TokenLoc); 12316 } 12317 12318 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12319 bool Diagnose) { 12320 if (!getLangOpts().ObjC1) 12321 return false; 12322 12323 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12324 if (!PT) 12325 return false; 12326 12327 if (!PT->isObjCIdType()) { 12328 // Check if the destination is the 'NSString' interface. 12329 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12330 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12331 return false; 12332 } 12333 12334 // Ignore any parens, implicit casts (should only be 12335 // array-to-pointer decays), and not-so-opaque values. The last is 12336 // important for making this trigger for property assignments. 12337 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12338 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12339 if (OV->getSourceExpr()) 12340 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12341 12342 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12343 if (!SL || !SL->isAscii()) 12344 return false; 12345 if (Diagnose) { 12346 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12347 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12348 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12349 } 12350 return true; 12351 } 12352 12353 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12354 const Expr *SrcExpr) { 12355 if (!DstType->isFunctionPointerType() || 12356 !SrcExpr->getType()->isFunctionType()) 12357 return false; 12358 12359 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12360 if (!DRE) 12361 return false; 12362 12363 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12364 if (!FD) 12365 return false; 12366 12367 return !S.checkAddressOfFunctionIsAvailable(FD, 12368 /*Complain=*/true, 12369 SrcExpr->getLocStart()); 12370 } 12371 12372 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12373 SourceLocation Loc, 12374 QualType DstType, QualType SrcType, 12375 Expr *SrcExpr, AssignmentAction Action, 12376 bool *Complained) { 12377 if (Complained) 12378 *Complained = false; 12379 12380 // Decode the result (notice that AST's are still created for extensions). 12381 bool CheckInferredResultType = false; 12382 bool isInvalid = false; 12383 unsigned DiagKind = 0; 12384 FixItHint Hint; 12385 ConversionFixItGenerator ConvHints; 12386 bool MayHaveConvFixit = false; 12387 bool MayHaveFunctionDiff = false; 12388 const ObjCInterfaceDecl *IFace = nullptr; 12389 const ObjCProtocolDecl *PDecl = nullptr; 12390 12391 switch (ConvTy) { 12392 case Compatible: 12393 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12394 return false; 12395 12396 case PointerToInt: 12397 DiagKind = diag::ext_typecheck_convert_pointer_int; 12398 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12399 MayHaveConvFixit = true; 12400 break; 12401 case IntToPointer: 12402 DiagKind = diag::ext_typecheck_convert_int_pointer; 12403 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12404 MayHaveConvFixit = true; 12405 break; 12406 case IncompatiblePointer: 12407 DiagKind = 12408 (Action == AA_Passing_CFAudited ? 12409 diag::err_arc_typecheck_convert_incompatible_pointer : 12410 diag::ext_typecheck_convert_incompatible_pointer); 12411 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12412 SrcType->isObjCObjectPointerType(); 12413 if (Hint.isNull() && !CheckInferredResultType) { 12414 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12415 } 12416 else if (CheckInferredResultType) { 12417 SrcType = SrcType.getUnqualifiedType(); 12418 DstType = DstType.getUnqualifiedType(); 12419 } 12420 MayHaveConvFixit = true; 12421 break; 12422 case IncompatiblePointerSign: 12423 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12424 break; 12425 case FunctionVoidPointer: 12426 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12427 break; 12428 case IncompatiblePointerDiscardsQualifiers: { 12429 // Perform array-to-pointer decay if necessary. 12430 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12431 12432 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12433 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12434 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12435 DiagKind = diag::err_typecheck_incompatible_address_space; 12436 break; 12437 12438 12439 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12440 DiagKind = diag::err_typecheck_incompatible_ownership; 12441 break; 12442 } 12443 12444 llvm_unreachable("unknown error case for discarding qualifiers!"); 12445 // fallthrough 12446 } 12447 case CompatiblePointerDiscardsQualifiers: 12448 // If the qualifiers lost were because we were applying the 12449 // (deprecated) C++ conversion from a string literal to a char* 12450 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12451 // Ideally, this check would be performed in 12452 // checkPointerTypesForAssignment. However, that would require a 12453 // bit of refactoring (so that the second argument is an 12454 // expression, rather than a type), which should be done as part 12455 // of a larger effort to fix checkPointerTypesForAssignment for 12456 // C++ semantics. 12457 if (getLangOpts().CPlusPlus && 12458 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12459 return false; 12460 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12461 break; 12462 case IncompatibleNestedPointerQualifiers: 12463 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12464 break; 12465 case IntToBlockPointer: 12466 DiagKind = diag::err_int_to_block_pointer; 12467 break; 12468 case IncompatibleBlockPointer: 12469 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12470 break; 12471 case IncompatibleObjCQualifiedId: { 12472 if (SrcType->isObjCQualifiedIdType()) { 12473 const ObjCObjectPointerType *srcOPT = 12474 SrcType->getAs<ObjCObjectPointerType>(); 12475 for (auto *srcProto : srcOPT->quals()) { 12476 PDecl = srcProto; 12477 break; 12478 } 12479 if (const ObjCInterfaceType *IFaceT = 12480 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12481 IFace = IFaceT->getDecl(); 12482 } 12483 else if (DstType->isObjCQualifiedIdType()) { 12484 const ObjCObjectPointerType *dstOPT = 12485 DstType->getAs<ObjCObjectPointerType>(); 12486 for (auto *dstProto : dstOPT->quals()) { 12487 PDecl = dstProto; 12488 break; 12489 } 12490 if (const ObjCInterfaceType *IFaceT = 12491 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12492 IFace = IFaceT->getDecl(); 12493 } 12494 DiagKind = diag::warn_incompatible_qualified_id; 12495 break; 12496 } 12497 case IncompatibleVectors: 12498 DiagKind = diag::warn_incompatible_vectors; 12499 break; 12500 case IncompatibleObjCWeakRef: 12501 DiagKind = diag::err_arc_weak_unavailable_assign; 12502 break; 12503 case Incompatible: 12504 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12505 if (Complained) 12506 *Complained = true; 12507 return true; 12508 } 12509 12510 DiagKind = diag::err_typecheck_convert_incompatible; 12511 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12512 MayHaveConvFixit = true; 12513 isInvalid = true; 12514 MayHaveFunctionDiff = true; 12515 break; 12516 } 12517 12518 QualType FirstType, SecondType; 12519 switch (Action) { 12520 case AA_Assigning: 12521 case AA_Initializing: 12522 // The destination type comes first. 12523 FirstType = DstType; 12524 SecondType = SrcType; 12525 break; 12526 12527 case AA_Returning: 12528 case AA_Passing: 12529 case AA_Passing_CFAudited: 12530 case AA_Converting: 12531 case AA_Sending: 12532 case AA_Casting: 12533 // The source type comes first. 12534 FirstType = SrcType; 12535 SecondType = DstType; 12536 break; 12537 } 12538 12539 PartialDiagnostic FDiag = PDiag(DiagKind); 12540 if (Action == AA_Passing_CFAudited) 12541 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12542 else 12543 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12544 12545 // If we can fix the conversion, suggest the FixIts. 12546 assert(ConvHints.isNull() || Hint.isNull()); 12547 if (!ConvHints.isNull()) { 12548 for (FixItHint &H : ConvHints.Hints) 12549 FDiag << H; 12550 } else { 12551 FDiag << Hint; 12552 } 12553 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12554 12555 if (MayHaveFunctionDiff) 12556 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12557 12558 Diag(Loc, FDiag); 12559 if (DiagKind == diag::warn_incompatible_qualified_id && 12560 PDecl && IFace && !IFace->hasDefinition()) 12561 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12562 << IFace->getName() << PDecl->getName(); 12563 12564 if (SecondType == Context.OverloadTy) 12565 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12566 FirstType, /*TakingAddress=*/true); 12567 12568 if (CheckInferredResultType) 12569 EmitRelatedResultTypeNote(SrcExpr); 12570 12571 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12572 EmitRelatedResultTypeNoteForReturn(DstType); 12573 12574 if (Complained) 12575 *Complained = true; 12576 return isInvalid; 12577 } 12578 12579 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12580 llvm::APSInt *Result) { 12581 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12582 public: 12583 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12584 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12585 } 12586 } Diagnoser; 12587 12588 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12589 } 12590 12591 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12592 llvm::APSInt *Result, 12593 unsigned DiagID, 12594 bool AllowFold) { 12595 class IDDiagnoser : public VerifyICEDiagnoser { 12596 unsigned DiagID; 12597 12598 public: 12599 IDDiagnoser(unsigned DiagID) 12600 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12601 12602 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12603 S.Diag(Loc, DiagID) << SR; 12604 } 12605 } Diagnoser(DiagID); 12606 12607 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12608 } 12609 12610 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12611 SourceRange SR) { 12612 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12613 } 12614 12615 ExprResult 12616 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12617 VerifyICEDiagnoser &Diagnoser, 12618 bool AllowFold) { 12619 SourceLocation DiagLoc = E->getLocStart(); 12620 12621 if (getLangOpts().CPlusPlus11) { 12622 // C++11 [expr.const]p5: 12623 // If an expression of literal class type is used in a context where an 12624 // integral constant expression is required, then that class type shall 12625 // have a single non-explicit conversion function to an integral or 12626 // unscoped enumeration type 12627 ExprResult Converted; 12628 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12629 public: 12630 CXX11ConvertDiagnoser(bool Silent) 12631 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12632 Silent, true) {} 12633 12634 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12635 QualType T) override { 12636 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12637 } 12638 12639 SemaDiagnosticBuilder diagnoseIncomplete( 12640 Sema &S, SourceLocation Loc, QualType T) override { 12641 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12642 } 12643 12644 SemaDiagnosticBuilder diagnoseExplicitConv( 12645 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12646 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12647 } 12648 12649 SemaDiagnosticBuilder noteExplicitConv( 12650 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12651 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12652 << ConvTy->isEnumeralType() << ConvTy; 12653 } 12654 12655 SemaDiagnosticBuilder diagnoseAmbiguous( 12656 Sema &S, SourceLocation Loc, QualType T) override { 12657 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12658 } 12659 12660 SemaDiagnosticBuilder noteAmbiguous( 12661 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12662 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12663 << ConvTy->isEnumeralType() << ConvTy; 12664 } 12665 12666 SemaDiagnosticBuilder diagnoseConversion( 12667 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12668 llvm_unreachable("conversion functions are permitted"); 12669 } 12670 } ConvertDiagnoser(Diagnoser.Suppress); 12671 12672 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12673 ConvertDiagnoser); 12674 if (Converted.isInvalid()) 12675 return Converted; 12676 E = Converted.get(); 12677 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12678 return ExprError(); 12679 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12680 // An ICE must be of integral or unscoped enumeration type. 12681 if (!Diagnoser.Suppress) 12682 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12683 return ExprError(); 12684 } 12685 12686 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12687 // in the non-ICE case. 12688 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12689 if (Result) 12690 *Result = E->EvaluateKnownConstInt(Context); 12691 return E; 12692 } 12693 12694 Expr::EvalResult EvalResult; 12695 SmallVector<PartialDiagnosticAt, 8> Notes; 12696 EvalResult.Diag = &Notes; 12697 12698 // Try to evaluate the expression, and produce diagnostics explaining why it's 12699 // not a constant expression as a side-effect. 12700 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12701 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12702 12703 // In C++11, we can rely on diagnostics being produced for any expression 12704 // which is not a constant expression. If no diagnostics were produced, then 12705 // this is a constant expression. 12706 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12707 if (Result) 12708 *Result = EvalResult.Val.getInt(); 12709 return E; 12710 } 12711 12712 // If our only note is the usual "invalid subexpression" note, just point 12713 // the caret at its location rather than producing an essentially 12714 // redundant note. 12715 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12716 diag::note_invalid_subexpr_in_const_expr) { 12717 DiagLoc = Notes[0].first; 12718 Notes.clear(); 12719 } 12720 12721 if (!Folded || !AllowFold) { 12722 if (!Diagnoser.Suppress) { 12723 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12724 for (const PartialDiagnosticAt &Note : Notes) 12725 Diag(Note.first, Note.second); 12726 } 12727 12728 return ExprError(); 12729 } 12730 12731 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12732 for (const PartialDiagnosticAt &Note : Notes) 12733 Diag(Note.first, Note.second); 12734 12735 if (Result) 12736 *Result = EvalResult.Val.getInt(); 12737 return E; 12738 } 12739 12740 namespace { 12741 // Handle the case where we conclude a expression which we speculatively 12742 // considered to be unevaluated is actually evaluated. 12743 class TransformToPE : public TreeTransform<TransformToPE> { 12744 typedef TreeTransform<TransformToPE> BaseTransform; 12745 12746 public: 12747 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12748 12749 // Make sure we redo semantic analysis 12750 bool AlwaysRebuild() { return true; } 12751 12752 // Make sure we handle LabelStmts correctly. 12753 // FIXME: This does the right thing, but maybe we need a more general 12754 // fix to TreeTransform? 12755 StmtResult TransformLabelStmt(LabelStmt *S) { 12756 S->getDecl()->setStmt(nullptr); 12757 return BaseTransform::TransformLabelStmt(S); 12758 } 12759 12760 // We need to special-case DeclRefExprs referring to FieldDecls which 12761 // are not part of a member pointer formation; normal TreeTransforming 12762 // doesn't catch this case because of the way we represent them in the AST. 12763 // FIXME: This is a bit ugly; is it really the best way to handle this 12764 // case? 12765 // 12766 // Error on DeclRefExprs referring to FieldDecls. 12767 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12768 if (isa<FieldDecl>(E->getDecl()) && 12769 !SemaRef.isUnevaluatedContext()) 12770 return SemaRef.Diag(E->getLocation(), 12771 diag::err_invalid_non_static_member_use) 12772 << E->getDecl() << E->getSourceRange(); 12773 12774 return BaseTransform::TransformDeclRefExpr(E); 12775 } 12776 12777 // Exception: filter out member pointer formation 12778 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12779 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12780 return E; 12781 12782 return BaseTransform::TransformUnaryOperator(E); 12783 } 12784 12785 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12786 // Lambdas never need to be transformed. 12787 return E; 12788 } 12789 }; 12790 } 12791 12792 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12793 assert(isUnevaluatedContext() && 12794 "Should only transform unevaluated expressions"); 12795 ExprEvalContexts.back().Context = 12796 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12797 if (isUnevaluatedContext()) 12798 return E; 12799 return TransformToPE(*this).TransformExpr(E); 12800 } 12801 12802 void 12803 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12804 Decl *LambdaContextDecl, 12805 bool IsDecltype) { 12806 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 12807 LambdaContextDecl, IsDecltype); 12808 Cleanup.reset(); 12809 if (!MaybeODRUseExprs.empty()) 12810 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12811 } 12812 12813 void 12814 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12815 ReuseLambdaContextDecl_t, 12816 bool IsDecltype) { 12817 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12818 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12819 } 12820 12821 void Sema::PopExpressionEvaluationContext() { 12822 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12823 unsigned NumTypos = Rec.NumTypos; 12824 12825 if (!Rec.Lambdas.empty()) { 12826 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12827 unsigned D; 12828 if (Rec.isUnevaluated()) { 12829 // C++11 [expr.prim.lambda]p2: 12830 // A lambda-expression shall not appear in an unevaluated operand 12831 // (Clause 5). 12832 D = diag::err_lambda_unevaluated_operand; 12833 } else { 12834 // C++1y [expr.const]p2: 12835 // A conditional-expression e is a core constant expression unless the 12836 // evaluation of e, following the rules of the abstract machine, would 12837 // evaluate [...] a lambda-expression. 12838 D = diag::err_lambda_in_constant_expression; 12839 } 12840 for (const auto *L : Rec.Lambdas) 12841 Diag(L->getLocStart(), D); 12842 } else { 12843 // Mark the capture expressions odr-used. This was deferred 12844 // during lambda expression creation. 12845 for (auto *Lambda : Rec.Lambdas) { 12846 for (auto *C : Lambda->capture_inits()) 12847 MarkDeclarationsReferencedInExpr(C); 12848 } 12849 } 12850 } 12851 12852 // When are coming out of an unevaluated context, clear out any 12853 // temporaries that we may have created as part of the evaluation of 12854 // the expression in that context: they aren't relevant because they 12855 // will never be constructed. 12856 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12857 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12858 ExprCleanupObjects.end()); 12859 Cleanup = Rec.ParentCleanup; 12860 CleanupVarDeclMarking(); 12861 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12862 // Otherwise, merge the contexts together. 12863 } else { 12864 Cleanup.mergeFrom(Rec.ParentCleanup); 12865 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12866 Rec.SavedMaybeODRUseExprs.end()); 12867 } 12868 12869 // Pop the current expression evaluation context off the stack. 12870 ExprEvalContexts.pop_back(); 12871 12872 if (!ExprEvalContexts.empty()) 12873 ExprEvalContexts.back().NumTypos += NumTypos; 12874 else 12875 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12876 "last ExpressionEvaluationContextRecord"); 12877 } 12878 12879 void Sema::DiscardCleanupsInEvaluationContext() { 12880 ExprCleanupObjects.erase( 12881 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12882 ExprCleanupObjects.end()); 12883 Cleanup.reset(); 12884 MaybeODRUseExprs.clear(); 12885 } 12886 12887 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12888 if (!E->getType()->isVariablyModifiedType()) 12889 return E; 12890 return TransformToPotentiallyEvaluated(E); 12891 } 12892 12893 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12894 // Do not mark anything as "used" within a dependent context; wait for 12895 // an instantiation. 12896 if (SemaRef.CurContext->isDependentContext()) 12897 return false; 12898 12899 switch (SemaRef.ExprEvalContexts.back().Context) { 12900 case Sema::Unevaluated: 12901 case Sema::UnevaluatedAbstract: 12902 // We are in an expression that is not potentially evaluated; do nothing. 12903 // (Depending on how you read the standard, we actually do need to do 12904 // something here for null pointer constants, but the standard's 12905 // definition of a null pointer constant is completely crazy.) 12906 return false; 12907 12908 case Sema::DiscardedStatement: 12909 // These are technically a potentially evaluated but they have the effect 12910 // of suppressing use marking. 12911 return false; 12912 12913 case Sema::ConstantEvaluated: 12914 case Sema::PotentiallyEvaluated: 12915 // We are in a potentially evaluated expression (or a constant-expression 12916 // in C++03); we need to do implicit template instantiation, implicitly 12917 // define class members, and mark most declarations as used. 12918 return true; 12919 12920 case Sema::PotentiallyEvaluatedIfUsed: 12921 // Referenced declarations will only be used if the construct in the 12922 // containing expression is used. 12923 return false; 12924 } 12925 llvm_unreachable("Invalid context"); 12926 } 12927 12928 /// \brief Mark a function referenced, and check whether it is odr-used 12929 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12930 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12931 bool MightBeOdrUse) { 12932 assert(Func && "No function?"); 12933 12934 Func->setReferenced(); 12935 12936 // C++11 [basic.def.odr]p3: 12937 // A function whose name appears as a potentially-evaluated expression is 12938 // odr-used if it is the unique lookup result or the selected member of a 12939 // set of overloaded functions [...]. 12940 // 12941 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12942 // can just check that here. 12943 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 12944 12945 // Determine whether we require a function definition to exist, per 12946 // C++11 [temp.inst]p3: 12947 // Unless a function template specialization has been explicitly 12948 // instantiated or explicitly specialized, the function template 12949 // specialization is implicitly instantiated when the specialization is 12950 // referenced in a context that requires a function definition to exist. 12951 // 12952 // We consider constexpr function templates to be referenced in a context 12953 // that requires a definition to exist whenever they are referenced. 12954 // 12955 // FIXME: This instantiates constexpr functions too frequently. If this is 12956 // really an unevaluated context (and we're not just in the definition of a 12957 // function template or overload resolution or other cases which we 12958 // incorrectly consider to be unevaluated contexts), and we're not in a 12959 // subexpression which we actually need to evaluate (for instance, a 12960 // template argument, array bound or an expression in a braced-init-list), 12961 // we are not permitted to instantiate this constexpr function definition. 12962 // 12963 // FIXME: This also implicitly defines special members too frequently. They 12964 // are only supposed to be implicitly defined if they are odr-used, but they 12965 // are not odr-used from constant expressions in unevaluated contexts. 12966 // However, they cannot be referenced if they are deleted, and they are 12967 // deleted whenever the implicit definition of the special member would 12968 // fail (with very few exceptions). 12969 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12970 bool NeedDefinition = 12971 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 12972 (MD && !MD->isUserProvided()))); 12973 12974 // C++14 [temp.expl.spec]p6: 12975 // If a template [...] is explicitly specialized then that specialization 12976 // shall be declared before the first use of that specialization that would 12977 // cause an implicit instantiation to take place, in every translation unit 12978 // in which such a use occurs 12979 if (NeedDefinition && 12980 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 12981 Func->getMemberSpecializationInfo())) 12982 checkSpecializationVisibility(Loc, Func); 12983 12984 // If we don't need to mark the function as used, and we don't need to 12985 // try to provide a definition, there's nothing more to do. 12986 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 12987 (!NeedDefinition || Func->getBody())) 12988 return; 12989 12990 // Note that this declaration has been used. 12991 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12992 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12993 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12994 if (Constructor->isDefaultConstructor()) { 12995 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12996 return; 12997 DefineImplicitDefaultConstructor(Loc, Constructor); 12998 } else if (Constructor->isCopyConstructor()) { 12999 DefineImplicitCopyConstructor(Loc, Constructor); 13000 } else if (Constructor->isMoveConstructor()) { 13001 DefineImplicitMoveConstructor(Loc, Constructor); 13002 } 13003 } else if (Constructor->getInheritedConstructor()) { 13004 DefineInheritingConstructor(Loc, Constructor); 13005 } 13006 } else if (CXXDestructorDecl *Destructor = 13007 dyn_cast<CXXDestructorDecl>(Func)) { 13008 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13009 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13010 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13011 return; 13012 DefineImplicitDestructor(Loc, Destructor); 13013 } 13014 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13015 MarkVTableUsed(Loc, Destructor->getParent()); 13016 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13017 if (MethodDecl->isOverloadedOperator() && 13018 MethodDecl->getOverloadedOperator() == OO_Equal) { 13019 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13020 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13021 if (MethodDecl->isCopyAssignmentOperator()) 13022 DefineImplicitCopyAssignment(Loc, MethodDecl); 13023 else if (MethodDecl->isMoveAssignmentOperator()) 13024 DefineImplicitMoveAssignment(Loc, MethodDecl); 13025 } 13026 } else if (isa<CXXConversionDecl>(MethodDecl) && 13027 MethodDecl->getParent()->isLambda()) { 13028 CXXConversionDecl *Conversion = 13029 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13030 if (Conversion->isLambdaToBlockPointerConversion()) 13031 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13032 else 13033 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13034 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13035 MarkVTableUsed(Loc, MethodDecl->getParent()); 13036 } 13037 13038 // Recursive functions should be marked when used from another function. 13039 // FIXME: Is this really right? 13040 if (CurContext == Func) return; 13041 13042 // Resolve the exception specification for any function which is 13043 // used: CodeGen will need it. 13044 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13045 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13046 ResolveExceptionSpec(Loc, FPT); 13047 13048 // Implicit instantiation of function templates and member functions of 13049 // class templates. 13050 if (Func->isImplicitlyInstantiable()) { 13051 bool AlreadyInstantiated = false; 13052 SourceLocation PointOfInstantiation = Loc; 13053 if (FunctionTemplateSpecializationInfo *SpecInfo 13054 = Func->getTemplateSpecializationInfo()) { 13055 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13056 SpecInfo->setPointOfInstantiation(Loc); 13057 else if (SpecInfo->getTemplateSpecializationKind() 13058 == TSK_ImplicitInstantiation) { 13059 AlreadyInstantiated = true; 13060 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13061 } 13062 } else if (MemberSpecializationInfo *MSInfo 13063 = Func->getMemberSpecializationInfo()) { 13064 if (MSInfo->getPointOfInstantiation().isInvalid()) 13065 MSInfo->setPointOfInstantiation(Loc); 13066 else if (MSInfo->getTemplateSpecializationKind() 13067 == TSK_ImplicitInstantiation) { 13068 AlreadyInstantiated = true; 13069 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13070 } 13071 } 13072 13073 if (!AlreadyInstantiated || Func->isConstexpr()) { 13074 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13075 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13076 ActiveTemplateInstantiations.size()) 13077 PendingLocalImplicitInstantiations.push_back( 13078 std::make_pair(Func, PointOfInstantiation)); 13079 else if (Func->isConstexpr()) 13080 // Do not defer instantiations of constexpr functions, to avoid the 13081 // expression evaluator needing to call back into Sema if it sees a 13082 // call to such a function. 13083 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13084 else { 13085 PendingInstantiations.push_back(std::make_pair(Func, 13086 PointOfInstantiation)); 13087 // Notify the consumer that a function was implicitly instantiated. 13088 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13089 } 13090 } 13091 } else { 13092 // Walk redefinitions, as some of them may be instantiable. 13093 for (auto i : Func->redecls()) { 13094 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13095 MarkFunctionReferenced(Loc, i, OdrUse); 13096 } 13097 } 13098 13099 if (!OdrUse) return; 13100 13101 // Keep track of used but undefined functions. 13102 if (!Func->isDefined()) { 13103 if (mightHaveNonExternalLinkage(Func)) 13104 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13105 else if (Func->getMostRecentDecl()->isInlined() && 13106 !LangOpts.GNUInline && 13107 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13108 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13109 } 13110 13111 Func->markUsed(Context); 13112 } 13113 13114 static void 13115 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13116 VarDecl *var, DeclContext *DC) { 13117 DeclContext *VarDC = var->getDeclContext(); 13118 13119 // If the parameter still belongs to the translation unit, then 13120 // we're actually just using one parameter in the declaration of 13121 // the next. 13122 if (isa<ParmVarDecl>(var) && 13123 isa<TranslationUnitDecl>(VarDC)) 13124 return; 13125 13126 // For C code, don't diagnose about capture if we're not actually in code 13127 // right now; it's impossible to write a non-constant expression outside of 13128 // function context, so we'll get other (more useful) diagnostics later. 13129 // 13130 // For C++, things get a bit more nasty... it would be nice to suppress this 13131 // diagnostic for certain cases like using a local variable in an array bound 13132 // for a member of a local class, but the correct predicate is not obvious. 13133 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13134 return; 13135 13136 if (isa<CXXMethodDecl>(VarDC) && 13137 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13138 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 13139 << var->getIdentifier(); 13140 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 13141 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 13142 << var->getIdentifier() << fn->getDeclName(); 13143 } else if (isa<BlockDecl>(VarDC)) { 13144 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 13145 << var->getIdentifier(); 13146 } else { 13147 // FIXME: Is there any other context where a local variable can be 13148 // declared? 13149 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 13150 << var->getIdentifier(); 13151 } 13152 13153 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13154 << var->getIdentifier(); 13155 13156 // FIXME: Add additional diagnostic info about class etc. which prevents 13157 // capture. 13158 } 13159 13160 13161 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13162 bool &SubCapturesAreNested, 13163 QualType &CaptureType, 13164 QualType &DeclRefType) { 13165 // Check whether we've already captured it. 13166 if (CSI->CaptureMap.count(Var)) { 13167 // If we found a capture, any subcaptures are nested. 13168 SubCapturesAreNested = true; 13169 13170 // Retrieve the capture type for this variable. 13171 CaptureType = CSI->getCapture(Var).getCaptureType(); 13172 13173 // Compute the type of an expression that refers to this variable. 13174 DeclRefType = CaptureType.getNonReferenceType(); 13175 13176 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13177 // are mutable in the sense that user can change their value - they are 13178 // private instances of the captured declarations. 13179 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13180 if (Cap.isCopyCapture() && 13181 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13182 !(isa<CapturedRegionScopeInfo>(CSI) && 13183 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13184 DeclRefType.addConst(); 13185 return true; 13186 } 13187 return false; 13188 } 13189 13190 // Only block literals, captured statements, and lambda expressions can 13191 // capture; other scopes don't work. 13192 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13193 SourceLocation Loc, 13194 const bool Diagnose, Sema &S) { 13195 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13196 return getLambdaAwareParentOfDeclContext(DC); 13197 else if (Var->hasLocalStorage()) { 13198 if (Diagnose) 13199 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13200 } 13201 return nullptr; 13202 } 13203 13204 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13205 // certain types of variables (unnamed, variably modified types etc.) 13206 // so check for eligibility. 13207 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13208 SourceLocation Loc, 13209 const bool Diagnose, Sema &S) { 13210 13211 bool IsBlock = isa<BlockScopeInfo>(CSI); 13212 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13213 13214 // Lambdas are not allowed to capture unnamed variables 13215 // (e.g. anonymous unions). 13216 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13217 // assuming that's the intent. 13218 if (IsLambda && !Var->getDeclName()) { 13219 if (Diagnose) { 13220 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13221 S.Diag(Var->getLocation(), diag::note_declared_at); 13222 } 13223 return false; 13224 } 13225 13226 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13227 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13228 if (Diagnose) { 13229 S.Diag(Loc, diag::err_ref_vm_type); 13230 S.Diag(Var->getLocation(), diag::note_previous_decl) 13231 << Var->getDeclName(); 13232 } 13233 return false; 13234 } 13235 // Prohibit structs with flexible array members too. 13236 // We cannot capture what is in the tail end of the struct. 13237 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13238 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13239 if (Diagnose) { 13240 if (IsBlock) 13241 S.Diag(Loc, diag::err_ref_flexarray_type); 13242 else 13243 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13244 << Var->getDeclName(); 13245 S.Diag(Var->getLocation(), diag::note_previous_decl) 13246 << Var->getDeclName(); 13247 } 13248 return false; 13249 } 13250 } 13251 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13252 // Lambdas and captured statements are not allowed to capture __block 13253 // variables; they don't support the expected semantics. 13254 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13255 if (Diagnose) { 13256 S.Diag(Loc, diag::err_capture_block_variable) 13257 << Var->getDeclName() << !IsLambda; 13258 S.Diag(Var->getLocation(), diag::note_previous_decl) 13259 << Var->getDeclName(); 13260 } 13261 return false; 13262 } 13263 13264 return true; 13265 } 13266 13267 // Returns true if the capture by block was successful. 13268 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13269 SourceLocation Loc, 13270 const bool BuildAndDiagnose, 13271 QualType &CaptureType, 13272 QualType &DeclRefType, 13273 const bool Nested, 13274 Sema &S) { 13275 Expr *CopyExpr = nullptr; 13276 bool ByRef = false; 13277 13278 // Blocks are not allowed to capture arrays. 13279 if (CaptureType->isArrayType()) { 13280 if (BuildAndDiagnose) { 13281 S.Diag(Loc, diag::err_ref_array_type); 13282 S.Diag(Var->getLocation(), diag::note_previous_decl) 13283 << Var->getDeclName(); 13284 } 13285 return false; 13286 } 13287 13288 // Forbid the block-capture of autoreleasing variables. 13289 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13290 if (BuildAndDiagnose) { 13291 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13292 << /*block*/ 0; 13293 S.Diag(Var->getLocation(), diag::note_previous_decl) 13294 << Var->getDeclName(); 13295 } 13296 return false; 13297 } 13298 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13299 if (HasBlocksAttr || CaptureType->isReferenceType() || 13300 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13301 // Block capture by reference does not change the capture or 13302 // declaration reference types. 13303 ByRef = true; 13304 } else { 13305 // Block capture by copy introduces 'const'. 13306 CaptureType = CaptureType.getNonReferenceType().withConst(); 13307 DeclRefType = CaptureType; 13308 13309 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13310 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13311 // The capture logic needs the destructor, so make sure we mark it. 13312 // Usually this is unnecessary because most local variables have 13313 // their destructors marked at declaration time, but parameters are 13314 // an exception because it's technically only the call site that 13315 // actually requires the destructor. 13316 if (isa<ParmVarDecl>(Var)) 13317 S.FinalizeVarWithDestructor(Var, Record); 13318 13319 // Enter a new evaluation context to insulate the copy 13320 // full-expression. 13321 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13322 13323 // According to the blocks spec, the capture of a variable from 13324 // the stack requires a const copy constructor. This is not true 13325 // of the copy/move done to move a __block variable to the heap. 13326 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13327 DeclRefType.withConst(), 13328 VK_LValue, Loc); 13329 13330 ExprResult Result 13331 = S.PerformCopyInitialization( 13332 InitializedEntity::InitializeBlock(Var->getLocation(), 13333 CaptureType, false), 13334 Loc, DeclRef); 13335 13336 // Build a full-expression copy expression if initialization 13337 // succeeded and used a non-trivial constructor. Recover from 13338 // errors by pretending that the copy isn't necessary. 13339 if (!Result.isInvalid() && 13340 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13341 ->isTrivial()) { 13342 Result = S.MaybeCreateExprWithCleanups(Result); 13343 CopyExpr = Result.get(); 13344 } 13345 } 13346 } 13347 } 13348 13349 // Actually capture the variable. 13350 if (BuildAndDiagnose) 13351 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13352 SourceLocation(), CaptureType, CopyExpr); 13353 13354 return true; 13355 13356 } 13357 13358 13359 /// \brief Capture the given variable in the captured region. 13360 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13361 VarDecl *Var, 13362 SourceLocation Loc, 13363 const bool BuildAndDiagnose, 13364 QualType &CaptureType, 13365 QualType &DeclRefType, 13366 const bool RefersToCapturedVariable, 13367 Sema &S) { 13368 // By default, capture variables by reference. 13369 bool ByRef = true; 13370 // Using an LValue reference type is consistent with Lambdas (see below). 13371 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13372 if (S.IsOpenMPCapturedDecl(Var)) 13373 DeclRefType = DeclRefType.getUnqualifiedType(); 13374 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13375 } 13376 13377 if (ByRef) 13378 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13379 else 13380 CaptureType = DeclRefType; 13381 13382 Expr *CopyExpr = nullptr; 13383 if (BuildAndDiagnose) { 13384 // The current implementation assumes that all variables are captured 13385 // by references. Since there is no capture by copy, no expression 13386 // evaluation will be needed. 13387 RecordDecl *RD = RSI->TheRecordDecl; 13388 13389 FieldDecl *Field 13390 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13391 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13392 nullptr, false, ICIS_NoInit); 13393 Field->setImplicit(true); 13394 Field->setAccess(AS_private); 13395 RD->addDecl(Field); 13396 13397 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13398 DeclRefType, VK_LValue, Loc); 13399 Var->setReferenced(true); 13400 Var->markUsed(S.Context); 13401 } 13402 13403 // Actually capture the variable. 13404 if (BuildAndDiagnose) 13405 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13406 SourceLocation(), CaptureType, CopyExpr); 13407 13408 13409 return true; 13410 } 13411 13412 /// \brief Create a field within the lambda class for the variable 13413 /// being captured. 13414 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13415 QualType FieldType, QualType DeclRefType, 13416 SourceLocation Loc, 13417 bool RefersToCapturedVariable) { 13418 CXXRecordDecl *Lambda = LSI->Lambda; 13419 13420 // Build the non-static data member. 13421 FieldDecl *Field 13422 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13423 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13424 nullptr, false, ICIS_NoInit); 13425 Field->setImplicit(true); 13426 Field->setAccess(AS_private); 13427 Lambda->addDecl(Field); 13428 } 13429 13430 /// \brief Capture the given variable in the lambda. 13431 static bool captureInLambda(LambdaScopeInfo *LSI, 13432 VarDecl *Var, 13433 SourceLocation Loc, 13434 const bool BuildAndDiagnose, 13435 QualType &CaptureType, 13436 QualType &DeclRefType, 13437 const bool RefersToCapturedVariable, 13438 const Sema::TryCaptureKind Kind, 13439 SourceLocation EllipsisLoc, 13440 const bool IsTopScope, 13441 Sema &S) { 13442 13443 // Determine whether we are capturing by reference or by value. 13444 bool ByRef = false; 13445 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13446 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13447 } else { 13448 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13449 } 13450 13451 // Compute the type of the field that will capture this variable. 13452 if (ByRef) { 13453 // C++11 [expr.prim.lambda]p15: 13454 // An entity is captured by reference if it is implicitly or 13455 // explicitly captured but not captured by copy. It is 13456 // unspecified whether additional unnamed non-static data 13457 // members are declared in the closure type for entities 13458 // captured by reference. 13459 // 13460 // FIXME: It is not clear whether we want to build an lvalue reference 13461 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13462 // to do the former, while EDG does the latter. Core issue 1249 will 13463 // clarify, but for now we follow GCC because it's a more permissive and 13464 // easily defensible position. 13465 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13466 } else { 13467 // C++11 [expr.prim.lambda]p14: 13468 // For each entity captured by copy, an unnamed non-static 13469 // data member is declared in the closure type. The 13470 // declaration order of these members is unspecified. The type 13471 // of such a data member is the type of the corresponding 13472 // captured entity if the entity is not a reference to an 13473 // object, or the referenced type otherwise. [Note: If the 13474 // captured entity is a reference to a function, the 13475 // corresponding data member is also a reference to a 13476 // function. - end note ] 13477 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13478 if (!RefType->getPointeeType()->isFunctionType()) 13479 CaptureType = RefType->getPointeeType(); 13480 } 13481 13482 // Forbid the lambda copy-capture of autoreleasing variables. 13483 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13484 if (BuildAndDiagnose) { 13485 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13486 S.Diag(Var->getLocation(), diag::note_previous_decl) 13487 << Var->getDeclName(); 13488 } 13489 return false; 13490 } 13491 13492 // Make sure that by-copy captures are of a complete and non-abstract type. 13493 if (BuildAndDiagnose) { 13494 if (!CaptureType->isDependentType() && 13495 S.RequireCompleteType(Loc, CaptureType, 13496 diag::err_capture_of_incomplete_type, 13497 Var->getDeclName())) 13498 return false; 13499 13500 if (S.RequireNonAbstractType(Loc, CaptureType, 13501 diag::err_capture_of_abstract_type)) 13502 return false; 13503 } 13504 } 13505 13506 // Capture this variable in the lambda. 13507 if (BuildAndDiagnose) 13508 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13509 RefersToCapturedVariable); 13510 13511 // Compute the type of a reference to this captured variable. 13512 if (ByRef) 13513 DeclRefType = CaptureType.getNonReferenceType(); 13514 else { 13515 // C++ [expr.prim.lambda]p5: 13516 // The closure type for a lambda-expression has a public inline 13517 // function call operator [...]. This function call operator is 13518 // declared const (9.3.1) if and only if the lambda-expression’s 13519 // parameter-declaration-clause is not followed by mutable. 13520 DeclRefType = CaptureType.getNonReferenceType(); 13521 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13522 DeclRefType.addConst(); 13523 } 13524 13525 // Add the capture. 13526 if (BuildAndDiagnose) 13527 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13528 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13529 13530 return true; 13531 } 13532 13533 bool Sema::tryCaptureVariable( 13534 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13535 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13536 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13537 // An init-capture is notionally from the context surrounding its 13538 // declaration, but its parent DC is the lambda class. 13539 DeclContext *VarDC = Var->getDeclContext(); 13540 if (Var->isInitCapture()) 13541 VarDC = VarDC->getParent(); 13542 13543 DeclContext *DC = CurContext; 13544 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13545 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13546 // We need to sync up the Declaration Context with the 13547 // FunctionScopeIndexToStopAt 13548 if (FunctionScopeIndexToStopAt) { 13549 unsigned FSIndex = FunctionScopes.size() - 1; 13550 while (FSIndex != MaxFunctionScopesIndex) { 13551 DC = getLambdaAwareParentOfDeclContext(DC); 13552 --FSIndex; 13553 } 13554 } 13555 13556 13557 // If the variable is declared in the current context, there is no need to 13558 // capture it. 13559 if (VarDC == DC) return true; 13560 13561 // Capture global variables if it is required to use private copy of this 13562 // variable. 13563 bool IsGlobal = !Var->hasLocalStorage(); 13564 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13565 return true; 13566 13567 // Walk up the stack to determine whether we can capture the variable, 13568 // performing the "simple" checks that don't depend on type. We stop when 13569 // we've either hit the declared scope of the variable or find an existing 13570 // capture of that variable. We start from the innermost capturing-entity 13571 // (the DC) and ensure that all intervening capturing-entities 13572 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13573 // declcontext can either capture the variable or have already captured 13574 // the variable. 13575 CaptureType = Var->getType(); 13576 DeclRefType = CaptureType.getNonReferenceType(); 13577 bool Nested = false; 13578 bool Explicit = (Kind != TryCapture_Implicit); 13579 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13580 do { 13581 // Only block literals, captured statements, and lambda expressions can 13582 // capture; other scopes don't work. 13583 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13584 ExprLoc, 13585 BuildAndDiagnose, 13586 *this); 13587 // We need to check for the parent *first* because, if we *have* 13588 // private-captured a global variable, we need to recursively capture it in 13589 // intermediate blocks, lambdas, etc. 13590 if (!ParentDC) { 13591 if (IsGlobal) { 13592 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13593 break; 13594 } 13595 return true; 13596 } 13597 13598 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13599 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13600 13601 13602 // Check whether we've already captured it. 13603 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13604 DeclRefType)) 13605 break; 13606 // If we are instantiating a generic lambda call operator body, 13607 // we do not want to capture new variables. What was captured 13608 // during either a lambdas transformation or initial parsing 13609 // should be used. 13610 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13611 if (BuildAndDiagnose) { 13612 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13613 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13614 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13615 Diag(Var->getLocation(), diag::note_previous_decl) 13616 << Var->getDeclName(); 13617 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13618 } else 13619 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13620 } 13621 return true; 13622 } 13623 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13624 // certain types of variables (unnamed, variably modified types etc.) 13625 // so check for eligibility. 13626 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13627 return true; 13628 13629 // Try to capture variable-length arrays types. 13630 if (Var->getType()->isVariablyModifiedType()) { 13631 // We're going to walk down into the type and look for VLA 13632 // expressions. 13633 QualType QTy = Var->getType(); 13634 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13635 QTy = PVD->getOriginalType(); 13636 captureVariablyModifiedType(Context, QTy, CSI); 13637 } 13638 13639 if (getLangOpts().OpenMP) { 13640 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13641 // OpenMP private variables should not be captured in outer scope, so 13642 // just break here. Similarly, global variables that are captured in a 13643 // target region should not be captured outside the scope of the region. 13644 if (RSI->CapRegionKind == CR_OpenMP) { 13645 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13646 // When we detect target captures we are looking from inside the 13647 // target region, therefore we need to propagate the capture from the 13648 // enclosing region. Therefore, the capture is not initially nested. 13649 if (IsTargetCap) 13650 FunctionScopesIndex--; 13651 13652 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13653 Nested = !IsTargetCap; 13654 DeclRefType = DeclRefType.getUnqualifiedType(); 13655 CaptureType = Context.getLValueReferenceType(DeclRefType); 13656 break; 13657 } 13658 } 13659 } 13660 } 13661 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13662 // No capture-default, and this is not an explicit capture 13663 // so cannot capture this variable. 13664 if (BuildAndDiagnose) { 13665 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13666 Diag(Var->getLocation(), diag::note_previous_decl) 13667 << Var->getDeclName(); 13668 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13669 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13670 diag::note_lambda_decl); 13671 // FIXME: If we error out because an outer lambda can not implicitly 13672 // capture a variable that an inner lambda explicitly captures, we 13673 // should have the inner lambda do the explicit capture - because 13674 // it makes for cleaner diagnostics later. This would purely be done 13675 // so that the diagnostic does not misleadingly claim that a variable 13676 // can not be captured by a lambda implicitly even though it is captured 13677 // explicitly. Suggestion: 13678 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13679 // at the function head 13680 // - cache the StartingDeclContext - this must be a lambda 13681 // - captureInLambda in the innermost lambda the variable. 13682 } 13683 return true; 13684 } 13685 13686 FunctionScopesIndex--; 13687 DC = ParentDC; 13688 Explicit = false; 13689 } while (!VarDC->Equals(DC)); 13690 13691 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13692 // computing the type of the capture at each step, checking type-specific 13693 // requirements, and adding captures if requested. 13694 // If the variable had already been captured previously, we start capturing 13695 // at the lambda nested within that one. 13696 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13697 ++I) { 13698 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13699 13700 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13701 if (!captureInBlock(BSI, Var, ExprLoc, 13702 BuildAndDiagnose, CaptureType, 13703 DeclRefType, Nested, *this)) 13704 return true; 13705 Nested = true; 13706 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13707 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13708 BuildAndDiagnose, CaptureType, 13709 DeclRefType, Nested, *this)) 13710 return true; 13711 Nested = true; 13712 } else { 13713 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13714 if (!captureInLambda(LSI, Var, ExprLoc, 13715 BuildAndDiagnose, CaptureType, 13716 DeclRefType, Nested, Kind, EllipsisLoc, 13717 /*IsTopScope*/I == N - 1, *this)) 13718 return true; 13719 Nested = true; 13720 } 13721 } 13722 return false; 13723 } 13724 13725 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13726 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13727 QualType CaptureType; 13728 QualType DeclRefType; 13729 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13730 /*BuildAndDiagnose=*/true, CaptureType, 13731 DeclRefType, nullptr); 13732 } 13733 13734 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13735 QualType CaptureType; 13736 QualType DeclRefType; 13737 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13738 /*BuildAndDiagnose=*/false, CaptureType, 13739 DeclRefType, nullptr); 13740 } 13741 13742 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13743 QualType CaptureType; 13744 QualType DeclRefType; 13745 13746 // Determine whether we can capture this variable. 13747 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13748 /*BuildAndDiagnose=*/false, CaptureType, 13749 DeclRefType, nullptr)) 13750 return QualType(); 13751 13752 return DeclRefType; 13753 } 13754 13755 13756 13757 // If either the type of the variable or the initializer is dependent, 13758 // return false. Otherwise, determine whether the variable is a constant 13759 // expression. Use this if you need to know if a variable that might or 13760 // might not be dependent is truly a constant expression. 13761 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13762 ASTContext &Context) { 13763 13764 if (Var->getType()->isDependentType()) 13765 return false; 13766 const VarDecl *DefVD = nullptr; 13767 Var->getAnyInitializer(DefVD); 13768 if (!DefVD) 13769 return false; 13770 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13771 Expr *Init = cast<Expr>(Eval->Value); 13772 if (Init->isValueDependent()) 13773 return false; 13774 return IsVariableAConstantExpression(Var, Context); 13775 } 13776 13777 13778 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13779 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13780 // an object that satisfies the requirements for appearing in a 13781 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13782 // is immediately applied." This function handles the lvalue-to-rvalue 13783 // conversion part. 13784 MaybeODRUseExprs.erase(E->IgnoreParens()); 13785 13786 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13787 // to a variable that is a constant expression, and if so, identify it as 13788 // a reference to a variable that does not involve an odr-use of that 13789 // variable. 13790 if (LambdaScopeInfo *LSI = getCurLambda()) { 13791 Expr *SansParensExpr = E->IgnoreParens(); 13792 VarDecl *Var = nullptr; 13793 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13794 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13795 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13796 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13797 13798 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13799 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13800 } 13801 } 13802 13803 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13804 Res = CorrectDelayedTyposInExpr(Res); 13805 13806 if (!Res.isUsable()) 13807 return Res; 13808 13809 // If a constant-expression is a reference to a variable where we delay 13810 // deciding whether it is an odr-use, just assume we will apply the 13811 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13812 // (a non-type template argument), we have special handling anyway. 13813 UpdateMarkingForLValueToRValue(Res.get()); 13814 return Res; 13815 } 13816 13817 void Sema::CleanupVarDeclMarking() { 13818 for (Expr *E : MaybeODRUseExprs) { 13819 VarDecl *Var; 13820 SourceLocation Loc; 13821 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13822 Var = cast<VarDecl>(DRE->getDecl()); 13823 Loc = DRE->getLocation(); 13824 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13825 Var = cast<VarDecl>(ME->getMemberDecl()); 13826 Loc = ME->getMemberLoc(); 13827 } else { 13828 llvm_unreachable("Unexpected expression"); 13829 } 13830 13831 MarkVarDeclODRUsed(Var, Loc, *this, 13832 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13833 } 13834 13835 MaybeODRUseExprs.clear(); 13836 } 13837 13838 13839 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13840 VarDecl *Var, Expr *E) { 13841 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13842 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13843 Var->setReferenced(); 13844 13845 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13846 bool MarkODRUsed = true; 13847 13848 // If the context is not potentially evaluated, this is not an odr-use and 13849 // does not trigger instantiation. 13850 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13851 if (SemaRef.isUnevaluatedContext()) 13852 return; 13853 13854 // If we don't yet know whether this context is going to end up being an 13855 // evaluated context, and we're referencing a variable from an enclosing 13856 // scope, add a potential capture. 13857 // 13858 // FIXME: Is this necessary? These contexts are only used for default 13859 // arguments, where local variables can't be used. 13860 const bool RefersToEnclosingScope = 13861 (SemaRef.CurContext != Var->getDeclContext() && 13862 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13863 if (RefersToEnclosingScope) { 13864 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13865 // If a variable could potentially be odr-used, defer marking it so 13866 // until we finish analyzing the full expression for any 13867 // lvalue-to-rvalue 13868 // or discarded value conversions that would obviate odr-use. 13869 // Add it to the list of potential captures that will be analyzed 13870 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13871 // unless the variable is a reference that was initialized by a constant 13872 // expression (this will never need to be captured or odr-used). 13873 assert(E && "Capture variable should be used in an expression."); 13874 if (!Var->getType()->isReferenceType() || 13875 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13876 LSI->addPotentialCapture(E->IgnoreParens()); 13877 } 13878 } 13879 13880 if (!isTemplateInstantiation(TSK)) 13881 return; 13882 13883 // Instantiate, but do not mark as odr-used, variable templates. 13884 MarkODRUsed = false; 13885 } 13886 13887 VarTemplateSpecializationDecl *VarSpec = 13888 dyn_cast<VarTemplateSpecializationDecl>(Var); 13889 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13890 "Can't instantiate a partial template specialization."); 13891 13892 // If this might be a member specialization of a static data member, check 13893 // the specialization is visible. We already did the checks for variable 13894 // template specializations when we created them. 13895 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 13896 SemaRef.checkSpecializationVisibility(Loc, Var); 13897 13898 // Perform implicit instantiation of static data members, static data member 13899 // templates of class templates, and variable template specializations. Delay 13900 // instantiations of variable templates, except for those that could be used 13901 // in a constant expression. 13902 if (isTemplateInstantiation(TSK)) { 13903 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13904 13905 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13906 if (Var->getPointOfInstantiation().isInvalid()) { 13907 // This is a modification of an existing AST node. Notify listeners. 13908 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13909 L->StaticDataMemberInstantiated(Var); 13910 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13911 // Don't bother trying to instantiate it again, unless we might need 13912 // its initializer before we get to the end of the TU. 13913 TryInstantiating = false; 13914 } 13915 13916 if (Var->getPointOfInstantiation().isInvalid()) 13917 Var->setTemplateSpecializationKind(TSK, Loc); 13918 13919 if (TryInstantiating) { 13920 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13921 bool InstantiationDependent = false; 13922 bool IsNonDependent = 13923 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13924 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13925 : true; 13926 13927 // Do not instantiate specializations that are still type-dependent. 13928 if (IsNonDependent) { 13929 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13930 // Do not defer instantiations of variables which could be used in a 13931 // constant expression. 13932 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13933 } else { 13934 SemaRef.PendingInstantiations 13935 .push_back(std::make_pair(Var, PointOfInstantiation)); 13936 } 13937 } 13938 } 13939 } 13940 13941 if (!MarkODRUsed) 13942 return; 13943 13944 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13945 // the requirements for appearing in a constant expression (5.19) and, if 13946 // it is an object, the lvalue-to-rvalue conversion (4.1) 13947 // is immediately applied." We check the first part here, and 13948 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13949 // Note that we use the C++11 definition everywhere because nothing in 13950 // C++03 depends on whether we get the C++03 version correct. The second 13951 // part does not apply to references, since they are not objects. 13952 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13953 // A reference initialized by a constant expression can never be 13954 // odr-used, so simply ignore it. 13955 if (!Var->getType()->isReferenceType()) 13956 SemaRef.MaybeODRUseExprs.insert(E); 13957 } else 13958 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13959 /*MaxFunctionScopeIndex ptr*/ nullptr); 13960 } 13961 13962 /// \brief Mark a variable referenced, and check whether it is odr-used 13963 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13964 /// used directly for normal expressions referring to VarDecl. 13965 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13966 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13967 } 13968 13969 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13970 Decl *D, Expr *E, bool MightBeOdrUse) { 13971 if (SemaRef.isInOpenMPDeclareTargetContext()) 13972 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 13973 13974 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13975 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13976 return; 13977 } 13978 13979 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 13980 13981 // If this is a call to a method via a cast, also mark the method in the 13982 // derived class used in case codegen can devirtualize the call. 13983 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13984 if (!ME) 13985 return; 13986 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13987 if (!MD) 13988 return; 13989 // Only attempt to devirtualize if this is truly a virtual call. 13990 bool IsVirtualCall = MD->isVirtual() && 13991 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13992 if (!IsVirtualCall) 13993 return; 13994 const Expr *Base = ME->getBase(); 13995 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13996 if (!MostDerivedClassDecl) 13997 return; 13998 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13999 if (!DM || DM->isPure()) 14000 return; 14001 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14002 } 14003 14004 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14005 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14006 // TODO: update this with DR# once a defect report is filed. 14007 // C++11 defect. The address of a pure member should not be an ODR use, even 14008 // if it's a qualified reference. 14009 bool OdrUse = true; 14010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14011 if (Method->isVirtual()) 14012 OdrUse = false; 14013 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14014 } 14015 14016 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14017 void Sema::MarkMemberReferenced(MemberExpr *E) { 14018 // C++11 [basic.def.odr]p2: 14019 // A non-overloaded function whose name appears as a potentially-evaluated 14020 // expression or a member of a set of candidate functions, if selected by 14021 // overload resolution when referred to from a potentially-evaluated 14022 // expression, is odr-used, unless it is a pure virtual function and its 14023 // name is not explicitly qualified. 14024 bool MightBeOdrUse = true; 14025 if (E->performsVirtualDispatch(getLangOpts())) { 14026 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14027 if (Method->isPure()) 14028 MightBeOdrUse = false; 14029 } 14030 SourceLocation Loc = E->getMemberLoc().isValid() ? 14031 E->getMemberLoc() : E->getLocStart(); 14032 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14033 } 14034 14035 /// \brief Perform marking for a reference to an arbitrary declaration. It 14036 /// marks the declaration referenced, and performs odr-use checking for 14037 /// functions and variables. This method should not be used when building a 14038 /// normal expression which refers to a variable. 14039 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14040 bool MightBeOdrUse) { 14041 if (MightBeOdrUse) { 14042 if (auto *VD = dyn_cast<VarDecl>(D)) { 14043 MarkVariableReferenced(Loc, VD); 14044 return; 14045 } 14046 } 14047 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14048 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14049 return; 14050 } 14051 D->setReferenced(); 14052 } 14053 14054 namespace { 14055 // Mark all of the declarations referenced 14056 // FIXME: Not fully implemented yet! We need to have a better understanding 14057 // of when we're entering 14058 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14059 Sema &S; 14060 SourceLocation Loc; 14061 14062 public: 14063 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14064 14065 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14066 14067 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14068 bool TraverseRecordType(RecordType *T); 14069 }; 14070 } 14071 14072 bool MarkReferencedDecls::TraverseTemplateArgument( 14073 const TemplateArgument &Arg) { 14074 if (Arg.getKind() == TemplateArgument::Declaration) { 14075 if (Decl *D = Arg.getAsDecl()) 14076 S.MarkAnyDeclReferenced(Loc, D, true); 14077 } 14078 14079 return Inherited::TraverseTemplateArgument(Arg); 14080 } 14081 14082 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14083 if (ClassTemplateSpecializationDecl *Spec 14084 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14085 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14086 return TraverseTemplateArguments(Args.data(), Args.size()); 14087 } 14088 14089 return true; 14090 } 14091 14092 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14093 MarkReferencedDecls Marker(*this, Loc); 14094 Marker.TraverseType(Context.getCanonicalType(T)); 14095 } 14096 14097 namespace { 14098 /// \brief Helper class that marks all of the declarations referenced by 14099 /// potentially-evaluated subexpressions as "referenced". 14100 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14101 Sema &S; 14102 bool SkipLocalVariables; 14103 14104 public: 14105 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14106 14107 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14108 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14109 14110 void VisitDeclRefExpr(DeclRefExpr *E) { 14111 // If we were asked not to visit local variables, don't. 14112 if (SkipLocalVariables) { 14113 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14114 if (VD->hasLocalStorage()) 14115 return; 14116 } 14117 14118 S.MarkDeclRefReferenced(E); 14119 } 14120 14121 void VisitMemberExpr(MemberExpr *E) { 14122 S.MarkMemberReferenced(E); 14123 Inherited::VisitMemberExpr(E); 14124 } 14125 14126 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14127 S.MarkFunctionReferenced(E->getLocStart(), 14128 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14129 Visit(E->getSubExpr()); 14130 } 14131 14132 void VisitCXXNewExpr(CXXNewExpr *E) { 14133 if (E->getOperatorNew()) 14134 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14135 if (E->getOperatorDelete()) 14136 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14137 Inherited::VisitCXXNewExpr(E); 14138 } 14139 14140 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14141 if (E->getOperatorDelete()) 14142 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14143 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14144 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14145 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14146 S.MarkFunctionReferenced(E->getLocStart(), 14147 S.LookupDestructor(Record)); 14148 } 14149 14150 Inherited::VisitCXXDeleteExpr(E); 14151 } 14152 14153 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14154 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14155 Inherited::VisitCXXConstructExpr(E); 14156 } 14157 14158 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14159 Visit(E->getExpr()); 14160 } 14161 14162 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14163 Inherited::VisitImplicitCastExpr(E); 14164 14165 if (E->getCastKind() == CK_LValueToRValue) 14166 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14167 } 14168 }; 14169 } 14170 14171 /// \brief Mark any declarations that appear within this expression or any 14172 /// potentially-evaluated subexpressions as "referenced". 14173 /// 14174 /// \param SkipLocalVariables If true, don't mark local variables as 14175 /// 'referenced'. 14176 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14177 bool SkipLocalVariables) { 14178 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14179 } 14180 14181 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14182 /// of the program being compiled. 14183 /// 14184 /// This routine emits the given diagnostic when the code currently being 14185 /// type-checked is "potentially evaluated", meaning that there is a 14186 /// possibility that the code will actually be executable. Code in sizeof() 14187 /// expressions, code used only during overload resolution, etc., are not 14188 /// potentially evaluated. This routine will suppress such diagnostics or, 14189 /// in the absolutely nutty case of potentially potentially evaluated 14190 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14191 /// later. 14192 /// 14193 /// This routine should be used for all diagnostics that describe the run-time 14194 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14195 /// Failure to do so will likely result in spurious diagnostics or failures 14196 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14197 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14198 const PartialDiagnostic &PD) { 14199 switch (ExprEvalContexts.back().Context) { 14200 case Unevaluated: 14201 case UnevaluatedAbstract: 14202 case DiscardedStatement: 14203 // The argument will never be evaluated, so don't complain. 14204 break; 14205 14206 case ConstantEvaluated: 14207 // Relevant diagnostics should be produced by constant evaluation. 14208 break; 14209 14210 case PotentiallyEvaluated: 14211 case PotentiallyEvaluatedIfUsed: 14212 if (Statement && getCurFunctionOrMethodDecl()) { 14213 FunctionScopes.back()->PossiblyUnreachableDiags. 14214 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14215 } 14216 else 14217 Diag(Loc, PD); 14218 14219 return true; 14220 } 14221 14222 return false; 14223 } 14224 14225 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14226 CallExpr *CE, FunctionDecl *FD) { 14227 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14228 return false; 14229 14230 // If we're inside a decltype's expression, don't check for a valid return 14231 // type or construct temporaries until we know whether this is the last call. 14232 if (ExprEvalContexts.back().IsDecltype) { 14233 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14234 return false; 14235 } 14236 14237 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14238 FunctionDecl *FD; 14239 CallExpr *CE; 14240 14241 public: 14242 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14243 : FD(FD), CE(CE) { } 14244 14245 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14246 if (!FD) { 14247 S.Diag(Loc, diag::err_call_incomplete_return) 14248 << T << CE->getSourceRange(); 14249 return; 14250 } 14251 14252 S.Diag(Loc, diag::err_call_function_incomplete_return) 14253 << CE->getSourceRange() << FD->getDeclName() << T; 14254 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14255 << FD->getDeclName(); 14256 } 14257 } Diagnoser(FD, CE); 14258 14259 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14260 return true; 14261 14262 return false; 14263 } 14264 14265 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14266 // will prevent this condition from triggering, which is what we want. 14267 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14268 SourceLocation Loc; 14269 14270 unsigned diagnostic = diag::warn_condition_is_assignment; 14271 bool IsOrAssign = false; 14272 14273 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14274 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14275 return; 14276 14277 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14278 14279 // Greylist some idioms by putting them into a warning subcategory. 14280 if (ObjCMessageExpr *ME 14281 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14282 Selector Sel = ME->getSelector(); 14283 14284 // self = [<foo> init...] 14285 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14286 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14287 14288 // <foo> = [<bar> nextObject] 14289 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14290 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14291 } 14292 14293 Loc = Op->getOperatorLoc(); 14294 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14295 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14296 return; 14297 14298 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14299 Loc = Op->getOperatorLoc(); 14300 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14301 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14302 else { 14303 // Not an assignment. 14304 return; 14305 } 14306 14307 Diag(Loc, diagnostic) << E->getSourceRange(); 14308 14309 SourceLocation Open = E->getLocStart(); 14310 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14311 Diag(Loc, diag::note_condition_assign_silence) 14312 << FixItHint::CreateInsertion(Open, "(") 14313 << FixItHint::CreateInsertion(Close, ")"); 14314 14315 if (IsOrAssign) 14316 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14317 << FixItHint::CreateReplacement(Loc, "!="); 14318 else 14319 Diag(Loc, diag::note_condition_assign_to_comparison) 14320 << FixItHint::CreateReplacement(Loc, "=="); 14321 } 14322 14323 /// \brief Redundant parentheses over an equality comparison can indicate 14324 /// that the user intended an assignment used as condition. 14325 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14326 // Don't warn if the parens came from a macro. 14327 SourceLocation parenLoc = ParenE->getLocStart(); 14328 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14329 return; 14330 // Don't warn for dependent expressions. 14331 if (ParenE->isTypeDependent()) 14332 return; 14333 14334 Expr *E = ParenE->IgnoreParens(); 14335 14336 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14337 if (opE->getOpcode() == BO_EQ && 14338 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14339 == Expr::MLV_Valid) { 14340 SourceLocation Loc = opE->getOperatorLoc(); 14341 14342 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14343 SourceRange ParenERange = ParenE->getSourceRange(); 14344 Diag(Loc, diag::note_equality_comparison_silence) 14345 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14346 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14347 Diag(Loc, diag::note_equality_comparison_to_assign) 14348 << FixItHint::CreateReplacement(Loc, "="); 14349 } 14350 } 14351 14352 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14353 bool IsConstexpr) { 14354 DiagnoseAssignmentAsCondition(E); 14355 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14356 DiagnoseEqualityWithExtraParens(parenE); 14357 14358 ExprResult result = CheckPlaceholderExpr(E); 14359 if (result.isInvalid()) return ExprError(); 14360 E = result.get(); 14361 14362 if (!E->isTypeDependent()) { 14363 if (getLangOpts().CPlusPlus) 14364 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14365 14366 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14367 if (ERes.isInvalid()) 14368 return ExprError(); 14369 E = ERes.get(); 14370 14371 QualType T = E->getType(); 14372 if (!T->isScalarType()) { // C99 6.8.4.1p1 14373 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14374 << T << E->getSourceRange(); 14375 return ExprError(); 14376 } 14377 CheckBoolLikeConversion(E, Loc); 14378 } 14379 14380 return E; 14381 } 14382 14383 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14384 Expr *SubExpr, ConditionKind CK) { 14385 // Empty conditions are valid in for-statements. 14386 if (!SubExpr) 14387 return ConditionResult(); 14388 14389 ExprResult Cond; 14390 switch (CK) { 14391 case ConditionKind::Boolean: 14392 Cond = CheckBooleanCondition(Loc, SubExpr); 14393 break; 14394 14395 case ConditionKind::ConstexprIf: 14396 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14397 break; 14398 14399 case ConditionKind::Switch: 14400 Cond = CheckSwitchCondition(Loc, SubExpr); 14401 break; 14402 } 14403 if (Cond.isInvalid()) 14404 return ConditionError(); 14405 14406 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14407 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14408 if (!FullExpr.get()) 14409 return ConditionError(); 14410 14411 return ConditionResult(*this, nullptr, FullExpr, 14412 CK == ConditionKind::ConstexprIf); 14413 } 14414 14415 namespace { 14416 /// A visitor for rebuilding a call to an __unknown_any expression 14417 /// to have an appropriate type. 14418 struct RebuildUnknownAnyFunction 14419 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14420 14421 Sema &S; 14422 14423 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14424 14425 ExprResult VisitStmt(Stmt *S) { 14426 llvm_unreachable("unexpected statement!"); 14427 } 14428 14429 ExprResult VisitExpr(Expr *E) { 14430 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14431 << E->getSourceRange(); 14432 return ExprError(); 14433 } 14434 14435 /// Rebuild an expression which simply semantically wraps another 14436 /// expression which it shares the type and value kind of. 14437 template <class T> ExprResult rebuildSugarExpr(T *E) { 14438 ExprResult SubResult = Visit(E->getSubExpr()); 14439 if (SubResult.isInvalid()) return ExprError(); 14440 14441 Expr *SubExpr = SubResult.get(); 14442 E->setSubExpr(SubExpr); 14443 E->setType(SubExpr->getType()); 14444 E->setValueKind(SubExpr->getValueKind()); 14445 assert(E->getObjectKind() == OK_Ordinary); 14446 return E; 14447 } 14448 14449 ExprResult VisitParenExpr(ParenExpr *E) { 14450 return rebuildSugarExpr(E); 14451 } 14452 14453 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14454 return rebuildSugarExpr(E); 14455 } 14456 14457 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14458 ExprResult SubResult = Visit(E->getSubExpr()); 14459 if (SubResult.isInvalid()) return ExprError(); 14460 14461 Expr *SubExpr = SubResult.get(); 14462 E->setSubExpr(SubExpr); 14463 E->setType(S.Context.getPointerType(SubExpr->getType())); 14464 assert(E->getValueKind() == VK_RValue); 14465 assert(E->getObjectKind() == OK_Ordinary); 14466 return E; 14467 } 14468 14469 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14470 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14471 14472 E->setType(VD->getType()); 14473 14474 assert(E->getValueKind() == VK_RValue); 14475 if (S.getLangOpts().CPlusPlus && 14476 !(isa<CXXMethodDecl>(VD) && 14477 cast<CXXMethodDecl>(VD)->isInstance())) 14478 E->setValueKind(VK_LValue); 14479 14480 return E; 14481 } 14482 14483 ExprResult VisitMemberExpr(MemberExpr *E) { 14484 return resolveDecl(E, E->getMemberDecl()); 14485 } 14486 14487 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14488 return resolveDecl(E, E->getDecl()); 14489 } 14490 }; 14491 } 14492 14493 /// Given a function expression of unknown-any type, try to rebuild it 14494 /// to have a function type. 14495 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14496 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14497 if (Result.isInvalid()) return ExprError(); 14498 return S.DefaultFunctionArrayConversion(Result.get()); 14499 } 14500 14501 namespace { 14502 /// A visitor for rebuilding an expression of type __unknown_anytype 14503 /// into one which resolves the type directly on the referring 14504 /// expression. Strict preservation of the original source 14505 /// structure is not a goal. 14506 struct RebuildUnknownAnyExpr 14507 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14508 14509 Sema &S; 14510 14511 /// The current destination type. 14512 QualType DestType; 14513 14514 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14515 : S(S), DestType(CastType) {} 14516 14517 ExprResult VisitStmt(Stmt *S) { 14518 llvm_unreachable("unexpected statement!"); 14519 } 14520 14521 ExprResult VisitExpr(Expr *E) { 14522 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14523 << E->getSourceRange(); 14524 return ExprError(); 14525 } 14526 14527 ExprResult VisitCallExpr(CallExpr *E); 14528 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14529 14530 /// Rebuild an expression which simply semantically wraps another 14531 /// expression which it shares the type and value kind of. 14532 template <class T> ExprResult rebuildSugarExpr(T *E) { 14533 ExprResult SubResult = Visit(E->getSubExpr()); 14534 if (SubResult.isInvalid()) return ExprError(); 14535 Expr *SubExpr = SubResult.get(); 14536 E->setSubExpr(SubExpr); 14537 E->setType(SubExpr->getType()); 14538 E->setValueKind(SubExpr->getValueKind()); 14539 assert(E->getObjectKind() == OK_Ordinary); 14540 return E; 14541 } 14542 14543 ExprResult VisitParenExpr(ParenExpr *E) { 14544 return rebuildSugarExpr(E); 14545 } 14546 14547 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14548 return rebuildSugarExpr(E); 14549 } 14550 14551 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14552 const PointerType *Ptr = DestType->getAs<PointerType>(); 14553 if (!Ptr) { 14554 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14555 << E->getSourceRange(); 14556 return ExprError(); 14557 } 14558 assert(E->getValueKind() == VK_RValue); 14559 assert(E->getObjectKind() == OK_Ordinary); 14560 E->setType(DestType); 14561 14562 // Build the sub-expression as if it were an object of the pointee type. 14563 DestType = Ptr->getPointeeType(); 14564 ExprResult SubResult = Visit(E->getSubExpr()); 14565 if (SubResult.isInvalid()) return ExprError(); 14566 E->setSubExpr(SubResult.get()); 14567 return E; 14568 } 14569 14570 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14571 14572 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14573 14574 ExprResult VisitMemberExpr(MemberExpr *E) { 14575 return resolveDecl(E, E->getMemberDecl()); 14576 } 14577 14578 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14579 return resolveDecl(E, E->getDecl()); 14580 } 14581 }; 14582 } 14583 14584 /// Rebuilds a call expression which yielded __unknown_anytype. 14585 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14586 Expr *CalleeExpr = E->getCallee(); 14587 14588 enum FnKind { 14589 FK_MemberFunction, 14590 FK_FunctionPointer, 14591 FK_BlockPointer 14592 }; 14593 14594 FnKind Kind; 14595 QualType CalleeType = CalleeExpr->getType(); 14596 if (CalleeType == S.Context.BoundMemberTy) { 14597 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14598 Kind = FK_MemberFunction; 14599 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14600 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14601 CalleeType = Ptr->getPointeeType(); 14602 Kind = FK_FunctionPointer; 14603 } else { 14604 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14605 Kind = FK_BlockPointer; 14606 } 14607 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14608 14609 // Verify that this is a legal result type of a function. 14610 if (DestType->isArrayType() || DestType->isFunctionType()) { 14611 unsigned diagID = diag::err_func_returning_array_function; 14612 if (Kind == FK_BlockPointer) 14613 diagID = diag::err_block_returning_array_function; 14614 14615 S.Diag(E->getExprLoc(), diagID) 14616 << DestType->isFunctionType() << DestType; 14617 return ExprError(); 14618 } 14619 14620 // Otherwise, go ahead and set DestType as the call's result. 14621 E->setType(DestType.getNonLValueExprType(S.Context)); 14622 E->setValueKind(Expr::getValueKindForType(DestType)); 14623 assert(E->getObjectKind() == OK_Ordinary); 14624 14625 // Rebuild the function type, replacing the result type with DestType. 14626 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14627 if (Proto) { 14628 // __unknown_anytype(...) is a special case used by the debugger when 14629 // it has no idea what a function's signature is. 14630 // 14631 // We want to build this call essentially under the K&R 14632 // unprototyped rules, but making a FunctionNoProtoType in C++ 14633 // would foul up all sorts of assumptions. However, we cannot 14634 // simply pass all arguments as variadic arguments, nor can we 14635 // portably just call the function under a non-variadic type; see 14636 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14637 // However, it turns out that in practice it is generally safe to 14638 // call a function declared as "A foo(B,C,D);" under the prototype 14639 // "A foo(B,C,D,...);". The only known exception is with the 14640 // Windows ABI, where any variadic function is implicitly cdecl 14641 // regardless of its normal CC. Therefore we change the parameter 14642 // types to match the types of the arguments. 14643 // 14644 // This is a hack, but it is far superior to moving the 14645 // corresponding target-specific code from IR-gen to Sema/AST. 14646 14647 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14648 SmallVector<QualType, 8> ArgTypes; 14649 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14650 ArgTypes.reserve(E->getNumArgs()); 14651 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14652 Expr *Arg = E->getArg(i); 14653 QualType ArgType = Arg->getType(); 14654 if (E->isLValue()) { 14655 ArgType = S.Context.getLValueReferenceType(ArgType); 14656 } else if (E->isXValue()) { 14657 ArgType = S.Context.getRValueReferenceType(ArgType); 14658 } 14659 ArgTypes.push_back(ArgType); 14660 } 14661 ParamTypes = ArgTypes; 14662 } 14663 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14664 Proto->getExtProtoInfo()); 14665 } else { 14666 DestType = S.Context.getFunctionNoProtoType(DestType, 14667 FnType->getExtInfo()); 14668 } 14669 14670 // Rebuild the appropriate pointer-to-function type. 14671 switch (Kind) { 14672 case FK_MemberFunction: 14673 // Nothing to do. 14674 break; 14675 14676 case FK_FunctionPointer: 14677 DestType = S.Context.getPointerType(DestType); 14678 break; 14679 14680 case FK_BlockPointer: 14681 DestType = S.Context.getBlockPointerType(DestType); 14682 break; 14683 } 14684 14685 // Finally, we can recurse. 14686 ExprResult CalleeResult = Visit(CalleeExpr); 14687 if (!CalleeResult.isUsable()) return ExprError(); 14688 E->setCallee(CalleeResult.get()); 14689 14690 // Bind a temporary if necessary. 14691 return S.MaybeBindToTemporary(E); 14692 } 14693 14694 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14695 // Verify that this is a legal result type of a call. 14696 if (DestType->isArrayType() || DestType->isFunctionType()) { 14697 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14698 << DestType->isFunctionType() << DestType; 14699 return ExprError(); 14700 } 14701 14702 // Rewrite the method result type if available. 14703 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14704 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14705 Method->setReturnType(DestType); 14706 } 14707 14708 // Change the type of the message. 14709 E->setType(DestType.getNonReferenceType()); 14710 E->setValueKind(Expr::getValueKindForType(DestType)); 14711 14712 return S.MaybeBindToTemporary(E); 14713 } 14714 14715 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14716 // The only case we should ever see here is a function-to-pointer decay. 14717 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14718 assert(E->getValueKind() == VK_RValue); 14719 assert(E->getObjectKind() == OK_Ordinary); 14720 14721 E->setType(DestType); 14722 14723 // Rebuild the sub-expression as the pointee (function) type. 14724 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14725 14726 ExprResult Result = Visit(E->getSubExpr()); 14727 if (!Result.isUsable()) return ExprError(); 14728 14729 E->setSubExpr(Result.get()); 14730 return E; 14731 } else if (E->getCastKind() == CK_LValueToRValue) { 14732 assert(E->getValueKind() == VK_RValue); 14733 assert(E->getObjectKind() == OK_Ordinary); 14734 14735 assert(isa<BlockPointerType>(E->getType())); 14736 14737 E->setType(DestType); 14738 14739 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14740 DestType = S.Context.getLValueReferenceType(DestType); 14741 14742 ExprResult Result = Visit(E->getSubExpr()); 14743 if (!Result.isUsable()) return ExprError(); 14744 14745 E->setSubExpr(Result.get()); 14746 return E; 14747 } else { 14748 llvm_unreachable("Unhandled cast type!"); 14749 } 14750 } 14751 14752 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14753 ExprValueKind ValueKind = VK_LValue; 14754 QualType Type = DestType; 14755 14756 // We know how to make this work for certain kinds of decls: 14757 14758 // - functions 14759 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14760 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14761 DestType = Ptr->getPointeeType(); 14762 ExprResult Result = resolveDecl(E, VD); 14763 if (Result.isInvalid()) return ExprError(); 14764 return S.ImpCastExprToType(Result.get(), Type, 14765 CK_FunctionToPointerDecay, VK_RValue); 14766 } 14767 14768 if (!Type->isFunctionType()) { 14769 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14770 << VD << E->getSourceRange(); 14771 return ExprError(); 14772 } 14773 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14774 // We must match the FunctionDecl's type to the hack introduced in 14775 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14776 // type. See the lengthy commentary in that routine. 14777 QualType FDT = FD->getType(); 14778 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14779 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14780 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14781 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14782 SourceLocation Loc = FD->getLocation(); 14783 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14784 FD->getDeclContext(), 14785 Loc, Loc, FD->getNameInfo().getName(), 14786 DestType, FD->getTypeSourceInfo(), 14787 SC_None, false/*isInlineSpecified*/, 14788 FD->hasPrototype(), 14789 false/*isConstexprSpecified*/); 14790 14791 if (FD->getQualifier()) 14792 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14793 14794 SmallVector<ParmVarDecl*, 16> Params; 14795 for (const auto &AI : FT->param_types()) { 14796 ParmVarDecl *Param = 14797 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14798 Param->setScopeInfo(0, Params.size()); 14799 Params.push_back(Param); 14800 } 14801 NewFD->setParams(Params); 14802 DRE->setDecl(NewFD); 14803 VD = DRE->getDecl(); 14804 } 14805 } 14806 14807 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14808 if (MD->isInstance()) { 14809 ValueKind = VK_RValue; 14810 Type = S.Context.BoundMemberTy; 14811 } 14812 14813 // Function references aren't l-values in C. 14814 if (!S.getLangOpts().CPlusPlus) 14815 ValueKind = VK_RValue; 14816 14817 // - variables 14818 } else if (isa<VarDecl>(VD)) { 14819 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14820 Type = RefTy->getPointeeType(); 14821 } else if (Type->isFunctionType()) { 14822 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14823 << VD << E->getSourceRange(); 14824 return ExprError(); 14825 } 14826 14827 // - nothing else 14828 } else { 14829 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14830 << VD << E->getSourceRange(); 14831 return ExprError(); 14832 } 14833 14834 // Modifying the declaration like this is friendly to IR-gen but 14835 // also really dangerous. 14836 VD->setType(DestType); 14837 E->setType(Type); 14838 E->setValueKind(ValueKind); 14839 return E; 14840 } 14841 14842 /// Check a cast of an unknown-any type. We intentionally only 14843 /// trigger this for C-style casts. 14844 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14845 Expr *CastExpr, CastKind &CastKind, 14846 ExprValueKind &VK, CXXCastPath &Path) { 14847 // The type we're casting to must be either void or complete. 14848 if (!CastType->isVoidType() && 14849 RequireCompleteType(TypeRange.getBegin(), CastType, 14850 diag::err_typecheck_cast_to_incomplete)) 14851 return ExprError(); 14852 14853 // Rewrite the casted expression from scratch. 14854 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14855 if (!result.isUsable()) return ExprError(); 14856 14857 CastExpr = result.get(); 14858 VK = CastExpr->getValueKind(); 14859 CastKind = CK_NoOp; 14860 14861 return CastExpr; 14862 } 14863 14864 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14865 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14866 } 14867 14868 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14869 Expr *arg, QualType ¶mType) { 14870 // If the syntactic form of the argument is not an explicit cast of 14871 // any sort, just do default argument promotion. 14872 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14873 if (!castArg) { 14874 ExprResult result = DefaultArgumentPromotion(arg); 14875 if (result.isInvalid()) return ExprError(); 14876 paramType = result.get()->getType(); 14877 return result; 14878 } 14879 14880 // Otherwise, use the type that was written in the explicit cast. 14881 assert(!arg->hasPlaceholderType()); 14882 paramType = castArg->getTypeAsWritten(); 14883 14884 // Copy-initialize a parameter of that type. 14885 InitializedEntity entity = 14886 InitializedEntity::InitializeParameter(Context, paramType, 14887 /*consumed*/ false); 14888 return PerformCopyInitialization(entity, callLoc, arg); 14889 } 14890 14891 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14892 Expr *orig = E; 14893 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14894 while (true) { 14895 E = E->IgnoreParenImpCasts(); 14896 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14897 E = call->getCallee(); 14898 diagID = diag::err_uncasted_call_of_unknown_any; 14899 } else { 14900 break; 14901 } 14902 } 14903 14904 SourceLocation loc; 14905 NamedDecl *d; 14906 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14907 loc = ref->getLocation(); 14908 d = ref->getDecl(); 14909 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14910 loc = mem->getMemberLoc(); 14911 d = mem->getMemberDecl(); 14912 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14913 diagID = diag::err_uncasted_call_of_unknown_any; 14914 loc = msg->getSelectorStartLoc(); 14915 d = msg->getMethodDecl(); 14916 if (!d) { 14917 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14918 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14919 << orig->getSourceRange(); 14920 return ExprError(); 14921 } 14922 } else { 14923 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14924 << E->getSourceRange(); 14925 return ExprError(); 14926 } 14927 14928 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14929 14930 // Never recoverable. 14931 return ExprError(); 14932 } 14933 14934 /// Check for operands with placeholder types and complain if found. 14935 /// Returns true if there was an error and no recovery was possible. 14936 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14937 if (!getLangOpts().CPlusPlus) { 14938 // C cannot handle TypoExpr nodes on either side of a binop because it 14939 // doesn't handle dependent types properly, so make sure any TypoExprs have 14940 // been dealt with before checking the operands. 14941 ExprResult Result = CorrectDelayedTyposInExpr(E); 14942 if (!Result.isUsable()) return ExprError(); 14943 E = Result.get(); 14944 } 14945 14946 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14947 if (!placeholderType) return E; 14948 14949 switch (placeholderType->getKind()) { 14950 14951 // Overloaded expressions. 14952 case BuiltinType::Overload: { 14953 // Try to resolve a single function template specialization. 14954 // This is obligatory. 14955 ExprResult Result = E; 14956 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 14957 return Result; 14958 14959 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 14960 // leaves Result unchanged on failure. 14961 Result = E; 14962 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 14963 return Result; 14964 14965 // If that failed, try to recover with a call. 14966 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 14967 /*complain*/ true); 14968 return Result; 14969 } 14970 14971 // Bound member functions. 14972 case BuiltinType::BoundMember: { 14973 ExprResult result = E; 14974 const Expr *BME = E->IgnoreParens(); 14975 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14976 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14977 if (isa<CXXPseudoDestructorExpr>(BME)) { 14978 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14979 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14980 if (ME->getMemberNameInfo().getName().getNameKind() == 14981 DeclarationName::CXXDestructorName) 14982 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14983 } 14984 tryToRecoverWithCall(result, PD, 14985 /*complain*/ true); 14986 return result; 14987 } 14988 14989 // ARC unbridged casts. 14990 case BuiltinType::ARCUnbridgedCast: { 14991 Expr *realCast = stripARCUnbridgedCast(E); 14992 diagnoseARCUnbridgedCast(realCast); 14993 return realCast; 14994 } 14995 14996 // Expressions of unknown type. 14997 case BuiltinType::UnknownAny: 14998 return diagnoseUnknownAnyExpr(*this, E); 14999 15000 // Pseudo-objects. 15001 case BuiltinType::PseudoObject: 15002 return checkPseudoObjectRValue(E); 15003 15004 case BuiltinType::BuiltinFn: { 15005 // Accept __noop without parens by implicitly converting it to a call expr. 15006 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15007 if (DRE) { 15008 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15009 if (FD->getBuiltinID() == Builtin::BI__noop) { 15010 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15011 CK_BuiltinFnToFnPtr).get(); 15012 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15013 VK_RValue, SourceLocation()); 15014 } 15015 } 15016 15017 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15018 return ExprError(); 15019 } 15020 15021 // Expressions of unknown type. 15022 case BuiltinType::OMPArraySection: 15023 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15024 return ExprError(); 15025 15026 // Everything else should be impossible. 15027 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15028 case BuiltinType::Id: 15029 #include "clang/Basic/OpenCLImageTypes.def" 15030 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15031 #define PLACEHOLDER_TYPE(Id, SingletonId) 15032 #include "clang/AST/BuiltinTypes.def" 15033 break; 15034 } 15035 15036 llvm_unreachable("invalid placeholder type!"); 15037 } 15038 15039 bool Sema::CheckCaseExpression(Expr *E) { 15040 if (E->isTypeDependent()) 15041 return true; 15042 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15043 return E->getType()->isIntegralOrEnumerationType(); 15044 return false; 15045 } 15046 15047 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15048 ExprResult 15049 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15050 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15051 "Unknown Objective-C Boolean value!"); 15052 QualType BoolT = Context.ObjCBuiltinBoolTy; 15053 if (!Context.getBOOLDecl()) { 15054 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15055 Sema::LookupOrdinaryName); 15056 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15057 NamedDecl *ND = Result.getFoundDecl(); 15058 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15059 Context.setBOOLDecl(TD); 15060 } 15061 } 15062 if (Context.getBOOLDecl()) 15063 BoolT = Context.getBOOLType(); 15064 return new (Context) 15065 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15066 } 15067