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 while (DC != var->getDeclContext()) { 9657 Prev = DC; 9658 DC = DC->getParent(); 9659 } 9660 // Unless we have an init-capture, we've gone one step too far. 9661 if (!var->isInitCapture()) 9662 DC = Prev; 9663 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9664 } 9665 9666 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9667 Ty = Ty.getNonReferenceType(); 9668 if (IsDereference && Ty->isPointerType()) 9669 Ty = Ty->getPointeeType(); 9670 return !Ty.isConstQualified(); 9671 } 9672 9673 /// Emit the "read-only variable not assignable" error and print notes to give 9674 /// more information about why the variable is not assignable, such as pointing 9675 /// to the declaration of a const variable, showing that a method is const, or 9676 /// that the function is returning a const reference. 9677 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9678 SourceLocation Loc) { 9679 // Update err_typecheck_assign_const and note_typecheck_assign_const 9680 // when this enum is changed. 9681 enum { 9682 ConstFunction, 9683 ConstVariable, 9684 ConstMember, 9685 ConstMethod, 9686 ConstUnknown, // Keep as last element 9687 }; 9688 9689 SourceRange ExprRange = E->getSourceRange(); 9690 9691 // Only emit one error on the first const found. All other consts will emit 9692 // a note to the error. 9693 bool DiagnosticEmitted = false; 9694 9695 // Track if the current expression is the result of a derefence, and if the 9696 // next checked expression is the result of a derefence. 9697 bool IsDereference = false; 9698 bool NextIsDereference = false; 9699 9700 // Loop to process MemberExpr chains. 9701 while (true) { 9702 IsDereference = NextIsDereference; 9703 NextIsDereference = false; 9704 9705 E = E->IgnoreParenImpCasts(); 9706 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9707 NextIsDereference = ME->isArrow(); 9708 const ValueDecl *VD = ME->getMemberDecl(); 9709 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9710 // Mutable fields can be modified even if the class is const. 9711 if (Field->isMutable()) { 9712 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9713 break; 9714 } 9715 9716 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9717 if (!DiagnosticEmitted) { 9718 S.Diag(Loc, diag::err_typecheck_assign_const) 9719 << ExprRange << ConstMember << false /*static*/ << Field 9720 << Field->getType(); 9721 DiagnosticEmitted = true; 9722 } 9723 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9724 << ConstMember << false /*static*/ << Field << Field->getType() 9725 << Field->getSourceRange(); 9726 } 9727 E = ME->getBase(); 9728 continue; 9729 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9730 if (VDecl->getType().isConstQualified()) { 9731 if (!DiagnosticEmitted) { 9732 S.Diag(Loc, diag::err_typecheck_assign_const) 9733 << ExprRange << ConstMember << true /*static*/ << VDecl 9734 << VDecl->getType(); 9735 DiagnosticEmitted = true; 9736 } 9737 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9738 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9739 << VDecl->getSourceRange(); 9740 } 9741 // Static fields do not inherit constness from parents. 9742 break; 9743 } 9744 break; 9745 } // End MemberExpr 9746 break; 9747 } 9748 9749 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9750 // Function calls 9751 const FunctionDecl *FD = CE->getDirectCallee(); 9752 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9753 if (!DiagnosticEmitted) { 9754 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9755 << ConstFunction << FD; 9756 DiagnosticEmitted = true; 9757 } 9758 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9759 diag::note_typecheck_assign_const) 9760 << ConstFunction << FD << FD->getReturnType() 9761 << FD->getReturnTypeSourceRange(); 9762 } 9763 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9764 // Point to variable declaration. 9765 if (const ValueDecl *VD = DRE->getDecl()) { 9766 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9767 if (!DiagnosticEmitted) { 9768 S.Diag(Loc, diag::err_typecheck_assign_const) 9769 << ExprRange << ConstVariable << VD << VD->getType(); 9770 DiagnosticEmitted = true; 9771 } 9772 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9773 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9774 } 9775 } 9776 } else if (isa<CXXThisExpr>(E)) { 9777 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9778 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9779 if (MD->isConst()) { 9780 if (!DiagnosticEmitted) { 9781 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9782 << ConstMethod << MD; 9783 DiagnosticEmitted = true; 9784 } 9785 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9786 << ConstMethod << MD << MD->getSourceRange(); 9787 } 9788 } 9789 } 9790 } 9791 9792 if (DiagnosticEmitted) 9793 return; 9794 9795 // Can't determine a more specific message, so display the generic error. 9796 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9797 } 9798 9799 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9800 /// emit an error and return true. If so, return false. 9801 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9802 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9803 9804 S.CheckShadowingDeclModification(E, Loc); 9805 9806 SourceLocation OrigLoc = Loc; 9807 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9808 &Loc); 9809 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9810 IsLV = Expr::MLV_InvalidMessageExpression; 9811 if (IsLV == Expr::MLV_Valid) 9812 return false; 9813 9814 unsigned DiagID = 0; 9815 bool NeedType = false; 9816 switch (IsLV) { // C99 6.5.16p2 9817 case Expr::MLV_ConstQualified: 9818 // Use a specialized diagnostic when we're assigning to an object 9819 // from an enclosing function or block. 9820 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9821 if (NCCK == NCCK_Block) 9822 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9823 else 9824 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9825 break; 9826 } 9827 9828 // In ARC, use some specialized diagnostics for occasions where we 9829 // infer 'const'. These are always pseudo-strong variables. 9830 if (S.getLangOpts().ObjCAutoRefCount) { 9831 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9832 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9833 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9834 9835 // Use the normal diagnostic if it's pseudo-__strong but the 9836 // user actually wrote 'const'. 9837 if (var->isARCPseudoStrong() && 9838 (!var->getTypeSourceInfo() || 9839 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9840 // There are two pseudo-strong cases: 9841 // - self 9842 ObjCMethodDecl *method = S.getCurMethodDecl(); 9843 if (method && var == method->getSelfDecl()) 9844 DiagID = method->isClassMethod() 9845 ? diag::err_typecheck_arc_assign_self_class_method 9846 : diag::err_typecheck_arc_assign_self; 9847 9848 // - fast enumeration variables 9849 else 9850 DiagID = diag::err_typecheck_arr_assign_enumeration; 9851 9852 SourceRange Assign; 9853 if (Loc != OrigLoc) 9854 Assign = SourceRange(OrigLoc, OrigLoc); 9855 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9856 // We need to preserve the AST regardless, so migration tool 9857 // can do its job. 9858 return false; 9859 } 9860 } 9861 } 9862 9863 // If none of the special cases above are triggered, then this is a 9864 // simple const assignment. 9865 if (DiagID == 0) { 9866 DiagnoseConstAssignment(S, E, Loc); 9867 return true; 9868 } 9869 9870 break; 9871 case Expr::MLV_ConstAddrSpace: 9872 DiagnoseConstAssignment(S, E, Loc); 9873 return true; 9874 case Expr::MLV_ArrayType: 9875 case Expr::MLV_ArrayTemporary: 9876 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9877 NeedType = true; 9878 break; 9879 case Expr::MLV_NotObjectType: 9880 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9881 NeedType = true; 9882 break; 9883 case Expr::MLV_LValueCast: 9884 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9885 break; 9886 case Expr::MLV_Valid: 9887 llvm_unreachable("did not take early return for MLV_Valid"); 9888 case Expr::MLV_InvalidExpression: 9889 case Expr::MLV_MemberFunction: 9890 case Expr::MLV_ClassTemporary: 9891 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9892 break; 9893 case Expr::MLV_IncompleteType: 9894 case Expr::MLV_IncompleteVoidType: 9895 return S.RequireCompleteType(Loc, E->getType(), 9896 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9897 case Expr::MLV_DuplicateVectorComponents: 9898 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9899 break; 9900 case Expr::MLV_NoSetterProperty: 9901 llvm_unreachable("readonly properties should be processed differently"); 9902 case Expr::MLV_InvalidMessageExpression: 9903 DiagID = diag::error_readonly_message_assignment; 9904 break; 9905 case Expr::MLV_SubObjCPropertySetting: 9906 DiagID = diag::error_no_subobject_property_setting; 9907 break; 9908 } 9909 9910 SourceRange Assign; 9911 if (Loc != OrigLoc) 9912 Assign = SourceRange(OrigLoc, OrigLoc); 9913 if (NeedType) 9914 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9915 else 9916 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9917 return true; 9918 } 9919 9920 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9921 SourceLocation Loc, 9922 Sema &Sema) { 9923 // C / C++ fields 9924 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9925 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9926 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9927 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9928 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9929 } 9930 9931 // Objective-C instance variables 9932 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9933 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9934 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9935 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9936 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9937 if (RL && RR && RL->getDecl() == RR->getDecl()) 9938 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9939 } 9940 } 9941 9942 // C99 6.5.16.1 9943 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9944 SourceLocation Loc, 9945 QualType CompoundType) { 9946 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9947 9948 // Verify that LHS is a modifiable lvalue, and emit error if not. 9949 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9950 return QualType(); 9951 9952 QualType LHSType = LHSExpr->getType(); 9953 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9954 CompoundType; 9955 AssignConvertType ConvTy; 9956 if (CompoundType.isNull()) { 9957 Expr *RHSCheck = RHS.get(); 9958 9959 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9960 9961 QualType LHSTy(LHSType); 9962 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9963 if (RHS.isInvalid()) 9964 return QualType(); 9965 // Special case of NSObject attributes on c-style pointer types. 9966 if (ConvTy == IncompatiblePointer && 9967 ((Context.isObjCNSObjectType(LHSType) && 9968 RHSType->isObjCObjectPointerType()) || 9969 (Context.isObjCNSObjectType(RHSType) && 9970 LHSType->isObjCObjectPointerType()))) 9971 ConvTy = Compatible; 9972 9973 if (ConvTy == Compatible && 9974 LHSType->isObjCObjectType()) 9975 Diag(Loc, diag::err_objc_object_assignment) 9976 << LHSType; 9977 9978 // If the RHS is a unary plus or minus, check to see if they = and + are 9979 // right next to each other. If so, the user may have typo'd "x =+ 4" 9980 // instead of "x += 4". 9981 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9982 RHSCheck = ICE->getSubExpr(); 9983 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9984 if ((UO->getOpcode() == UO_Plus || 9985 UO->getOpcode() == UO_Minus) && 9986 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9987 // Only if the two operators are exactly adjacent. 9988 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9989 // And there is a space or other character before the subexpr of the 9990 // unary +/-. We don't want to warn on "x=-1". 9991 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9992 UO->getSubExpr()->getLocStart().isFileID()) { 9993 Diag(Loc, diag::warn_not_compound_assign) 9994 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9995 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9996 } 9997 } 9998 9999 if (ConvTy == Compatible) { 10000 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10001 // Warn about retain cycles where a block captures the LHS, but 10002 // not if the LHS is a simple variable into which the block is 10003 // being stored...unless that variable can be captured by reference! 10004 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10005 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10006 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10007 checkRetainCycles(LHSExpr, RHS.get()); 10008 10009 // It is safe to assign a weak reference into a strong variable. 10010 // Although this code can still have problems: 10011 // id x = self.weakProp; 10012 // id y = self.weakProp; 10013 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10014 // paths through the function. This should be revisited if 10015 // -Wrepeated-use-of-weak is made flow-sensitive. 10016 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10017 RHS.get()->getLocStart())) 10018 getCurFunction()->markSafeWeakUse(RHS.get()); 10019 10020 } else if (getLangOpts().ObjCAutoRefCount) { 10021 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10022 } 10023 } 10024 } else { 10025 // Compound assignment "x += y" 10026 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10027 } 10028 10029 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10030 RHS.get(), AA_Assigning)) 10031 return QualType(); 10032 10033 CheckForNullPointerDereference(*this, LHSExpr); 10034 10035 // C99 6.5.16p3: The type of an assignment expression is the type of the 10036 // left operand unless the left operand has qualified type, in which case 10037 // it is the unqualified version of the type of the left operand. 10038 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10039 // is converted to the type of the assignment expression (above). 10040 // C++ 5.17p1: the type of the assignment expression is that of its left 10041 // operand. 10042 return (getLangOpts().CPlusPlus 10043 ? LHSType : LHSType.getUnqualifiedType()); 10044 } 10045 10046 // Only ignore explicit casts to void. 10047 static bool IgnoreCommaOperand(const Expr *E) { 10048 E = E->IgnoreParens(); 10049 10050 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10051 if (CE->getCastKind() == CK_ToVoid) { 10052 return true; 10053 } 10054 } 10055 10056 return false; 10057 } 10058 10059 // Look for instances where it is likely the comma operator is confused with 10060 // another operator. There is a whitelist of acceptable expressions for the 10061 // left hand side of the comma operator, otherwise emit a warning. 10062 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10063 // No warnings in macros 10064 if (Loc.isMacroID()) 10065 return; 10066 10067 // Don't warn in template instantiations. 10068 if (!ActiveTemplateInstantiations.empty()) 10069 return; 10070 10071 // Scope isn't fine-grained enough to whitelist the specific cases, so 10072 // instead, skip more than needed, then call back into here with the 10073 // CommaVisitor in SemaStmt.cpp. 10074 // The whitelisted locations are the initialization and increment portions 10075 // of a for loop. The additional checks are on the condition of 10076 // if statements, do/while loops, and for loops. 10077 const unsigned ForIncrementFlags = 10078 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10079 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10080 const unsigned ScopeFlags = getCurScope()->getFlags(); 10081 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10082 (ScopeFlags & ForInitFlags) == ForInitFlags) 10083 return; 10084 10085 // If there are multiple comma operators used together, get the RHS of the 10086 // of the comma operator as the LHS. 10087 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10088 if (BO->getOpcode() != BO_Comma) 10089 break; 10090 LHS = BO->getRHS(); 10091 } 10092 10093 // Only allow some expressions on LHS to not warn. 10094 if (IgnoreCommaOperand(LHS)) 10095 return; 10096 10097 Diag(Loc, diag::warn_comma_operator); 10098 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10099 << LHS->getSourceRange() 10100 << FixItHint::CreateInsertion(LHS->getLocStart(), 10101 LangOpts.CPlusPlus ? "static_cast<void>(" 10102 : "(void)(") 10103 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10104 ")"); 10105 } 10106 10107 // C99 6.5.17 10108 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10109 SourceLocation Loc) { 10110 LHS = S.CheckPlaceholderExpr(LHS.get()); 10111 RHS = S.CheckPlaceholderExpr(RHS.get()); 10112 if (LHS.isInvalid() || RHS.isInvalid()) 10113 return QualType(); 10114 10115 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10116 // operands, but not unary promotions. 10117 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10118 10119 // So we treat the LHS as a ignored value, and in C++ we allow the 10120 // containing site to determine what should be done with the RHS. 10121 LHS = S.IgnoredValueConversions(LHS.get()); 10122 if (LHS.isInvalid()) 10123 return QualType(); 10124 10125 S.DiagnoseUnusedExprResult(LHS.get()); 10126 10127 if (!S.getLangOpts().CPlusPlus) { 10128 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10129 if (RHS.isInvalid()) 10130 return QualType(); 10131 if (!RHS.get()->getType()->isVoidType()) 10132 S.RequireCompleteType(Loc, RHS.get()->getType(), 10133 diag::err_incomplete_type); 10134 } 10135 10136 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10137 S.DiagnoseCommaOperator(LHS.get(), Loc); 10138 10139 return RHS.get()->getType(); 10140 } 10141 10142 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10143 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10144 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10145 ExprValueKind &VK, 10146 ExprObjectKind &OK, 10147 SourceLocation OpLoc, 10148 bool IsInc, bool IsPrefix) { 10149 if (Op->isTypeDependent()) 10150 return S.Context.DependentTy; 10151 10152 QualType ResType = Op->getType(); 10153 // Atomic types can be used for increment / decrement where the non-atomic 10154 // versions can, so ignore the _Atomic() specifier for the purpose of 10155 // checking. 10156 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10157 ResType = ResAtomicType->getValueType(); 10158 10159 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10160 10161 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10162 // Decrement of bool is not allowed. 10163 if (!IsInc) { 10164 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10165 return QualType(); 10166 } 10167 // Increment of bool sets it to true, but is deprecated. 10168 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10169 : diag::warn_increment_bool) 10170 << Op->getSourceRange(); 10171 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10172 // Error on enum increments and decrements in C++ mode 10173 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10174 return QualType(); 10175 } else if (ResType->isRealType()) { 10176 // OK! 10177 } else if (ResType->isPointerType()) { 10178 // C99 6.5.2.4p2, 6.5.6p2 10179 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10180 return QualType(); 10181 } else if (ResType->isObjCObjectPointerType()) { 10182 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10183 // Otherwise, we just need a complete type. 10184 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10185 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10186 return QualType(); 10187 } else if (ResType->isAnyComplexType()) { 10188 // C99 does not support ++/-- on complex types, we allow as an extension. 10189 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10190 << ResType << Op->getSourceRange(); 10191 } else if (ResType->isPlaceholderType()) { 10192 ExprResult PR = S.CheckPlaceholderExpr(Op); 10193 if (PR.isInvalid()) return QualType(); 10194 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10195 IsInc, IsPrefix); 10196 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10197 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10198 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10199 (ResType->getAs<VectorType>()->getVectorKind() != 10200 VectorType::AltiVecBool)) { 10201 // The z vector extensions allow ++ and -- for non-bool vectors. 10202 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10203 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10204 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10205 } else { 10206 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10207 << ResType << int(IsInc) << Op->getSourceRange(); 10208 return QualType(); 10209 } 10210 // At this point, we know we have a real, complex or pointer type. 10211 // Now make sure the operand is a modifiable lvalue. 10212 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10213 return QualType(); 10214 // In C++, a prefix increment is the same type as the operand. Otherwise 10215 // (in C or with postfix), the increment is the unqualified type of the 10216 // operand. 10217 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10218 VK = VK_LValue; 10219 OK = Op->getObjectKind(); 10220 return ResType; 10221 } else { 10222 VK = VK_RValue; 10223 return ResType.getUnqualifiedType(); 10224 } 10225 } 10226 10227 10228 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10229 /// This routine allows us to typecheck complex/recursive expressions 10230 /// where the declaration is needed for type checking. We only need to 10231 /// handle cases when the expression references a function designator 10232 /// or is an lvalue. Here are some examples: 10233 /// - &(x) => x 10234 /// - &*****f => f for f a function designator. 10235 /// - &s.xx => s 10236 /// - &s.zz[1].yy -> s, if zz is an array 10237 /// - *(x + 1) -> x, if x is an array 10238 /// - &"123"[2] -> 0 10239 /// - & __real__ x -> x 10240 static ValueDecl *getPrimaryDecl(Expr *E) { 10241 switch (E->getStmtClass()) { 10242 case Stmt::DeclRefExprClass: 10243 return cast<DeclRefExpr>(E)->getDecl(); 10244 case Stmt::MemberExprClass: 10245 // If this is an arrow operator, the address is an offset from 10246 // the base's value, so the object the base refers to is 10247 // irrelevant. 10248 if (cast<MemberExpr>(E)->isArrow()) 10249 return nullptr; 10250 // Otherwise, the expression refers to a part of the base 10251 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10252 case Stmt::ArraySubscriptExprClass: { 10253 // FIXME: This code shouldn't be necessary! We should catch the implicit 10254 // promotion of register arrays earlier. 10255 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10256 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10257 if (ICE->getSubExpr()->getType()->isArrayType()) 10258 return getPrimaryDecl(ICE->getSubExpr()); 10259 } 10260 return nullptr; 10261 } 10262 case Stmt::UnaryOperatorClass: { 10263 UnaryOperator *UO = cast<UnaryOperator>(E); 10264 10265 switch(UO->getOpcode()) { 10266 case UO_Real: 10267 case UO_Imag: 10268 case UO_Extension: 10269 return getPrimaryDecl(UO->getSubExpr()); 10270 default: 10271 return nullptr; 10272 } 10273 } 10274 case Stmt::ParenExprClass: 10275 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10276 case Stmt::ImplicitCastExprClass: 10277 // If the result of an implicit cast is an l-value, we care about 10278 // the sub-expression; otherwise, the result here doesn't matter. 10279 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10280 default: 10281 return nullptr; 10282 } 10283 } 10284 10285 namespace { 10286 enum { 10287 AO_Bit_Field = 0, 10288 AO_Vector_Element = 1, 10289 AO_Property_Expansion = 2, 10290 AO_Register_Variable = 3, 10291 AO_No_Error = 4 10292 }; 10293 } 10294 /// \brief Diagnose invalid operand for address of operations. 10295 /// 10296 /// \param Type The type of operand which cannot have its address taken. 10297 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10298 Expr *E, unsigned Type) { 10299 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10300 } 10301 10302 /// CheckAddressOfOperand - The operand of & must be either a function 10303 /// designator or an lvalue designating an object. If it is an lvalue, the 10304 /// object cannot be declared with storage class register or be a bit field. 10305 /// Note: The usual conversions are *not* applied to the operand of the & 10306 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10307 /// In C++, the operand might be an overloaded function name, in which case 10308 /// we allow the '&' but retain the overloaded-function type. 10309 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10310 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10311 if (PTy->getKind() == BuiltinType::Overload) { 10312 Expr *E = OrigOp.get()->IgnoreParens(); 10313 if (!isa<OverloadExpr>(E)) { 10314 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10315 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10316 << OrigOp.get()->getSourceRange(); 10317 return QualType(); 10318 } 10319 10320 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10321 if (isa<UnresolvedMemberExpr>(Ovl)) 10322 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10323 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10324 << OrigOp.get()->getSourceRange(); 10325 return QualType(); 10326 } 10327 10328 return Context.OverloadTy; 10329 } 10330 10331 if (PTy->getKind() == BuiltinType::UnknownAny) 10332 return Context.UnknownAnyTy; 10333 10334 if (PTy->getKind() == BuiltinType::BoundMember) { 10335 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10336 << OrigOp.get()->getSourceRange(); 10337 return QualType(); 10338 } 10339 10340 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10341 if (OrigOp.isInvalid()) return QualType(); 10342 } 10343 10344 if (OrigOp.get()->isTypeDependent()) 10345 return Context.DependentTy; 10346 10347 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10348 10349 // Make sure to ignore parentheses in subsequent checks 10350 Expr *op = OrigOp.get()->IgnoreParens(); 10351 10352 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10353 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10354 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10355 return QualType(); 10356 } 10357 10358 if (getLangOpts().C99) { 10359 // Implement C99-only parts of addressof rules. 10360 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10361 if (uOp->getOpcode() == UO_Deref) 10362 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10363 // (assuming the deref expression is valid). 10364 return uOp->getSubExpr()->getType(); 10365 } 10366 // Technically, there should be a check for array subscript 10367 // expressions here, but the result of one is always an lvalue anyway. 10368 } 10369 ValueDecl *dcl = getPrimaryDecl(op); 10370 10371 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10372 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10373 op->getLocStart())) 10374 return QualType(); 10375 10376 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10377 unsigned AddressOfError = AO_No_Error; 10378 10379 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10380 bool sfinae = (bool)isSFINAEContext(); 10381 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10382 : diag::ext_typecheck_addrof_temporary) 10383 << op->getType() << op->getSourceRange(); 10384 if (sfinae) 10385 return QualType(); 10386 // Materialize the temporary as an lvalue so that we can take its address. 10387 OrigOp = op = 10388 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10389 } else if (isa<ObjCSelectorExpr>(op)) { 10390 return Context.getPointerType(op->getType()); 10391 } else if (lval == Expr::LV_MemberFunction) { 10392 // If it's an instance method, make a member pointer. 10393 // The expression must have exactly the form &A::foo. 10394 10395 // If the underlying expression isn't a decl ref, give up. 10396 if (!isa<DeclRefExpr>(op)) { 10397 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10398 << OrigOp.get()->getSourceRange(); 10399 return QualType(); 10400 } 10401 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10402 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10403 10404 // The id-expression was parenthesized. 10405 if (OrigOp.get() != DRE) { 10406 Diag(OpLoc, diag::err_parens_pointer_member_function) 10407 << OrigOp.get()->getSourceRange(); 10408 10409 // The method was named without a qualifier. 10410 } else if (!DRE->getQualifier()) { 10411 if (MD->getParent()->getName().empty()) 10412 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10413 << op->getSourceRange(); 10414 else { 10415 SmallString<32> Str; 10416 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10417 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10418 << op->getSourceRange() 10419 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10420 } 10421 } 10422 10423 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10424 if (isa<CXXDestructorDecl>(MD)) 10425 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10426 10427 QualType MPTy = Context.getMemberPointerType( 10428 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10429 // Under the MS ABI, lock down the inheritance model now. 10430 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10431 (void)isCompleteType(OpLoc, MPTy); 10432 return MPTy; 10433 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10434 // C99 6.5.3.2p1 10435 // The operand must be either an l-value or a function designator 10436 if (!op->getType()->isFunctionType()) { 10437 // Use a special diagnostic for loads from property references. 10438 if (isa<PseudoObjectExpr>(op)) { 10439 AddressOfError = AO_Property_Expansion; 10440 } else { 10441 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10442 << op->getType() << op->getSourceRange(); 10443 return QualType(); 10444 } 10445 } 10446 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10447 // The operand cannot be a bit-field 10448 AddressOfError = AO_Bit_Field; 10449 } else if (op->getObjectKind() == OK_VectorComponent) { 10450 // The operand cannot be an element of a vector 10451 AddressOfError = AO_Vector_Element; 10452 } else if (dcl) { // C99 6.5.3.2p1 10453 // We have an lvalue with a decl. Make sure the decl is not declared 10454 // with the register storage-class specifier. 10455 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10456 // in C++ it is not error to take address of a register 10457 // variable (c++03 7.1.1P3) 10458 if (vd->getStorageClass() == SC_Register && 10459 !getLangOpts().CPlusPlus) { 10460 AddressOfError = AO_Register_Variable; 10461 } 10462 } else if (isa<MSPropertyDecl>(dcl)) { 10463 AddressOfError = AO_Property_Expansion; 10464 } else if (isa<FunctionTemplateDecl>(dcl)) { 10465 return Context.OverloadTy; 10466 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10467 // Okay: we can take the address of a field. 10468 // Could be a pointer to member, though, if there is an explicit 10469 // scope qualifier for the class. 10470 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10471 DeclContext *Ctx = dcl->getDeclContext(); 10472 if (Ctx && Ctx->isRecord()) { 10473 if (dcl->getType()->isReferenceType()) { 10474 Diag(OpLoc, 10475 diag::err_cannot_form_pointer_to_member_of_reference_type) 10476 << dcl->getDeclName() << dcl->getType(); 10477 return QualType(); 10478 } 10479 10480 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10481 Ctx = Ctx->getParent(); 10482 10483 QualType MPTy = Context.getMemberPointerType( 10484 op->getType(), 10485 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10486 // Under the MS ABI, lock down the inheritance model now. 10487 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10488 (void)isCompleteType(OpLoc, MPTy); 10489 return MPTy; 10490 } 10491 } 10492 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10493 llvm_unreachable("Unknown/unexpected decl type"); 10494 } 10495 10496 if (AddressOfError != AO_No_Error) { 10497 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10498 return QualType(); 10499 } 10500 10501 if (lval == Expr::LV_IncompleteVoidType) { 10502 // Taking the address of a void variable is technically illegal, but we 10503 // allow it in cases which are otherwise valid. 10504 // Example: "extern void x; void* y = &x;". 10505 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10506 } 10507 10508 // If the operand has type "type", the result has type "pointer to type". 10509 if (op->getType()->isObjCObjectType()) 10510 return Context.getObjCObjectPointerType(op->getType()); 10511 10512 // OpenCL v2.0 s6.12.5 - The unary operators & cannot be used with a block. 10513 if (getLangOpts().OpenCL && OrigOp.get()->getType()->isBlockPointerType()) { 10514 Diag(OpLoc, diag::err_typecheck_unary_expr) << OrigOp.get()->getType() 10515 << op->getSourceRange(); 10516 return QualType(); 10517 } 10518 10519 return Context.getPointerType(op->getType()); 10520 } 10521 10522 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10523 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10524 if (!DRE) 10525 return; 10526 const Decl *D = DRE->getDecl(); 10527 if (!D) 10528 return; 10529 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10530 if (!Param) 10531 return; 10532 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10533 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10534 return; 10535 if (FunctionScopeInfo *FD = S.getCurFunction()) 10536 if (!FD->ModifiedNonNullParams.count(Param)) 10537 FD->ModifiedNonNullParams.insert(Param); 10538 } 10539 10540 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10541 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10542 SourceLocation OpLoc) { 10543 if (Op->isTypeDependent()) 10544 return S.Context.DependentTy; 10545 10546 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10547 if (ConvResult.isInvalid()) 10548 return QualType(); 10549 Op = ConvResult.get(); 10550 QualType OpTy = Op->getType(); 10551 QualType Result; 10552 10553 if (isa<CXXReinterpretCastExpr>(Op)) { 10554 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10555 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10556 Op->getSourceRange()); 10557 } 10558 10559 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10560 { 10561 Result = PT->getPointeeType(); 10562 // OpenCL v2.0 s6.12.5 - The unary operators * cannot be used with a block. 10563 if (S.getLangOpts().OpenCLVersion >= 200 && Result->isBlockPointerType()) { 10564 S.Diag(OpLoc, diag::err_opencl_dereferencing) << OpTy 10565 << Op->getSourceRange(); 10566 return QualType(); 10567 } 10568 } 10569 else if (const ObjCObjectPointerType *OPT = 10570 OpTy->getAs<ObjCObjectPointerType>()) 10571 Result = OPT->getPointeeType(); 10572 else { 10573 ExprResult PR = S.CheckPlaceholderExpr(Op); 10574 if (PR.isInvalid()) return QualType(); 10575 if (PR.get() != Op) 10576 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10577 } 10578 10579 if (Result.isNull()) { 10580 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10581 << OpTy << Op->getSourceRange(); 10582 return QualType(); 10583 } 10584 10585 // Note that per both C89 and C99, indirection is always legal, even if Result 10586 // is an incomplete type or void. It would be possible to warn about 10587 // dereferencing a void pointer, but it's completely well-defined, and such a 10588 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10589 // for pointers to 'void' but is fine for any other pointer type: 10590 // 10591 // C++ [expr.unary.op]p1: 10592 // [...] the expression to which [the unary * operator] is applied shall 10593 // be a pointer to an object type, or a pointer to a function type 10594 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10595 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10596 << OpTy << Op->getSourceRange(); 10597 10598 // Dereferences are usually l-values... 10599 VK = VK_LValue; 10600 10601 // ...except that certain expressions are never l-values in C. 10602 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10603 VK = VK_RValue; 10604 10605 return Result; 10606 } 10607 10608 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10609 BinaryOperatorKind Opc; 10610 switch (Kind) { 10611 default: llvm_unreachable("Unknown binop!"); 10612 case tok::periodstar: Opc = BO_PtrMemD; break; 10613 case tok::arrowstar: Opc = BO_PtrMemI; break; 10614 case tok::star: Opc = BO_Mul; break; 10615 case tok::slash: Opc = BO_Div; break; 10616 case tok::percent: Opc = BO_Rem; break; 10617 case tok::plus: Opc = BO_Add; break; 10618 case tok::minus: Opc = BO_Sub; break; 10619 case tok::lessless: Opc = BO_Shl; break; 10620 case tok::greatergreater: Opc = BO_Shr; break; 10621 case tok::lessequal: Opc = BO_LE; break; 10622 case tok::less: Opc = BO_LT; break; 10623 case tok::greaterequal: Opc = BO_GE; break; 10624 case tok::greater: Opc = BO_GT; break; 10625 case tok::exclaimequal: Opc = BO_NE; break; 10626 case tok::equalequal: Opc = BO_EQ; break; 10627 case tok::amp: Opc = BO_And; break; 10628 case tok::caret: Opc = BO_Xor; break; 10629 case tok::pipe: Opc = BO_Or; break; 10630 case tok::ampamp: Opc = BO_LAnd; break; 10631 case tok::pipepipe: Opc = BO_LOr; break; 10632 case tok::equal: Opc = BO_Assign; break; 10633 case tok::starequal: Opc = BO_MulAssign; break; 10634 case tok::slashequal: Opc = BO_DivAssign; break; 10635 case tok::percentequal: Opc = BO_RemAssign; break; 10636 case tok::plusequal: Opc = BO_AddAssign; break; 10637 case tok::minusequal: Opc = BO_SubAssign; break; 10638 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10639 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10640 case tok::ampequal: Opc = BO_AndAssign; break; 10641 case tok::caretequal: Opc = BO_XorAssign; break; 10642 case tok::pipeequal: Opc = BO_OrAssign; break; 10643 case tok::comma: Opc = BO_Comma; break; 10644 } 10645 return Opc; 10646 } 10647 10648 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10649 tok::TokenKind Kind) { 10650 UnaryOperatorKind Opc; 10651 switch (Kind) { 10652 default: llvm_unreachable("Unknown unary op!"); 10653 case tok::plusplus: Opc = UO_PreInc; break; 10654 case tok::minusminus: Opc = UO_PreDec; break; 10655 case tok::amp: Opc = UO_AddrOf; break; 10656 case tok::star: Opc = UO_Deref; break; 10657 case tok::plus: Opc = UO_Plus; break; 10658 case tok::minus: Opc = UO_Minus; break; 10659 case tok::tilde: Opc = UO_Not; break; 10660 case tok::exclaim: Opc = UO_LNot; break; 10661 case tok::kw___real: Opc = UO_Real; break; 10662 case tok::kw___imag: Opc = UO_Imag; break; 10663 case tok::kw___extension__: Opc = UO_Extension; break; 10664 } 10665 return Opc; 10666 } 10667 10668 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10669 /// This warning is only emitted for builtin assignment operations. It is also 10670 /// suppressed in the event of macro expansions. 10671 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10672 SourceLocation OpLoc) { 10673 if (!S.ActiveTemplateInstantiations.empty()) 10674 return; 10675 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10676 return; 10677 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10678 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10679 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10680 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10681 if (!LHSDeclRef || !RHSDeclRef || 10682 LHSDeclRef->getLocation().isMacroID() || 10683 RHSDeclRef->getLocation().isMacroID()) 10684 return; 10685 const ValueDecl *LHSDecl = 10686 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10687 const ValueDecl *RHSDecl = 10688 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10689 if (LHSDecl != RHSDecl) 10690 return; 10691 if (LHSDecl->getType().isVolatileQualified()) 10692 return; 10693 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10694 if (RefTy->getPointeeType().isVolatileQualified()) 10695 return; 10696 10697 S.Diag(OpLoc, diag::warn_self_assignment) 10698 << LHSDeclRef->getType() 10699 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10700 } 10701 10702 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10703 /// is usually indicative of introspection within the Objective-C pointer. 10704 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10705 SourceLocation OpLoc) { 10706 if (!S.getLangOpts().ObjC1) 10707 return; 10708 10709 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10710 const Expr *LHS = L.get(); 10711 const Expr *RHS = R.get(); 10712 10713 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10714 ObjCPointerExpr = LHS; 10715 OtherExpr = RHS; 10716 } 10717 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10718 ObjCPointerExpr = RHS; 10719 OtherExpr = LHS; 10720 } 10721 10722 // This warning is deliberately made very specific to reduce false 10723 // positives with logic that uses '&' for hashing. This logic mainly 10724 // looks for code trying to introspect into tagged pointers, which 10725 // code should generally never do. 10726 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10727 unsigned Diag = diag::warn_objc_pointer_masking; 10728 // Determine if we are introspecting the result of performSelectorXXX. 10729 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10730 // Special case messages to -performSelector and friends, which 10731 // can return non-pointer values boxed in a pointer value. 10732 // Some clients may wish to silence warnings in this subcase. 10733 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10734 Selector S = ME->getSelector(); 10735 StringRef SelArg0 = S.getNameForSlot(0); 10736 if (SelArg0.startswith("performSelector")) 10737 Diag = diag::warn_objc_pointer_masking_performSelector; 10738 } 10739 10740 S.Diag(OpLoc, Diag) 10741 << ObjCPointerExpr->getSourceRange(); 10742 } 10743 } 10744 10745 static NamedDecl *getDeclFromExpr(Expr *E) { 10746 if (!E) 10747 return nullptr; 10748 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10749 return DRE->getDecl(); 10750 if (auto *ME = dyn_cast<MemberExpr>(E)) 10751 return ME->getMemberDecl(); 10752 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10753 return IRE->getDecl(); 10754 return nullptr; 10755 } 10756 10757 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10758 /// operator @p Opc at location @c TokLoc. This routine only supports 10759 /// built-in operations; ActOnBinOp handles overloaded operators. 10760 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10761 BinaryOperatorKind Opc, 10762 Expr *LHSExpr, Expr *RHSExpr) { 10763 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10764 // The syntax only allows initializer lists on the RHS of assignment, 10765 // so we don't need to worry about accepting invalid code for 10766 // non-assignment operators. 10767 // C++11 5.17p9: 10768 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10769 // of x = {} is x = T(). 10770 InitializationKind Kind = 10771 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10772 InitializedEntity Entity = 10773 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10774 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10775 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10776 if (Init.isInvalid()) 10777 return Init; 10778 RHSExpr = Init.get(); 10779 } 10780 10781 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10782 QualType ResultTy; // Result type of the binary operator. 10783 // The following two variables are used for compound assignment operators 10784 QualType CompLHSTy; // Type of LHS after promotions for computation 10785 QualType CompResultTy; // Type of computation result 10786 ExprValueKind VK = VK_RValue; 10787 ExprObjectKind OK = OK_Ordinary; 10788 10789 if (!getLangOpts().CPlusPlus) { 10790 // C cannot handle TypoExpr nodes on either side of a binop because it 10791 // doesn't handle dependent types properly, so make sure any TypoExprs have 10792 // been dealt with before checking the operands. 10793 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10794 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10795 if (Opc != BO_Assign) 10796 return ExprResult(E); 10797 // Avoid correcting the RHS to the same Expr as the LHS. 10798 Decl *D = getDeclFromExpr(E); 10799 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10800 }); 10801 if (!LHS.isUsable() || !RHS.isUsable()) 10802 return ExprError(); 10803 } 10804 10805 if (getLangOpts().OpenCL) { 10806 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10807 // the ATOMIC_VAR_INIT macro. 10808 if (LHSExpr->getType()->isAtomicType() || 10809 RHSExpr->getType()->isAtomicType()) { 10810 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10811 if (BO_Assign == Opc) 10812 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10813 else 10814 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10815 return ExprError(); 10816 } 10817 } 10818 10819 switch (Opc) { 10820 case BO_Assign: 10821 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10822 if (getLangOpts().CPlusPlus && 10823 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10824 VK = LHS.get()->getValueKind(); 10825 OK = LHS.get()->getObjectKind(); 10826 } 10827 if (!ResultTy.isNull()) { 10828 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10829 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10830 } 10831 RecordModifiableNonNullParam(*this, LHS.get()); 10832 break; 10833 case BO_PtrMemD: 10834 case BO_PtrMemI: 10835 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10836 Opc == BO_PtrMemI); 10837 break; 10838 case BO_Mul: 10839 case BO_Div: 10840 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10841 Opc == BO_Div); 10842 break; 10843 case BO_Rem: 10844 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10845 break; 10846 case BO_Add: 10847 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10848 break; 10849 case BO_Sub: 10850 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10851 break; 10852 case BO_Shl: 10853 case BO_Shr: 10854 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10855 break; 10856 case BO_LE: 10857 case BO_LT: 10858 case BO_GE: 10859 case BO_GT: 10860 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10861 break; 10862 case BO_EQ: 10863 case BO_NE: 10864 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10865 break; 10866 case BO_And: 10867 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10868 case BO_Xor: 10869 case BO_Or: 10870 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10871 break; 10872 case BO_LAnd: 10873 case BO_LOr: 10874 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10875 break; 10876 case BO_MulAssign: 10877 case BO_DivAssign: 10878 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10879 Opc == BO_DivAssign); 10880 CompLHSTy = CompResultTy; 10881 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10882 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10883 break; 10884 case BO_RemAssign: 10885 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10886 CompLHSTy = CompResultTy; 10887 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10888 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10889 break; 10890 case BO_AddAssign: 10891 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10892 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10893 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10894 break; 10895 case BO_SubAssign: 10896 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10897 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10898 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10899 break; 10900 case BO_ShlAssign: 10901 case BO_ShrAssign: 10902 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10903 CompLHSTy = CompResultTy; 10904 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10905 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10906 break; 10907 case BO_AndAssign: 10908 case BO_OrAssign: // fallthrough 10909 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10910 case BO_XorAssign: 10911 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, 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_Comma: 10917 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10918 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10919 VK = RHS.get()->getValueKind(); 10920 OK = RHS.get()->getObjectKind(); 10921 } 10922 break; 10923 } 10924 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10925 return ExprError(); 10926 10927 // Check for array bounds violations for both sides of the BinaryOperator 10928 CheckArrayAccess(LHS.get()); 10929 CheckArrayAccess(RHS.get()); 10930 10931 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10932 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10933 &Context.Idents.get("object_setClass"), 10934 SourceLocation(), LookupOrdinaryName); 10935 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10936 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 10937 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10938 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10939 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10940 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10941 } 10942 else 10943 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10944 } 10945 else if (const ObjCIvarRefExpr *OIRE = 10946 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10947 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10948 10949 if (CompResultTy.isNull()) 10950 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10951 OK, OpLoc, FPFeatures.fp_contract); 10952 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10953 OK_ObjCProperty) { 10954 VK = VK_LValue; 10955 OK = LHS.get()->getObjectKind(); 10956 } 10957 return new (Context) CompoundAssignOperator( 10958 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10959 OpLoc, FPFeatures.fp_contract); 10960 } 10961 10962 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10963 /// operators are mixed in a way that suggests that the programmer forgot that 10964 /// comparison operators have higher precedence. The most typical example of 10965 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10966 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10967 SourceLocation OpLoc, Expr *LHSExpr, 10968 Expr *RHSExpr) { 10969 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10970 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10971 10972 // Check that one of the sides is a comparison operator and the other isn't. 10973 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10974 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10975 if (isLeftComp == isRightComp) 10976 return; 10977 10978 // Bitwise operations are sometimes used as eager logical ops. 10979 // Don't diagnose this. 10980 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10981 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10982 if (isLeftBitwise || isRightBitwise) 10983 return; 10984 10985 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10986 OpLoc) 10987 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10988 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10989 SourceRange ParensRange = isLeftComp ? 10990 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10991 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10992 10993 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10994 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10995 SuggestParentheses(Self, OpLoc, 10996 Self.PDiag(diag::note_precedence_silence) << OpStr, 10997 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10998 SuggestParentheses(Self, OpLoc, 10999 Self.PDiag(diag::note_precedence_bitwise_first) 11000 << BinaryOperator::getOpcodeStr(Opc), 11001 ParensRange); 11002 } 11003 11004 /// \brief It accepts a '&&' expr that is inside a '||' one. 11005 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11006 /// in parentheses. 11007 static void 11008 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11009 BinaryOperator *Bop) { 11010 assert(Bop->getOpcode() == BO_LAnd); 11011 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11012 << Bop->getSourceRange() << OpLoc; 11013 SuggestParentheses(Self, Bop->getOperatorLoc(), 11014 Self.PDiag(diag::note_precedence_silence) 11015 << Bop->getOpcodeStr(), 11016 Bop->getSourceRange()); 11017 } 11018 11019 /// \brief Returns true if the given expression can be evaluated as a constant 11020 /// 'true'. 11021 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11022 bool Res; 11023 return !E->isValueDependent() && 11024 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11025 } 11026 11027 /// \brief Returns true if the given expression can be evaluated as a constant 11028 /// 'false'. 11029 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11030 bool Res; 11031 return !E->isValueDependent() && 11032 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11033 } 11034 11035 /// \brief Look for '&&' in the left hand of a '||' expr. 11036 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11037 Expr *LHSExpr, Expr *RHSExpr) { 11038 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11039 if (Bop->getOpcode() == BO_LAnd) { 11040 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11041 if (EvaluatesAsFalse(S, RHSExpr)) 11042 return; 11043 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11044 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11045 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11046 } else if (Bop->getOpcode() == BO_LOr) { 11047 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11048 // If it's "a || b && 1 || c" we didn't warn earlier for 11049 // "a || b && 1", but warn now. 11050 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11051 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11052 } 11053 } 11054 } 11055 } 11056 11057 /// \brief Look for '&&' in the right hand of a '||' expr. 11058 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11059 Expr *LHSExpr, Expr *RHSExpr) { 11060 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11061 if (Bop->getOpcode() == BO_LAnd) { 11062 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11063 if (EvaluatesAsFalse(S, LHSExpr)) 11064 return; 11065 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11066 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11067 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11068 } 11069 } 11070 } 11071 11072 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11073 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11074 /// the '&' expression in parentheses. 11075 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11076 SourceLocation OpLoc, Expr *SubExpr) { 11077 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11078 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11079 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11080 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11081 << Bop->getSourceRange() << OpLoc; 11082 SuggestParentheses(S, Bop->getOperatorLoc(), 11083 S.PDiag(diag::note_precedence_silence) 11084 << Bop->getOpcodeStr(), 11085 Bop->getSourceRange()); 11086 } 11087 } 11088 } 11089 11090 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11091 Expr *SubExpr, StringRef Shift) { 11092 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11093 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11094 StringRef Op = Bop->getOpcodeStr(); 11095 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11096 << Bop->getSourceRange() << OpLoc << Shift << Op; 11097 SuggestParentheses(S, Bop->getOperatorLoc(), 11098 S.PDiag(diag::note_precedence_silence) << Op, 11099 Bop->getSourceRange()); 11100 } 11101 } 11102 } 11103 11104 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11105 Expr *LHSExpr, Expr *RHSExpr) { 11106 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11107 if (!OCE) 11108 return; 11109 11110 FunctionDecl *FD = OCE->getDirectCallee(); 11111 if (!FD || !FD->isOverloadedOperator()) 11112 return; 11113 11114 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11115 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11116 return; 11117 11118 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11119 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11120 << (Kind == OO_LessLess); 11121 SuggestParentheses(S, OCE->getOperatorLoc(), 11122 S.PDiag(diag::note_precedence_silence) 11123 << (Kind == OO_LessLess ? "<<" : ">>"), 11124 OCE->getSourceRange()); 11125 SuggestParentheses(S, OpLoc, 11126 S.PDiag(diag::note_evaluate_comparison_first), 11127 SourceRange(OCE->getArg(1)->getLocStart(), 11128 RHSExpr->getLocEnd())); 11129 } 11130 11131 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11132 /// precedence. 11133 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11134 SourceLocation OpLoc, Expr *LHSExpr, 11135 Expr *RHSExpr){ 11136 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11137 if (BinaryOperator::isBitwiseOp(Opc)) 11138 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11139 11140 // Diagnose "arg1 & arg2 | arg3" 11141 if ((Opc == BO_Or || Opc == BO_Xor) && 11142 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11143 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11144 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11145 } 11146 11147 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11148 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11149 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11150 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11151 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11152 } 11153 11154 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11155 || Opc == BO_Shr) { 11156 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11157 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11158 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11159 } 11160 11161 // Warn on overloaded shift operators and comparisons, such as: 11162 // cout << 5 == 4; 11163 if (BinaryOperator::isComparisonOp(Opc)) 11164 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11165 } 11166 11167 // Binary Operators. 'Tok' is the token for the operator. 11168 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11169 tok::TokenKind Kind, 11170 Expr *LHSExpr, Expr *RHSExpr) { 11171 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11172 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11173 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11174 11175 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11176 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11177 11178 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11179 } 11180 11181 /// Build an overloaded binary operator expression in the given scope. 11182 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11183 BinaryOperatorKind Opc, 11184 Expr *LHS, Expr *RHS) { 11185 // Find all of the overloaded operators visible from this 11186 // point. We perform both an operator-name lookup from the local 11187 // scope and an argument-dependent lookup based on the types of 11188 // the arguments. 11189 UnresolvedSet<16> Functions; 11190 OverloadedOperatorKind OverOp 11191 = BinaryOperator::getOverloadedOperator(Opc); 11192 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11193 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11194 RHS->getType(), Functions); 11195 11196 // Build the (potentially-overloaded, potentially-dependent) 11197 // binary operation. 11198 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11199 } 11200 11201 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11202 BinaryOperatorKind Opc, 11203 Expr *LHSExpr, Expr *RHSExpr) { 11204 // We want to end up calling one of checkPseudoObjectAssignment 11205 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11206 // both expressions are overloadable or either is type-dependent), 11207 // or CreateBuiltinBinOp (in any other case). We also want to get 11208 // any placeholder types out of the way. 11209 11210 // Handle pseudo-objects in the LHS. 11211 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11212 // Assignments with a pseudo-object l-value need special analysis. 11213 if (pty->getKind() == BuiltinType::PseudoObject && 11214 BinaryOperator::isAssignmentOp(Opc)) 11215 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11216 11217 // Don't resolve overloads if the other type is overloadable. 11218 if (pty->getKind() == BuiltinType::Overload) { 11219 // We can't actually test that if we still have a placeholder, 11220 // though. Fortunately, none of the exceptions we see in that 11221 // code below are valid when the LHS is an overload set. Note 11222 // that an overload set can be dependently-typed, but it never 11223 // instantiates to having an overloadable type. 11224 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11225 if (resolvedRHS.isInvalid()) return ExprError(); 11226 RHSExpr = resolvedRHS.get(); 11227 11228 if (RHSExpr->isTypeDependent() || 11229 RHSExpr->getType()->isOverloadableType()) 11230 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11231 } 11232 11233 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11234 if (LHS.isInvalid()) return ExprError(); 11235 LHSExpr = LHS.get(); 11236 } 11237 11238 // Handle pseudo-objects in the RHS. 11239 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11240 // An overload in the RHS can potentially be resolved by the type 11241 // being assigned to. 11242 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11243 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11244 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11245 11246 if (LHSExpr->getType()->isOverloadableType()) 11247 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11248 11249 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11250 } 11251 11252 // Don't resolve overloads if the other type is overloadable. 11253 if (pty->getKind() == BuiltinType::Overload && 11254 LHSExpr->getType()->isOverloadableType()) 11255 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11256 11257 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11258 if (!resolvedRHS.isUsable()) return ExprError(); 11259 RHSExpr = resolvedRHS.get(); 11260 } 11261 11262 if (getLangOpts().CPlusPlus) { 11263 // If either expression is type-dependent, always build an 11264 // overloaded op. 11265 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11266 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11267 11268 // Otherwise, build an overloaded op if either expression has an 11269 // overloadable type. 11270 if (LHSExpr->getType()->isOverloadableType() || 11271 RHSExpr->getType()->isOverloadableType()) 11272 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11273 } 11274 11275 // Build a built-in binary operation. 11276 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11277 } 11278 11279 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11280 UnaryOperatorKind Opc, 11281 Expr *InputExpr) { 11282 ExprResult Input = InputExpr; 11283 ExprValueKind VK = VK_RValue; 11284 ExprObjectKind OK = OK_Ordinary; 11285 QualType resultType; 11286 if (getLangOpts().OpenCL) { 11287 // The only legal unary operation for atomics is '&'. 11288 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 11289 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11290 << InputExpr->getType() 11291 << Input.get()->getSourceRange()); 11292 } 11293 } 11294 switch (Opc) { 11295 case UO_PreInc: 11296 case UO_PreDec: 11297 case UO_PostInc: 11298 case UO_PostDec: 11299 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11300 OpLoc, 11301 Opc == UO_PreInc || 11302 Opc == UO_PostInc, 11303 Opc == UO_PreInc || 11304 Opc == UO_PreDec); 11305 break; 11306 case UO_AddrOf: 11307 resultType = CheckAddressOfOperand(Input, OpLoc); 11308 RecordModifiableNonNullParam(*this, InputExpr); 11309 break; 11310 case UO_Deref: { 11311 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11312 if (Input.isInvalid()) return ExprError(); 11313 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11314 break; 11315 } 11316 case UO_Plus: 11317 case UO_Minus: 11318 Input = UsualUnaryConversions(Input.get()); 11319 if (Input.isInvalid()) return ExprError(); 11320 resultType = Input.get()->getType(); 11321 if (resultType->isDependentType()) 11322 break; 11323 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11324 break; 11325 else if (resultType->isVectorType() && 11326 // The z vector extensions don't allow + or - with bool vectors. 11327 (!Context.getLangOpts().ZVector || 11328 resultType->getAs<VectorType>()->getVectorKind() != 11329 VectorType::AltiVecBool)) 11330 break; 11331 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11332 Opc == UO_Plus && 11333 resultType->isPointerType()) 11334 break; 11335 11336 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11337 << resultType << Input.get()->getSourceRange()); 11338 11339 case UO_Not: // bitwise complement 11340 Input = UsualUnaryConversions(Input.get()); 11341 if (Input.isInvalid()) 11342 return ExprError(); 11343 resultType = Input.get()->getType(); 11344 if (resultType->isDependentType()) 11345 break; 11346 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11347 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11348 // C99 does not support '~' for complex conjugation. 11349 Diag(OpLoc, diag::ext_integer_complement_complex) 11350 << resultType << Input.get()->getSourceRange(); 11351 else if (resultType->hasIntegerRepresentation()) 11352 break; 11353 else if (resultType->isExtVectorType()) { 11354 if (Context.getLangOpts().OpenCL) { 11355 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11356 // on vector float types. 11357 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11358 if (!T->isIntegerType()) 11359 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11360 << resultType << Input.get()->getSourceRange()); 11361 } 11362 break; 11363 } else { 11364 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11365 << resultType << Input.get()->getSourceRange()); 11366 } 11367 break; 11368 11369 case UO_LNot: // logical negation 11370 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11371 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11372 if (Input.isInvalid()) return ExprError(); 11373 resultType = Input.get()->getType(); 11374 11375 // Though we still have to promote half FP to float... 11376 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11377 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11378 resultType = Context.FloatTy; 11379 } 11380 11381 if (resultType->isDependentType()) 11382 break; 11383 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11384 // C99 6.5.3.3p1: ok, fallthrough; 11385 if (Context.getLangOpts().CPlusPlus) { 11386 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11387 // operand contextually converted to bool. 11388 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11389 ScalarTypeToBooleanCastKind(resultType)); 11390 } else if (Context.getLangOpts().OpenCL && 11391 Context.getLangOpts().OpenCLVersion < 120) { 11392 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11393 // operate on scalar float types. 11394 if (!resultType->isIntegerType()) 11395 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11396 << resultType << Input.get()->getSourceRange()); 11397 } 11398 } else if (resultType->isExtVectorType()) { 11399 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 vector float types. 11403 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11404 if (!T->isIntegerType()) 11405 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11406 << resultType << Input.get()->getSourceRange()); 11407 } 11408 // Vector logical not returns the signed variant of the operand type. 11409 resultType = GetSignedVectorType(resultType); 11410 break; 11411 } else { 11412 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11413 << resultType << Input.get()->getSourceRange()); 11414 } 11415 11416 // LNot always has type int. C99 6.5.3.3p5. 11417 // In C++, it's bool. C++ 5.3.1p8 11418 resultType = Context.getLogicalOperationType(); 11419 break; 11420 case UO_Real: 11421 case UO_Imag: 11422 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11423 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11424 // complex l-values to ordinary l-values and all other values to r-values. 11425 if (Input.isInvalid()) return ExprError(); 11426 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11427 if (Input.get()->getValueKind() != VK_RValue && 11428 Input.get()->getObjectKind() == OK_Ordinary) 11429 VK = Input.get()->getValueKind(); 11430 } else if (!getLangOpts().CPlusPlus) { 11431 // In C, a volatile scalar is read by __imag. In C++, it is not. 11432 Input = DefaultLvalueConversion(Input.get()); 11433 } 11434 break; 11435 case UO_Extension: 11436 case UO_Coawait: 11437 resultType = Input.get()->getType(); 11438 VK = Input.get()->getValueKind(); 11439 OK = Input.get()->getObjectKind(); 11440 break; 11441 } 11442 if (resultType.isNull() || Input.isInvalid()) 11443 return ExprError(); 11444 11445 // Check for array bounds violations in the operand of the UnaryOperator, 11446 // except for the '*' and '&' operators that have to be handled specially 11447 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11448 // that are explicitly defined as valid by the standard). 11449 if (Opc != UO_AddrOf && Opc != UO_Deref) 11450 CheckArrayAccess(Input.get()); 11451 11452 return new (Context) 11453 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11454 } 11455 11456 /// \brief Determine whether the given expression is a qualified member 11457 /// access expression, of a form that could be turned into a pointer to member 11458 /// with the address-of operator. 11459 static bool isQualifiedMemberAccess(Expr *E) { 11460 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11461 if (!DRE->getQualifier()) 11462 return false; 11463 11464 ValueDecl *VD = DRE->getDecl(); 11465 if (!VD->isCXXClassMember()) 11466 return false; 11467 11468 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11469 return true; 11470 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11471 return Method->isInstance(); 11472 11473 return false; 11474 } 11475 11476 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11477 if (!ULE->getQualifier()) 11478 return false; 11479 11480 for (NamedDecl *D : ULE->decls()) { 11481 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11482 if (Method->isInstance()) 11483 return true; 11484 } else { 11485 // Overload set does not contain methods. 11486 break; 11487 } 11488 } 11489 11490 return false; 11491 } 11492 11493 return false; 11494 } 11495 11496 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11497 UnaryOperatorKind Opc, Expr *Input) { 11498 // First things first: handle placeholders so that the 11499 // overloaded-operator check considers the right type. 11500 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11501 // Increment and decrement of pseudo-object references. 11502 if (pty->getKind() == BuiltinType::PseudoObject && 11503 UnaryOperator::isIncrementDecrementOp(Opc)) 11504 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11505 11506 // extension is always a builtin operator. 11507 if (Opc == UO_Extension) 11508 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11509 11510 // & gets special logic for several kinds of placeholder. 11511 // The builtin code knows what to do. 11512 if (Opc == UO_AddrOf && 11513 (pty->getKind() == BuiltinType::Overload || 11514 pty->getKind() == BuiltinType::UnknownAny || 11515 pty->getKind() == BuiltinType::BoundMember)) 11516 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11517 11518 // Anything else needs to be handled now. 11519 ExprResult Result = CheckPlaceholderExpr(Input); 11520 if (Result.isInvalid()) return ExprError(); 11521 Input = Result.get(); 11522 } 11523 11524 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11525 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11526 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11527 // Find all of the overloaded operators visible from this 11528 // point. We perform both an operator-name lookup from the local 11529 // scope and an argument-dependent lookup based on the types of 11530 // the arguments. 11531 UnresolvedSet<16> Functions; 11532 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11533 if (S && OverOp != OO_None) 11534 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11535 Functions); 11536 11537 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11538 } 11539 11540 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11541 } 11542 11543 // Unary Operators. 'Tok' is the token for the operator. 11544 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11545 tok::TokenKind Op, Expr *Input) { 11546 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11547 } 11548 11549 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11550 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11551 LabelDecl *TheDecl) { 11552 TheDecl->markUsed(Context); 11553 // Create the AST node. The address of a label always has type 'void*'. 11554 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11555 Context.getPointerType(Context.VoidTy)); 11556 } 11557 11558 /// Given the last statement in a statement-expression, check whether 11559 /// the result is a producing expression (like a call to an 11560 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11561 /// release out of the full-expression. Otherwise, return null. 11562 /// Cannot fail. 11563 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11564 // Should always be wrapped with one of these. 11565 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11566 if (!cleanups) return nullptr; 11567 11568 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11569 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11570 return nullptr; 11571 11572 // Splice out the cast. This shouldn't modify any interesting 11573 // features of the statement. 11574 Expr *producer = cast->getSubExpr(); 11575 assert(producer->getType() == cast->getType()); 11576 assert(producer->getValueKind() == cast->getValueKind()); 11577 cleanups->setSubExpr(producer); 11578 return cleanups; 11579 } 11580 11581 void Sema::ActOnStartStmtExpr() { 11582 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11583 } 11584 11585 void Sema::ActOnStmtExprError() { 11586 // Note that function is also called by TreeTransform when leaving a 11587 // StmtExpr scope without rebuilding anything. 11588 11589 DiscardCleanupsInEvaluationContext(); 11590 PopExpressionEvaluationContext(); 11591 } 11592 11593 ExprResult 11594 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11595 SourceLocation RPLoc) { // "({..})" 11596 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11597 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11598 11599 if (hasAnyUnrecoverableErrorsInThisFunction()) 11600 DiscardCleanupsInEvaluationContext(); 11601 assert(!Cleanup.exprNeedsCleanups() && 11602 "cleanups within StmtExpr not correctly bound!"); 11603 PopExpressionEvaluationContext(); 11604 11605 // FIXME: there are a variety of strange constraints to enforce here, for 11606 // example, it is not possible to goto into a stmt expression apparently. 11607 // More semantic analysis is needed. 11608 11609 // If there are sub-stmts in the compound stmt, take the type of the last one 11610 // as the type of the stmtexpr. 11611 QualType Ty = Context.VoidTy; 11612 bool StmtExprMayBindToTemp = false; 11613 if (!Compound->body_empty()) { 11614 Stmt *LastStmt = Compound->body_back(); 11615 LabelStmt *LastLabelStmt = nullptr; 11616 // If LastStmt is a label, skip down through into the body. 11617 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11618 LastLabelStmt = Label; 11619 LastStmt = Label->getSubStmt(); 11620 } 11621 11622 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11623 // Do function/array conversion on the last expression, but not 11624 // lvalue-to-rvalue. However, initialize an unqualified type. 11625 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11626 if (LastExpr.isInvalid()) 11627 return ExprError(); 11628 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11629 11630 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11631 // In ARC, if the final expression ends in a consume, splice 11632 // the consume out and bind it later. In the alternate case 11633 // (when dealing with a retainable type), the result 11634 // initialization will create a produce. In both cases the 11635 // result will be +1, and we'll need to balance that out with 11636 // a bind. 11637 if (Expr *rebuiltLastStmt 11638 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11639 LastExpr = rebuiltLastStmt; 11640 } else { 11641 LastExpr = PerformCopyInitialization( 11642 InitializedEntity::InitializeResult(LPLoc, 11643 Ty, 11644 false), 11645 SourceLocation(), 11646 LastExpr); 11647 } 11648 11649 if (LastExpr.isInvalid()) 11650 return ExprError(); 11651 if (LastExpr.get() != nullptr) { 11652 if (!LastLabelStmt) 11653 Compound->setLastStmt(LastExpr.get()); 11654 else 11655 LastLabelStmt->setSubStmt(LastExpr.get()); 11656 StmtExprMayBindToTemp = true; 11657 } 11658 } 11659 } 11660 } 11661 11662 // FIXME: Check that expression type is complete/non-abstract; statement 11663 // expressions are not lvalues. 11664 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11665 if (StmtExprMayBindToTemp) 11666 return MaybeBindToTemporary(ResStmtExpr); 11667 return ResStmtExpr; 11668 } 11669 11670 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11671 TypeSourceInfo *TInfo, 11672 ArrayRef<OffsetOfComponent> Components, 11673 SourceLocation RParenLoc) { 11674 QualType ArgTy = TInfo->getType(); 11675 bool Dependent = ArgTy->isDependentType(); 11676 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11677 11678 // We must have at least one component that refers to the type, and the first 11679 // one is known to be a field designator. Verify that the ArgTy represents 11680 // a struct/union/class. 11681 if (!Dependent && !ArgTy->isRecordType()) 11682 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11683 << ArgTy << TypeRange); 11684 11685 // Type must be complete per C99 7.17p3 because a declaring a variable 11686 // with an incomplete type would be ill-formed. 11687 if (!Dependent 11688 && RequireCompleteType(BuiltinLoc, ArgTy, 11689 diag::err_offsetof_incomplete_type, TypeRange)) 11690 return ExprError(); 11691 11692 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11693 // GCC extension, diagnose them. 11694 // FIXME: This diagnostic isn't actually visible because the location is in 11695 // a system header! 11696 if (Components.size() != 1) 11697 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11698 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11699 11700 bool DidWarnAboutNonPOD = false; 11701 QualType CurrentType = ArgTy; 11702 SmallVector<OffsetOfNode, 4> Comps; 11703 SmallVector<Expr*, 4> Exprs; 11704 for (const OffsetOfComponent &OC : Components) { 11705 if (OC.isBrackets) { 11706 // Offset of an array sub-field. TODO: Should we allow vector elements? 11707 if (!CurrentType->isDependentType()) { 11708 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11709 if(!AT) 11710 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11711 << CurrentType); 11712 CurrentType = AT->getElementType(); 11713 } else 11714 CurrentType = Context.DependentTy; 11715 11716 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11717 if (IdxRval.isInvalid()) 11718 return ExprError(); 11719 Expr *Idx = IdxRval.get(); 11720 11721 // The expression must be an integral expression. 11722 // FIXME: An integral constant expression? 11723 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11724 !Idx->getType()->isIntegerType()) 11725 return ExprError(Diag(Idx->getLocStart(), 11726 diag::err_typecheck_subscript_not_integer) 11727 << Idx->getSourceRange()); 11728 11729 // Record this array index. 11730 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11731 Exprs.push_back(Idx); 11732 continue; 11733 } 11734 11735 // Offset of a field. 11736 if (CurrentType->isDependentType()) { 11737 // We have the offset of a field, but we can't look into the dependent 11738 // type. Just record the identifier of the field. 11739 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11740 CurrentType = Context.DependentTy; 11741 continue; 11742 } 11743 11744 // We need to have a complete type to look into. 11745 if (RequireCompleteType(OC.LocStart, CurrentType, 11746 diag::err_offsetof_incomplete_type)) 11747 return ExprError(); 11748 11749 // Look for the designated field. 11750 const RecordType *RC = CurrentType->getAs<RecordType>(); 11751 if (!RC) 11752 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11753 << CurrentType); 11754 RecordDecl *RD = RC->getDecl(); 11755 11756 // C++ [lib.support.types]p5: 11757 // The macro offsetof accepts a restricted set of type arguments in this 11758 // International Standard. type shall be a POD structure or a POD union 11759 // (clause 9). 11760 // C++11 [support.types]p4: 11761 // If type is not a standard-layout class (Clause 9), the results are 11762 // undefined. 11763 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11764 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11765 unsigned DiagID = 11766 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11767 : diag::ext_offsetof_non_pod_type; 11768 11769 if (!IsSafe && !DidWarnAboutNonPOD && 11770 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11771 PDiag(DiagID) 11772 << SourceRange(Components[0].LocStart, OC.LocEnd) 11773 << CurrentType)) 11774 DidWarnAboutNonPOD = true; 11775 } 11776 11777 // Look for the field. 11778 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11779 LookupQualifiedName(R, RD); 11780 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11781 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11782 if (!MemberDecl) { 11783 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11784 MemberDecl = IndirectMemberDecl->getAnonField(); 11785 } 11786 11787 if (!MemberDecl) 11788 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11789 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11790 OC.LocEnd)); 11791 11792 // C99 7.17p3: 11793 // (If the specified member is a bit-field, the behavior is undefined.) 11794 // 11795 // We diagnose this as an error. 11796 if (MemberDecl->isBitField()) { 11797 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11798 << MemberDecl->getDeclName() 11799 << SourceRange(BuiltinLoc, RParenLoc); 11800 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11801 return ExprError(); 11802 } 11803 11804 RecordDecl *Parent = MemberDecl->getParent(); 11805 if (IndirectMemberDecl) 11806 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11807 11808 // If the member was found in a base class, introduce OffsetOfNodes for 11809 // the base class indirections. 11810 CXXBasePaths Paths; 11811 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11812 Paths)) { 11813 if (Paths.getDetectedVirtual()) { 11814 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11815 << MemberDecl->getDeclName() 11816 << SourceRange(BuiltinLoc, RParenLoc); 11817 return ExprError(); 11818 } 11819 11820 CXXBasePath &Path = Paths.front(); 11821 for (const CXXBasePathElement &B : Path) 11822 Comps.push_back(OffsetOfNode(B.Base)); 11823 } 11824 11825 if (IndirectMemberDecl) { 11826 for (auto *FI : IndirectMemberDecl->chain()) { 11827 assert(isa<FieldDecl>(FI)); 11828 Comps.push_back(OffsetOfNode(OC.LocStart, 11829 cast<FieldDecl>(FI), OC.LocEnd)); 11830 } 11831 } else 11832 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11833 11834 CurrentType = MemberDecl->getType().getNonReferenceType(); 11835 } 11836 11837 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11838 Comps, Exprs, RParenLoc); 11839 } 11840 11841 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11842 SourceLocation BuiltinLoc, 11843 SourceLocation TypeLoc, 11844 ParsedType ParsedArgTy, 11845 ArrayRef<OffsetOfComponent> Components, 11846 SourceLocation RParenLoc) { 11847 11848 TypeSourceInfo *ArgTInfo; 11849 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11850 if (ArgTy.isNull()) 11851 return ExprError(); 11852 11853 if (!ArgTInfo) 11854 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11855 11856 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11857 } 11858 11859 11860 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11861 Expr *CondExpr, 11862 Expr *LHSExpr, Expr *RHSExpr, 11863 SourceLocation RPLoc) { 11864 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11865 11866 ExprValueKind VK = VK_RValue; 11867 ExprObjectKind OK = OK_Ordinary; 11868 QualType resType; 11869 bool ValueDependent = false; 11870 bool CondIsTrue = false; 11871 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11872 resType = Context.DependentTy; 11873 ValueDependent = true; 11874 } else { 11875 // The conditional expression is required to be a constant expression. 11876 llvm::APSInt condEval(32); 11877 ExprResult CondICE 11878 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11879 diag::err_typecheck_choose_expr_requires_constant, false); 11880 if (CondICE.isInvalid()) 11881 return ExprError(); 11882 CondExpr = CondICE.get(); 11883 CondIsTrue = condEval.getZExtValue(); 11884 11885 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11886 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11887 11888 resType = ActiveExpr->getType(); 11889 ValueDependent = ActiveExpr->isValueDependent(); 11890 VK = ActiveExpr->getValueKind(); 11891 OK = ActiveExpr->getObjectKind(); 11892 } 11893 11894 return new (Context) 11895 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11896 CondIsTrue, resType->isDependentType(), ValueDependent); 11897 } 11898 11899 //===----------------------------------------------------------------------===// 11900 // Clang Extensions. 11901 //===----------------------------------------------------------------------===// 11902 11903 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11904 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11905 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11906 11907 if (LangOpts.CPlusPlus) { 11908 Decl *ManglingContextDecl; 11909 if (MangleNumberingContext *MCtx = 11910 getCurrentMangleNumberContext(Block->getDeclContext(), 11911 ManglingContextDecl)) { 11912 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11913 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11914 } 11915 } 11916 11917 PushBlockScope(CurScope, Block); 11918 CurContext->addDecl(Block); 11919 if (CurScope) 11920 PushDeclContext(CurScope, Block); 11921 else 11922 CurContext = Block; 11923 11924 getCurBlock()->HasImplicitReturnType = true; 11925 11926 // Enter a new evaluation context to insulate the block from any 11927 // cleanups from the enclosing full-expression. 11928 PushExpressionEvaluationContext(PotentiallyEvaluated); 11929 } 11930 11931 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11932 Scope *CurScope) { 11933 assert(ParamInfo.getIdentifier() == nullptr && 11934 "block-id should have no identifier!"); 11935 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11936 BlockScopeInfo *CurBlock = getCurBlock(); 11937 11938 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11939 QualType T = Sig->getType(); 11940 11941 // FIXME: We should allow unexpanded parameter packs here, but that would, 11942 // in turn, make the block expression contain unexpanded parameter packs. 11943 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11944 // Drop the parameters. 11945 FunctionProtoType::ExtProtoInfo EPI; 11946 EPI.HasTrailingReturn = false; 11947 EPI.TypeQuals |= DeclSpec::TQ_const; 11948 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11949 Sig = Context.getTrivialTypeSourceInfo(T); 11950 } 11951 11952 // GetTypeForDeclarator always produces a function type for a block 11953 // literal signature. Furthermore, it is always a FunctionProtoType 11954 // unless the function was written with a typedef. 11955 assert(T->isFunctionType() && 11956 "GetTypeForDeclarator made a non-function block signature"); 11957 11958 // Look for an explicit signature in that function type. 11959 FunctionProtoTypeLoc ExplicitSignature; 11960 11961 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11962 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11963 11964 // Check whether that explicit signature was synthesized by 11965 // GetTypeForDeclarator. If so, don't save that as part of the 11966 // written signature. 11967 if (ExplicitSignature.getLocalRangeBegin() == 11968 ExplicitSignature.getLocalRangeEnd()) { 11969 // This would be much cheaper if we stored TypeLocs instead of 11970 // TypeSourceInfos. 11971 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11972 unsigned Size = Result.getFullDataSize(); 11973 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11974 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11975 11976 ExplicitSignature = FunctionProtoTypeLoc(); 11977 } 11978 } 11979 11980 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11981 CurBlock->FunctionType = T; 11982 11983 const FunctionType *Fn = T->getAs<FunctionType>(); 11984 QualType RetTy = Fn->getReturnType(); 11985 bool isVariadic = 11986 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11987 11988 CurBlock->TheDecl->setIsVariadic(isVariadic); 11989 11990 // Context.DependentTy is used as a placeholder for a missing block 11991 // return type. TODO: what should we do with declarators like: 11992 // ^ * { ... } 11993 // If the answer is "apply template argument deduction".... 11994 if (RetTy != Context.DependentTy) { 11995 CurBlock->ReturnType = RetTy; 11996 CurBlock->TheDecl->setBlockMissingReturnType(false); 11997 CurBlock->HasImplicitReturnType = false; 11998 } 11999 12000 // Push block parameters from the declarator if we had them. 12001 SmallVector<ParmVarDecl*, 8> Params; 12002 if (ExplicitSignature) { 12003 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12004 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12005 if (Param->getIdentifier() == nullptr && 12006 !Param->isImplicit() && 12007 !Param->isInvalidDecl() && 12008 !getLangOpts().CPlusPlus) 12009 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12010 Params.push_back(Param); 12011 } 12012 12013 // Fake up parameter variables if we have a typedef, like 12014 // ^ fntype { ... } 12015 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12016 for (const auto &I : Fn->param_types()) { 12017 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12018 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12019 Params.push_back(Param); 12020 } 12021 } 12022 12023 // Set the parameters on the block decl. 12024 if (!Params.empty()) { 12025 CurBlock->TheDecl->setParams(Params); 12026 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12027 /*CheckParameterNames=*/false); 12028 } 12029 12030 // Finally we can process decl attributes. 12031 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12032 12033 // Put the parameter variables in scope. 12034 for (auto AI : CurBlock->TheDecl->parameters()) { 12035 AI->setOwningFunction(CurBlock->TheDecl); 12036 12037 // If this has an identifier, add it to the scope stack. 12038 if (AI->getIdentifier()) { 12039 CheckShadow(CurBlock->TheScope, AI); 12040 12041 PushOnScopeChains(AI, CurBlock->TheScope); 12042 } 12043 } 12044 } 12045 12046 /// ActOnBlockError - If there is an error parsing a block, this callback 12047 /// is invoked to pop the information about the block from the action impl. 12048 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12049 // Leave the expression-evaluation context. 12050 DiscardCleanupsInEvaluationContext(); 12051 PopExpressionEvaluationContext(); 12052 12053 // Pop off CurBlock, handle nested blocks. 12054 PopDeclContext(); 12055 PopFunctionScopeInfo(); 12056 } 12057 12058 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12059 /// literal was successfully completed. ^(int x){...} 12060 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12061 Stmt *Body, Scope *CurScope) { 12062 // If blocks are disabled, emit an error. 12063 if (!LangOpts.Blocks) 12064 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12065 12066 // Leave the expression-evaluation context. 12067 if (hasAnyUnrecoverableErrorsInThisFunction()) 12068 DiscardCleanupsInEvaluationContext(); 12069 assert(!Cleanup.exprNeedsCleanups() && 12070 "cleanups within block not correctly bound!"); 12071 PopExpressionEvaluationContext(); 12072 12073 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12074 12075 if (BSI->HasImplicitReturnType) 12076 deduceClosureReturnType(*BSI); 12077 12078 PopDeclContext(); 12079 12080 QualType RetTy = Context.VoidTy; 12081 if (!BSI->ReturnType.isNull()) 12082 RetTy = BSI->ReturnType; 12083 12084 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12085 QualType BlockTy; 12086 12087 // Set the captured variables on the block. 12088 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12089 SmallVector<BlockDecl::Capture, 4> Captures; 12090 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12091 if (Cap.isThisCapture()) 12092 continue; 12093 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12094 Cap.isNested(), Cap.getInitExpr()); 12095 Captures.push_back(NewCap); 12096 } 12097 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12098 12099 // If the user wrote a function type in some form, try to use that. 12100 if (!BSI->FunctionType.isNull()) { 12101 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12102 12103 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12104 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12105 12106 // Turn protoless block types into nullary block types. 12107 if (isa<FunctionNoProtoType>(FTy)) { 12108 FunctionProtoType::ExtProtoInfo EPI; 12109 EPI.ExtInfo = Ext; 12110 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12111 12112 // Otherwise, if we don't need to change anything about the function type, 12113 // preserve its sugar structure. 12114 } else if (FTy->getReturnType() == RetTy && 12115 (!NoReturn || FTy->getNoReturnAttr())) { 12116 BlockTy = BSI->FunctionType; 12117 12118 // Otherwise, make the minimal modifications to the function type. 12119 } else { 12120 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12121 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12122 EPI.TypeQuals = 0; // FIXME: silently? 12123 EPI.ExtInfo = Ext; 12124 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12125 } 12126 12127 // If we don't have a function type, just build one from nothing. 12128 } else { 12129 FunctionProtoType::ExtProtoInfo EPI; 12130 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12131 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12132 } 12133 12134 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12135 BlockTy = Context.getBlockPointerType(BlockTy); 12136 12137 // If needed, diagnose invalid gotos and switches in the block. 12138 if (getCurFunction()->NeedsScopeChecking() && 12139 !PP.isCodeCompletionEnabled()) 12140 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12141 12142 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12143 12144 // Try to apply the named return value optimization. We have to check again 12145 // if we can do this, though, because blocks keep return statements around 12146 // to deduce an implicit return type. 12147 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12148 !BSI->TheDecl->isDependentContext()) 12149 computeNRVO(Body, BSI); 12150 12151 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12152 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12153 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12154 12155 // If the block isn't obviously global, i.e. it captures anything at 12156 // all, then we need to do a few things in the surrounding context: 12157 if (Result->getBlockDecl()->hasCaptures()) { 12158 // First, this expression has a new cleanup object. 12159 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12160 Cleanup.setExprNeedsCleanups(true); 12161 12162 // It also gets a branch-protected scope if any of the captured 12163 // variables needs destruction. 12164 for (const auto &CI : Result->getBlockDecl()->captures()) { 12165 const VarDecl *var = CI.getVariable(); 12166 if (var->getType().isDestructedType() != QualType::DK_none) { 12167 getCurFunction()->setHasBranchProtectedScope(); 12168 break; 12169 } 12170 } 12171 } 12172 12173 return Result; 12174 } 12175 12176 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12177 SourceLocation RPLoc) { 12178 TypeSourceInfo *TInfo; 12179 GetTypeFromParser(Ty, &TInfo); 12180 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12181 } 12182 12183 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12184 Expr *E, TypeSourceInfo *TInfo, 12185 SourceLocation RPLoc) { 12186 Expr *OrigExpr = E; 12187 bool IsMS = false; 12188 12189 // CUDA device code does not support varargs. 12190 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12191 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12192 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12193 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12194 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12195 } 12196 } 12197 12198 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12199 // as Microsoft ABI on an actual Microsoft platform, where 12200 // __builtin_ms_va_list and __builtin_va_list are the same.) 12201 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12202 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12203 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12204 if (Context.hasSameType(MSVaListType, E->getType())) { 12205 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12206 return ExprError(); 12207 IsMS = true; 12208 } 12209 } 12210 12211 // Get the va_list type 12212 QualType VaListType = Context.getBuiltinVaListType(); 12213 if (!IsMS) { 12214 if (VaListType->isArrayType()) { 12215 // Deal with implicit array decay; for example, on x86-64, 12216 // va_list is an array, but it's supposed to decay to 12217 // a pointer for va_arg. 12218 VaListType = Context.getArrayDecayedType(VaListType); 12219 // Make sure the input expression also decays appropriately. 12220 ExprResult Result = UsualUnaryConversions(E); 12221 if (Result.isInvalid()) 12222 return ExprError(); 12223 E = Result.get(); 12224 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12225 // If va_list is a record type and we are compiling in C++ mode, 12226 // check the argument using reference binding. 12227 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12228 Context, Context.getLValueReferenceType(VaListType), false); 12229 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12230 if (Init.isInvalid()) 12231 return ExprError(); 12232 E = Init.getAs<Expr>(); 12233 } else { 12234 // Otherwise, the va_list argument must be an l-value because 12235 // it is modified by va_arg. 12236 if (!E->isTypeDependent() && 12237 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12238 return ExprError(); 12239 } 12240 } 12241 12242 if (!IsMS && !E->isTypeDependent() && 12243 !Context.hasSameType(VaListType, E->getType())) 12244 return ExprError(Diag(E->getLocStart(), 12245 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12246 << OrigExpr->getType() << E->getSourceRange()); 12247 12248 if (!TInfo->getType()->isDependentType()) { 12249 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12250 diag::err_second_parameter_to_va_arg_incomplete, 12251 TInfo->getTypeLoc())) 12252 return ExprError(); 12253 12254 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12255 TInfo->getType(), 12256 diag::err_second_parameter_to_va_arg_abstract, 12257 TInfo->getTypeLoc())) 12258 return ExprError(); 12259 12260 if (!TInfo->getType().isPODType(Context)) { 12261 Diag(TInfo->getTypeLoc().getBeginLoc(), 12262 TInfo->getType()->isObjCLifetimeType() 12263 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12264 : diag::warn_second_parameter_to_va_arg_not_pod) 12265 << TInfo->getType() 12266 << TInfo->getTypeLoc().getSourceRange(); 12267 } 12268 12269 // Check for va_arg where arguments of the given type will be promoted 12270 // (i.e. this va_arg is guaranteed to have undefined behavior). 12271 QualType PromoteType; 12272 if (TInfo->getType()->isPromotableIntegerType()) { 12273 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12274 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12275 PromoteType = QualType(); 12276 } 12277 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12278 PromoteType = Context.DoubleTy; 12279 if (!PromoteType.isNull()) 12280 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12281 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12282 << TInfo->getType() 12283 << PromoteType 12284 << TInfo->getTypeLoc().getSourceRange()); 12285 } 12286 12287 QualType T = TInfo->getType().getNonLValueExprType(Context); 12288 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12289 } 12290 12291 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12292 // The type of __null will be int or long, depending on the size of 12293 // pointers on the target. 12294 QualType Ty; 12295 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12296 if (pw == Context.getTargetInfo().getIntWidth()) 12297 Ty = Context.IntTy; 12298 else if (pw == Context.getTargetInfo().getLongWidth()) 12299 Ty = Context.LongTy; 12300 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12301 Ty = Context.LongLongTy; 12302 else { 12303 llvm_unreachable("I don't know size of pointer!"); 12304 } 12305 12306 return new (Context) GNUNullExpr(Ty, TokenLoc); 12307 } 12308 12309 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12310 bool Diagnose) { 12311 if (!getLangOpts().ObjC1) 12312 return false; 12313 12314 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12315 if (!PT) 12316 return false; 12317 12318 if (!PT->isObjCIdType()) { 12319 // Check if the destination is the 'NSString' interface. 12320 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12321 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12322 return false; 12323 } 12324 12325 // Ignore any parens, implicit casts (should only be 12326 // array-to-pointer decays), and not-so-opaque values. The last is 12327 // important for making this trigger for property assignments. 12328 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12329 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12330 if (OV->getSourceExpr()) 12331 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12332 12333 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12334 if (!SL || !SL->isAscii()) 12335 return false; 12336 if (Diagnose) { 12337 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12338 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12339 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12340 } 12341 return true; 12342 } 12343 12344 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12345 const Expr *SrcExpr) { 12346 if (!DstType->isFunctionPointerType() || 12347 !SrcExpr->getType()->isFunctionType()) 12348 return false; 12349 12350 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12351 if (!DRE) 12352 return false; 12353 12354 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12355 if (!FD) 12356 return false; 12357 12358 return !S.checkAddressOfFunctionIsAvailable(FD, 12359 /*Complain=*/true, 12360 SrcExpr->getLocStart()); 12361 } 12362 12363 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12364 SourceLocation Loc, 12365 QualType DstType, QualType SrcType, 12366 Expr *SrcExpr, AssignmentAction Action, 12367 bool *Complained) { 12368 if (Complained) 12369 *Complained = false; 12370 12371 // Decode the result (notice that AST's are still created for extensions). 12372 bool CheckInferredResultType = false; 12373 bool isInvalid = false; 12374 unsigned DiagKind = 0; 12375 FixItHint Hint; 12376 ConversionFixItGenerator ConvHints; 12377 bool MayHaveConvFixit = false; 12378 bool MayHaveFunctionDiff = false; 12379 const ObjCInterfaceDecl *IFace = nullptr; 12380 const ObjCProtocolDecl *PDecl = nullptr; 12381 12382 switch (ConvTy) { 12383 case Compatible: 12384 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12385 return false; 12386 12387 case PointerToInt: 12388 DiagKind = diag::ext_typecheck_convert_pointer_int; 12389 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12390 MayHaveConvFixit = true; 12391 break; 12392 case IntToPointer: 12393 DiagKind = diag::ext_typecheck_convert_int_pointer; 12394 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12395 MayHaveConvFixit = true; 12396 break; 12397 case IncompatiblePointer: 12398 DiagKind = 12399 (Action == AA_Passing_CFAudited ? 12400 diag::err_arc_typecheck_convert_incompatible_pointer : 12401 diag::ext_typecheck_convert_incompatible_pointer); 12402 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12403 SrcType->isObjCObjectPointerType(); 12404 if (Hint.isNull() && !CheckInferredResultType) { 12405 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12406 } 12407 else if (CheckInferredResultType) { 12408 SrcType = SrcType.getUnqualifiedType(); 12409 DstType = DstType.getUnqualifiedType(); 12410 } 12411 MayHaveConvFixit = true; 12412 break; 12413 case IncompatiblePointerSign: 12414 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12415 break; 12416 case FunctionVoidPointer: 12417 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12418 break; 12419 case IncompatiblePointerDiscardsQualifiers: { 12420 // Perform array-to-pointer decay if necessary. 12421 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12422 12423 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12424 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12425 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12426 DiagKind = diag::err_typecheck_incompatible_address_space; 12427 break; 12428 12429 12430 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12431 DiagKind = diag::err_typecheck_incompatible_ownership; 12432 break; 12433 } 12434 12435 llvm_unreachable("unknown error case for discarding qualifiers!"); 12436 // fallthrough 12437 } 12438 case CompatiblePointerDiscardsQualifiers: 12439 // If the qualifiers lost were because we were applying the 12440 // (deprecated) C++ conversion from a string literal to a char* 12441 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12442 // Ideally, this check would be performed in 12443 // checkPointerTypesForAssignment. However, that would require a 12444 // bit of refactoring (so that the second argument is an 12445 // expression, rather than a type), which should be done as part 12446 // of a larger effort to fix checkPointerTypesForAssignment for 12447 // C++ semantics. 12448 if (getLangOpts().CPlusPlus && 12449 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12450 return false; 12451 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12452 break; 12453 case IncompatibleNestedPointerQualifiers: 12454 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12455 break; 12456 case IntToBlockPointer: 12457 DiagKind = diag::err_int_to_block_pointer; 12458 break; 12459 case IncompatibleBlockPointer: 12460 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12461 break; 12462 case IncompatibleObjCQualifiedId: { 12463 if (SrcType->isObjCQualifiedIdType()) { 12464 const ObjCObjectPointerType *srcOPT = 12465 SrcType->getAs<ObjCObjectPointerType>(); 12466 for (auto *srcProto : srcOPT->quals()) { 12467 PDecl = srcProto; 12468 break; 12469 } 12470 if (const ObjCInterfaceType *IFaceT = 12471 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12472 IFace = IFaceT->getDecl(); 12473 } 12474 else if (DstType->isObjCQualifiedIdType()) { 12475 const ObjCObjectPointerType *dstOPT = 12476 DstType->getAs<ObjCObjectPointerType>(); 12477 for (auto *dstProto : dstOPT->quals()) { 12478 PDecl = dstProto; 12479 break; 12480 } 12481 if (const ObjCInterfaceType *IFaceT = 12482 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12483 IFace = IFaceT->getDecl(); 12484 } 12485 DiagKind = diag::warn_incompatible_qualified_id; 12486 break; 12487 } 12488 case IncompatibleVectors: 12489 DiagKind = diag::warn_incompatible_vectors; 12490 break; 12491 case IncompatibleObjCWeakRef: 12492 DiagKind = diag::err_arc_weak_unavailable_assign; 12493 break; 12494 case Incompatible: 12495 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12496 if (Complained) 12497 *Complained = true; 12498 return true; 12499 } 12500 12501 DiagKind = diag::err_typecheck_convert_incompatible; 12502 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12503 MayHaveConvFixit = true; 12504 isInvalid = true; 12505 MayHaveFunctionDiff = true; 12506 break; 12507 } 12508 12509 QualType FirstType, SecondType; 12510 switch (Action) { 12511 case AA_Assigning: 12512 case AA_Initializing: 12513 // The destination type comes first. 12514 FirstType = DstType; 12515 SecondType = SrcType; 12516 break; 12517 12518 case AA_Returning: 12519 case AA_Passing: 12520 case AA_Passing_CFAudited: 12521 case AA_Converting: 12522 case AA_Sending: 12523 case AA_Casting: 12524 // The source type comes first. 12525 FirstType = SrcType; 12526 SecondType = DstType; 12527 break; 12528 } 12529 12530 PartialDiagnostic FDiag = PDiag(DiagKind); 12531 if (Action == AA_Passing_CFAudited) 12532 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12533 else 12534 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12535 12536 // If we can fix the conversion, suggest the FixIts. 12537 assert(ConvHints.isNull() || Hint.isNull()); 12538 if (!ConvHints.isNull()) { 12539 for (FixItHint &H : ConvHints.Hints) 12540 FDiag << H; 12541 } else { 12542 FDiag << Hint; 12543 } 12544 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12545 12546 if (MayHaveFunctionDiff) 12547 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12548 12549 Diag(Loc, FDiag); 12550 if (DiagKind == diag::warn_incompatible_qualified_id && 12551 PDecl && IFace && !IFace->hasDefinition()) 12552 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12553 << IFace->getName() << PDecl->getName(); 12554 12555 if (SecondType == Context.OverloadTy) 12556 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12557 FirstType, /*TakingAddress=*/true); 12558 12559 if (CheckInferredResultType) 12560 EmitRelatedResultTypeNote(SrcExpr); 12561 12562 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12563 EmitRelatedResultTypeNoteForReturn(DstType); 12564 12565 if (Complained) 12566 *Complained = true; 12567 return isInvalid; 12568 } 12569 12570 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12571 llvm::APSInt *Result) { 12572 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12573 public: 12574 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12575 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12576 } 12577 } Diagnoser; 12578 12579 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12580 } 12581 12582 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12583 llvm::APSInt *Result, 12584 unsigned DiagID, 12585 bool AllowFold) { 12586 class IDDiagnoser : public VerifyICEDiagnoser { 12587 unsigned DiagID; 12588 12589 public: 12590 IDDiagnoser(unsigned DiagID) 12591 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12592 12593 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12594 S.Diag(Loc, DiagID) << SR; 12595 } 12596 } Diagnoser(DiagID); 12597 12598 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12599 } 12600 12601 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12602 SourceRange SR) { 12603 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12604 } 12605 12606 ExprResult 12607 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12608 VerifyICEDiagnoser &Diagnoser, 12609 bool AllowFold) { 12610 SourceLocation DiagLoc = E->getLocStart(); 12611 12612 if (getLangOpts().CPlusPlus11) { 12613 // C++11 [expr.const]p5: 12614 // If an expression of literal class type is used in a context where an 12615 // integral constant expression is required, then that class type shall 12616 // have a single non-explicit conversion function to an integral or 12617 // unscoped enumeration type 12618 ExprResult Converted; 12619 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12620 public: 12621 CXX11ConvertDiagnoser(bool Silent) 12622 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12623 Silent, true) {} 12624 12625 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12626 QualType T) override { 12627 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12628 } 12629 12630 SemaDiagnosticBuilder diagnoseIncomplete( 12631 Sema &S, SourceLocation Loc, QualType T) override { 12632 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12633 } 12634 12635 SemaDiagnosticBuilder diagnoseExplicitConv( 12636 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12637 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12638 } 12639 12640 SemaDiagnosticBuilder noteExplicitConv( 12641 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12642 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12643 << ConvTy->isEnumeralType() << ConvTy; 12644 } 12645 12646 SemaDiagnosticBuilder diagnoseAmbiguous( 12647 Sema &S, SourceLocation Loc, QualType T) override { 12648 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12649 } 12650 12651 SemaDiagnosticBuilder noteAmbiguous( 12652 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12653 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12654 << ConvTy->isEnumeralType() << ConvTy; 12655 } 12656 12657 SemaDiagnosticBuilder diagnoseConversion( 12658 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12659 llvm_unreachable("conversion functions are permitted"); 12660 } 12661 } ConvertDiagnoser(Diagnoser.Suppress); 12662 12663 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12664 ConvertDiagnoser); 12665 if (Converted.isInvalid()) 12666 return Converted; 12667 E = Converted.get(); 12668 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12669 return ExprError(); 12670 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12671 // An ICE must be of integral or unscoped enumeration type. 12672 if (!Diagnoser.Suppress) 12673 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12674 return ExprError(); 12675 } 12676 12677 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12678 // in the non-ICE case. 12679 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12680 if (Result) 12681 *Result = E->EvaluateKnownConstInt(Context); 12682 return E; 12683 } 12684 12685 Expr::EvalResult EvalResult; 12686 SmallVector<PartialDiagnosticAt, 8> Notes; 12687 EvalResult.Diag = &Notes; 12688 12689 // Try to evaluate the expression, and produce diagnostics explaining why it's 12690 // not a constant expression as a side-effect. 12691 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12692 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12693 12694 // In C++11, we can rely on diagnostics being produced for any expression 12695 // which is not a constant expression. If no diagnostics were produced, then 12696 // this is a constant expression. 12697 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12698 if (Result) 12699 *Result = EvalResult.Val.getInt(); 12700 return E; 12701 } 12702 12703 // If our only note is the usual "invalid subexpression" note, just point 12704 // the caret at its location rather than producing an essentially 12705 // redundant note. 12706 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12707 diag::note_invalid_subexpr_in_const_expr) { 12708 DiagLoc = Notes[0].first; 12709 Notes.clear(); 12710 } 12711 12712 if (!Folded || !AllowFold) { 12713 if (!Diagnoser.Suppress) { 12714 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12715 for (const PartialDiagnosticAt &Note : Notes) 12716 Diag(Note.first, Note.second); 12717 } 12718 12719 return ExprError(); 12720 } 12721 12722 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12723 for (const PartialDiagnosticAt &Note : Notes) 12724 Diag(Note.first, Note.second); 12725 12726 if (Result) 12727 *Result = EvalResult.Val.getInt(); 12728 return E; 12729 } 12730 12731 namespace { 12732 // Handle the case where we conclude a expression which we speculatively 12733 // considered to be unevaluated is actually evaluated. 12734 class TransformToPE : public TreeTransform<TransformToPE> { 12735 typedef TreeTransform<TransformToPE> BaseTransform; 12736 12737 public: 12738 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12739 12740 // Make sure we redo semantic analysis 12741 bool AlwaysRebuild() { return true; } 12742 12743 // Make sure we handle LabelStmts correctly. 12744 // FIXME: This does the right thing, but maybe we need a more general 12745 // fix to TreeTransform? 12746 StmtResult TransformLabelStmt(LabelStmt *S) { 12747 S->getDecl()->setStmt(nullptr); 12748 return BaseTransform::TransformLabelStmt(S); 12749 } 12750 12751 // We need to special-case DeclRefExprs referring to FieldDecls which 12752 // are not part of a member pointer formation; normal TreeTransforming 12753 // doesn't catch this case because of the way we represent them in the AST. 12754 // FIXME: This is a bit ugly; is it really the best way to handle this 12755 // case? 12756 // 12757 // Error on DeclRefExprs referring to FieldDecls. 12758 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12759 if (isa<FieldDecl>(E->getDecl()) && 12760 !SemaRef.isUnevaluatedContext()) 12761 return SemaRef.Diag(E->getLocation(), 12762 diag::err_invalid_non_static_member_use) 12763 << E->getDecl() << E->getSourceRange(); 12764 12765 return BaseTransform::TransformDeclRefExpr(E); 12766 } 12767 12768 // Exception: filter out member pointer formation 12769 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12770 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12771 return E; 12772 12773 return BaseTransform::TransformUnaryOperator(E); 12774 } 12775 12776 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12777 // Lambdas never need to be transformed. 12778 return E; 12779 } 12780 }; 12781 } 12782 12783 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12784 assert(isUnevaluatedContext() && 12785 "Should only transform unevaluated expressions"); 12786 ExprEvalContexts.back().Context = 12787 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12788 if (isUnevaluatedContext()) 12789 return E; 12790 return TransformToPE(*this).TransformExpr(E); 12791 } 12792 12793 void 12794 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12795 Decl *LambdaContextDecl, 12796 bool IsDecltype) { 12797 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 12798 LambdaContextDecl, IsDecltype); 12799 Cleanup.reset(); 12800 if (!MaybeODRUseExprs.empty()) 12801 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12802 } 12803 12804 void 12805 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12806 ReuseLambdaContextDecl_t, 12807 bool IsDecltype) { 12808 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12809 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12810 } 12811 12812 void Sema::PopExpressionEvaluationContext() { 12813 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12814 unsigned NumTypos = Rec.NumTypos; 12815 12816 if (!Rec.Lambdas.empty()) { 12817 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12818 unsigned D; 12819 if (Rec.isUnevaluated()) { 12820 // C++11 [expr.prim.lambda]p2: 12821 // A lambda-expression shall not appear in an unevaluated operand 12822 // (Clause 5). 12823 D = diag::err_lambda_unevaluated_operand; 12824 } else { 12825 // C++1y [expr.const]p2: 12826 // A conditional-expression e is a core constant expression unless the 12827 // evaluation of e, following the rules of the abstract machine, would 12828 // evaluate [...] a lambda-expression. 12829 D = diag::err_lambda_in_constant_expression; 12830 } 12831 for (const auto *L : Rec.Lambdas) 12832 Diag(L->getLocStart(), D); 12833 } else { 12834 // Mark the capture expressions odr-used. This was deferred 12835 // during lambda expression creation. 12836 for (auto *Lambda : Rec.Lambdas) { 12837 for (auto *C : Lambda->capture_inits()) 12838 MarkDeclarationsReferencedInExpr(C); 12839 } 12840 } 12841 } 12842 12843 // When are coming out of an unevaluated context, clear out any 12844 // temporaries that we may have created as part of the evaluation of 12845 // the expression in that context: they aren't relevant because they 12846 // will never be constructed. 12847 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12848 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12849 ExprCleanupObjects.end()); 12850 Cleanup = Rec.ParentCleanup; 12851 CleanupVarDeclMarking(); 12852 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12853 // Otherwise, merge the contexts together. 12854 } else { 12855 Cleanup.mergeFrom(Rec.ParentCleanup); 12856 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12857 Rec.SavedMaybeODRUseExprs.end()); 12858 } 12859 12860 // Pop the current expression evaluation context off the stack. 12861 ExprEvalContexts.pop_back(); 12862 12863 if (!ExprEvalContexts.empty()) 12864 ExprEvalContexts.back().NumTypos += NumTypos; 12865 else 12866 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12867 "last ExpressionEvaluationContextRecord"); 12868 } 12869 12870 void Sema::DiscardCleanupsInEvaluationContext() { 12871 ExprCleanupObjects.erase( 12872 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12873 ExprCleanupObjects.end()); 12874 Cleanup.reset(); 12875 MaybeODRUseExprs.clear(); 12876 } 12877 12878 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12879 if (!E->getType()->isVariablyModifiedType()) 12880 return E; 12881 return TransformToPotentiallyEvaluated(E); 12882 } 12883 12884 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12885 // Do not mark anything as "used" within a dependent context; wait for 12886 // an instantiation. 12887 if (SemaRef.CurContext->isDependentContext()) 12888 return false; 12889 12890 switch (SemaRef.ExprEvalContexts.back().Context) { 12891 case Sema::Unevaluated: 12892 case Sema::UnevaluatedAbstract: 12893 // We are in an expression that is not potentially evaluated; do nothing. 12894 // (Depending on how you read the standard, we actually do need to do 12895 // something here for null pointer constants, but the standard's 12896 // definition of a null pointer constant is completely crazy.) 12897 return false; 12898 12899 case Sema::DiscardedStatement: 12900 // These are technically a potentially evaluated but they have the effect 12901 // of suppressing use marking. 12902 return false; 12903 12904 case Sema::ConstantEvaluated: 12905 case Sema::PotentiallyEvaluated: 12906 // We are in a potentially evaluated expression (or a constant-expression 12907 // in C++03); we need to do implicit template instantiation, implicitly 12908 // define class members, and mark most declarations as used. 12909 return true; 12910 12911 case Sema::PotentiallyEvaluatedIfUsed: 12912 // Referenced declarations will only be used if the construct in the 12913 // containing expression is used. 12914 return false; 12915 } 12916 llvm_unreachable("Invalid context"); 12917 } 12918 12919 /// \brief Mark a function referenced, and check whether it is odr-used 12920 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12921 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12922 bool MightBeOdrUse) { 12923 assert(Func && "No function?"); 12924 12925 Func->setReferenced(); 12926 12927 // C++11 [basic.def.odr]p3: 12928 // A function whose name appears as a potentially-evaluated expression is 12929 // odr-used if it is the unique lookup result or the selected member of a 12930 // set of overloaded functions [...]. 12931 // 12932 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12933 // can just check that here. 12934 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 12935 12936 // Determine whether we require a function definition to exist, per 12937 // C++11 [temp.inst]p3: 12938 // Unless a function template specialization has been explicitly 12939 // instantiated or explicitly specialized, the function template 12940 // specialization is implicitly instantiated when the specialization is 12941 // referenced in a context that requires a function definition to exist. 12942 // 12943 // We consider constexpr function templates to be referenced in a context 12944 // that requires a definition to exist whenever they are referenced. 12945 // 12946 // FIXME: This instantiates constexpr functions too frequently. If this is 12947 // really an unevaluated context (and we're not just in the definition of a 12948 // function template or overload resolution or other cases which we 12949 // incorrectly consider to be unevaluated contexts), and we're not in a 12950 // subexpression which we actually need to evaluate (for instance, a 12951 // template argument, array bound or an expression in a braced-init-list), 12952 // we are not permitted to instantiate this constexpr function definition. 12953 // 12954 // FIXME: This also implicitly defines special members too frequently. They 12955 // are only supposed to be implicitly defined if they are odr-used, but they 12956 // are not odr-used from constant expressions in unevaluated contexts. 12957 // However, they cannot be referenced if they are deleted, and they are 12958 // deleted whenever the implicit definition of the special member would 12959 // fail (with very few exceptions). 12960 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12961 bool NeedDefinition = 12962 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 12963 (MD && !MD->isUserProvided()))); 12964 12965 // C++14 [temp.expl.spec]p6: 12966 // If a template [...] is explicitly specialized then that specialization 12967 // shall be declared before the first use of that specialization that would 12968 // cause an implicit instantiation to take place, in every translation unit 12969 // in which such a use occurs 12970 if (NeedDefinition && 12971 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 12972 Func->getMemberSpecializationInfo())) 12973 checkSpecializationVisibility(Loc, Func); 12974 12975 // If we don't need to mark the function as used, and we don't need to 12976 // try to provide a definition, there's nothing more to do. 12977 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 12978 (!NeedDefinition || Func->getBody())) 12979 return; 12980 12981 // Note that this declaration has been used. 12982 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12983 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12984 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12985 if (Constructor->isDefaultConstructor()) { 12986 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12987 return; 12988 DefineImplicitDefaultConstructor(Loc, Constructor); 12989 } else if (Constructor->isCopyConstructor()) { 12990 DefineImplicitCopyConstructor(Loc, Constructor); 12991 } else if (Constructor->isMoveConstructor()) { 12992 DefineImplicitMoveConstructor(Loc, Constructor); 12993 } 12994 } else if (Constructor->getInheritedConstructor()) { 12995 DefineInheritingConstructor(Loc, Constructor); 12996 } 12997 } else if (CXXDestructorDecl *Destructor = 12998 dyn_cast<CXXDestructorDecl>(Func)) { 12999 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13000 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13001 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13002 return; 13003 DefineImplicitDestructor(Loc, Destructor); 13004 } 13005 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13006 MarkVTableUsed(Loc, Destructor->getParent()); 13007 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13008 if (MethodDecl->isOverloadedOperator() && 13009 MethodDecl->getOverloadedOperator() == OO_Equal) { 13010 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13011 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13012 if (MethodDecl->isCopyAssignmentOperator()) 13013 DefineImplicitCopyAssignment(Loc, MethodDecl); 13014 else if (MethodDecl->isMoveAssignmentOperator()) 13015 DefineImplicitMoveAssignment(Loc, MethodDecl); 13016 } 13017 } else if (isa<CXXConversionDecl>(MethodDecl) && 13018 MethodDecl->getParent()->isLambda()) { 13019 CXXConversionDecl *Conversion = 13020 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13021 if (Conversion->isLambdaToBlockPointerConversion()) 13022 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13023 else 13024 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13025 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13026 MarkVTableUsed(Loc, MethodDecl->getParent()); 13027 } 13028 13029 // Recursive functions should be marked when used from another function. 13030 // FIXME: Is this really right? 13031 if (CurContext == Func) return; 13032 13033 // Resolve the exception specification for any function which is 13034 // used: CodeGen will need it. 13035 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13036 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13037 ResolveExceptionSpec(Loc, FPT); 13038 13039 // Implicit instantiation of function templates and member functions of 13040 // class templates. 13041 if (Func->isImplicitlyInstantiable()) { 13042 bool AlreadyInstantiated = false; 13043 SourceLocation PointOfInstantiation = Loc; 13044 if (FunctionTemplateSpecializationInfo *SpecInfo 13045 = Func->getTemplateSpecializationInfo()) { 13046 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13047 SpecInfo->setPointOfInstantiation(Loc); 13048 else if (SpecInfo->getTemplateSpecializationKind() 13049 == TSK_ImplicitInstantiation) { 13050 AlreadyInstantiated = true; 13051 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13052 } 13053 } else if (MemberSpecializationInfo *MSInfo 13054 = Func->getMemberSpecializationInfo()) { 13055 if (MSInfo->getPointOfInstantiation().isInvalid()) 13056 MSInfo->setPointOfInstantiation(Loc); 13057 else if (MSInfo->getTemplateSpecializationKind() 13058 == TSK_ImplicitInstantiation) { 13059 AlreadyInstantiated = true; 13060 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13061 } 13062 } 13063 13064 if (!AlreadyInstantiated || Func->isConstexpr()) { 13065 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13066 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13067 ActiveTemplateInstantiations.size()) 13068 PendingLocalImplicitInstantiations.push_back( 13069 std::make_pair(Func, PointOfInstantiation)); 13070 else if (Func->isConstexpr()) 13071 // Do not defer instantiations of constexpr functions, to avoid the 13072 // expression evaluator needing to call back into Sema if it sees a 13073 // call to such a function. 13074 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13075 else { 13076 PendingInstantiations.push_back(std::make_pair(Func, 13077 PointOfInstantiation)); 13078 // Notify the consumer that a function was implicitly instantiated. 13079 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13080 } 13081 } 13082 } else { 13083 // Walk redefinitions, as some of them may be instantiable. 13084 for (auto i : Func->redecls()) { 13085 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13086 MarkFunctionReferenced(Loc, i, OdrUse); 13087 } 13088 } 13089 13090 if (!OdrUse) return; 13091 13092 // Keep track of used but undefined functions. 13093 if (!Func->isDefined()) { 13094 if (mightHaveNonExternalLinkage(Func)) 13095 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13096 else if (Func->getMostRecentDecl()->isInlined() && 13097 !LangOpts.GNUInline && 13098 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13099 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13100 } 13101 13102 Func->markUsed(Context); 13103 } 13104 13105 static void 13106 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13107 VarDecl *var, DeclContext *DC) { 13108 DeclContext *VarDC = var->getDeclContext(); 13109 13110 // If the parameter still belongs to the translation unit, then 13111 // we're actually just using one parameter in the declaration of 13112 // the next. 13113 if (isa<ParmVarDecl>(var) && 13114 isa<TranslationUnitDecl>(VarDC)) 13115 return; 13116 13117 // For C code, don't diagnose about capture if we're not actually in code 13118 // right now; it's impossible to write a non-constant expression outside of 13119 // function context, so we'll get other (more useful) diagnostics later. 13120 // 13121 // For C++, things get a bit more nasty... it would be nice to suppress this 13122 // diagnostic for certain cases like using a local variable in an array bound 13123 // for a member of a local class, but the correct predicate is not obvious. 13124 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13125 return; 13126 13127 if (isa<CXXMethodDecl>(VarDC) && 13128 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13129 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 13130 << var->getIdentifier(); 13131 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 13132 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 13133 << var->getIdentifier() << fn->getDeclName(); 13134 } else if (isa<BlockDecl>(VarDC)) { 13135 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 13136 << var->getIdentifier(); 13137 } else { 13138 // FIXME: Is there any other context where a local variable can be 13139 // declared? 13140 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 13141 << var->getIdentifier(); 13142 } 13143 13144 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13145 << var->getIdentifier(); 13146 13147 // FIXME: Add additional diagnostic info about class etc. which prevents 13148 // capture. 13149 } 13150 13151 13152 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13153 bool &SubCapturesAreNested, 13154 QualType &CaptureType, 13155 QualType &DeclRefType) { 13156 // Check whether we've already captured it. 13157 if (CSI->CaptureMap.count(Var)) { 13158 // If we found a capture, any subcaptures are nested. 13159 SubCapturesAreNested = true; 13160 13161 // Retrieve the capture type for this variable. 13162 CaptureType = CSI->getCapture(Var).getCaptureType(); 13163 13164 // Compute the type of an expression that refers to this variable. 13165 DeclRefType = CaptureType.getNonReferenceType(); 13166 13167 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13168 // are mutable in the sense that user can change their value - they are 13169 // private instances of the captured declarations. 13170 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13171 if (Cap.isCopyCapture() && 13172 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13173 !(isa<CapturedRegionScopeInfo>(CSI) && 13174 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13175 DeclRefType.addConst(); 13176 return true; 13177 } 13178 return false; 13179 } 13180 13181 // Only block literals, captured statements, and lambda expressions can 13182 // capture; other scopes don't work. 13183 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13184 SourceLocation Loc, 13185 const bool Diagnose, Sema &S) { 13186 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13187 return getLambdaAwareParentOfDeclContext(DC); 13188 else if (Var->hasLocalStorage()) { 13189 if (Diagnose) 13190 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13191 } 13192 return nullptr; 13193 } 13194 13195 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13196 // certain types of variables (unnamed, variably modified types etc.) 13197 // so check for eligibility. 13198 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13199 SourceLocation Loc, 13200 const bool Diagnose, Sema &S) { 13201 13202 bool IsBlock = isa<BlockScopeInfo>(CSI); 13203 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13204 13205 // Lambdas are not allowed to capture unnamed variables 13206 // (e.g. anonymous unions). 13207 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13208 // assuming that's the intent. 13209 if (IsLambda && !Var->getDeclName()) { 13210 if (Diagnose) { 13211 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13212 S.Diag(Var->getLocation(), diag::note_declared_at); 13213 } 13214 return false; 13215 } 13216 13217 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13218 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13219 if (Diagnose) { 13220 S.Diag(Loc, diag::err_ref_vm_type); 13221 S.Diag(Var->getLocation(), diag::note_previous_decl) 13222 << Var->getDeclName(); 13223 } 13224 return false; 13225 } 13226 // Prohibit structs with flexible array members too. 13227 // We cannot capture what is in the tail end of the struct. 13228 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13229 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13230 if (Diagnose) { 13231 if (IsBlock) 13232 S.Diag(Loc, diag::err_ref_flexarray_type); 13233 else 13234 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13235 << Var->getDeclName(); 13236 S.Diag(Var->getLocation(), diag::note_previous_decl) 13237 << Var->getDeclName(); 13238 } 13239 return false; 13240 } 13241 } 13242 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13243 // Lambdas and captured statements are not allowed to capture __block 13244 // variables; they don't support the expected semantics. 13245 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13246 if (Diagnose) { 13247 S.Diag(Loc, diag::err_capture_block_variable) 13248 << Var->getDeclName() << !IsLambda; 13249 S.Diag(Var->getLocation(), diag::note_previous_decl) 13250 << Var->getDeclName(); 13251 } 13252 return false; 13253 } 13254 13255 return true; 13256 } 13257 13258 // Returns true if the capture by block was successful. 13259 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13260 SourceLocation Loc, 13261 const bool BuildAndDiagnose, 13262 QualType &CaptureType, 13263 QualType &DeclRefType, 13264 const bool Nested, 13265 Sema &S) { 13266 Expr *CopyExpr = nullptr; 13267 bool ByRef = false; 13268 13269 // Blocks are not allowed to capture arrays. 13270 if (CaptureType->isArrayType()) { 13271 if (BuildAndDiagnose) { 13272 S.Diag(Loc, diag::err_ref_array_type); 13273 S.Diag(Var->getLocation(), diag::note_previous_decl) 13274 << Var->getDeclName(); 13275 } 13276 return false; 13277 } 13278 13279 // Forbid the block-capture of autoreleasing variables. 13280 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13281 if (BuildAndDiagnose) { 13282 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13283 << /*block*/ 0; 13284 S.Diag(Var->getLocation(), diag::note_previous_decl) 13285 << Var->getDeclName(); 13286 } 13287 return false; 13288 } 13289 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13290 if (HasBlocksAttr || CaptureType->isReferenceType() || 13291 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13292 // Block capture by reference does not change the capture or 13293 // declaration reference types. 13294 ByRef = true; 13295 } else { 13296 // Block capture by copy introduces 'const'. 13297 CaptureType = CaptureType.getNonReferenceType().withConst(); 13298 DeclRefType = CaptureType; 13299 13300 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13301 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13302 // The capture logic needs the destructor, so make sure we mark it. 13303 // Usually this is unnecessary because most local variables have 13304 // their destructors marked at declaration time, but parameters are 13305 // an exception because it's technically only the call site that 13306 // actually requires the destructor. 13307 if (isa<ParmVarDecl>(Var)) 13308 S.FinalizeVarWithDestructor(Var, Record); 13309 13310 // Enter a new evaluation context to insulate the copy 13311 // full-expression. 13312 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13313 13314 // According to the blocks spec, the capture of a variable from 13315 // the stack requires a const copy constructor. This is not true 13316 // of the copy/move done to move a __block variable to the heap. 13317 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13318 DeclRefType.withConst(), 13319 VK_LValue, Loc); 13320 13321 ExprResult Result 13322 = S.PerformCopyInitialization( 13323 InitializedEntity::InitializeBlock(Var->getLocation(), 13324 CaptureType, false), 13325 Loc, DeclRef); 13326 13327 // Build a full-expression copy expression if initialization 13328 // succeeded and used a non-trivial constructor. Recover from 13329 // errors by pretending that the copy isn't necessary. 13330 if (!Result.isInvalid() && 13331 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13332 ->isTrivial()) { 13333 Result = S.MaybeCreateExprWithCleanups(Result); 13334 CopyExpr = Result.get(); 13335 } 13336 } 13337 } 13338 } 13339 13340 // Actually capture the variable. 13341 if (BuildAndDiagnose) 13342 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13343 SourceLocation(), CaptureType, CopyExpr); 13344 13345 return true; 13346 13347 } 13348 13349 13350 /// \brief Capture the given variable in the captured region. 13351 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13352 VarDecl *Var, 13353 SourceLocation Loc, 13354 const bool BuildAndDiagnose, 13355 QualType &CaptureType, 13356 QualType &DeclRefType, 13357 const bool RefersToCapturedVariable, 13358 Sema &S) { 13359 // By default, capture variables by reference. 13360 bool ByRef = true; 13361 // Using an LValue reference type is consistent with Lambdas (see below). 13362 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13363 if (S.IsOpenMPCapturedDecl(Var)) 13364 DeclRefType = DeclRefType.getUnqualifiedType(); 13365 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13366 } 13367 13368 if (ByRef) 13369 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13370 else 13371 CaptureType = DeclRefType; 13372 13373 Expr *CopyExpr = nullptr; 13374 if (BuildAndDiagnose) { 13375 // The current implementation assumes that all variables are captured 13376 // by references. Since there is no capture by copy, no expression 13377 // evaluation will be needed. 13378 RecordDecl *RD = RSI->TheRecordDecl; 13379 13380 FieldDecl *Field 13381 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13382 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13383 nullptr, false, ICIS_NoInit); 13384 Field->setImplicit(true); 13385 Field->setAccess(AS_private); 13386 RD->addDecl(Field); 13387 13388 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13389 DeclRefType, VK_LValue, Loc); 13390 Var->setReferenced(true); 13391 Var->markUsed(S.Context); 13392 } 13393 13394 // Actually capture the variable. 13395 if (BuildAndDiagnose) 13396 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13397 SourceLocation(), CaptureType, CopyExpr); 13398 13399 13400 return true; 13401 } 13402 13403 /// \brief Create a field within the lambda class for the variable 13404 /// being captured. 13405 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13406 QualType FieldType, QualType DeclRefType, 13407 SourceLocation Loc, 13408 bool RefersToCapturedVariable) { 13409 CXXRecordDecl *Lambda = LSI->Lambda; 13410 13411 // Build the non-static data member. 13412 FieldDecl *Field 13413 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13414 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13415 nullptr, false, ICIS_NoInit); 13416 Field->setImplicit(true); 13417 Field->setAccess(AS_private); 13418 Lambda->addDecl(Field); 13419 } 13420 13421 /// \brief Capture the given variable in the lambda. 13422 static bool captureInLambda(LambdaScopeInfo *LSI, 13423 VarDecl *Var, 13424 SourceLocation Loc, 13425 const bool BuildAndDiagnose, 13426 QualType &CaptureType, 13427 QualType &DeclRefType, 13428 const bool RefersToCapturedVariable, 13429 const Sema::TryCaptureKind Kind, 13430 SourceLocation EllipsisLoc, 13431 const bool IsTopScope, 13432 Sema &S) { 13433 13434 // Determine whether we are capturing by reference or by value. 13435 bool ByRef = false; 13436 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13437 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13438 } else { 13439 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13440 } 13441 13442 // Compute the type of the field that will capture this variable. 13443 if (ByRef) { 13444 // C++11 [expr.prim.lambda]p15: 13445 // An entity is captured by reference if it is implicitly or 13446 // explicitly captured but not captured by copy. It is 13447 // unspecified whether additional unnamed non-static data 13448 // members are declared in the closure type for entities 13449 // captured by reference. 13450 // 13451 // FIXME: It is not clear whether we want to build an lvalue reference 13452 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13453 // to do the former, while EDG does the latter. Core issue 1249 will 13454 // clarify, but for now we follow GCC because it's a more permissive and 13455 // easily defensible position. 13456 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13457 } else { 13458 // C++11 [expr.prim.lambda]p14: 13459 // For each entity captured by copy, an unnamed non-static 13460 // data member is declared in the closure type. The 13461 // declaration order of these members is unspecified. The type 13462 // of such a data member is the type of the corresponding 13463 // captured entity if the entity is not a reference to an 13464 // object, or the referenced type otherwise. [Note: If the 13465 // captured entity is a reference to a function, the 13466 // corresponding data member is also a reference to a 13467 // function. - end note ] 13468 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13469 if (!RefType->getPointeeType()->isFunctionType()) 13470 CaptureType = RefType->getPointeeType(); 13471 } 13472 13473 // Forbid the lambda copy-capture of autoreleasing variables. 13474 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13475 if (BuildAndDiagnose) { 13476 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13477 S.Diag(Var->getLocation(), diag::note_previous_decl) 13478 << Var->getDeclName(); 13479 } 13480 return false; 13481 } 13482 13483 // Make sure that by-copy captures are of a complete and non-abstract type. 13484 if (BuildAndDiagnose) { 13485 if (!CaptureType->isDependentType() && 13486 S.RequireCompleteType(Loc, CaptureType, 13487 diag::err_capture_of_incomplete_type, 13488 Var->getDeclName())) 13489 return false; 13490 13491 if (S.RequireNonAbstractType(Loc, CaptureType, 13492 diag::err_capture_of_abstract_type)) 13493 return false; 13494 } 13495 } 13496 13497 // Capture this variable in the lambda. 13498 if (BuildAndDiagnose) 13499 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13500 RefersToCapturedVariable); 13501 13502 // Compute the type of a reference to this captured variable. 13503 if (ByRef) 13504 DeclRefType = CaptureType.getNonReferenceType(); 13505 else { 13506 // C++ [expr.prim.lambda]p5: 13507 // The closure type for a lambda-expression has a public inline 13508 // function call operator [...]. This function call operator is 13509 // declared const (9.3.1) if and only if the lambda-expression’s 13510 // parameter-declaration-clause is not followed by mutable. 13511 DeclRefType = CaptureType.getNonReferenceType(); 13512 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13513 DeclRefType.addConst(); 13514 } 13515 13516 // Add the capture. 13517 if (BuildAndDiagnose) 13518 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13519 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13520 13521 return true; 13522 } 13523 13524 bool Sema::tryCaptureVariable( 13525 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13526 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13527 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13528 // An init-capture is notionally from the context surrounding its 13529 // declaration, but its parent DC is the lambda class. 13530 DeclContext *VarDC = Var->getDeclContext(); 13531 if (Var->isInitCapture()) 13532 VarDC = VarDC->getParent(); 13533 13534 DeclContext *DC = CurContext; 13535 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13536 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13537 // We need to sync up the Declaration Context with the 13538 // FunctionScopeIndexToStopAt 13539 if (FunctionScopeIndexToStopAt) { 13540 unsigned FSIndex = FunctionScopes.size() - 1; 13541 while (FSIndex != MaxFunctionScopesIndex) { 13542 DC = getLambdaAwareParentOfDeclContext(DC); 13543 --FSIndex; 13544 } 13545 } 13546 13547 13548 // If the variable is declared in the current context, there is no need to 13549 // capture it. 13550 if (VarDC == DC) return true; 13551 13552 // Capture global variables if it is required to use private copy of this 13553 // variable. 13554 bool IsGlobal = !Var->hasLocalStorage(); 13555 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13556 return true; 13557 13558 // Walk up the stack to determine whether we can capture the variable, 13559 // performing the "simple" checks that don't depend on type. We stop when 13560 // we've either hit the declared scope of the variable or find an existing 13561 // capture of that variable. We start from the innermost capturing-entity 13562 // (the DC) and ensure that all intervening capturing-entities 13563 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13564 // declcontext can either capture the variable or have already captured 13565 // the variable. 13566 CaptureType = Var->getType(); 13567 DeclRefType = CaptureType.getNonReferenceType(); 13568 bool Nested = false; 13569 bool Explicit = (Kind != TryCapture_Implicit); 13570 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13571 do { 13572 // Only block literals, captured statements, and lambda expressions can 13573 // capture; other scopes don't work. 13574 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13575 ExprLoc, 13576 BuildAndDiagnose, 13577 *this); 13578 // We need to check for the parent *first* because, if we *have* 13579 // private-captured a global variable, we need to recursively capture it in 13580 // intermediate blocks, lambdas, etc. 13581 if (!ParentDC) { 13582 if (IsGlobal) { 13583 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13584 break; 13585 } 13586 return true; 13587 } 13588 13589 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13590 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13591 13592 13593 // Check whether we've already captured it. 13594 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13595 DeclRefType)) 13596 break; 13597 // If we are instantiating a generic lambda call operator body, 13598 // we do not want to capture new variables. What was captured 13599 // during either a lambdas transformation or initial parsing 13600 // should be used. 13601 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13602 if (BuildAndDiagnose) { 13603 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13604 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13605 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13606 Diag(Var->getLocation(), diag::note_previous_decl) 13607 << Var->getDeclName(); 13608 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13609 } else 13610 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13611 } 13612 return true; 13613 } 13614 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13615 // certain types of variables (unnamed, variably modified types etc.) 13616 // so check for eligibility. 13617 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13618 return true; 13619 13620 // Try to capture variable-length arrays types. 13621 if (Var->getType()->isVariablyModifiedType()) { 13622 // We're going to walk down into the type and look for VLA 13623 // expressions. 13624 QualType QTy = Var->getType(); 13625 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13626 QTy = PVD->getOriginalType(); 13627 captureVariablyModifiedType(Context, QTy, CSI); 13628 } 13629 13630 if (getLangOpts().OpenMP) { 13631 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13632 // OpenMP private variables should not be captured in outer scope, so 13633 // just break here. Similarly, global variables that are captured in a 13634 // target region should not be captured outside the scope of the region. 13635 if (RSI->CapRegionKind == CR_OpenMP) { 13636 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13637 // When we detect target captures we are looking from inside the 13638 // target region, therefore we need to propagate the capture from the 13639 // enclosing region. Therefore, the capture is not initially nested. 13640 if (IsTargetCap) 13641 FunctionScopesIndex--; 13642 13643 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13644 Nested = !IsTargetCap; 13645 DeclRefType = DeclRefType.getUnqualifiedType(); 13646 CaptureType = Context.getLValueReferenceType(DeclRefType); 13647 break; 13648 } 13649 } 13650 } 13651 } 13652 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13653 // No capture-default, and this is not an explicit capture 13654 // so cannot capture this variable. 13655 if (BuildAndDiagnose) { 13656 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13657 Diag(Var->getLocation(), diag::note_previous_decl) 13658 << Var->getDeclName(); 13659 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13660 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13661 diag::note_lambda_decl); 13662 // FIXME: If we error out because an outer lambda can not implicitly 13663 // capture a variable that an inner lambda explicitly captures, we 13664 // should have the inner lambda do the explicit capture - because 13665 // it makes for cleaner diagnostics later. This would purely be done 13666 // so that the diagnostic does not misleadingly claim that a variable 13667 // can not be captured by a lambda implicitly even though it is captured 13668 // explicitly. Suggestion: 13669 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13670 // at the function head 13671 // - cache the StartingDeclContext - this must be a lambda 13672 // - captureInLambda in the innermost lambda the variable. 13673 } 13674 return true; 13675 } 13676 13677 FunctionScopesIndex--; 13678 DC = ParentDC; 13679 Explicit = false; 13680 } while (!VarDC->Equals(DC)); 13681 13682 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13683 // computing the type of the capture at each step, checking type-specific 13684 // requirements, and adding captures if requested. 13685 // If the variable had already been captured previously, we start capturing 13686 // at the lambda nested within that one. 13687 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13688 ++I) { 13689 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13690 13691 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13692 if (!captureInBlock(BSI, Var, ExprLoc, 13693 BuildAndDiagnose, CaptureType, 13694 DeclRefType, Nested, *this)) 13695 return true; 13696 Nested = true; 13697 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13698 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13699 BuildAndDiagnose, CaptureType, 13700 DeclRefType, Nested, *this)) 13701 return true; 13702 Nested = true; 13703 } else { 13704 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13705 if (!captureInLambda(LSI, Var, ExprLoc, 13706 BuildAndDiagnose, CaptureType, 13707 DeclRefType, Nested, Kind, EllipsisLoc, 13708 /*IsTopScope*/I == N - 1, *this)) 13709 return true; 13710 Nested = true; 13711 } 13712 } 13713 return false; 13714 } 13715 13716 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13717 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13718 QualType CaptureType; 13719 QualType DeclRefType; 13720 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13721 /*BuildAndDiagnose=*/true, CaptureType, 13722 DeclRefType, nullptr); 13723 } 13724 13725 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13726 QualType CaptureType; 13727 QualType DeclRefType; 13728 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13729 /*BuildAndDiagnose=*/false, CaptureType, 13730 DeclRefType, nullptr); 13731 } 13732 13733 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13734 QualType CaptureType; 13735 QualType DeclRefType; 13736 13737 // Determine whether we can capture this variable. 13738 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13739 /*BuildAndDiagnose=*/false, CaptureType, 13740 DeclRefType, nullptr)) 13741 return QualType(); 13742 13743 return DeclRefType; 13744 } 13745 13746 13747 13748 // If either the type of the variable or the initializer is dependent, 13749 // return false. Otherwise, determine whether the variable is a constant 13750 // expression. Use this if you need to know if a variable that might or 13751 // might not be dependent is truly a constant expression. 13752 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13753 ASTContext &Context) { 13754 13755 if (Var->getType()->isDependentType()) 13756 return false; 13757 const VarDecl *DefVD = nullptr; 13758 Var->getAnyInitializer(DefVD); 13759 if (!DefVD) 13760 return false; 13761 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13762 Expr *Init = cast<Expr>(Eval->Value); 13763 if (Init->isValueDependent()) 13764 return false; 13765 return IsVariableAConstantExpression(Var, Context); 13766 } 13767 13768 13769 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13770 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13771 // an object that satisfies the requirements for appearing in a 13772 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13773 // is immediately applied." This function handles the lvalue-to-rvalue 13774 // conversion part. 13775 MaybeODRUseExprs.erase(E->IgnoreParens()); 13776 13777 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13778 // to a variable that is a constant expression, and if so, identify it as 13779 // a reference to a variable that does not involve an odr-use of that 13780 // variable. 13781 if (LambdaScopeInfo *LSI = getCurLambda()) { 13782 Expr *SansParensExpr = E->IgnoreParens(); 13783 VarDecl *Var = nullptr; 13784 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13785 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13786 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13787 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13788 13789 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13790 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13791 } 13792 } 13793 13794 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13795 Res = CorrectDelayedTyposInExpr(Res); 13796 13797 if (!Res.isUsable()) 13798 return Res; 13799 13800 // If a constant-expression is a reference to a variable where we delay 13801 // deciding whether it is an odr-use, just assume we will apply the 13802 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13803 // (a non-type template argument), we have special handling anyway. 13804 UpdateMarkingForLValueToRValue(Res.get()); 13805 return Res; 13806 } 13807 13808 void Sema::CleanupVarDeclMarking() { 13809 for (Expr *E : MaybeODRUseExprs) { 13810 VarDecl *Var; 13811 SourceLocation Loc; 13812 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13813 Var = cast<VarDecl>(DRE->getDecl()); 13814 Loc = DRE->getLocation(); 13815 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13816 Var = cast<VarDecl>(ME->getMemberDecl()); 13817 Loc = ME->getMemberLoc(); 13818 } else { 13819 llvm_unreachable("Unexpected expression"); 13820 } 13821 13822 MarkVarDeclODRUsed(Var, Loc, *this, 13823 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13824 } 13825 13826 MaybeODRUseExprs.clear(); 13827 } 13828 13829 13830 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13831 VarDecl *Var, Expr *E) { 13832 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13833 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13834 Var->setReferenced(); 13835 13836 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13837 bool MarkODRUsed = true; 13838 13839 // If the context is not potentially evaluated, this is not an odr-use and 13840 // does not trigger instantiation. 13841 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13842 if (SemaRef.isUnevaluatedContext()) 13843 return; 13844 13845 // If we don't yet know whether this context is going to end up being an 13846 // evaluated context, and we're referencing a variable from an enclosing 13847 // scope, add a potential capture. 13848 // 13849 // FIXME: Is this necessary? These contexts are only used for default 13850 // arguments, where local variables can't be used. 13851 const bool RefersToEnclosingScope = 13852 (SemaRef.CurContext != Var->getDeclContext() && 13853 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13854 if (RefersToEnclosingScope) { 13855 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13856 // If a variable could potentially be odr-used, defer marking it so 13857 // until we finish analyzing the full expression for any 13858 // lvalue-to-rvalue 13859 // or discarded value conversions that would obviate odr-use. 13860 // Add it to the list of potential captures that will be analyzed 13861 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13862 // unless the variable is a reference that was initialized by a constant 13863 // expression (this will never need to be captured or odr-used). 13864 assert(E && "Capture variable should be used in an expression."); 13865 if (!Var->getType()->isReferenceType() || 13866 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13867 LSI->addPotentialCapture(E->IgnoreParens()); 13868 } 13869 } 13870 13871 if (!isTemplateInstantiation(TSK)) 13872 return; 13873 13874 // Instantiate, but do not mark as odr-used, variable templates. 13875 MarkODRUsed = false; 13876 } 13877 13878 VarTemplateSpecializationDecl *VarSpec = 13879 dyn_cast<VarTemplateSpecializationDecl>(Var); 13880 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13881 "Can't instantiate a partial template specialization."); 13882 13883 // If this might be a member specialization of a static data member, check 13884 // the specialization is visible. We already did the checks for variable 13885 // template specializations when we created them. 13886 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 13887 SemaRef.checkSpecializationVisibility(Loc, Var); 13888 13889 // Perform implicit instantiation of static data members, static data member 13890 // templates of class templates, and variable template specializations. Delay 13891 // instantiations of variable templates, except for those that could be used 13892 // in a constant expression. 13893 if (isTemplateInstantiation(TSK)) { 13894 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13895 13896 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13897 if (Var->getPointOfInstantiation().isInvalid()) { 13898 // This is a modification of an existing AST node. Notify listeners. 13899 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13900 L->StaticDataMemberInstantiated(Var); 13901 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13902 // Don't bother trying to instantiate it again, unless we might need 13903 // its initializer before we get to the end of the TU. 13904 TryInstantiating = false; 13905 } 13906 13907 if (Var->getPointOfInstantiation().isInvalid()) 13908 Var->setTemplateSpecializationKind(TSK, Loc); 13909 13910 if (TryInstantiating) { 13911 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13912 bool InstantiationDependent = false; 13913 bool IsNonDependent = 13914 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13915 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13916 : true; 13917 13918 // Do not instantiate specializations that are still type-dependent. 13919 if (IsNonDependent) { 13920 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13921 // Do not defer instantiations of variables which could be used in a 13922 // constant expression. 13923 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13924 } else { 13925 SemaRef.PendingInstantiations 13926 .push_back(std::make_pair(Var, PointOfInstantiation)); 13927 } 13928 } 13929 } 13930 } 13931 13932 if (!MarkODRUsed) 13933 return; 13934 13935 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13936 // the requirements for appearing in a constant expression (5.19) and, if 13937 // it is an object, the lvalue-to-rvalue conversion (4.1) 13938 // is immediately applied." We check the first part here, and 13939 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13940 // Note that we use the C++11 definition everywhere because nothing in 13941 // C++03 depends on whether we get the C++03 version correct. The second 13942 // part does not apply to references, since they are not objects. 13943 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13944 // A reference initialized by a constant expression can never be 13945 // odr-used, so simply ignore it. 13946 if (!Var->getType()->isReferenceType()) 13947 SemaRef.MaybeODRUseExprs.insert(E); 13948 } else 13949 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13950 /*MaxFunctionScopeIndex ptr*/ nullptr); 13951 } 13952 13953 /// \brief Mark a variable referenced, and check whether it is odr-used 13954 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13955 /// used directly for normal expressions referring to VarDecl. 13956 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13957 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13958 } 13959 13960 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13961 Decl *D, Expr *E, bool MightBeOdrUse) { 13962 if (SemaRef.isInOpenMPDeclareTargetContext()) 13963 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 13964 13965 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13966 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13967 return; 13968 } 13969 13970 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 13971 13972 // If this is a call to a method via a cast, also mark the method in the 13973 // derived class used in case codegen can devirtualize the call. 13974 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13975 if (!ME) 13976 return; 13977 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13978 if (!MD) 13979 return; 13980 // Only attempt to devirtualize if this is truly a virtual call. 13981 bool IsVirtualCall = MD->isVirtual() && 13982 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13983 if (!IsVirtualCall) 13984 return; 13985 const Expr *Base = ME->getBase(); 13986 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13987 if (!MostDerivedClassDecl) 13988 return; 13989 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13990 if (!DM || DM->isPure()) 13991 return; 13992 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 13993 } 13994 13995 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13996 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13997 // TODO: update this with DR# once a defect report is filed. 13998 // C++11 defect. The address of a pure member should not be an ODR use, even 13999 // if it's a qualified reference. 14000 bool OdrUse = true; 14001 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14002 if (Method->isVirtual()) 14003 OdrUse = false; 14004 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14005 } 14006 14007 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14008 void Sema::MarkMemberReferenced(MemberExpr *E) { 14009 // C++11 [basic.def.odr]p2: 14010 // A non-overloaded function whose name appears as a potentially-evaluated 14011 // expression or a member of a set of candidate functions, if selected by 14012 // overload resolution when referred to from a potentially-evaluated 14013 // expression, is odr-used, unless it is a pure virtual function and its 14014 // name is not explicitly qualified. 14015 bool MightBeOdrUse = true; 14016 if (E->performsVirtualDispatch(getLangOpts())) { 14017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14018 if (Method->isPure()) 14019 MightBeOdrUse = false; 14020 } 14021 SourceLocation Loc = E->getMemberLoc().isValid() ? 14022 E->getMemberLoc() : E->getLocStart(); 14023 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14024 } 14025 14026 /// \brief Perform marking for a reference to an arbitrary declaration. It 14027 /// marks the declaration referenced, and performs odr-use checking for 14028 /// functions and variables. This method should not be used when building a 14029 /// normal expression which refers to a variable. 14030 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14031 bool MightBeOdrUse) { 14032 if (MightBeOdrUse) { 14033 if (auto *VD = dyn_cast<VarDecl>(D)) { 14034 MarkVariableReferenced(Loc, VD); 14035 return; 14036 } 14037 } 14038 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14039 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14040 return; 14041 } 14042 D->setReferenced(); 14043 } 14044 14045 namespace { 14046 // Mark all of the declarations referenced 14047 // FIXME: Not fully implemented yet! We need to have a better understanding 14048 // of when we're entering 14049 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14050 Sema &S; 14051 SourceLocation Loc; 14052 14053 public: 14054 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14055 14056 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14057 14058 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14059 bool TraverseRecordType(RecordType *T); 14060 }; 14061 } 14062 14063 bool MarkReferencedDecls::TraverseTemplateArgument( 14064 const TemplateArgument &Arg) { 14065 if (Arg.getKind() == TemplateArgument::Declaration) { 14066 if (Decl *D = Arg.getAsDecl()) 14067 S.MarkAnyDeclReferenced(Loc, D, true); 14068 } 14069 14070 return Inherited::TraverseTemplateArgument(Arg); 14071 } 14072 14073 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14074 if (ClassTemplateSpecializationDecl *Spec 14075 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14076 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14077 return TraverseTemplateArguments(Args.data(), Args.size()); 14078 } 14079 14080 return true; 14081 } 14082 14083 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14084 MarkReferencedDecls Marker(*this, Loc); 14085 Marker.TraverseType(Context.getCanonicalType(T)); 14086 } 14087 14088 namespace { 14089 /// \brief Helper class that marks all of the declarations referenced by 14090 /// potentially-evaluated subexpressions as "referenced". 14091 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14092 Sema &S; 14093 bool SkipLocalVariables; 14094 14095 public: 14096 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14097 14098 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14099 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14100 14101 void VisitDeclRefExpr(DeclRefExpr *E) { 14102 // If we were asked not to visit local variables, don't. 14103 if (SkipLocalVariables) { 14104 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14105 if (VD->hasLocalStorage()) 14106 return; 14107 } 14108 14109 S.MarkDeclRefReferenced(E); 14110 } 14111 14112 void VisitMemberExpr(MemberExpr *E) { 14113 S.MarkMemberReferenced(E); 14114 Inherited::VisitMemberExpr(E); 14115 } 14116 14117 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14118 S.MarkFunctionReferenced(E->getLocStart(), 14119 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14120 Visit(E->getSubExpr()); 14121 } 14122 14123 void VisitCXXNewExpr(CXXNewExpr *E) { 14124 if (E->getOperatorNew()) 14125 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14126 if (E->getOperatorDelete()) 14127 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14128 Inherited::VisitCXXNewExpr(E); 14129 } 14130 14131 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14132 if (E->getOperatorDelete()) 14133 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14134 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14135 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14136 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14137 S.MarkFunctionReferenced(E->getLocStart(), 14138 S.LookupDestructor(Record)); 14139 } 14140 14141 Inherited::VisitCXXDeleteExpr(E); 14142 } 14143 14144 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14145 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14146 Inherited::VisitCXXConstructExpr(E); 14147 } 14148 14149 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14150 Visit(E->getExpr()); 14151 } 14152 14153 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14154 Inherited::VisitImplicitCastExpr(E); 14155 14156 if (E->getCastKind() == CK_LValueToRValue) 14157 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14158 } 14159 }; 14160 } 14161 14162 /// \brief Mark any declarations that appear within this expression or any 14163 /// potentially-evaluated subexpressions as "referenced". 14164 /// 14165 /// \param SkipLocalVariables If true, don't mark local variables as 14166 /// 'referenced'. 14167 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14168 bool SkipLocalVariables) { 14169 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14170 } 14171 14172 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14173 /// of the program being compiled. 14174 /// 14175 /// This routine emits the given diagnostic when the code currently being 14176 /// type-checked is "potentially evaluated", meaning that there is a 14177 /// possibility that the code will actually be executable. Code in sizeof() 14178 /// expressions, code used only during overload resolution, etc., are not 14179 /// potentially evaluated. This routine will suppress such diagnostics or, 14180 /// in the absolutely nutty case of potentially potentially evaluated 14181 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14182 /// later. 14183 /// 14184 /// This routine should be used for all diagnostics that describe the run-time 14185 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14186 /// Failure to do so will likely result in spurious diagnostics or failures 14187 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14188 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14189 const PartialDiagnostic &PD) { 14190 switch (ExprEvalContexts.back().Context) { 14191 case Unevaluated: 14192 case UnevaluatedAbstract: 14193 case DiscardedStatement: 14194 // The argument will never be evaluated, so don't complain. 14195 break; 14196 14197 case ConstantEvaluated: 14198 // Relevant diagnostics should be produced by constant evaluation. 14199 break; 14200 14201 case PotentiallyEvaluated: 14202 case PotentiallyEvaluatedIfUsed: 14203 if (Statement && getCurFunctionOrMethodDecl()) { 14204 FunctionScopes.back()->PossiblyUnreachableDiags. 14205 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14206 } 14207 else 14208 Diag(Loc, PD); 14209 14210 return true; 14211 } 14212 14213 return false; 14214 } 14215 14216 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14217 CallExpr *CE, FunctionDecl *FD) { 14218 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14219 return false; 14220 14221 // If we're inside a decltype's expression, don't check for a valid return 14222 // type or construct temporaries until we know whether this is the last call. 14223 if (ExprEvalContexts.back().IsDecltype) { 14224 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14225 return false; 14226 } 14227 14228 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14229 FunctionDecl *FD; 14230 CallExpr *CE; 14231 14232 public: 14233 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14234 : FD(FD), CE(CE) { } 14235 14236 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14237 if (!FD) { 14238 S.Diag(Loc, diag::err_call_incomplete_return) 14239 << T << CE->getSourceRange(); 14240 return; 14241 } 14242 14243 S.Diag(Loc, diag::err_call_function_incomplete_return) 14244 << CE->getSourceRange() << FD->getDeclName() << T; 14245 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14246 << FD->getDeclName(); 14247 } 14248 } Diagnoser(FD, CE); 14249 14250 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14251 return true; 14252 14253 return false; 14254 } 14255 14256 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14257 // will prevent this condition from triggering, which is what we want. 14258 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14259 SourceLocation Loc; 14260 14261 unsigned diagnostic = diag::warn_condition_is_assignment; 14262 bool IsOrAssign = false; 14263 14264 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14265 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14266 return; 14267 14268 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14269 14270 // Greylist some idioms by putting them into a warning subcategory. 14271 if (ObjCMessageExpr *ME 14272 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14273 Selector Sel = ME->getSelector(); 14274 14275 // self = [<foo> init...] 14276 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14277 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14278 14279 // <foo> = [<bar> nextObject] 14280 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14281 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14282 } 14283 14284 Loc = Op->getOperatorLoc(); 14285 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14286 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14287 return; 14288 14289 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14290 Loc = Op->getOperatorLoc(); 14291 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14292 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14293 else { 14294 // Not an assignment. 14295 return; 14296 } 14297 14298 Diag(Loc, diagnostic) << E->getSourceRange(); 14299 14300 SourceLocation Open = E->getLocStart(); 14301 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14302 Diag(Loc, diag::note_condition_assign_silence) 14303 << FixItHint::CreateInsertion(Open, "(") 14304 << FixItHint::CreateInsertion(Close, ")"); 14305 14306 if (IsOrAssign) 14307 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14308 << FixItHint::CreateReplacement(Loc, "!="); 14309 else 14310 Diag(Loc, diag::note_condition_assign_to_comparison) 14311 << FixItHint::CreateReplacement(Loc, "=="); 14312 } 14313 14314 /// \brief Redundant parentheses over an equality comparison can indicate 14315 /// that the user intended an assignment used as condition. 14316 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14317 // Don't warn if the parens came from a macro. 14318 SourceLocation parenLoc = ParenE->getLocStart(); 14319 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14320 return; 14321 // Don't warn for dependent expressions. 14322 if (ParenE->isTypeDependent()) 14323 return; 14324 14325 Expr *E = ParenE->IgnoreParens(); 14326 14327 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14328 if (opE->getOpcode() == BO_EQ && 14329 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14330 == Expr::MLV_Valid) { 14331 SourceLocation Loc = opE->getOperatorLoc(); 14332 14333 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14334 SourceRange ParenERange = ParenE->getSourceRange(); 14335 Diag(Loc, diag::note_equality_comparison_silence) 14336 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14337 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14338 Diag(Loc, diag::note_equality_comparison_to_assign) 14339 << FixItHint::CreateReplacement(Loc, "="); 14340 } 14341 } 14342 14343 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14344 bool IsConstexpr) { 14345 DiagnoseAssignmentAsCondition(E); 14346 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14347 DiagnoseEqualityWithExtraParens(parenE); 14348 14349 ExprResult result = CheckPlaceholderExpr(E); 14350 if (result.isInvalid()) return ExprError(); 14351 E = result.get(); 14352 14353 if (!E->isTypeDependent()) { 14354 if (getLangOpts().CPlusPlus) 14355 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14356 14357 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14358 if (ERes.isInvalid()) 14359 return ExprError(); 14360 E = ERes.get(); 14361 14362 QualType T = E->getType(); 14363 if (!T->isScalarType()) { // C99 6.8.4.1p1 14364 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14365 << T << E->getSourceRange(); 14366 return ExprError(); 14367 } 14368 CheckBoolLikeConversion(E, Loc); 14369 } 14370 14371 return E; 14372 } 14373 14374 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14375 Expr *SubExpr, ConditionKind CK) { 14376 // Empty conditions are valid in for-statements. 14377 if (!SubExpr) 14378 return ConditionResult(); 14379 14380 ExprResult Cond; 14381 switch (CK) { 14382 case ConditionKind::Boolean: 14383 Cond = CheckBooleanCondition(Loc, SubExpr); 14384 break; 14385 14386 case ConditionKind::ConstexprIf: 14387 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14388 break; 14389 14390 case ConditionKind::Switch: 14391 Cond = CheckSwitchCondition(Loc, SubExpr); 14392 break; 14393 } 14394 if (Cond.isInvalid()) 14395 return ConditionError(); 14396 14397 return ConditionResult(*this, nullptr, MakeFullExpr(Cond.get(), Loc), 14398 CK == ConditionKind::ConstexprIf); 14399 } 14400 14401 namespace { 14402 /// A visitor for rebuilding a call to an __unknown_any expression 14403 /// to have an appropriate type. 14404 struct RebuildUnknownAnyFunction 14405 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14406 14407 Sema &S; 14408 14409 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14410 14411 ExprResult VisitStmt(Stmt *S) { 14412 llvm_unreachable("unexpected statement!"); 14413 } 14414 14415 ExprResult VisitExpr(Expr *E) { 14416 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14417 << E->getSourceRange(); 14418 return ExprError(); 14419 } 14420 14421 /// Rebuild an expression which simply semantically wraps another 14422 /// expression which it shares the type and value kind of. 14423 template <class T> ExprResult rebuildSugarExpr(T *E) { 14424 ExprResult SubResult = Visit(E->getSubExpr()); 14425 if (SubResult.isInvalid()) return ExprError(); 14426 14427 Expr *SubExpr = SubResult.get(); 14428 E->setSubExpr(SubExpr); 14429 E->setType(SubExpr->getType()); 14430 E->setValueKind(SubExpr->getValueKind()); 14431 assert(E->getObjectKind() == OK_Ordinary); 14432 return E; 14433 } 14434 14435 ExprResult VisitParenExpr(ParenExpr *E) { 14436 return rebuildSugarExpr(E); 14437 } 14438 14439 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14440 return rebuildSugarExpr(E); 14441 } 14442 14443 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14444 ExprResult SubResult = Visit(E->getSubExpr()); 14445 if (SubResult.isInvalid()) return ExprError(); 14446 14447 Expr *SubExpr = SubResult.get(); 14448 E->setSubExpr(SubExpr); 14449 E->setType(S.Context.getPointerType(SubExpr->getType())); 14450 assert(E->getValueKind() == VK_RValue); 14451 assert(E->getObjectKind() == OK_Ordinary); 14452 return E; 14453 } 14454 14455 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14456 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14457 14458 E->setType(VD->getType()); 14459 14460 assert(E->getValueKind() == VK_RValue); 14461 if (S.getLangOpts().CPlusPlus && 14462 !(isa<CXXMethodDecl>(VD) && 14463 cast<CXXMethodDecl>(VD)->isInstance())) 14464 E->setValueKind(VK_LValue); 14465 14466 return E; 14467 } 14468 14469 ExprResult VisitMemberExpr(MemberExpr *E) { 14470 return resolveDecl(E, E->getMemberDecl()); 14471 } 14472 14473 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14474 return resolveDecl(E, E->getDecl()); 14475 } 14476 }; 14477 } 14478 14479 /// Given a function expression of unknown-any type, try to rebuild it 14480 /// to have a function type. 14481 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14482 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14483 if (Result.isInvalid()) return ExprError(); 14484 return S.DefaultFunctionArrayConversion(Result.get()); 14485 } 14486 14487 namespace { 14488 /// A visitor for rebuilding an expression of type __unknown_anytype 14489 /// into one which resolves the type directly on the referring 14490 /// expression. Strict preservation of the original source 14491 /// structure is not a goal. 14492 struct RebuildUnknownAnyExpr 14493 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14494 14495 Sema &S; 14496 14497 /// The current destination type. 14498 QualType DestType; 14499 14500 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14501 : S(S), DestType(CastType) {} 14502 14503 ExprResult VisitStmt(Stmt *S) { 14504 llvm_unreachable("unexpected statement!"); 14505 } 14506 14507 ExprResult VisitExpr(Expr *E) { 14508 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14509 << E->getSourceRange(); 14510 return ExprError(); 14511 } 14512 14513 ExprResult VisitCallExpr(CallExpr *E); 14514 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14515 14516 /// Rebuild an expression which simply semantically wraps another 14517 /// expression which it shares the type and value kind of. 14518 template <class T> ExprResult rebuildSugarExpr(T *E) { 14519 ExprResult SubResult = Visit(E->getSubExpr()); 14520 if (SubResult.isInvalid()) return ExprError(); 14521 Expr *SubExpr = SubResult.get(); 14522 E->setSubExpr(SubExpr); 14523 E->setType(SubExpr->getType()); 14524 E->setValueKind(SubExpr->getValueKind()); 14525 assert(E->getObjectKind() == OK_Ordinary); 14526 return E; 14527 } 14528 14529 ExprResult VisitParenExpr(ParenExpr *E) { 14530 return rebuildSugarExpr(E); 14531 } 14532 14533 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14534 return rebuildSugarExpr(E); 14535 } 14536 14537 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14538 const PointerType *Ptr = DestType->getAs<PointerType>(); 14539 if (!Ptr) { 14540 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14541 << E->getSourceRange(); 14542 return ExprError(); 14543 } 14544 assert(E->getValueKind() == VK_RValue); 14545 assert(E->getObjectKind() == OK_Ordinary); 14546 E->setType(DestType); 14547 14548 // Build the sub-expression as if it were an object of the pointee type. 14549 DestType = Ptr->getPointeeType(); 14550 ExprResult SubResult = Visit(E->getSubExpr()); 14551 if (SubResult.isInvalid()) return ExprError(); 14552 E->setSubExpr(SubResult.get()); 14553 return E; 14554 } 14555 14556 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14557 14558 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14559 14560 ExprResult VisitMemberExpr(MemberExpr *E) { 14561 return resolveDecl(E, E->getMemberDecl()); 14562 } 14563 14564 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14565 return resolveDecl(E, E->getDecl()); 14566 } 14567 }; 14568 } 14569 14570 /// Rebuilds a call expression which yielded __unknown_anytype. 14571 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14572 Expr *CalleeExpr = E->getCallee(); 14573 14574 enum FnKind { 14575 FK_MemberFunction, 14576 FK_FunctionPointer, 14577 FK_BlockPointer 14578 }; 14579 14580 FnKind Kind; 14581 QualType CalleeType = CalleeExpr->getType(); 14582 if (CalleeType == S.Context.BoundMemberTy) { 14583 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14584 Kind = FK_MemberFunction; 14585 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14586 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14587 CalleeType = Ptr->getPointeeType(); 14588 Kind = FK_FunctionPointer; 14589 } else { 14590 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14591 Kind = FK_BlockPointer; 14592 } 14593 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14594 14595 // Verify that this is a legal result type of a function. 14596 if (DestType->isArrayType() || DestType->isFunctionType()) { 14597 unsigned diagID = diag::err_func_returning_array_function; 14598 if (Kind == FK_BlockPointer) 14599 diagID = diag::err_block_returning_array_function; 14600 14601 S.Diag(E->getExprLoc(), diagID) 14602 << DestType->isFunctionType() << DestType; 14603 return ExprError(); 14604 } 14605 14606 // Otherwise, go ahead and set DestType as the call's result. 14607 E->setType(DestType.getNonLValueExprType(S.Context)); 14608 E->setValueKind(Expr::getValueKindForType(DestType)); 14609 assert(E->getObjectKind() == OK_Ordinary); 14610 14611 // Rebuild the function type, replacing the result type with DestType. 14612 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14613 if (Proto) { 14614 // __unknown_anytype(...) is a special case used by the debugger when 14615 // it has no idea what a function's signature is. 14616 // 14617 // We want to build this call essentially under the K&R 14618 // unprototyped rules, but making a FunctionNoProtoType in C++ 14619 // would foul up all sorts of assumptions. However, we cannot 14620 // simply pass all arguments as variadic arguments, nor can we 14621 // portably just call the function under a non-variadic type; see 14622 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14623 // However, it turns out that in practice it is generally safe to 14624 // call a function declared as "A foo(B,C,D);" under the prototype 14625 // "A foo(B,C,D,...);". The only known exception is with the 14626 // Windows ABI, where any variadic function is implicitly cdecl 14627 // regardless of its normal CC. Therefore we change the parameter 14628 // types to match the types of the arguments. 14629 // 14630 // This is a hack, but it is far superior to moving the 14631 // corresponding target-specific code from IR-gen to Sema/AST. 14632 14633 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14634 SmallVector<QualType, 8> ArgTypes; 14635 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14636 ArgTypes.reserve(E->getNumArgs()); 14637 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14638 Expr *Arg = E->getArg(i); 14639 QualType ArgType = Arg->getType(); 14640 if (E->isLValue()) { 14641 ArgType = S.Context.getLValueReferenceType(ArgType); 14642 } else if (E->isXValue()) { 14643 ArgType = S.Context.getRValueReferenceType(ArgType); 14644 } 14645 ArgTypes.push_back(ArgType); 14646 } 14647 ParamTypes = ArgTypes; 14648 } 14649 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14650 Proto->getExtProtoInfo()); 14651 } else { 14652 DestType = S.Context.getFunctionNoProtoType(DestType, 14653 FnType->getExtInfo()); 14654 } 14655 14656 // Rebuild the appropriate pointer-to-function type. 14657 switch (Kind) { 14658 case FK_MemberFunction: 14659 // Nothing to do. 14660 break; 14661 14662 case FK_FunctionPointer: 14663 DestType = S.Context.getPointerType(DestType); 14664 break; 14665 14666 case FK_BlockPointer: 14667 DestType = S.Context.getBlockPointerType(DestType); 14668 break; 14669 } 14670 14671 // Finally, we can recurse. 14672 ExprResult CalleeResult = Visit(CalleeExpr); 14673 if (!CalleeResult.isUsable()) return ExprError(); 14674 E->setCallee(CalleeResult.get()); 14675 14676 // Bind a temporary if necessary. 14677 return S.MaybeBindToTemporary(E); 14678 } 14679 14680 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14681 // Verify that this is a legal result type of a call. 14682 if (DestType->isArrayType() || DestType->isFunctionType()) { 14683 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14684 << DestType->isFunctionType() << DestType; 14685 return ExprError(); 14686 } 14687 14688 // Rewrite the method result type if available. 14689 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14690 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14691 Method->setReturnType(DestType); 14692 } 14693 14694 // Change the type of the message. 14695 E->setType(DestType.getNonReferenceType()); 14696 E->setValueKind(Expr::getValueKindForType(DestType)); 14697 14698 return S.MaybeBindToTemporary(E); 14699 } 14700 14701 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14702 // The only case we should ever see here is a function-to-pointer decay. 14703 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14704 assert(E->getValueKind() == VK_RValue); 14705 assert(E->getObjectKind() == OK_Ordinary); 14706 14707 E->setType(DestType); 14708 14709 // Rebuild the sub-expression as the pointee (function) type. 14710 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14711 14712 ExprResult Result = Visit(E->getSubExpr()); 14713 if (!Result.isUsable()) return ExprError(); 14714 14715 E->setSubExpr(Result.get()); 14716 return E; 14717 } else if (E->getCastKind() == CK_LValueToRValue) { 14718 assert(E->getValueKind() == VK_RValue); 14719 assert(E->getObjectKind() == OK_Ordinary); 14720 14721 assert(isa<BlockPointerType>(E->getType())); 14722 14723 E->setType(DestType); 14724 14725 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14726 DestType = S.Context.getLValueReferenceType(DestType); 14727 14728 ExprResult Result = Visit(E->getSubExpr()); 14729 if (!Result.isUsable()) return ExprError(); 14730 14731 E->setSubExpr(Result.get()); 14732 return E; 14733 } else { 14734 llvm_unreachable("Unhandled cast type!"); 14735 } 14736 } 14737 14738 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14739 ExprValueKind ValueKind = VK_LValue; 14740 QualType Type = DestType; 14741 14742 // We know how to make this work for certain kinds of decls: 14743 14744 // - functions 14745 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14746 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14747 DestType = Ptr->getPointeeType(); 14748 ExprResult Result = resolveDecl(E, VD); 14749 if (Result.isInvalid()) return ExprError(); 14750 return S.ImpCastExprToType(Result.get(), Type, 14751 CK_FunctionToPointerDecay, VK_RValue); 14752 } 14753 14754 if (!Type->isFunctionType()) { 14755 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14756 << VD << E->getSourceRange(); 14757 return ExprError(); 14758 } 14759 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14760 // We must match the FunctionDecl's type to the hack introduced in 14761 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14762 // type. See the lengthy commentary in that routine. 14763 QualType FDT = FD->getType(); 14764 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14765 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14766 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14767 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14768 SourceLocation Loc = FD->getLocation(); 14769 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14770 FD->getDeclContext(), 14771 Loc, Loc, FD->getNameInfo().getName(), 14772 DestType, FD->getTypeSourceInfo(), 14773 SC_None, false/*isInlineSpecified*/, 14774 FD->hasPrototype(), 14775 false/*isConstexprSpecified*/); 14776 14777 if (FD->getQualifier()) 14778 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14779 14780 SmallVector<ParmVarDecl*, 16> Params; 14781 for (const auto &AI : FT->param_types()) { 14782 ParmVarDecl *Param = 14783 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14784 Param->setScopeInfo(0, Params.size()); 14785 Params.push_back(Param); 14786 } 14787 NewFD->setParams(Params); 14788 DRE->setDecl(NewFD); 14789 VD = DRE->getDecl(); 14790 } 14791 } 14792 14793 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14794 if (MD->isInstance()) { 14795 ValueKind = VK_RValue; 14796 Type = S.Context.BoundMemberTy; 14797 } 14798 14799 // Function references aren't l-values in C. 14800 if (!S.getLangOpts().CPlusPlus) 14801 ValueKind = VK_RValue; 14802 14803 // - variables 14804 } else if (isa<VarDecl>(VD)) { 14805 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14806 Type = RefTy->getPointeeType(); 14807 } else if (Type->isFunctionType()) { 14808 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14809 << VD << E->getSourceRange(); 14810 return ExprError(); 14811 } 14812 14813 // - nothing else 14814 } else { 14815 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14816 << VD << E->getSourceRange(); 14817 return ExprError(); 14818 } 14819 14820 // Modifying the declaration like this is friendly to IR-gen but 14821 // also really dangerous. 14822 VD->setType(DestType); 14823 E->setType(Type); 14824 E->setValueKind(ValueKind); 14825 return E; 14826 } 14827 14828 /// Check a cast of an unknown-any type. We intentionally only 14829 /// trigger this for C-style casts. 14830 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14831 Expr *CastExpr, CastKind &CastKind, 14832 ExprValueKind &VK, CXXCastPath &Path) { 14833 // The type we're casting to must be either void or complete. 14834 if (!CastType->isVoidType() && 14835 RequireCompleteType(TypeRange.getBegin(), CastType, 14836 diag::err_typecheck_cast_to_incomplete)) 14837 return ExprError(); 14838 14839 // Rewrite the casted expression from scratch. 14840 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14841 if (!result.isUsable()) return ExprError(); 14842 14843 CastExpr = result.get(); 14844 VK = CastExpr->getValueKind(); 14845 CastKind = CK_NoOp; 14846 14847 return CastExpr; 14848 } 14849 14850 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14851 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14852 } 14853 14854 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14855 Expr *arg, QualType ¶mType) { 14856 // If the syntactic form of the argument is not an explicit cast of 14857 // any sort, just do default argument promotion. 14858 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14859 if (!castArg) { 14860 ExprResult result = DefaultArgumentPromotion(arg); 14861 if (result.isInvalid()) return ExprError(); 14862 paramType = result.get()->getType(); 14863 return result; 14864 } 14865 14866 // Otherwise, use the type that was written in the explicit cast. 14867 assert(!arg->hasPlaceholderType()); 14868 paramType = castArg->getTypeAsWritten(); 14869 14870 // Copy-initialize a parameter of that type. 14871 InitializedEntity entity = 14872 InitializedEntity::InitializeParameter(Context, paramType, 14873 /*consumed*/ false); 14874 return PerformCopyInitialization(entity, callLoc, arg); 14875 } 14876 14877 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14878 Expr *orig = E; 14879 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14880 while (true) { 14881 E = E->IgnoreParenImpCasts(); 14882 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14883 E = call->getCallee(); 14884 diagID = diag::err_uncasted_call_of_unknown_any; 14885 } else { 14886 break; 14887 } 14888 } 14889 14890 SourceLocation loc; 14891 NamedDecl *d; 14892 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14893 loc = ref->getLocation(); 14894 d = ref->getDecl(); 14895 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14896 loc = mem->getMemberLoc(); 14897 d = mem->getMemberDecl(); 14898 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14899 diagID = diag::err_uncasted_call_of_unknown_any; 14900 loc = msg->getSelectorStartLoc(); 14901 d = msg->getMethodDecl(); 14902 if (!d) { 14903 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14904 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14905 << orig->getSourceRange(); 14906 return ExprError(); 14907 } 14908 } else { 14909 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14910 << E->getSourceRange(); 14911 return ExprError(); 14912 } 14913 14914 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14915 14916 // Never recoverable. 14917 return ExprError(); 14918 } 14919 14920 /// Check for operands with placeholder types and complain if found. 14921 /// Returns true if there was an error and no recovery was possible. 14922 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14923 if (!getLangOpts().CPlusPlus) { 14924 // C cannot handle TypoExpr nodes on either side of a binop because it 14925 // doesn't handle dependent types properly, so make sure any TypoExprs have 14926 // been dealt with before checking the operands. 14927 ExprResult Result = CorrectDelayedTyposInExpr(E); 14928 if (!Result.isUsable()) return ExprError(); 14929 E = Result.get(); 14930 } 14931 14932 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14933 if (!placeholderType) return E; 14934 14935 switch (placeholderType->getKind()) { 14936 14937 // Overloaded expressions. 14938 case BuiltinType::Overload: { 14939 // Try to resolve a single function template specialization. 14940 // This is obligatory. 14941 ExprResult Result = E; 14942 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 14943 return Result; 14944 14945 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 14946 // leaves Result unchanged on failure. 14947 Result = E; 14948 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 14949 return Result; 14950 14951 // If that failed, try to recover with a call. 14952 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 14953 /*complain*/ true); 14954 return Result; 14955 } 14956 14957 // Bound member functions. 14958 case BuiltinType::BoundMember: { 14959 ExprResult result = E; 14960 const Expr *BME = E->IgnoreParens(); 14961 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14962 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14963 if (isa<CXXPseudoDestructorExpr>(BME)) { 14964 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14965 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14966 if (ME->getMemberNameInfo().getName().getNameKind() == 14967 DeclarationName::CXXDestructorName) 14968 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14969 } 14970 tryToRecoverWithCall(result, PD, 14971 /*complain*/ true); 14972 return result; 14973 } 14974 14975 // ARC unbridged casts. 14976 case BuiltinType::ARCUnbridgedCast: { 14977 Expr *realCast = stripARCUnbridgedCast(E); 14978 diagnoseARCUnbridgedCast(realCast); 14979 return realCast; 14980 } 14981 14982 // Expressions of unknown type. 14983 case BuiltinType::UnknownAny: 14984 return diagnoseUnknownAnyExpr(*this, E); 14985 14986 // Pseudo-objects. 14987 case BuiltinType::PseudoObject: 14988 return checkPseudoObjectRValue(E); 14989 14990 case BuiltinType::BuiltinFn: { 14991 // Accept __noop without parens by implicitly converting it to a call expr. 14992 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14993 if (DRE) { 14994 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14995 if (FD->getBuiltinID() == Builtin::BI__noop) { 14996 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14997 CK_BuiltinFnToFnPtr).get(); 14998 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14999 VK_RValue, SourceLocation()); 15000 } 15001 } 15002 15003 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15004 return ExprError(); 15005 } 15006 15007 // Expressions of unknown type. 15008 case BuiltinType::OMPArraySection: 15009 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15010 return ExprError(); 15011 15012 // Everything else should be impossible. 15013 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15014 case BuiltinType::Id: 15015 #include "clang/Basic/OpenCLImageTypes.def" 15016 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15017 #define PLACEHOLDER_TYPE(Id, SingletonId) 15018 #include "clang/AST/BuiltinTypes.def" 15019 break; 15020 } 15021 15022 llvm_unreachable("invalid placeholder type!"); 15023 } 15024 15025 bool Sema::CheckCaseExpression(Expr *E) { 15026 if (E->isTypeDependent()) 15027 return true; 15028 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15029 return E->getType()->isIntegralOrEnumerationType(); 15030 return false; 15031 } 15032 15033 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15034 ExprResult 15035 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15036 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15037 "Unknown Objective-C Boolean value!"); 15038 QualType BoolT = Context.ObjCBuiltinBoolTy; 15039 if (!Context.getBOOLDecl()) { 15040 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15041 Sema::LookupOrdinaryName); 15042 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15043 NamedDecl *ND = Result.getFoundDecl(); 15044 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15045 Context.setBOOLDecl(TD); 15046 } 15047 } 15048 if (Context.getBOOLDecl()) 15049 BoolT = Context.getBOOLType(); 15050 return new (Context) 15051 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15052 } 15053