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, /*Diagnose=*/true); 220 221 return; 222 } 223 224 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 225 if (CXXConstructorDecl *BaseCD = 226 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 227 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 228 if (BaseCD->isDeleted()) { 229 NoteDeletedFunction(BaseCD); 230 } else { 231 // FIXME: An explanation of why exactly it can't be inherited 232 // would be nice. 233 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 234 } 235 return; 236 } 237 } 238 239 Diag(Decl->getLocation(), diag::note_availability_specified_here) 240 << Decl << true; 241 } 242 243 /// \brief Determine whether a FunctionDecl was ever declared with an 244 /// explicit storage class. 245 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 246 for (auto I : D->redecls()) { 247 if (I->getStorageClass() != SC_None) 248 return true; 249 } 250 return false; 251 } 252 253 /// \brief Check whether we're in an extern inline function and referring to a 254 /// variable or function with internal linkage (C11 6.7.4p3). 255 /// 256 /// This is only a warning because we used to silently accept this code, but 257 /// in many cases it will not behave correctly. This is not enabled in C++ mode 258 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 259 /// and so while there may still be user mistakes, most of the time we can't 260 /// prove that there are errors. 261 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 262 const NamedDecl *D, 263 SourceLocation Loc) { 264 // This is disabled under C++; there are too many ways for this to fire in 265 // contexts where the warning is a false positive, or where it is technically 266 // correct but benign. 267 if (S.getLangOpts().CPlusPlus) 268 return; 269 270 // Check if this is an inlined function or method. 271 FunctionDecl *Current = S.getCurFunctionDecl(); 272 if (!Current) 273 return; 274 if (!Current->isInlined()) 275 return; 276 if (!Current->isExternallyVisible()) 277 return; 278 279 // Check if the decl has internal linkage. 280 if (D->getFormalLinkage() != InternalLinkage) 281 return; 282 283 // Downgrade from ExtWarn to Extension if 284 // (1) the supposedly external inline function is in the main file, 285 // and probably won't be included anywhere else. 286 // (2) the thing we're referencing is a pure function. 287 // (3) the thing we're referencing is another inline function. 288 // This last can give us false negatives, but it's better than warning on 289 // wrappers for simple C library functions. 290 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 291 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 292 if (!DowngradeWarning && UsedFn) 293 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 294 295 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 296 : diag::ext_internal_in_extern_inline) 297 << /*IsVar=*/!UsedFn << D; 298 299 S.MaybeSuggestAddingStaticToDecl(Current); 300 301 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 302 << D; 303 } 304 305 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 306 const FunctionDecl *First = Cur->getFirstDecl(); 307 308 // Suggest "static" on the function, if possible. 309 if (!hasAnyExplicitStorageClass(First)) { 310 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 311 Diag(DeclBegin, diag::note_convert_inline_to_static) 312 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 313 } 314 } 315 316 /// \brief Determine whether the use of this declaration is valid, and 317 /// emit any corresponding diagnostics. 318 /// 319 /// This routine diagnoses various problems with referencing 320 /// declarations that can occur when using a declaration. For example, 321 /// it might warn if a deprecated or unavailable declaration is being 322 /// used, or produce an error (and return true) if a C++0x deleted 323 /// function is being used. 324 /// 325 /// \returns true if there was an error (this declaration cannot be 326 /// referenced), false otherwise. 327 /// 328 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 329 const ObjCInterfaceDecl *UnknownObjCClass, 330 bool ObjCPropertyAccess) { 331 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 332 // If there were any diagnostics suppressed by template argument deduction, 333 // emit them now. 334 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 335 if (Pos != SuppressedDiagnostics.end()) { 336 for (const PartialDiagnosticAt &Suppressed : Pos->second) 337 Diag(Suppressed.first, Suppressed.second); 338 339 // Clear out the list of suppressed diagnostics, so that we don't emit 340 // them again for this specialization. However, we don't obsolete this 341 // entry from the table, because we want to avoid ever emitting these 342 // diagnostics again. 343 Pos->second.clear(); 344 } 345 346 // C++ [basic.start.main]p3: 347 // The function 'main' shall not be used within a program. 348 if (cast<FunctionDecl>(D)->isMain()) 349 Diag(Loc, diag::ext_main_used); 350 } 351 352 // See if this is an auto-typed variable whose initializer we are parsing. 353 if (ParsingInitForAutoVars.count(D)) { 354 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 355 356 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 357 << D->getDeclName() << (unsigned)AT->getKeyword(); 358 return true; 359 } 360 361 // See if this is a deleted function. 362 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 363 if (FD->isDeleted()) { 364 Diag(Loc, diag::err_deleted_function_use); 365 NoteDeletedFunction(FD); 366 return true; 367 } 368 369 // If the function has a deduced return type, and we can't deduce it, 370 // then we can't use it either. 371 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 372 DeduceReturnType(FD, Loc)) 373 return true; 374 } 375 376 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 377 // Only the variables omp_in and omp_out are allowed in the combiner. 378 // Only the variables omp_priv and omp_orig are allowed in the 379 // initializer-clause. 380 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 381 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 382 isa<VarDecl>(D)) { 383 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 384 << getCurFunction()->HasOMPDeclareReductionCombiner; 385 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 386 return true; 387 } 388 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 389 ObjCPropertyAccess); 390 391 DiagnoseUnusedOfDecl(*this, D, Loc); 392 393 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 394 395 return false; 396 } 397 398 /// \brief Retrieve the message suffix that should be added to a 399 /// diagnostic complaining about the given function being deleted or 400 /// unavailable. 401 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 402 std::string Message; 403 if (FD->getAvailability(&Message)) 404 return ": " + Message; 405 406 return std::string(); 407 } 408 409 /// DiagnoseSentinelCalls - This routine checks whether a call or 410 /// message-send is to a declaration with the sentinel attribute, and 411 /// if so, it checks that the requirements of the sentinel are 412 /// satisfied. 413 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 414 ArrayRef<Expr *> Args) { 415 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 416 if (!attr) 417 return; 418 419 // The number of formal parameters of the declaration. 420 unsigned numFormalParams; 421 422 // The kind of declaration. This is also an index into a %select in 423 // the diagnostic. 424 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 425 426 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 427 numFormalParams = MD->param_size(); 428 calleeType = CT_Method; 429 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 430 numFormalParams = FD->param_size(); 431 calleeType = CT_Function; 432 } else if (isa<VarDecl>(D)) { 433 QualType type = cast<ValueDecl>(D)->getType(); 434 const FunctionType *fn = nullptr; 435 if (const PointerType *ptr = type->getAs<PointerType>()) { 436 fn = ptr->getPointeeType()->getAs<FunctionType>(); 437 if (!fn) return; 438 calleeType = CT_Function; 439 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 440 fn = ptr->getPointeeType()->castAs<FunctionType>(); 441 calleeType = CT_Block; 442 } else { 443 return; 444 } 445 446 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 447 numFormalParams = proto->getNumParams(); 448 } else { 449 numFormalParams = 0; 450 } 451 } else { 452 return; 453 } 454 455 // "nullPos" is the number of formal parameters at the end which 456 // effectively count as part of the variadic arguments. This is 457 // useful if you would prefer to not have *any* formal parameters, 458 // but the language forces you to have at least one. 459 unsigned nullPos = attr->getNullPos(); 460 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 461 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 462 463 // The number of arguments which should follow the sentinel. 464 unsigned numArgsAfterSentinel = attr->getSentinel(); 465 466 // If there aren't enough arguments for all the formal parameters, 467 // the sentinel, and the args after the sentinel, complain. 468 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 469 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 470 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 471 return; 472 } 473 474 // Otherwise, find the sentinel expression. 475 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 476 if (!sentinelExpr) return; 477 if (sentinelExpr->isValueDependent()) return; 478 if (Context.isSentinelNullExpr(sentinelExpr)) return; 479 480 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 481 // or 'NULL' if those are actually defined in the context. Only use 482 // 'nil' for ObjC methods, where it's much more likely that the 483 // variadic arguments form a list of object pointers. 484 SourceLocation MissingNilLoc 485 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 486 std::string NullValue; 487 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 488 NullValue = "nil"; 489 else if (getLangOpts().CPlusPlus11) 490 NullValue = "nullptr"; 491 else if (PP.isMacroDefined("NULL")) 492 NullValue = "NULL"; 493 else 494 NullValue = "(void*) 0"; 495 496 if (MissingNilLoc.isInvalid()) 497 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 498 else 499 Diag(MissingNilLoc, diag::warn_missing_sentinel) 500 << int(calleeType) 501 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 502 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 503 } 504 505 SourceRange Sema::getExprRange(Expr *E) const { 506 return E ? E->getSourceRange() : SourceRange(); 507 } 508 509 //===----------------------------------------------------------------------===// 510 // Standard Promotions and Conversions 511 //===----------------------------------------------------------------------===// 512 513 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 514 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 515 // Handle any placeholder expressions which made it here. 516 if (E->getType()->isPlaceholderType()) { 517 ExprResult result = CheckPlaceholderExpr(E); 518 if (result.isInvalid()) return ExprError(); 519 E = result.get(); 520 } 521 522 QualType Ty = E->getType(); 523 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 524 525 if (Ty->isFunctionType()) { 526 // If we are here, we are not calling a function but taking 527 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 528 if (getLangOpts().OpenCL) { 529 if (Diagnose) 530 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 531 return ExprError(); 532 } 533 534 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 535 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 536 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 537 return ExprError(); 538 539 E = ImpCastExprToType(E, Context.getPointerType(Ty), 540 CK_FunctionToPointerDecay).get(); 541 } else if (Ty->isArrayType()) { 542 // In C90 mode, arrays only promote to pointers if the array expression is 543 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 544 // type 'array of type' is converted to an expression that has type 'pointer 545 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 546 // that has type 'array of type' ...". The relevant change is "an lvalue" 547 // (C90) to "an expression" (C99). 548 // 549 // C++ 4.2p1: 550 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 551 // T" can be converted to an rvalue of type "pointer to T". 552 // 553 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 554 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 555 CK_ArrayToPointerDecay).get(); 556 } 557 return E; 558 } 559 560 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 561 // Check to see if we are dereferencing a null pointer. If so, 562 // and if not volatile-qualified, this is undefined behavior that the 563 // optimizer will delete, so warn about it. People sometimes try to use this 564 // to get a deterministic trap and are surprised by clang's behavior. This 565 // only handles the pattern "*null", which is a very syntactic check. 566 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 567 if (UO->getOpcode() == UO_Deref && 568 UO->getSubExpr()->IgnoreParenCasts()-> 569 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 570 !UO->getType().isVolatileQualified()) { 571 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 572 S.PDiag(diag::warn_indirection_through_null) 573 << UO->getSubExpr()->getSourceRange()); 574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 575 S.PDiag(diag::note_indirection_through_null)); 576 } 577 } 578 579 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 580 SourceLocation AssignLoc, 581 const Expr* RHS) { 582 const ObjCIvarDecl *IV = OIRE->getDecl(); 583 if (!IV) 584 return; 585 586 DeclarationName MemberName = IV->getDeclName(); 587 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 588 if (!Member || !Member->isStr("isa")) 589 return; 590 591 const Expr *Base = OIRE->getBase(); 592 QualType BaseType = Base->getType(); 593 if (OIRE->isArrow()) 594 BaseType = BaseType->getPointeeType(); 595 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 596 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 597 ObjCInterfaceDecl *ClassDeclared = nullptr; 598 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 599 if (!ClassDeclared->getSuperClass() 600 && (*ClassDeclared->ivar_begin()) == IV) { 601 if (RHS) { 602 NamedDecl *ObjectSetClass = 603 S.LookupSingleName(S.TUScope, 604 &S.Context.Idents.get("object_setClass"), 605 SourceLocation(), S.LookupOrdinaryName); 606 if (ObjectSetClass) { 607 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 608 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 609 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 610 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 611 AssignLoc), ",") << 612 FixItHint::CreateInsertion(RHSLocEnd, ")"); 613 } 614 else 615 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 616 } else { 617 NamedDecl *ObjectGetClass = 618 S.LookupSingleName(S.TUScope, 619 &S.Context.Idents.get("object_getClass"), 620 SourceLocation(), S.LookupOrdinaryName); 621 if (ObjectGetClass) 622 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 623 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 624 FixItHint::CreateReplacement( 625 SourceRange(OIRE->getOpLoc(), 626 OIRE->getLocEnd()), ")"); 627 else 628 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 629 } 630 S.Diag(IV->getLocation(), diag::note_ivar_decl); 631 } 632 } 633 } 634 635 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 636 // Handle any placeholder expressions which made it here. 637 if (E->getType()->isPlaceholderType()) { 638 ExprResult result = CheckPlaceholderExpr(E); 639 if (result.isInvalid()) return ExprError(); 640 E = result.get(); 641 } 642 643 // C++ [conv.lval]p1: 644 // A glvalue of a non-function, non-array type T can be 645 // converted to a prvalue. 646 if (!E->isGLValue()) return E; 647 648 QualType T = E->getType(); 649 assert(!T.isNull() && "r-value conversion on typeless expression?"); 650 651 // We don't want to throw lvalue-to-rvalue casts on top of 652 // expressions of certain types in C++. 653 if (getLangOpts().CPlusPlus && 654 (E->getType() == Context.OverloadTy || 655 T->isDependentType() || 656 T->isRecordType())) 657 return E; 658 659 // The C standard is actually really unclear on this point, and 660 // DR106 tells us what the result should be but not why. It's 661 // generally best to say that void types just doesn't undergo 662 // lvalue-to-rvalue at all. Note that expressions of unqualified 663 // 'void' type are never l-values, but qualified void can be. 664 if (T->isVoidType()) 665 return E; 666 667 // OpenCL usually rejects direct accesses to values of 'half' type. 668 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 669 T->isHalfType()) { 670 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 671 << 0 << T; 672 return ExprError(); 673 } 674 675 CheckForNullPointerDereference(*this, E); 676 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 677 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 678 &Context.Idents.get("object_getClass"), 679 SourceLocation(), LookupOrdinaryName); 680 if (ObjectGetClass) 681 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 682 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 683 FixItHint::CreateReplacement( 684 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 685 else 686 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 687 } 688 else if (const ObjCIvarRefExpr *OIRE = 689 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 690 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 691 692 // C++ [conv.lval]p1: 693 // [...] If T is a non-class type, the type of the prvalue is the 694 // cv-unqualified version of T. Otherwise, the type of the 695 // rvalue is T. 696 // 697 // C99 6.3.2.1p2: 698 // If the lvalue has qualified type, the value has the unqualified 699 // version of the type of the lvalue; otherwise, the value has the 700 // type of the lvalue. 701 if (T.hasQualifiers()) 702 T = T.getUnqualifiedType(); 703 704 // Under the MS ABI, lock down the inheritance model now. 705 if (T->isMemberPointerType() && 706 Context.getTargetInfo().getCXXABI().isMicrosoft()) 707 (void)isCompleteType(E->getExprLoc(), T); 708 709 UpdateMarkingForLValueToRValue(E); 710 711 // Loading a __weak object implicitly retains the value, so we need a cleanup to 712 // balance that. 713 if (getLangOpts().ObjCAutoRefCount && 714 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 715 ExprNeedsCleanups = true; 716 717 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 718 nullptr, VK_RValue); 719 720 // C11 6.3.2.1p2: 721 // ... if the lvalue has atomic type, the value has the non-atomic version 722 // of the type of the lvalue ... 723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 724 T = Atomic->getValueType().getUnqualifiedType(); 725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 726 nullptr, VK_RValue); 727 } 728 729 return Res; 730 } 731 732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 734 if (Res.isInvalid()) 735 return ExprError(); 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res; 740 } 741 742 /// CallExprUnaryConversions - a special case of an unary conversion 743 /// performed on a function designator of a call expression. 744 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 745 QualType Ty = E->getType(); 746 ExprResult Res = E; 747 // Only do implicit cast for a function type, but not for a pointer 748 // to function type. 749 if (Ty->isFunctionType()) { 750 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 751 CK_FunctionToPointerDecay).get(); 752 if (Res.isInvalid()) 753 return ExprError(); 754 } 755 Res = DefaultLvalueConversion(Res.get()); 756 if (Res.isInvalid()) 757 return ExprError(); 758 return Res.get(); 759 } 760 761 /// UsualUnaryConversions - Performs various conversions that are common to most 762 /// operators (C99 6.3). The conversions of array and function types are 763 /// sometimes suppressed. For example, the array->pointer conversion doesn't 764 /// apply if the array is an argument to the sizeof or address (&) operators. 765 /// In these instances, this routine should *not* be called. 766 ExprResult Sema::UsualUnaryConversions(Expr *E) { 767 // First, convert to an r-value. 768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 769 if (Res.isInvalid()) 770 return ExprError(); 771 E = Res.get(); 772 773 QualType Ty = E->getType(); 774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 775 776 // Half FP have to be promoted to float unless it is natively supported 777 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 778 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 779 780 // Try to perform integral promotions if the object has a theoretically 781 // promotable type. 782 if (Ty->isIntegralOrUnscopedEnumerationType()) { 783 // C99 6.3.1.1p2: 784 // 785 // The following may be used in an expression wherever an int or 786 // unsigned int may be used: 787 // - an object or expression with an integer type whose integer 788 // conversion rank is less than or equal to the rank of int 789 // and unsigned int. 790 // - A bit-field of type _Bool, int, signed int, or unsigned int. 791 // 792 // If an int can represent all values of the original type, the 793 // value is converted to an int; otherwise, it is converted to an 794 // unsigned int. These are called the integer promotions. All 795 // other types are unchanged by the integer promotions. 796 797 QualType PTy = Context.isPromotableBitField(E); 798 if (!PTy.isNull()) { 799 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 800 return E; 801 } 802 if (Ty->isPromotableIntegerType()) { 803 QualType PT = Context.getPromotedIntegerType(Ty); 804 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 805 return E; 806 } 807 } 808 return E; 809 } 810 811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 812 /// do not have a prototype. Arguments that have type float or __fp16 813 /// are promoted to double. All other argument types are converted by 814 /// UsualUnaryConversions(). 815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 816 QualType Ty = E->getType(); 817 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 818 819 ExprResult Res = UsualUnaryConversions(E); 820 if (Res.isInvalid()) 821 return ExprError(); 822 E = Res.get(); 823 824 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 825 // double. 826 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 827 if (BTy && (BTy->getKind() == BuiltinType::Half || 828 BTy->getKind() == BuiltinType::Float)) 829 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 830 831 // C++ performs lvalue-to-rvalue conversion as a default argument 832 // promotion, even on class types, but note: 833 // C++11 [conv.lval]p2: 834 // When an lvalue-to-rvalue conversion occurs in an unevaluated 835 // operand or a subexpression thereof the value contained in the 836 // referenced object is not accessed. Otherwise, if the glvalue 837 // has a class type, the conversion copy-initializes a temporary 838 // of type T from the glvalue and the result of the conversion 839 // is a prvalue for the temporary. 840 // FIXME: add some way to gate this entire thing for correctness in 841 // potentially potentially evaluated contexts. 842 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 843 ExprResult Temp = PerformCopyInitialization( 844 InitializedEntity::InitializeTemporary(E->getType()), 845 E->getExprLoc(), E); 846 if (Temp.isInvalid()) 847 return ExprError(); 848 E = Temp.get(); 849 } 850 851 return E; 852 } 853 854 /// Determine the degree of POD-ness for an expression. 855 /// Incomplete types are considered POD, since this check can be performed 856 /// when we're in an unevaluated context. 857 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 858 if (Ty->isIncompleteType()) { 859 // C++11 [expr.call]p7: 860 // After these conversions, if the argument does not have arithmetic, 861 // enumeration, pointer, pointer to member, or class type, the program 862 // is ill-formed. 863 // 864 // Since we've already performed array-to-pointer and function-to-pointer 865 // decay, the only such type in C++ is cv void. This also handles 866 // initializer lists as variadic arguments. 867 if (Ty->isVoidType()) 868 return VAK_Invalid; 869 870 if (Ty->isObjCObjectType()) 871 return VAK_Invalid; 872 return VAK_Valid; 873 } 874 875 if (Ty.isCXX98PODType(Context)) 876 return VAK_Valid; 877 878 // C++11 [expr.call]p7: 879 // Passing a potentially-evaluated argument of class type (Clause 9) 880 // having a non-trivial copy constructor, a non-trivial move constructor, 881 // or a non-trivial destructor, with no corresponding parameter, 882 // is conditionally-supported with implementation-defined semantics. 883 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 884 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 885 if (!Record->hasNonTrivialCopyConstructor() && 886 !Record->hasNonTrivialMoveConstructor() && 887 !Record->hasNonTrivialDestructor()) 888 return VAK_ValidInCXX11; 889 890 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 891 return VAK_Valid; 892 893 if (Ty->isObjCObjectType()) 894 return VAK_Invalid; 895 896 if (getLangOpts().MSVCCompat) 897 return VAK_MSVCUndefined; 898 899 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 900 // permitted to reject them. We should consider doing so. 901 return VAK_Undefined; 902 } 903 904 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 905 // Don't allow one to pass an Objective-C interface to a vararg. 906 const QualType &Ty = E->getType(); 907 VarArgKind VAK = isValidVarArgType(Ty); 908 909 // Complain about passing non-POD types through varargs. 910 switch (VAK) { 911 case VAK_ValidInCXX11: 912 DiagRuntimeBehavior( 913 E->getLocStart(), nullptr, 914 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 915 << Ty << CT); 916 // Fall through. 917 case VAK_Valid: 918 if (Ty->isRecordType()) { 919 // This is unlikely to be what the user intended. If the class has a 920 // 'c_str' member function, the user probably meant to call that. 921 DiagRuntimeBehavior(E->getLocStart(), nullptr, 922 PDiag(diag::warn_pass_class_arg_to_vararg) 923 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 924 } 925 break; 926 927 case VAK_Undefined: 928 case VAK_MSVCUndefined: 929 DiagRuntimeBehavior( 930 E->getLocStart(), nullptr, 931 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 932 << getLangOpts().CPlusPlus11 << Ty << CT); 933 break; 934 935 case VAK_Invalid: 936 if (Ty->isObjCObjectType()) 937 DiagRuntimeBehavior( 938 E->getLocStart(), nullptr, 939 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 940 << Ty << CT); 941 else 942 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 943 << isa<InitListExpr>(E) << Ty << CT; 944 break; 945 } 946 } 947 948 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 949 /// will create a trap if the resulting type is not a POD type. 950 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 951 FunctionDecl *FDecl) { 952 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 953 // Strip the unbridged-cast placeholder expression off, if applicable. 954 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 955 (CT == VariadicMethod || 956 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 957 E = stripARCUnbridgedCast(E); 958 959 // Otherwise, do normal placeholder checking. 960 } else { 961 ExprResult ExprRes = CheckPlaceholderExpr(E); 962 if (ExprRes.isInvalid()) 963 return ExprError(); 964 E = ExprRes.get(); 965 } 966 } 967 968 ExprResult ExprRes = DefaultArgumentPromotion(E); 969 if (ExprRes.isInvalid()) 970 return ExprError(); 971 E = ExprRes.get(); 972 973 // Diagnostics regarding non-POD argument types are 974 // emitted along with format string checking in Sema::CheckFunctionCall(). 975 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 976 // Turn this into a trap. 977 CXXScopeSpec SS; 978 SourceLocation TemplateKWLoc; 979 UnqualifiedId Name; 980 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 981 E->getLocStart()); 982 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 983 Name, true, false); 984 if (TrapFn.isInvalid()) 985 return ExprError(); 986 987 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 988 E->getLocStart(), None, 989 E->getLocEnd()); 990 if (Call.isInvalid()) 991 return ExprError(); 992 993 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 994 Call.get(), E); 995 if (Comma.isInvalid()) 996 return ExprError(); 997 return Comma.get(); 998 } 999 1000 if (!getLangOpts().CPlusPlus && 1001 RequireCompleteType(E->getExprLoc(), E->getType(), 1002 diag::err_call_incomplete_argument)) 1003 return ExprError(); 1004 1005 return E; 1006 } 1007 1008 /// \brief Converts an integer to complex float type. Helper function of 1009 /// UsualArithmeticConversions() 1010 /// 1011 /// \return false if the integer expression is an integer type and is 1012 /// successfully converted to the complex type. 1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1014 ExprResult &ComplexExpr, 1015 QualType IntTy, 1016 QualType ComplexTy, 1017 bool SkipCast) { 1018 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1019 if (SkipCast) return false; 1020 if (IntTy->isIntegerType()) { 1021 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1022 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1024 CK_FloatingRealToComplex); 1025 } else { 1026 assert(IntTy->isComplexIntegerType()); 1027 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1028 CK_IntegralComplexToFloatingComplex); 1029 } 1030 return false; 1031 } 1032 1033 /// \brief Handle arithmetic conversion with complex types. Helper function of 1034 /// UsualArithmeticConversions() 1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1036 ExprResult &RHS, QualType LHSType, 1037 QualType RHSType, 1038 bool IsCompAssign) { 1039 // if we have an integer operand, the result is the complex type. 1040 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1041 /*skipCast*/false)) 1042 return LHSType; 1043 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1044 /*skipCast*/IsCompAssign)) 1045 return RHSType; 1046 1047 // This handles complex/complex, complex/float, or float/complex. 1048 // When both operands are complex, the shorter operand is converted to the 1049 // type of the longer, and that is the type of the result. This corresponds 1050 // to what is done when combining two real floating-point operands. 1051 // The fun begins when size promotion occur across type domains. 1052 // From H&S 6.3.4: When one operand is complex and the other is a real 1053 // floating-point type, the less precise type is converted, within it's 1054 // real or complex domain, to the precision of the other type. For example, 1055 // when combining a "long double" with a "double _Complex", the 1056 // "double _Complex" is promoted to "long double _Complex". 1057 1058 // Compute the rank of the two types, regardless of whether they are complex. 1059 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1060 1061 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1062 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1063 QualType LHSElementType = 1064 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1065 QualType RHSElementType = 1066 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1067 1068 QualType ResultType = S.Context.getComplexType(LHSElementType); 1069 if (Order < 0) { 1070 // Promote the precision of the LHS if not an assignment. 1071 ResultType = S.Context.getComplexType(RHSElementType); 1072 if (!IsCompAssign) { 1073 if (LHSComplexType) 1074 LHS = 1075 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1076 else 1077 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1078 } 1079 } else if (Order > 0) { 1080 // Promote the precision of the RHS. 1081 if (RHSComplexType) 1082 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1083 else 1084 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1085 } 1086 return ResultType; 1087 } 1088 1089 /// \brief Hande arithmetic conversion from integer to float. Helper function 1090 /// of UsualArithmeticConversions() 1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1092 ExprResult &IntExpr, 1093 QualType FloatTy, QualType IntTy, 1094 bool ConvertFloat, bool ConvertInt) { 1095 if (IntTy->isIntegerType()) { 1096 if (ConvertInt) 1097 // Convert intExpr to the lhs floating point type. 1098 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1099 CK_IntegralToFloating); 1100 return FloatTy; 1101 } 1102 1103 // Convert both sides to the appropriate complex float. 1104 assert(IntTy->isComplexIntegerType()); 1105 QualType result = S.Context.getComplexType(FloatTy); 1106 1107 // _Complex int -> _Complex float 1108 if (ConvertInt) 1109 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1110 CK_IntegralComplexToFloatingComplex); 1111 1112 // float -> _Complex float 1113 if (ConvertFloat) 1114 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1115 CK_FloatingRealToComplex); 1116 1117 return result; 1118 } 1119 1120 /// \brief Handle arithmethic conversion with floating point types. Helper 1121 /// function of UsualArithmeticConversions() 1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1123 ExprResult &RHS, QualType LHSType, 1124 QualType RHSType, bool IsCompAssign) { 1125 bool LHSFloat = LHSType->isRealFloatingType(); 1126 bool RHSFloat = RHSType->isRealFloatingType(); 1127 1128 // If we have two real floating types, convert the smaller operand 1129 // to the bigger result. 1130 if (LHSFloat && RHSFloat) { 1131 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1132 if (order > 0) { 1133 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1134 return LHSType; 1135 } 1136 1137 assert(order < 0 && "illegal float comparison"); 1138 if (!IsCompAssign) 1139 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1140 return RHSType; 1141 } 1142 1143 if (LHSFloat) { 1144 // Half FP has to be promoted to float unless it is natively supported 1145 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1146 LHSType = S.Context.FloatTy; 1147 1148 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1149 /*convertFloat=*/!IsCompAssign, 1150 /*convertInt=*/ true); 1151 } 1152 assert(RHSFloat); 1153 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1154 /*convertInt=*/ true, 1155 /*convertFloat=*/!IsCompAssign); 1156 } 1157 1158 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1159 1160 namespace { 1161 /// These helper callbacks are placed in an anonymous namespace to 1162 /// permit their use as function template parameters. 1163 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1164 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1165 } 1166 1167 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1168 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1169 CK_IntegralComplexCast); 1170 } 1171 } 1172 1173 /// \brief Handle integer arithmetic conversions. Helper function of 1174 /// UsualArithmeticConversions() 1175 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1176 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1177 ExprResult &RHS, QualType LHSType, 1178 QualType RHSType, bool IsCompAssign) { 1179 // The rules for this case are in C99 6.3.1.8 1180 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1181 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1182 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1183 if (LHSSigned == RHSSigned) { 1184 // Same signedness; use the higher-ranked type 1185 if (order >= 0) { 1186 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1187 return LHSType; 1188 } else if (!IsCompAssign) 1189 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1190 return RHSType; 1191 } else if (order != (LHSSigned ? 1 : -1)) { 1192 // The unsigned type has greater than or equal rank to the 1193 // signed type, so use the unsigned type 1194 if (RHSSigned) { 1195 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1196 return LHSType; 1197 } else if (!IsCompAssign) 1198 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1199 return RHSType; 1200 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1201 // The two types are different widths; if we are here, that 1202 // means the signed type is larger than the unsigned type, so 1203 // use the signed type. 1204 if (LHSSigned) { 1205 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1206 return LHSType; 1207 } else if (!IsCompAssign) 1208 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1209 return RHSType; 1210 } else { 1211 // The signed type is higher-ranked than the unsigned type, 1212 // but isn't actually any bigger (like unsigned int and long 1213 // on most 32-bit systems). Use the unsigned type corresponding 1214 // to the signed type. 1215 QualType result = 1216 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1217 RHS = (*doRHSCast)(S, RHS.get(), result); 1218 if (!IsCompAssign) 1219 LHS = (*doLHSCast)(S, LHS.get(), result); 1220 return result; 1221 } 1222 } 1223 1224 /// \brief Handle conversions with GCC complex int extension. Helper function 1225 /// of UsualArithmeticConversions() 1226 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1227 ExprResult &RHS, QualType LHSType, 1228 QualType RHSType, 1229 bool IsCompAssign) { 1230 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1231 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1232 1233 if (LHSComplexInt && RHSComplexInt) { 1234 QualType LHSEltType = LHSComplexInt->getElementType(); 1235 QualType RHSEltType = RHSComplexInt->getElementType(); 1236 QualType ScalarType = 1237 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1238 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1239 1240 return S.Context.getComplexType(ScalarType); 1241 } 1242 1243 if (LHSComplexInt) { 1244 QualType LHSEltType = LHSComplexInt->getElementType(); 1245 QualType ScalarType = 1246 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1247 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1248 QualType ComplexType = S.Context.getComplexType(ScalarType); 1249 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1250 CK_IntegralRealToComplex); 1251 1252 return ComplexType; 1253 } 1254 1255 assert(RHSComplexInt); 1256 1257 QualType RHSEltType = RHSComplexInt->getElementType(); 1258 QualType ScalarType = 1259 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1260 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1261 QualType ComplexType = S.Context.getComplexType(ScalarType); 1262 1263 if (!IsCompAssign) 1264 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1265 CK_IntegralRealToComplex); 1266 return ComplexType; 1267 } 1268 1269 /// UsualArithmeticConversions - Performs various conversions that are common to 1270 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1271 /// routine returns the first non-arithmetic type found. The client is 1272 /// responsible for emitting appropriate error diagnostics. 1273 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1274 bool IsCompAssign) { 1275 if (!IsCompAssign) { 1276 LHS = UsualUnaryConversions(LHS.get()); 1277 if (LHS.isInvalid()) 1278 return QualType(); 1279 } 1280 1281 RHS = UsualUnaryConversions(RHS.get()); 1282 if (RHS.isInvalid()) 1283 return QualType(); 1284 1285 // For conversion purposes, we ignore any qualifiers. 1286 // For example, "const float" and "float" are equivalent. 1287 QualType LHSType = 1288 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1289 QualType RHSType = 1290 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1291 1292 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1293 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1294 LHSType = AtomicLHS->getValueType(); 1295 1296 // If both types are identical, no conversion is needed. 1297 if (LHSType == RHSType) 1298 return LHSType; 1299 1300 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1301 // The caller can deal with this (e.g. pointer + int). 1302 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1303 return QualType(); 1304 1305 // Apply unary and bitfield promotions to the LHS's type. 1306 QualType LHSUnpromotedType = LHSType; 1307 if (LHSType->isPromotableIntegerType()) 1308 LHSType = Context.getPromotedIntegerType(LHSType); 1309 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1310 if (!LHSBitfieldPromoteTy.isNull()) 1311 LHSType = LHSBitfieldPromoteTy; 1312 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1313 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1314 1315 // If both types are identical, no conversion is needed. 1316 if (LHSType == RHSType) 1317 return LHSType; 1318 1319 // At this point, we have two different arithmetic types. 1320 1321 // Handle complex types first (C99 6.3.1.8p1). 1322 if (LHSType->isComplexType() || RHSType->isComplexType()) 1323 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1324 IsCompAssign); 1325 1326 // Now handle "real" floating types (i.e. float, double, long double). 1327 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1328 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1329 IsCompAssign); 1330 1331 // Handle GCC complex int extension. 1332 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1333 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1334 IsCompAssign); 1335 1336 // Finally, we have two differing integer types. 1337 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1338 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1339 } 1340 1341 1342 //===----------------------------------------------------------------------===// 1343 // Semantic Analysis for various Expression Types 1344 //===----------------------------------------------------------------------===// 1345 1346 1347 ExprResult 1348 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1349 SourceLocation DefaultLoc, 1350 SourceLocation RParenLoc, 1351 Expr *ControllingExpr, 1352 ArrayRef<ParsedType> ArgTypes, 1353 ArrayRef<Expr *> ArgExprs) { 1354 unsigned NumAssocs = ArgTypes.size(); 1355 assert(NumAssocs == ArgExprs.size()); 1356 1357 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1358 for (unsigned i = 0; i < NumAssocs; ++i) { 1359 if (ArgTypes[i]) 1360 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1361 else 1362 Types[i] = nullptr; 1363 } 1364 1365 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1366 ControllingExpr, 1367 llvm::makeArrayRef(Types, NumAssocs), 1368 ArgExprs); 1369 delete [] Types; 1370 return ER; 1371 } 1372 1373 ExprResult 1374 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1375 SourceLocation DefaultLoc, 1376 SourceLocation RParenLoc, 1377 Expr *ControllingExpr, 1378 ArrayRef<TypeSourceInfo *> Types, 1379 ArrayRef<Expr *> Exprs) { 1380 unsigned NumAssocs = Types.size(); 1381 assert(NumAssocs == Exprs.size()); 1382 1383 // Decay and strip qualifiers for the controlling expression type, and handle 1384 // placeholder type replacement. See committee discussion from WG14 DR423. 1385 { 1386 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1387 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1388 if (R.isInvalid()) 1389 return ExprError(); 1390 ControllingExpr = R.get(); 1391 } 1392 1393 // The controlling expression is an unevaluated operand, so side effects are 1394 // likely unintended. 1395 if (ActiveTemplateInstantiations.empty() && 1396 ControllingExpr->HasSideEffects(Context, false)) 1397 Diag(ControllingExpr->getExprLoc(), 1398 diag::warn_side_effects_unevaluated_context); 1399 1400 bool TypeErrorFound = false, 1401 IsResultDependent = ControllingExpr->isTypeDependent(), 1402 ContainsUnexpandedParameterPack 1403 = ControllingExpr->containsUnexpandedParameterPack(); 1404 1405 for (unsigned i = 0; i < NumAssocs; ++i) { 1406 if (Exprs[i]->containsUnexpandedParameterPack()) 1407 ContainsUnexpandedParameterPack = true; 1408 1409 if (Types[i]) { 1410 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1411 ContainsUnexpandedParameterPack = true; 1412 1413 if (Types[i]->getType()->isDependentType()) { 1414 IsResultDependent = true; 1415 } else { 1416 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1417 // complete object type other than a variably modified type." 1418 unsigned D = 0; 1419 if (Types[i]->getType()->isIncompleteType()) 1420 D = diag::err_assoc_type_incomplete; 1421 else if (!Types[i]->getType()->isObjectType()) 1422 D = diag::err_assoc_type_nonobject; 1423 else if (Types[i]->getType()->isVariablyModifiedType()) 1424 D = diag::err_assoc_type_variably_modified; 1425 1426 if (D != 0) { 1427 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1428 << Types[i]->getTypeLoc().getSourceRange() 1429 << Types[i]->getType(); 1430 TypeErrorFound = true; 1431 } 1432 1433 // C11 6.5.1.1p2 "No two generic associations in the same generic 1434 // selection shall specify compatible types." 1435 for (unsigned j = i+1; j < NumAssocs; ++j) 1436 if (Types[j] && !Types[j]->getType()->isDependentType() && 1437 Context.typesAreCompatible(Types[i]->getType(), 1438 Types[j]->getType())) { 1439 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1440 diag::err_assoc_compatible_types) 1441 << Types[j]->getTypeLoc().getSourceRange() 1442 << Types[j]->getType() 1443 << Types[i]->getType(); 1444 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1445 diag::note_compat_assoc) 1446 << Types[i]->getTypeLoc().getSourceRange() 1447 << Types[i]->getType(); 1448 TypeErrorFound = true; 1449 } 1450 } 1451 } 1452 } 1453 if (TypeErrorFound) 1454 return ExprError(); 1455 1456 // If we determined that the generic selection is result-dependent, don't 1457 // try to compute the result expression. 1458 if (IsResultDependent) 1459 return new (Context) GenericSelectionExpr( 1460 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1461 ContainsUnexpandedParameterPack); 1462 1463 SmallVector<unsigned, 1> CompatIndices; 1464 unsigned DefaultIndex = -1U; 1465 for (unsigned i = 0; i < NumAssocs; ++i) { 1466 if (!Types[i]) 1467 DefaultIndex = i; 1468 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1469 Types[i]->getType())) 1470 CompatIndices.push_back(i); 1471 } 1472 1473 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1474 // type compatible with at most one of the types named in its generic 1475 // association list." 1476 if (CompatIndices.size() > 1) { 1477 // We strip parens here because the controlling expression is typically 1478 // parenthesized in macro definitions. 1479 ControllingExpr = ControllingExpr->IgnoreParens(); 1480 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1481 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1482 << (unsigned) CompatIndices.size(); 1483 for (unsigned I : CompatIndices) { 1484 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1485 diag::note_compat_assoc) 1486 << Types[I]->getTypeLoc().getSourceRange() 1487 << Types[I]->getType(); 1488 } 1489 return ExprError(); 1490 } 1491 1492 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1493 // its controlling expression shall have type compatible with exactly one of 1494 // the types named in its generic association list." 1495 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1496 // We strip parens here because the controlling expression is typically 1497 // parenthesized in macro definitions. 1498 ControllingExpr = ControllingExpr->IgnoreParens(); 1499 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1500 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1501 return ExprError(); 1502 } 1503 1504 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1505 // type name that is compatible with the type of the controlling expression, 1506 // then the result expression of the generic selection is the expression 1507 // in that generic association. Otherwise, the result expression of the 1508 // generic selection is the expression in the default generic association." 1509 unsigned ResultIndex = 1510 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1511 1512 return new (Context) GenericSelectionExpr( 1513 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1514 ContainsUnexpandedParameterPack, ResultIndex); 1515 } 1516 1517 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1518 /// location of the token and the offset of the ud-suffix within it. 1519 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1520 unsigned Offset) { 1521 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1522 S.getLangOpts()); 1523 } 1524 1525 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1526 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1527 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1528 IdentifierInfo *UDSuffix, 1529 SourceLocation UDSuffixLoc, 1530 ArrayRef<Expr*> Args, 1531 SourceLocation LitEndLoc) { 1532 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1533 1534 QualType ArgTy[2]; 1535 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1536 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1537 if (ArgTy[ArgIdx]->isArrayType()) 1538 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1539 } 1540 1541 DeclarationName OpName = 1542 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1543 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1544 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1545 1546 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1547 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1548 /*AllowRaw*/false, /*AllowTemplate*/false, 1549 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1550 return ExprError(); 1551 1552 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1553 } 1554 1555 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1556 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1557 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1558 /// multiple tokens. However, the common case is that StringToks points to one 1559 /// string. 1560 /// 1561 ExprResult 1562 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1563 assert(!StringToks.empty() && "Must have at least one string!"); 1564 1565 StringLiteralParser Literal(StringToks, PP); 1566 if (Literal.hadError) 1567 return ExprError(); 1568 1569 SmallVector<SourceLocation, 4> StringTokLocs; 1570 for (const Token &Tok : StringToks) 1571 StringTokLocs.push_back(Tok.getLocation()); 1572 1573 QualType CharTy = Context.CharTy; 1574 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1575 if (Literal.isWide()) { 1576 CharTy = Context.getWideCharType(); 1577 Kind = StringLiteral::Wide; 1578 } else if (Literal.isUTF8()) { 1579 Kind = StringLiteral::UTF8; 1580 } else if (Literal.isUTF16()) { 1581 CharTy = Context.Char16Ty; 1582 Kind = StringLiteral::UTF16; 1583 } else if (Literal.isUTF32()) { 1584 CharTy = Context.Char32Ty; 1585 Kind = StringLiteral::UTF32; 1586 } else if (Literal.isPascal()) { 1587 CharTy = Context.UnsignedCharTy; 1588 } 1589 1590 QualType CharTyConst = CharTy; 1591 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1592 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1593 CharTyConst.addConst(); 1594 1595 // Get an array type for the string, according to C99 6.4.5. This includes 1596 // the nul terminator character as well as the string length for pascal 1597 // strings. 1598 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1599 llvm::APInt(32, Literal.GetNumStringChars()+1), 1600 ArrayType::Normal, 0); 1601 1602 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1603 if (getLangOpts().OpenCL) { 1604 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1605 } 1606 1607 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1608 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1609 Kind, Literal.Pascal, StrTy, 1610 &StringTokLocs[0], 1611 StringTokLocs.size()); 1612 if (Literal.getUDSuffix().empty()) 1613 return Lit; 1614 1615 // We're building a user-defined literal. 1616 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1617 SourceLocation UDSuffixLoc = 1618 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1619 Literal.getUDSuffixOffset()); 1620 1621 // Make sure we're allowed user-defined literals here. 1622 if (!UDLScope) 1623 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1624 1625 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1626 // operator "" X (str, len) 1627 QualType SizeType = Context.getSizeType(); 1628 1629 DeclarationName OpName = 1630 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1631 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1632 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1633 1634 QualType ArgTy[] = { 1635 Context.getArrayDecayedType(StrTy), SizeType 1636 }; 1637 1638 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1639 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1640 /*AllowRaw*/false, /*AllowTemplate*/false, 1641 /*AllowStringTemplate*/true)) { 1642 1643 case LOLR_Cooked: { 1644 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1645 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1646 StringTokLocs[0]); 1647 Expr *Args[] = { Lit, LenArg }; 1648 1649 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1650 } 1651 1652 case LOLR_StringTemplate: { 1653 TemplateArgumentListInfo ExplicitArgs; 1654 1655 unsigned CharBits = Context.getIntWidth(CharTy); 1656 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1657 llvm::APSInt Value(CharBits, CharIsUnsigned); 1658 1659 TemplateArgument TypeArg(CharTy); 1660 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1661 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1662 1663 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1664 Value = Lit->getCodeUnit(I); 1665 TemplateArgument Arg(Context, Value, CharTy); 1666 TemplateArgumentLocInfo ArgInfo; 1667 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1668 } 1669 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1670 &ExplicitArgs); 1671 } 1672 case LOLR_Raw: 1673 case LOLR_Template: 1674 llvm_unreachable("unexpected literal operator lookup result"); 1675 case LOLR_Error: 1676 return ExprError(); 1677 } 1678 llvm_unreachable("unexpected literal operator lookup result"); 1679 } 1680 1681 ExprResult 1682 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1683 SourceLocation Loc, 1684 const CXXScopeSpec *SS) { 1685 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1686 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1687 } 1688 1689 /// BuildDeclRefExpr - Build an expression that references a 1690 /// declaration that does not require a closure capture. 1691 ExprResult 1692 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1693 const DeclarationNameInfo &NameInfo, 1694 const CXXScopeSpec *SS, NamedDecl *FoundD, 1695 const TemplateArgumentListInfo *TemplateArgs) { 1696 if (getLangOpts().CUDA) 1697 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1698 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1699 if (CheckCUDATarget(Caller, Callee)) { 1700 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1701 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1702 << IdentifyCUDATarget(Caller); 1703 Diag(D->getLocation(), diag::note_previous_decl) 1704 << D->getIdentifier(); 1705 return ExprError(); 1706 } 1707 } 1708 1709 bool RefersToCapturedVariable = 1710 isa<VarDecl>(D) && 1711 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1712 1713 DeclRefExpr *E; 1714 if (isa<VarTemplateSpecializationDecl>(D)) { 1715 VarTemplateSpecializationDecl *VarSpec = 1716 cast<VarTemplateSpecializationDecl>(D); 1717 1718 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1719 : NestedNameSpecifierLoc(), 1720 VarSpec->getTemplateKeywordLoc(), D, 1721 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1722 FoundD, TemplateArgs); 1723 } else { 1724 assert(!TemplateArgs && "No template arguments for non-variable" 1725 " template specialization references"); 1726 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1727 : NestedNameSpecifierLoc(), 1728 SourceLocation(), D, RefersToCapturedVariable, 1729 NameInfo, Ty, VK, FoundD); 1730 } 1731 1732 MarkDeclRefReferenced(E); 1733 1734 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1735 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1736 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1737 recordUseOfEvaluatedWeak(E); 1738 1739 // Just in case we're building an illegal pointer-to-member. 1740 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1741 if (FD && FD->isBitField()) 1742 E->setObjectKind(OK_BitField); 1743 1744 return E; 1745 } 1746 1747 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1748 /// possibly a list of template arguments. 1749 /// 1750 /// If this produces template arguments, it is permitted to call 1751 /// DecomposeTemplateName. 1752 /// 1753 /// This actually loses a lot of source location information for 1754 /// non-standard name kinds; we should consider preserving that in 1755 /// some way. 1756 void 1757 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1758 TemplateArgumentListInfo &Buffer, 1759 DeclarationNameInfo &NameInfo, 1760 const TemplateArgumentListInfo *&TemplateArgs) { 1761 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1762 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1763 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1764 1765 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1766 Id.TemplateId->NumArgs); 1767 translateTemplateArguments(TemplateArgsPtr, Buffer); 1768 1769 TemplateName TName = Id.TemplateId->Template.get(); 1770 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1771 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1772 TemplateArgs = &Buffer; 1773 } else { 1774 NameInfo = GetNameFromUnqualifiedId(Id); 1775 TemplateArgs = nullptr; 1776 } 1777 } 1778 1779 static void emitEmptyLookupTypoDiagnostic( 1780 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1781 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1782 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1783 DeclContext *Ctx = 1784 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1785 if (!TC) { 1786 // Emit a special diagnostic for failed member lookups. 1787 // FIXME: computing the declaration context might fail here (?) 1788 if (Ctx) 1789 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1790 << SS.getRange(); 1791 else 1792 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1793 return; 1794 } 1795 1796 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1797 bool DroppedSpecifier = 1798 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1799 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1800 ? diag::note_implicit_param_decl 1801 : diag::note_previous_decl; 1802 if (!Ctx) 1803 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1804 SemaRef.PDiag(NoteID)); 1805 else 1806 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1807 << Typo << Ctx << DroppedSpecifier 1808 << SS.getRange(), 1809 SemaRef.PDiag(NoteID)); 1810 } 1811 1812 /// Diagnose an empty lookup. 1813 /// 1814 /// \return false if new lookup candidates were found 1815 bool 1816 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1817 std::unique_ptr<CorrectionCandidateCallback> CCC, 1818 TemplateArgumentListInfo *ExplicitTemplateArgs, 1819 ArrayRef<Expr *> Args, TypoExpr **Out) { 1820 DeclarationName Name = R.getLookupName(); 1821 1822 unsigned diagnostic = diag::err_undeclared_var_use; 1823 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1824 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1825 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1826 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1827 diagnostic = diag::err_undeclared_use; 1828 diagnostic_suggest = diag::err_undeclared_use_suggest; 1829 } 1830 1831 // If the original lookup was an unqualified lookup, fake an 1832 // unqualified lookup. This is useful when (for example) the 1833 // original lookup would not have found something because it was a 1834 // dependent name. 1835 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1836 while (DC) { 1837 if (isa<CXXRecordDecl>(DC)) { 1838 LookupQualifiedName(R, DC); 1839 1840 if (!R.empty()) { 1841 // Don't give errors about ambiguities in this lookup. 1842 R.suppressDiagnostics(); 1843 1844 // During a default argument instantiation the CurContext points 1845 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1846 // function parameter list, hence add an explicit check. 1847 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1848 ActiveTemplateInstantiations.back().Kind == 1849 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1850 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1851 bool isInstance = CurMethod && 1852 CurMethod->isInstance() && 1853 DC == CurMethod->getParent() && !isDefaultArgument; 1854 1855 // Give a code modification hint to insert 'this->'. 1856 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1857 // Actually quite difficult! 1858 if (getLangOpts().MSVCCompat) 1859 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1860 if (isInstance) { 1861 Diag(R.getNameLoc(), diagnostic) << Name 1862 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1863 CheckCXXThisCapture(R.getNameLoc()); 1864 } else { 1865 Diag(R.getNameLoc(), diagnostic) << Name; 1866 } 1867 1868 // Do we really want to note all of these? 1869 for (NamedDecl *D : R) 1870 Diag(D->getLocation(), diag::note_dependent_var_use); 1871 1872 // Return true if we are inside a default argument instantiation 1873 // and the found name refers to an instance member function, otherwise 1874 // the function calling DiagnoseEmptyLookup will try to create an 1875 // implicit member call and this is wrong for default argument. 1876 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1877 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1878 return true; 1879 } 1880 1881 // Tell the callee to try to recover. 1882 return false; 1883 } 1884 1885 R.clear(); 1886 } 1887 1888 // In Microsoft mode, if we are performing lookup from within a friend 1889 // function definition declared at class scope then we must set 1890 // DC to the lexical parent to be able to search into the parent 1891 // class. 1892 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1893 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1894 DC->getLexicalParent()->isRecord()) 1895 DC = DC->getLexicalParent(); 1896 else 1897 DC = DC->getParent(); 1898 } 1899 1900 // We didn't find anything, so try to correct for a typo. 1901 TypoCorrection Corrected; 1902 if (S && Out) { 1903 SourceLocation TypoLoc = R.getNameLoc(); 1904 assert(!ExplicitTemplateArgs && 1905 "Diagnosing an empty lookup with explicit template args!"); 1906 *Out = CorrectTypoDelayed( 1907 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1908 [=](const TypoCorrection &TC) { 1909 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1910 diagnostic, diagnostic_suggest); 1911 }, 1912 nullptr, CTK_ErrorRecovery); 1913 if (*Out) 1914 return true; 1915 } else if (S && (Corrected = 1916 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1917 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1918 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1919 bool DroppedSpecifier = 1920 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1921 R.setLookupName(Corrected.getCorrection()); 1922 1923 bool AcceptableWithRecovery = false; 1924 bool AcceptableWithoutRecovery = false; 1925 NamedDecl *ND = Corrected.getFoundDecl(); 1926 if (ND) { 1927 if (Corrected.isOverloaded()) { 1928 OverloadCandidateSet OCS(R.getNameLoc(), 1929 OverloadCandidateSet::CSK_Normal); 1930 OverloadCandidateSet::iterator Best; 1931 for (NamedDecl *CD : Corrected) { 1932 if (FunctionTemplateDecl *FTD = 1933 dyn_cast<FunctionTemplateDecl>(CD)) 1934 AddTemplateOverloadCandidate( 1935 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1936 Args, OCS); 1937 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1938 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1939 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1940 Args, OCS); 1941 } 1942 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1943 case OR_Success: 1944 ND = Best->FoundDecl; 1945 Corrected.setCorrectionDecl(ND); 1946 break; 1947 default: 1948 // FIXME: Arbitrarily pick the first declaration for the note. 1949 Corrected.setCorrectionDecl(ND); 1950 break; 1951 } 1952 } 1953 R.addDecl(ND); 1954 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1955 CXXRecordDecl *Record = nullptr; 1956 if (Corrected.getCorrectionSpecifier()) { 1957 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1958 Record = Ty->getAsCXXRecordDecl(); 1959 } 1960 if (!Record) 1961 Record = cast<CXXRecordDecl>( 1962 ND->getDeclContext()->getRedeclContext()); 1963 R.setNamingClass(Record); 1964 } 1965 1966 auto *UnderlyingND = ND->getUnderlyingDecl(); 1967 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1968 isa<FunctionTemplateDecl>(UnderlyingND); 1969 // FIXME: If we ended up with a typo for a type name or 1970 // Objective-C class name, we're in trouble because the parser 1971 // is in the wrong place to recover. Suggest the typo 1972 // correction, but don't make it a fix-it since we're not going 1973 // to recover well anyway. 1974 AcceptableWithoutRecovery = 1975 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1976 } else { 1977 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1978 // because we aren't able to recover. 1979 AcceptableWithoutRecovery = true; 1980 } 1981 1982 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1983 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1984 ? diag::note_implicit_param_decl 1985 : diag::note_previous_decl; 1986 if (SS.isEmpty()) 1987 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1988 PDiag(NoteID), AcceptableWithRecovery); 1989 else 1990 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1991 << Name << computeDeclContext(SS, false) 1992 << DroppedSpecifier << SS.getRange(), 1993 PDiag(NoteID), AcceptableWithRecovery); 1994 1995 // Tell the callee whether to try to recover. 1996 return !AcceptableWithRecovery; 1997 } 1998 } 1999 R.clear(); 2000 2001 // Emit a special diagnostic for failed member lookups. 2002 // FIXME: computing the declaration context might fail here (?) 2003 if (!SS.isEmpty()) { 2004 Diag(R.getNameLoc(), diag::err_no_member) 2005 << Name << computeDeclContext(SS, false) 2006 << SS.getRange(); 2007 return true; 2008 } 2009 2010 // Give up, we can't recover. 2011 Diag(R.getNameLoc(), diagnostic) << Name; 2012 return true; 2013 } 2014 2015 /// In Microsoft mode, if we are inside a template class whose parent class has 2016 /// dependent base classes, and we can't resolve an unqualified identifier, then 2017 /// assume the identifier is a member of a dependent base class. We can only 2018 /// recover successfully in static methods, instance methods, and other contexts 2019 /// where 'this' is available. This doesn't precisely match MSVC's 2020 /// instantiation model, but it's close enough. 2021 static Expr * 2022 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2023 DeclarationNameInfo &NameInfo, 2024 SourceLocation TemplateKWLoc, 2025 const TemplateArgumentListInfo *TemplateArgs) { 2026 // Only try to recover from lookup into dependent bases in static methods or 2027 // contexts where 'this' is available. 2028 QualType ThisType = S.getCurrentThisType(); 2029 const CXXRecordDecl *RD = nullptr; 2030 if (!ThisType.isNull()) 2031 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2032 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2033 RD = MD->getParent(); 2034 if (!RD || !RD->hasAnyDependentBases()) 2035 return nullptr; 2036 2037 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2038 // is available, suggest inserting 'this->' as a fixit. 2039 SourceLocation Loc = NameInfo.getLoc(); 2040 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2041 DB << NameInfo.getName() << RD; 2042 2043 if (!ThisType.isNull()) { 2044 DB << FixItHint::CreateInsertion(Loc, "this->"); 2045 return CXXDependentScopeMemberExpr::Create( 2046 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2047 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2048 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2049 } 2050 2051 // Synthesize a fake NNS that points to the derived class. This will 2052 // perform name lookup during template instantiation. 2053 CXXScopeSpec SS; 2054 auto *NNS = 2055 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2056 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2057 return DependentScopeDeclRefExpr::Create( 2058 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2059 TemplateArgs); 2060 } 2061 2062 ExprResult 2063 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2064 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2065 bool HasTrailingLParen, bool IsAddressOfOperand, 2066 std::unique_ptr<CorrectionCandidateCallback> CCC, 2067 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2068 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2069 "cannot be direct & operand and have a trailing lparen"); 2070 if (SS.isInvalid()) 2071 return ExprError(); 2072 2073 TemplateArgumentListInfo TemplateArgsBuffer; 2074 2075 // Decompose the UnqualifiedId into the following data. 2076 DeclarationNameInfo NameInfo; 2077 const TemplateArgumentListInfo *TemplateArgs; 2078 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2079 2080 DeclarationName Name = NameInfo.getName(); 2081 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2082 SourceLocation NameLoc = NameInfo.getLoc(); 2083 2084 // C++ [temp.dep.expr]p3: 2085 // An id-expression is type-dependent if it contains: 2086 // -- an identifier that was declared with a dependent type, 2087 // (note: handled after lookup) 2088 // -- a template-id that is dependent, 2089 // (note: handled in BuildTemplateIdExpr) 2090 // -- a conversion-function-id that specifies a dependent type, 2091 // -- a nested-name-specifier that contains a class-name that 2092 // names a dependent type. 2093 // Determine whether this is a member of an unknown specialization; 2094 // we need to handle these differently. 2095 bool DependentID = false; 2096 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2097 Name.getCXXNameType()->isDependentType()) { 2098 DependentID = true; 2099 } else if (SS.isSet()) { 2100 if (DeclContext *DC = computeDeclContext(SS, false)) { 2101 if (RequireCompleteDeclContext(SS, DC)) 2102 return ExprError(); 2103 } else { 2104 DependentID = true; 2105 } 2106 } 2107 2108 if (DependentID) 2109 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2110 IsAddressOfOperand, TemplateArgs); 2111 2112 // Perform the required lookup. 2113 LookupResult R(*this, NameInfo, 2114 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2115 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2116 if (TemplateArgs) { 2117 // Lookup the template name again to correctly establish the context in 2118 // which it was found. This is really unfortunate as we already did the 2119 // lookup to determine that it was a template name in the first place. If 2120 // this becomes a performance hit, we can work harder to preserve those 2121 // results until we get here but it's likely not worth it. 2122 bool MemberOfUnknownSpecialization; 2123 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2124 MemberOfUnknownSpecialization); 2125 2126 if (MemberOfUnknownSpecialization || 2127 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2128 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2129 IsAddressOfOperand, TemplateArgs); 2130 } else { 2131 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2132 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2133 2134 // If the result might be in a dependent base class, this is a dependent 2135 // id-expression. 2136 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2137 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2138 IsAddressOfOperand, TemplateArgs); 2139 2140 // If this reference is in an Objective-C method, then we need to do 2141 // some special Objective-C lookup, too. 2142 if (IvarLookupFollowUp) { 2143 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2144 if (E.isInvalid()) 2145 return ExprError(); 2146 2147 if (Expr *Ex = E.getAs<Expr>()) 2148 return Ex; 2149 } 2150 } 2151 2152 if (R.isAmbiguous()) 2153 return ExprError(); 2154 2155 // This could be an implicitly declared function reference (legal in C90, 2156 // extension in C99, forbidden in C++). 2157 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2158 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2159 if (D) R.addDecl(D); 2160 } 2161 2162 // Determine whether this name might be a candidate for 2163 // argument-dependent lookup. 2164 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2165 2166 if (R.empty() && !ADL) { 2167 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2168 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2169 TemplateKWLoc, TemplateArgs)) 2170 return E; 2171 } 2172 2173 // Don't diagnose an empty lookup for inline assembly. 2174 if (IsInlineAsmIdentifier) 2175 return ExprError(); 2176 2177 // If this name wasn't predeclared and if this is not a function 2178 // call, diagnose the problem. 2179 TypoExpr *TE = nullptr; 2180 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2181 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2182 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2183 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2184 "Typo correction callback misconfigured"); 2185 if (CCC) { 2186 // Make sure the callback knows what the typo being diagnosed is. 2187 CCC->setTypoName(II); 2188 if (SS.isValid()) 2189 CCC->setTypoNNS(SS.getScopeRep()); 2190 } 2191 if (DiagnoseEmptyLookup(S, SS, R, 2192 CCC ? std::move(CCC) : std::move(DefaultValidator), 2193 nullptr, None, &TE)) { 2194 if (TE && KeywordReplacement) { 2195 auto &State = getTypoExprState(TE); 2196 auto BestTC = State.Consumer->getNextCorrection(); 2197 if (BestTC.isKeyword()) { 2198 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2199 if (State.DiagHandler) 2200 State.DiagHandler(BestTC); 2201 KeywordReplacement->startToken(); 2202 KeywordReplacement->setKind(II->getTokenID()); 2203 KeywordReplacement->setIdentifierInfo(II); 2204 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2205 // Clean up the state associated with the TypoExpr, since it has 2206 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2207 clearDelayedTypo(TE); 2208 // Signal that a correction to a keyword was performed by returning a 2209 // valid-but-null ExprResult. 2210 return (Expr*)nullptr; 2211 } 2212 State.Consumer->resetCorrectionStream(); 2213 } 2214 return TE ? TE : ExprError(); 2215 } 2216 2217 assert(!R.empty() && 2218 "DiagnoseEmptyLookup returned false but added no results"); 2219 2220 // If we found an Objective-C instance variable, let 2221 // LookupInObjCMethod build the appropriate expression to 2222 // reference the ivar. 2223 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2224 R.clear(); 2225 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2226 // In a hopelessly buggy code, Objective-C instance variable 2227 // lookup fails and no expression will be built to reference it. 2228 if (!E.isInvalid() && !E.get()) 2229 return ExprError(); 2230 return E; 2231 } 2232 } 2233 2234 // This is guaranteed from this point on. 2235 assert(!R.empty() || ADL); 2236 2237 // Check whether this might be a C++ implicit instance member access. 2238 // C++ [class.mfct.non-static]p3: 2239 // When an id-expression that is not part of a class member access 2240 // syntax and not used to form a pointer to member is used in the 2241 // body of a non-static member function of class X, if name lookup 2242 // resolves the name in the id-expression to a non-static non-type 2243 // member of some class C, the id-expression is transformed into a 2244 // class member access expression using (*this) as the 2245 // postfix-expression to the left of the . operator. 2246 // 2247 // But we don't actually need to do this for '&' operands if R 2248 // resolved to a function or overloaded function set, because the 2249 // expression is ill-formed if it actually works out to be a 2250 // non-static member function: 2251 // 2252 // C++ [expr.ref]p4: 2253 // Otherwise, if E1.E2 refers to a non-static member function. . . 2254 // [t]he expression can be used only as the left-hand operand of a 2255 // member function call. 2256 // 2257 // There are other safeguards against such uses, but it's important 2258 // to get this right here so that we don't end up making a 2259 // spuriously dependent expression if we're inside a dependent 2260 // instance method. 2261 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2262 bool MightBeImplicitMember; 2263 if (!IsAddressOfOperand) 2264 MightBeImplicitMember = true; 2265 else if (!SS.isEmpty()) 2266 MightBeImplicitMember = false; 2267 else if (R.isOverloadedResult()) 2268 MightBeImplicitMember = false; 2269 else if (R.isUnresolvableResult()) 2270 MightBeImplicitMember = true; 2271 else 2272 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2273 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2274 isa<MSPropertyDecl>(R.getFoundDecl()); 2275 2276 if (MightBeImplicitMember) 2277 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2278 R, TemplateArgs, S); 2279 } 2280 2281 if (TemplateArgs || TemplateKWLoc.isValid()) { 2282 2283 // In C++1y, if this is a variable template id, then check it 2284 // in BuildTemplateIdExpr(). 2285 // The single lookup result must be a variable template declaration. 2286 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2287 Id.TemplateId->Kind == TNK_Var_template) { 2288 assert(R.getAsSingle<VarTemplateDecl>() && 2289 "There should only be one declaration found."); 2290 } 2291 2292 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2293 } 2294 2295 return BuildDeclarationNameExpr(SS, R, ADL); 2296 } 2297 2298 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2299 /// declaration name, generally during template instantiation. 2300 /// There's a large number of things which don't need to be done along 2301 /// this path. 2302 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2303 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2304 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2305 DeclContext *DC = computeDeclContext(SS, false); 2306 if (!DC) 2307 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2308 NameInfo, /*TemplateArgs=*/nullptr); 2309 2310 if (RequireCompleteDeclContext(SS, DC)) 2311 return ExprError(); 2312 2313 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2314 LookupQualifiedName(R, DC); 2315 2316 if (R.isAmbiguous()) 2317 return ExprError(); 2318 2319 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2320 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2321 NameInfo, /*TemplateArgs=*/nullptr); 2322 2323 if (R.empty()) { 2324 Diag(NameInfo.getLoc(), diag::err_no_member) 2325 << NameInfo.getName() << DC << SS.getRange(); 2326 return ExprError(); 2327 } 2328 2329 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2330 // Diagnose a missing typename if this resolved unambiguously to a type in 2331 // a dependent context. If we can recover with a type, downgrade this to 2332 // a warning in Microsoft compatibility mode. 2333 unsigned DiagID = diag::err_typename_missing; 2334 if (RecoveryTSI && getLangOpts().MSVCCompat) 2335 DiagID = diag::ext_typename_missing; 2336 SourceLocation Loc = SS.getBeginLoc(); 2337 auto D = Diag(Loc, DiagID); 2338 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2339 << SourceRange(Loc, NameInfo.getEndLoc()); 2340 2341 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2342 // context. 2343 if (!RecoveryTSI) 2344 return ExprError(); 2345 2346 // Only issue the fixit if we're prepared to recover. 2347 D << FixItHint::CreateInsertion(Loc, "typename "); 2348 2349 // Recover by pretending this was an elaborated type. 2350 QualType Ty = Context.getTypeDeclType(TD); 2351 TypeLocBuilder TLB; 2352 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2353 2354 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2355 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2356 QTL.setElaboratedKeywordLoc(SourceLocation()); 2357 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2358 2359 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2360 2361 return ExprEmpty(); 2362 } 2363 2364 // Defend against this resolving to an implicit member access. We usually 2365 // won't get here if this might be a legitimate a class member (we end up in 2366 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2367 // a pointer-to-member or in an unevaluated context in C++11. 2368 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2369 return BuildPossibleImplicitMemberExpr(SS, 2370 /*TemplateKWLoc=*/SourceLocation(), 2371 R, /*TemplateArgs=*/nullptr, S); 2372 2373 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2374 } 2375 2376 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2377 /// detected that we're currently inside an ObjC method. Perform some 2378 /// additional lookup. 2379 /// 2380 /// Ideally, most of this would be done by lookup, but there's 2381 /// actually quite a lot of extra work involved. 2382 /// 2383 /// Returns a null sentinel to indicate trivial success. 2384 ExprResult 2385 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2386 IdentifierInfo *II, bool AllowBuiltinCreation) { 2387 SourceLocation Loc = Lookup.getNameLoc(); 2388 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2389 2390 // Check for error condition which is already reported. 2391 if (!CurMethod) 2392 return ExprError(); 2393 2394 // There are two cases to handle here. 1) scoped lookup could have failed, 2395 // in which case we should look for an ivar. 2) scoped lookup could have 2396 // found a decl, but that decl is outside the current instance method (i.e. 2397 // a global variable). In these two cases, we do a lookup for an ivar with 2398 // this name, if the lookup sucedes, we replace it our current decl. 2399 2400 // If we're in a class method, we don't normally want to look for 2401 // ivars. But if we don't find anything else, and there's an 2402 // ivar, that's an error. 2403 bool IsClassMethod = CurMethod->isClassMethod(); 2404 2405 bool LookForIvars; 2406 if (Lookup.empty()) 2407 LookForIvars = true; 2408 else if (IsClassMethod) 2409 LookForIvars = false; 2410 else 2411 LookForIvars = (Lookup.isSingleResult() && 2412 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2413 ObjCInterfaceDecl *IFace = nullptr; 2414 if (LookForIvars) { 2415 IFace = CurMethod->getClassInterface(); 2416 ObjCInterfaceDecl *ClassDeclared; 2417 ObjCIvarDecl *IV = nullptr; 2418 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2419 // Diagnose using an ivar in a class method. 2420 if (IsClassMethod) 2421 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2422 << IV->getDeclName()); 2423 2424 // If we're referencing an invalid decl, just return this as a silent 2425 // error node. The error diagnostic was already emitted on the decl. 2426 if (IV->isInvalidDecl()) 2427 return ExprError(); 2428 2429 // Check if referencing a field with __attribute__((deprecated)). 2430 if (DiagnoseUseOfDecl(IV, Loc)) 2431 return ExprError(); 2432 2433 // Diagnose the use of an ivar outside of the declaring class. 2434 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2435 !declaresSameEntity(ClassDeclared, IFace) && 2436 !getLangOpts().DebuggerSupport) 2437 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2438 2439 // FIXME: This should use a new expr for a direct reference, don't 2440 // turn this into Self->ivar, just return a BareIVarExpr or something. 2441 IdentifierInfo &II = Context.Idents.get("self"); 2442 UnqualifiedId SelfName; 2443 SelfName.setIdentifier(&II, SourceLocation()); 2444 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2445 CXXScopeSpec SelfScopeSpec; 2446 SourceLocation TemplateKWLoc; 2447 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2448 SelfName, false, false); 2449 if (SelfExpr.isInvalid()) 2450 return ExprError(); 2451 2452 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2453 if (SelfExpr.isInvalid()) 2454 return ExprError(); 2455 2456 MarkAnyDeclReferenced(Loc, IV, true); 2457 2458 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2459 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2460 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2461 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2462 2463 ObjCIvarRefExpr *Result = new (Context) 2464 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2465 IV->getLocation(), SelfExpr.get(), true, true); 2466 2467 if (getLangOpts().ObjCAutoRefCount) { 2468 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2469 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2470 recordUseOfEvaluatedWeak(Result); 2471 } 2472 if (CurContext->isClosure()) 2473 Diag(Loc, diag::warn_implicitly_retains_self) 2474 << FixItHint::CreateInsertion(Loc, "self->"); 2475 } 2476 2477 return Result; 2478 } 2479 } else if (CurMethod->isInstanceMethod()) { 2480 // We should warn if a local variable hides an ivar. 2481 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2482 ObjCInterfaceDecl *ClassDeclared; 2483 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2484 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2485 declaresSameEntity(IFace, ClassDeclared)) 2486 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2487 } 2488 } 2489 } else if (Lookup.isSingleResult() && 2490 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2491 // If accessing a stand-alone ivar in a class method, this is an error. 2492 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2493 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2494 << IV->getDeclName()); 2495 } 2496 2497 if (Lookup.empty() && II && AllowBuiltinCreation) { 2498 // FIXME. Consolidate this with similar code in LookupName. 2499 if (unsigned BuiltinID = II->getBuiltinID()) { 2500 if (!(getLangOpts().CPlusPlus && 2501 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2502 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2503 S, Lookup.isForRedeclaration(), 2504 Lookup.getNameLoc()); 2505 if (D) Lookup.addDecl(D); 2506 } 2507 } 2508 } 2509 // Sentinel value saying that we didn't do anything special. 2510 return ExprResult((Expr *)nullptr); 2511 } 2512 2513 /// \brief Cast a base object to a member's actual type. 2514 /// 2515 /// Logically this happens in three phases: 2516 /// 2517 /// * First we cast from the base type to the naming class. 2518 /// The naming class is the class into which we were looking 2519 /// when we found the member; it's the qualifier type if a 2520 /// qualifier was provided, and otherwise it's the base type. 2521 /// 2522 /// * Next we cast from the naming class to the declaring class. 2523 /// If the member we found was brought into a class's scope by 2524 /// a using declaration, this is that class; otherwise it's 2525 /// the class declaring the member. 2526 /// 2527 /// * Finally we cast from the declaring class to the "true" 2528 /// declaring class of the member. This conversion does not 2529 /// obey access control. 2530 ExprResult 2531 Sema::PerformObjectMemberConversion(Expr *From, 2532 NestedNameSpecifier *Qualifier, 2533 NamedDecl *FoundDecl, 2534 NamedDecl *Member) { 2535 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2536 if (!RD) 2537 return From; 2538 2539 QualType DestRecordType; 2540 QualType DestType; 2541 QualType FromRecordType; 2542 QualType FromType = From->getType(); 2543 bool PointerConversions = false; 2544 if (isa<FieldDecl>(Member)) { 2545 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2546 2547 if (FromType->getAs<PointerType>()) { 2548 DestType = Context.getPointerType(DestRecordType); 2549 FromRecordType = FromType->getPointeeType(); 2550 PointerConversions = true; 2551 } else { 2552 DestType = DestRecordType; 2553 FromRecordType = FromType; 2554 } 2555 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2556 if (Method->isStatic()) 2557 return From; 2558 2559 DestType = Method->getThisType(Context); 2560 DestRecordType = DestType->getPointeeType(); 2561 2562 if (FromType->getAs<PointerType>()) { 2563 FromRecordType = FromType->getPointeeType(); 2564 PointerConversions = true; 2565 } else { 2566 FromRecordType = FromType; 2567 DestType = DestRecordType; 2568 } 2569 } else { 2570 // No conversion necessary. 2571 return From; 2572 } 2573 2574 if (DestType->isDependentType() || FromType->isDependentType()) 2575 return From; 2576 2577 // If the unqualified types are the same, no conversion is necessary. 2578 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2579 return From; 2580 2581 SourceRange FromRange = From->getSourceRange(); 2582 SourceLocation FromLoc = FromRange.getBegin(); 2583 2584 ExprValueKind VK = From->getValueKind(); 2585 2586 // C++ [class.member.lookup]p8: 2587 // [...] Ambiguities can often be resolved by qualifying a name with its 2588 // class name. 2589 // 2590 // If the member was a qualified name and the qualified referred to a 2591 // specific base subobject type, we'll cast to that intermediate type 2592 // first and then to the object in which the member is declared. That allows 2593 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2594 // 2595 // class Base { public: int x; }; 2596 // class Derived1 : public Base { }; 2597 // class Derived2 : public Base { }; 2598 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2599 // 2600 // void VeryDerived::f() { 2601 // x = 17; // error: ambiguous base subobjects 2602 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2603 // } 2604 if (Qualifier && Qualifier->getAsType()) { 2605 QualType QType = QualType(Qualifier->getAsType(), 0); 2606 assert(QType->isRecordType() && "lookup done with non-record type"); 2607 2608 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2609 2610 // In C++98, the qualifier type doesn't actually have to be a base 2611 // type of the object type, in which case we just ignore it. 2612 // Otherwise build the appropriate casts. 2613 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2614 CXXCastPath BasePath; 2615 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2616 FromLoc, FromRange, &BasePath)) 2617 return ExprError(); 2618 2619 if (PointerConversions) 2620 QType = Context.getPointerType(QType); 2621 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2622 VK, &BasePath).get(); 2623 2624 FromType = QType; 2625 FromRecordType = QRecordType; 2626 2627 // If the qualifier type was the same as the destination type, 2628 // we're done. 2629 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2630 return From; 2631 } 2632 } 2633 2634 bool IgnoreAccess = false; 2635 2636 // If we actually found the member through a using declaration, cast 2637 // down to the using declaration's type. 2638 // 2639 // Pointer equality is fine here because only one declaration of a 2640 // class ever has member declarations. 2641 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2642 assert(isa<UsingShadowDecl>(FoundDecl)); 2643 QualType URecordType = Context.getTypeDeclType( 2644 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2645 2646 // We only need to do this if the naming-class to declaring-class 2647 // conversion is non-trivial. 2648 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2649 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2650 CXXCastPath BasePath; 2651 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2652 FromLoc, FromRange, &BasePath)) 2653 return ExprError(); 2654 2655 QualType UType = URecordType; 2656 if (PointerConversions) 2657 UType = Context.getPointerType(UType); 2658 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2659 VK, &BasePath).get(); 2660 FromType = UType; 2661 FromRecordType = URecordType; 2662 } 2663 2664 // We don't do access control for the conversion from the 2665 // declaring class to the true declaring class. 2666 IgnoreAccess = true; 2667 } 2668 2669 CXXCastPath BasePath; 2670 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2671 FromLoc, FromRange, &BasePath, 2672 IgnoreAccess)) 2673 return ExprError(); 2674 2675 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2676 VK, &BasePath); 2677 } 2678 2679 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2680 const LookupResult &R, 2681 bool HasTrailingLParen) { 2682 // Only when used directly as the postfix-expression of a call. 2683 if (!HasTrailingLParen) 2684 return false; 2685 2686 // Never if a scope specifier was provided. 2687 if (SS.isSet()) 2688 return false; 2689 2690 // Only in C++ or ObjC++. 2691 if (!getLangOpts().CPlusPlus) 2692 return false; 2693 2694 // Turn off ADL when we find certain kinds of declarations during 2695 // normal lookup: 2696 for (NamedDecl *D : R) { 2697 // C++0x [basic.lookup.argdep]p3: 2698 // -- a declaration of a class member 2699 // Since using decls preserve this property, we check this on the 2700 // original decl. 2701 if (D->isCXXClassMember()) 2702 return false; 2703 2704 // C++0x [basic.lookup.argdep]p3: 2705 // -- a block-scope function declaration that is not a 2706 // using-declaration 2707 // NOTE: we also trigger this for function templates (in fact, we 2708 // don't check the decl type at all, since all other decl types 2709 // turn off ADL anyway). 2710 if (isa<UsingShadowDecl>(D)) 2711 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2712 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2713 return false; 2714 2715 // C++0x [basic.lookup.argdep]p3: 2716 // -- a declaration that is neither a function or a function 2717 // template 2718 // And also for builtin functions. 2719 if (isa<FunctionDecl>(D)) { 2720 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2721 2722 // But also builtin functions. 2723 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2724 return false; 2725 } else if (!isa<FunctionTemplateDecl>(D)) 2726 return false; 2727 } 2728 2729 return true; 2730 } 2731 2732 2733 /// Diagnoses obvious problems with the use of the given declaration 2734 /// as an expression. This is only actually called for lookups that 2735 /// were not overloaded, and it doesn't promise that the declaration 2736 /// will in fact be used. 2737 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2738 if (isa<TypedefNameDecl>(D)) { 2739 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2740 return true; 2741 } 2742 2743 if (isa<ObjCInterfaceDecl>(D)) { 2744 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2745 return true; 2746 } 2747 2748 if (isa<NamespaceDecl>(D)) { 2749 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2750 return true; 2751 } 2752 2753 return false; 2754 } 2755 2756 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2757 LookupResult &R, bool NeedsADL, 2758 bool AcceptInvalidDecl) { 2759 // If this is a single, fully-resolved result and we don't need ADL, 2760 // just build an ordinary singleton decl ref. 2761 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2762 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2763 R.getRepresentativeDecl(), nullptr, 2764 AcceptInvalidDecl); 2765 2766 // We only need to check the declaration if there's exactly one 2767 // result, because in the overloaded case the results can only be 2768 // functions and function templates. 2769 if (R.isSingleResult() && 2770 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2771 return ExprError(); 2772 2773 // Otherwise, just build an unresolved lookup expression. Suppress 2774 // any lookup-related diagnostics; we'll hash these out later, when 2775 // we've picked a target. 2776 R.suppressDiagnostics(); 2777 2778 UnresolvedLookupExpr *ULE 2779 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2780 SS.getWithLocInContext(Context), 2781 R.getLookupNameInfo(), 2782 NeedsADL, R.isOverloadedResult(), 2783 R.begin(), R.end()); 2784 2785 return ULE; 2786 } 2787 2788 /// \brief Complete semantic analysis for a reference to the given declaration. 2789 ExprResult Sema::BuildDeclarationNameExpr( 2790 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2791 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2792 bool AcceptInvalidDecl) { 2793 assert(D && "Cannot refer to a NULL declaration"); 2794 assert(!isa<FunctionTemplateDecl>(D) && 2795 "Cannot refer unambiguously to a function template"); 2796 2797 SourceLocation Loc = NameInfo.getLoc(); 2798 if (CheckDeclInExpr(*this, Loc, D)) 2799 return ExprError(); 2800 2801 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2802 // Specifically diagnose references to class templates that are missing 2803 // a template argument list. 2804 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2805 << Template << SS.getRange(); 2806 Diag(Template->getLocation(), diag::note_template_decl_here); 2807 return ExprError(); 2808 } 2809 2810 // Make sure that we're referring to a value. 2811 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2812 if (!VD) { 2813 Diag(Loc, diag::err_ref_non_value) 2814 << D << SS.getRange(); 2815 Diag(D->getLocation(), diag::note_declared_at); 2816 return ExprError(); 2817 } 2818 2819 // Check whether this declaration can be used. Note that we suppress 2820 // this check when we're going to perform argument-dependent lookup 2821 // on this function name, because this might not be the function 2822 // that overload resolution actually selects. 2823 if (DiagnoseUseOfDecl(VD, Loc)) 2824 return ExprError(); 2825 2826 // Only create DeclRefExpr's for valid Decl's. 2827 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2828 return ExprError(); 2829 2830 // Handle members of anonymous structs and unions. If we got here, 2831 // and the reference is to a class member indirect field, then this 2832 // must be the subject of a pointer-to-member expression. 2833 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2834 if (!indirectField->isCXXClassMember()) 2835 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2836 indirectField); 2837 2838 { 2839 QualType type = VD->getType(); 2840 ExprValueKind valueKind = VK_RValue; 2841 2842 switch (D->getKind()) { 2843 // Ignore all the non-ValueDecl kinds. 2844 #define ABSTRACT_DECL(kind) 2845 #define VALUE(type, base) 2846 #define DECL(type, base) \ 2847 case Decl::type: 2848 #include "clang/AST/DeclNodes.inc" 2849 llvm_unreachable("invalid value decl kind"); 2850 2851 // These shouldn't make it here. 2852 case Decl::ObjCAtDefsField: 2853 case Decl::ObjCIvar: 2854 llvm_unreachable("forming non-member reference to ivar?"); 2855 2856 // Enum constants are always r-values and never references. 2857 // Unresolved using declarations are dependent. 2858 case Decl::EnumConstant: 2859 case Decl::UnresolvedUsingValue: 2860 case Decl::OMPDeclareReduction: 2861 valueKind = VK_RValue; 2862 break; 2863 2864 // Fields and indirect fields that got here must be for 2865 // pointer-to-member expressions; we just call them l-values for 2866 // internal consistency, because this subexpression doesn't really 2867 // exist in the high-level semantics. 2868 case Decl::Field: 2869 case Decl::IndirectField: 2870 assert(getLangOpts().CPlusPlus && 2871 "building reference to field in C?"); 2872 2873 // These can't have reference type in well-formed programs, but 2874 // for internal consistency we do this anyway. 2875 type = type.getNonReferenceType(); 2876 valueKind = VK_LValue; 2877 break; 2878 2879 // Non-type template parameters are either l-values or r-values 2880 // depending on the type. 2881 case Decl::NonTypeTemplateParm: { 2882 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2883 type = reftype->getPointeeType(); 2884 valueKind = VK_LValue; // even if the parameter is an r-value reference 2885 break; 2886 } 2887 2888 // For non-references, we need to strip qualifiers just in case 2889 // the template parameter was declared as 'const int' or whatever. 2890 valueKind = VK_RValue; 2891 type = type.getUnqualifiedType(); 2892 break; 2893 } 2894 2895 case Decl::Var: 2896 case Decl::VarTemplateSpecialization: 2897 case Decl::VarTemplatePartialSpecialization: 2898 case Decl::OMPCapturedExpr: 2899 // In C, "extern void blah;" is valid and is an r-value. 2900 if (!getLangOpts().CPlusPlus && 2901 !type.hasQualifiers() && 2902 type->isVoidType()) { 2903 valueKind = VK_RValue; 2904 break; 2905 } 2906 // fallthrough 2907 2908 case Decl::ImplicitParam: 2909 case Decl::ParmVar: { 2910 // These are always l-values. 2911 valueKind = VK_LValue; 2912 type = type.getNonReferenceType(); 2913 2914 // FIXME: Does the addition of const really only apply in 2915 // potentially-evaluated contexts? Since the variable isn't actually 2916 // captured in an unevaluated context, it seems that the answer is no. 2917 if (!isUnevaluatedContext()) { 2918 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2919 if (!CapturedType.isNull()) 2920 type = CapturedType; 2921 } 2922 2923 break; 2924 } 2925 2926 case Decl::Function: { 2927 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2928 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2929 type = Context.BuiltinFnTy; 2930 valueKind = VK_RValue; 2931 break; 2932 } 2933 } 2934 2935 const FunctionType *fty = type->castAs<FunctionType>(); 2936 2937 // If we're referring to a function with an __unknown_anytype 2938 // result type, make the entire expression __unknown_anytype. 2939 if (fty->getReturnType() == Context.UnknownAnyTy) { 2940 type = Context.UnknownAnyTy; 2941 valueKind = VK_RValue; 2942 break; 2943 } 2944 2945 // Functions are l-values in C++. 2946 if (getLangOpts().CPlusPlus) { 2947 valueKind = VK_LValue; 2948 break; 2949 } 2950 2951 // C99 DR 316 says that, if a function type comes from a 2952 // function definition (without a prototype), that type is only 2953 // used for checking compatibility. Therefore, when referencing 2954 // the function, we pretend that we don't have the full function 2955 // type. 2956 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2957 isa<FunctionProtoType>(fty)) 2958 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2959 fty->getExtInfo()); 2960 2961 // Functions are r-values in C. 2962 valueKind = VK_RValue; 2963 break; 2964 } 2965 2966 case Decl::MSProperty: 2967 valueKind = VK_LValue; 2968 break; 2969 2970 case Decl::CXXMethod: 2971 // If we're referring to a method with an __unknown_anytype 2972 // result type, make the entire expression __unknown_anytype. 2973 // This should only be possible with a type written directly. 2974 if (const FunctionProtoType *proto 2975 = dyn_cast<FunctionProtoType>(VD->getType())) 2976 if (proto->getReturnType() == Context.UnknownAnyTy) { 2977 type = Context.UnknownAnyTy; 2978 valueKind = VK_RValue; 2979 break; 2980 } 2981 2982 // C++ methods are l-values if static, r-values if non-static. 2983 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2984 valueKind = VK_LValue; 2985 break; 2986 } 2987 // fallthrough 2988 2989 case Decl::CXXConversion: 2990 case Decl::CXXDestructor: 2991 case Decl::CXXConstructor: 2992 valueKind = VK_RValue; 2993 break; 2994 } 2995 2996 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2997 TemplateArgs); 2998 } 2999 } 3000 3001 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3002 SmallString<32> &Target) { 3003 Target.resize(CharByteWidth * (Source.size() + 1)); 3004 char *ResultPtr = &Target[0]; 3005 const UTF8 *ErrorPtr; 3006 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3007 (void)success; 3008 assert(success); 3009 Target.resize(ResultPtr - &Target[0]); 3010 } 3011 3012 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3013 PredefinedExpr::IdentType IT) { 3014 // Pick the current block, lambda, captured statement or function. 3015 Decl *currentDecl = nullptr; 3016 if (const BlockScopeInfo *BSI = getCurBlock()) 3017 currentDecl = BSI->TheDecl; 3018 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3019 currentDecl = LSI->CallOperator; 3020 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3021 currentDecl = CSI->TheCapturedDecl; 3022 else 3023 currentDecl = getCurFunctionOrMethodDecl(); 3024 3025 if (!currentDecl) { 3026 Diag(Loc, diag::ext_predef_outside_function); 3027 currentDecl = Context.getTranslationUnitDecl(); 3028 } 3029 3030 QualType ResTy; 3031 StringLiteral *SL = nullptr; 3032 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3033 ResTy = Context.DependentTy; 3034 else { 3035 // Pre-defined identifiers are of type char[x], where x is the length of 3036 // the string. 3037 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3038 unsigned Length = Str.length(); 3039 3040 llvm::APInt LengthI(32, Length + 1); 3041 if (IT == PredefinedExpr::LFunction) { 3042 ResTy = Context.WideCharTy.withConst(); 3043 SmallString<32> RawChars; 3044 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3045 Str, RawChars); 3046 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3047 /*IndexTypeQuals*/ 0); 3048 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3049 /*Pascal*/ false, ResTy, Loc); 3050 } else { 3051 ResTy = Context.CharTy.withConst(); 3052 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3053 /*IndexTypeQuals*/ 0); 3054 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3055 /*Pascal*/ false, ResTy, Loc); 3056 } 3057 } 3058 3059 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3060 } 3061 3062 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3063 PredefinedExpr::IdentType IT; 3064 3065 switch (Kind) { 3066 default: llvm_unreachable("Unknown simple primary expr!"); 3067 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3068 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3069 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3070 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3071 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3072 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3073 } 3074 3075 return BuildPredefinedExpr(Loc, IT); 3076 } 3077 3078 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3079 SmallString<16> CharBuffer; 3080 bool Invalid = false; 3081 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3082 if (Invalid) 3083 return ExprError(); 3084 3085 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3086 PP, Tok.getKind()); 3087 if (Literal.hadError()) 3088 return ExprError(); 3089 3090 QualType Ty; 3091 if (Literal.isWide()) 3092 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3093 else if (Literal.isUTF16()) 3094 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3095 else if (Literal.isUTF32()) 3096 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3097 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3098 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3099 else 3100 Ty = Context.CharTy; // 'x' -> char in C++ 3101 3102 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3103 if (Literal.isWide()) 3104 Kind = CharacterLiteral::Wide; 3105 else if (Literal.isUTF16()) 3106 Kind = CharacterLiteral::UTF16; 3107 else if (Literal.isUTF32()) 3108 Kind = CharacterLiteral::UTF32; 3109 else if (Literal.isUTF8()) 3110 Kind = CharacterLiteral::UTF8; 3111 3112 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3113 Tok.getLocation()); 3114 3115 if (Literal.getUDSuffix().empty()) 3116 return Lit; 3117 3118 // We're building a user-defined literal. 3119 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3120 SourceLocation UDSuffixLoc = 3121 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3122 3123 // Make sure we're allowed user-defined literals here. 3124 if (!UDLScope) 3125 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3126 3127 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3128 // operator "" X (ch) 3129 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3130 Lit, Tok.getLocation()); 3131 } 3132 3133 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3134 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3135 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3136 Context.IntTy, Loc); 3137 } 3138 3139 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3140 QualType Ty, SourceLocation Loc) { 3141 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3142 3143 using llvm::APFloat; 3144 APFloat Val(Format); 3145 3146 APFloat::opStatus result = Literal.GetFloatValue(Val); 3147 3148 // Overflow is always an error, but underflow is only an error if 3149 // we underflowed to zero (APFloat reports denormals as underflow). 3150 if ((result & APFloat::opOverflow) || 3151 ((result & APFloat::opUnderflow) && Val.isZero())) { 3152 unsigned diagnostic; 3153 SmallString<20> buffer; 3154 if (result & APFloat::opOverflow) { 3155 diagnostic = diag::warn_float_overflow; 3156 APFloat::getLargest(Format).toString(buffer); 3157 } else { 3158 diagnostic = diag::warn_float_underflow; 3159 APFloat::getSmallest(Format).toString(buffer); 3160 } 3161 3162 S.Diag(Loc, diagnostic) 3163 << Ty 3164 << StringRef(buffer.data(), buffer.size()); 3165 } 3166 3167 bool isExact = (result == APFloat::opOK); 3168 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3169 } 3170 3171 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3172 assert(E && "Invalid expression"); 3173 3174 if (E->isValueDependent()) 3175 return false; 3176 3177 QualType QT = E->getType(); 3178 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3179 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3180 return true; 3181 } 3182 3183 llvm::APSInt ValueAPS; 3184 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3185 3186 if (R.isInvalid()) 3187 return true; 3188 3189 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3190 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3191 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3192 << ValueAPS.toString(10) << ValueIsPositive; 3193 return true; 3194 } 3195 3196 return false; 3197 } 3198 3199 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3200 // Fast path for a single digit (which is quite common). A single digit 3201 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3202 if (Tok.getLength() == 1) { 3203 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3204 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3205 } 3206 3207 SmallString<128> SpellingBuffer; 3208 // NumericLiteralParser wants to overread by one character. Add padding to 3209 // the buffer in case the token is copied to the buffer. If getSpelling() 3210 // returns a StringRef to the memory buffer, it should have a null char at 3211 // the EOF, so it is also safe. 3212 SpellingBuffer.resize(Tok.getLength() + 1); 3213 3214 // Get the spelling of the token, which eliminates trigraphs, etc. 3215 bool Invalid = false; 3216 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3217 if (Invalid) 3218 return ExprError(); 3219 3220 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3221 if (Literal.hadError) 3222 return ExprError(); 3223 3224 if (Literal.hasUDSuffix()) { 3225 // We're building a user-defined literal. 3226 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3227 SourceLocation UDSuffixLoc = 3228 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3229 3230 // Make sure we're allowed user-defined literals here. 3231 if (!UDLScope) 3232 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3233 3234 QualType CookedTy; 3235 if (Literal.isFloatingLiteral()) { 3236 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3237 // long double, the literal is treated as a call of the form 3238 // operator "" X (f L) 3239 CookedTy = Context.LongDoubleTy; 3240 } else { 3241 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3242 // unsigned long long, the literal is treated as a call of the form 3243 // operator "" X (n ULL) 3244 CookedTy = Context.UnsignedLongLongTy; 3245 } 3246 3247 DeclarationName OpName = 3248 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3249 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3250 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3251 3252 SourceLocation TokLoc = Tok.getLocation(); 3253 3254 // Perform literal operator lookup to determine if we're building a raw 3255 // literal or a cooked one. 3256 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3257 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3258 /*AllowRaw*/true, /*AllowTemplate*/true, 3259 /*AllowStringTemplate*/false)) { 3260 case LOLR_Error: 3261 return ExprError(); 3262 3263 case LOLR_Cooked: { 3264 Expr *Lit; 3265 if (Literal.isFloatingLiteral()) { 3266 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3267 } else { 3268 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3269 if (Literal.GetIntegerValue(ResultVal)) 3270 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3271 << /* Unsigned */ 1; 3272 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3273 Tok.getLocation()); 3274 } 3275 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3276 } 3277 3278 case LOLR_Raw: { 3279 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3280 // literal is treated as a call of the form 3281 // operator "" X ("n") 3282 unsigned Length = Literal.getUDSuffixOffset(); 3283 QualType StrTy = Context.getConstantArrayType( 3284 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3285 ArrayType::Normal, 0); 3286 Expr *Lit = StringLiteral::Create( 3287 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3288 /*Pascal*/false, StrTy, &TokLoc, 1); 3289 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3290 } 3291 3292 case LOLR_Template: { 3293 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3294 // template), L is treated as a call fo the form 3295 // operator "" X <'c1', 'c2', ... 'ck'>() 3296 // where n is the source character sequence c1 c2 ... ck. 3297 TemplateArgumentListInfo ExplicitArgs; 3298 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3299 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3300 llvm::APSInt Value(CharBits, CharIsUnsigned); 3301 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3302 Value = TokSpelling[I]; 3303 TemplateArgument Arg(Context, Value, Context.CharTy); 3304 TemplateArgumentLocInfo ArgInfo; 3305 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3306 } 3307 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3308 &ExplicitArgs); 3309 } 3310 case LOLR_StringTemplate: 3311 llvm_unreachable("unexpected literal operator lookup result"); 3312 } 3313 } 3314 3315 Expr *Res; 3316 3317 if (Literal.isFloatingLiteral()) { 3318 QualType Ty; 3319 if (Literal.isHalf){ 3320 if (getOpenCLOptions().cl_khr_fp16) 3321 Ty = Context.HalfTy; 3322 else { 3323 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3324 return ExprError(); 3325 } 3326 } else if (Literal.isFloat) 3327 Ty = Context.FloatTy; 3328 else if (!Literal.isLong) 3329 Ty = Context.DoubleTy; 3330 else 3331 Ty = Context.LongDoubleTy; 3332 3333 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3334 3335 if (Ty == Context.DoubleTy) { 3336 if (getLangOpts().SinglePrecisionConstants) { 3337 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3338 } else if (getLangOpts().OpenCL && 3339 !((getLangOpts().OpenCLVersion >= 120) || 3340 getOpenCLOptions().cl_khr_fp64)) { 3341 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3342 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3343 } 3344 } 3345 } else if (!Literal.isIntegerLiteral()) { 3346 return ExprError(); 3347 } else { 3348 QualType Ty; 3349 3350 // 'long long' is a C99 or C++11 feature. 3351 if (!getLangOpts().C99 && Literal.isLongLong) { 3352 if (getLangOpts().CPlusPlus) 3353 Diag(Tok.getLocation(), 3354 getLangOpts().CPlusPlus11 ? 3355 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3356 else 3357 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3358 } 3359 3360 // Get the value in the widest-possible width. 3361 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3362 llvm::APInt ResultVal(MaxWidth, 0); 3363 3364 if (Literal.GetIntegerValue(ResultVal)) { 3365 // If this value didn't fit into uintmax_t, error and force to ull. 3366 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3367 << /* Unsigned */ 1; 3368 Ty = Context.UnsignedLongLongTy; 3369 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3370 "long long is not intmax_t?"); 3371 } else { 3372 // If this value fits into a ULL, try to figure out what else it fits into 3373 // according to the rules of C99 6.4.4.1p5. 3374 3375 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3376 // be an unsigned int. 3377 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3378 3379 // Check from smallest to largest, picking the smallest type we can. 3380 unsigned Width = 0; 3381 3382 // Microsoft specific integer suffixes are explicitly sized. 3383 if (Literal.MicrosoftInteger) { 3384 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3385 Width = 8; 3386 Ty = Context.CharTy; 3387 } else { 3388 Width = Literal.MicrosoftInteger; 3389 Ty = Context.getIntTypeForBitwidth(Width, 3390 /*Signed=*/!Literal.isUnsigned); 3391 } 3392 } 3393 3394 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3395 // Are int/unsigned possibilities? 3396 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3397 3398 // Does it fit in a unsigned int? 3399 if (ResultVal.isIntN(IntSize)) { 3400 // Does it fit in a signed int? 3401 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3402 Ty = Context.IntTy; 3403 else if (AllowUnsigned) 3404 Ty = Context.UnsignedIntTy; 3405 Width = IntSize; 3406 } 3407 } 3408 3409 // Are long/unsigned long possibilities? 3410 if (Ty.isNull() && !Literal.isLongLong) { 3411 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3412 3413 // Does it fit in a unsigned long? 3414 if (ResultVal.isIntN(LongSize)) { 3415 // Does it fit in a signed long? 3416 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3417 Ty = Context.LongTy; 3418 else if (AllowUnsigned) 3419 Ty = Context.UnsignedLongTy; 3420 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3421 // is compatible. 3422 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3423 const unsigned LongLongSize = 3424 Context.getTargetInfo().getLongLongWidth(); 3425 Diag(Tok.getLocation(), 3426 getLangOpts().CPlusPlus 3427 ? Literal.isLong 3428 ? diag::warn_old_implicitly_unsigned_long_cxx 3429 : /*C++98 UB*/ diag:: 3430 ext_old_implicitly_unsigned_long_cxx 3431 : diag::warn_old_implicitly_unsigned_long) 3432 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3433 : /*will be ill-formed*/ 1); 3434 Ty = Context.UnsignedLongTy; 3435 } 3436 Width = LongSize; 3437 } 3438 } 3439 3440 // Check long long if needed. 3441 if (Ty.isNull()) { 3442 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3443 3444 // Does it fit in a unsigned long long? 3445 if (ResultVal.isIntN(LongLongSize)) { 3446 // Does it fit in a signed long long? 3447 // To be compatible with MSVC, hex integer literals ending with the 3448 // LL or i64 suffix are always signed in Microsoft mode. 3449 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3450 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3451 Ty = Context.LongLongTy; 3452 else if (AllowUnsigned) 3453 Ty = Context.UnsignedLongLongTy; 3454 Width = LongLongSize; 3455 } 3456 } 3457 3458 // If we still couldn't decide a type, we probably have something that 3459 // does not fit in a signed long long, but has no U suffix. 3460 if (Ty.isNull()) { 3461 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3462 Ty = Context.UnsignedLongLongTy; 3463 Width = Context.getTargetInfo().getLongLongWidth(); 3464 } 3465 3466 if (ResultVal.getBitWidth() != Width) 3467 ResultVal = ResultVal.trunc(Width); 3468 } 3469 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3470 } 3471 3472 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3473 if (Literal.isImaginary) 3474 Res = new (Context) ImaginaryLiteral(Res, 3475 Context.getComplexType(Res->getType())); 3476 3477 return Res; 3478 } 3479 3480 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3481 assert(E && "ActOnParenExpr() missing expr"); 3482 return new (Context) ParenExpr(L, R, E); 3483 } 3484 3485 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3486 SourceLocation Loc, 3487 SourceRange ArgRange) { 3488 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3489 // scalar or vector data type argument..." 3490 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3491 // type (C99 6.2.5p18) or void. 3492 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3493 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3494 << T << ArgRange; 3495 return true; 3496 } 3497 3498 assert((T->isVoidType() || !T->isIncompleteType()) && 3499 "Scalar types should always be complete"); 3500 return false; 3501 } 3502 3503 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3504 SourceLocation Loc, 3505 SourceRange ArgRange, 3506 UnaryExprOrTypeTrait TraitKind) { 3507 // Invalid types must be hard errors for SFINAE in C++. 3508 if (S.LangOpts.CPlusPlus) 3509 return true; 3510 3511 // C99 6.5.3.4p1: 3512 if (T->isFunctionType() && 3513 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3514 // sizeof(function)/alignof(function) is allowed as an extension. 3515 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3516 << TraitKind << ArgRange; 3517 return false; 3518 } 3519 3520 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3521 // this is an error (OpenCL v1.1 s6.3.k) 3522 if (T->isVoidType()) { 3523 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3524 : diag::ext_sizeof_alignof_void_type; 3525 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3526 return false; 3527 } 3528 3529 return true; 3530 } 3531 3532 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3533 SourceLocation Loc, 3534 SourceRange ArgRange, 3535 UnaryExprOrTypeTrait TraitKind) { 3536 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3537 // runtime doesn't allow it. 3538 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3539 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3540 << T << (TraitKind == UETT_SizeOf) 3541 << ArgRange; 3542 return true; 3543 } 3544 3545 return false; 3546 } 3547 3548 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3549 /// pointer type is equal to T) and emit a warning if it is. 3550 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3551 Expr *E) { 3552 // Don't warn if the operation changed the type. 3553 if (T != E->getType()) 3554 return; 3555 3556 // Now look for array decays. 3557 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3558 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3559 return; 3560 3561 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3562 << ICE->getType() 3563 << ICE->getSubExpr()->getType(); 3564 } 3565 3566 /// \brief Check the constraints on expression operands to unary type expression 3567 /// and type traits. 3568 /// 3569 /// Completes any types necessary and validates the constraints on the operand 3570 /// expression. The logic mostly mirrors the type-based overload, but may modify 3571 /// the expression as it completes the type for that expression through template 3572 /// instantiation, etc. 3573 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3574 UnaryExprOrTypeTrait ExprKind) { 3575 QualType ExprTy = E->getType(); 3576 assert(!ExprTy->isReferenceType()); 3577 3578 if (ExprKind == UETT_VecStep) 3579 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3580 E->getSourceRange()); 3581 3582 // Whitelist some types as extensions 3583 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3584 E->getSourceRange(), ExprKind)) 3585 return false; 3586 3587 // 'alignof' applied to an expression only requires the base element type of 3588 // the expression to be complete. 'sizeof' requires the expression's type to 3589 // be complete (and will attempt to complete it if it's an array of unknown 3590 // bound). 3591 if (ExprKind == UETT_AlignOf) { 3592 if (RequireCompleteType(E->getExprLoc(), 3593 Context.getBaseElementType(E->getType()), 3594 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3595 E->getSourceRange())) 3596 return true; 3597 } else { 3598 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3599 ExprKind, E->getSourceRange())) 3600 return true; 3601 } 3602 3603 // Completing the expression's type may have changed it. 3604 ExprTy = E->getType(); 3605 assert(!ExprTy->isReferenceType()); 3606 3607 if (ExprTy->isFunctionType()) { 3608 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3609 << ExprKind << E->getSourceRange(); 3610 return true; 3611 } 3612 3613 // The operand for sizeof and alignof is in an unevaluated expression context, 3614 // so side effects could result in unintended consequences. 3615 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3616 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3617 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3618 3619 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3620 E->getSourceRange(), ExprKind)) 3621 return true; 3622 3623 if (ExprKind == UETT_SizeOf) { 3624 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3625 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3626 QualType OType = PVD->getOriginalType(); 3627 QualType Type = PVD->getType(); 3628 if (Type->isPointerType() && OType->isArrayType()) { 3629 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3630 << Type << OType; 3631 Diag(PVD->getLocation(), diag::note_declared_at); 3632 } 3633 } 3634 } 3635 3636 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3637 // decays into a pointer and returns an unintended result. This is most 3638 // likely a typo for "sizeof(array) op x". 3639 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3640 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3641 BO->getLHS()); 3642 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3643 BO->getRHS()); 3644 } 3645 } 3646 3647 return false; 3648 } 3649 3650 /// \brief Check the constraints on operands to unary expression and type 3651 /// traits. 3652 /// 3653 /// This will complete any types necessary, and validate the various constraints 3654 /// on those operands. 3655 /// 3656 /// The UsualUnaryConversions() function is *not* called by this routine. 3657 /// C99 6.3.2.1p[2-4] all state: 3658 /// Except when it is the operand of the sizeof operator ... 3659 /// 3660 /// C++ [expr.sizeof]p4 3661 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3662 /// standard conversions are not applied to the operand of sizeof. 3663 /// 3664 /// This policy is followed for all of the unary trait expressions. 3665 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3666 SourceLocation OpLoc, 3667 SourceRange ExprRange, 3668 UnaryExprOrTypeTrait ExprKind) { 3669 if (ExprType->isDependentType()) 3670 return false; 3671 3672 // C++ [expr.sizeof]p2: 3673 // When applied to a reference or a reference type, the result 3674 // is the size of the referenced type. 3675 // C++11 [expr.alignof]p3: 3676 // When alignof is applied to a reference type, the result 3677 // shall be the alignment of the referenced type. 3678 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3679 ExprType = Ref->getPointeeType(); 3680 3681 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3682 // When alignof or _Alignof is applied to an array type, the result 3683 // is the alignment of the element type. 3684 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3685 ExprType = Context.getBaseElementType(ExprType); 3686 3687 if (ExprKind == UETT_VecStep) 3688 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3689 3690 // Whitelist some types as extensions 3691 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3692 ExprKind)) 3693 return false; 3694 3695 if (RequireCompleteType(OpLoc, ExprType, 3696 diag::err_sizeof_alignof_incomplete_type, 3697 ExprKind, ExprRange)) 3698 return true; 3699 3700 if (ExprType->isFunctionType()) { 3701 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3702 << ExprKind << ExprRange; 3703 return true; 3704 } 3705 3706 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3707 ExprKind)) 3708 return true; 3709 3710 return false; 3711 } 3712 3713 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3714 E = E->IgnoreParens(); 3715 3716 // Cannot know anything else if the expression is dependent. 3717 if (E->isTypeDependent()) 3718 return false; 3719 3720 if (E->getObjectKind() == OK_BitField) { 3721 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3722 << 1 << E->getSourceRange(); 3723 return true; 3724 } 3725 3726 ValueDecl *D = nullptr; 3727 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3728 D = DRE->getDecl(); 3729 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3730 D = ME->getMemberDecl(); 3731 } 3732 3733 // If it's a field, require the containing struct to have a 3734 // complete definition so that we can compute the layout. 3735 // 3736 // This can happen in C++11 onwards, either by naming the member 3737 // in a way that is not transformed into a member access expression 3738 // (in an unevaluated operand, for instance), or by naming the member 3739 // in a trailing-return-type. 3740 // 3741 // For the record, since __alignof__ on expressions is a GCC 3742 // extension, GCC seems to permit this but always gives the 3743 // nonsensical answer 0. 3744 // 3745 // We don't really need the layout here --- we could instead just 3746 // directly check for all the appropriate alignment-lowing 3747 // attributes --- but that would require duplicating a lot of 3748 // logic that just isn't worth duplicating for such a marginal 3749 // use-case. 3750 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3751 // Fast path this check, since we at least know the record has a 3752 // definition if we can find a member of it. 3753 if (!FD->getParent()->isCompleteDefinition()) { 3754 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3755 << E->getSourceRange(); 3756 return true; 3757 } 3758 3759 // Otherwise, if it's a field, and the field doesn't have 3760 // reference type, then it must have a complete type (or be a 3761 // flexible array member, which we explicitly want to 3762 // white-list anyway), which makes the following checks trivial. 3763 if (!FD->getType()->isReferenceType()) 3764 return false; 3765 } 3766 3767 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3768 } 3769 3770 bool Sema::CheckVecStepExpr(Expr *E) { 3771 E = E->IgnoreParens(); 3772 3773 // Cannot know anything else if the expression is dependent. 3774 if (E->isTypeDependent()) 3775 return false; 3776 3777 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3778 } 3779 3780 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3781 CapturingScopeInfo *CSI) { 3782 assert(T->isVariablyModifiedType()); 3783 assert(CSI != nullptr); 3784 3785 // We're going to walk down into the type and look for VLA expressions. 3786 do { 3787 const Type *Ty = T.getTypePtr(); 3788 switch (Ty->getTypeClass()) { 3789 #define TYPE(Class, Base) 3790 #define ABSTRACT_TYPE(Class, Base) 3791 #define NON_CANONICAL_TYPE(Class, Base) 3792 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3793 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3794 #include "clang/AST/TypeNodes.def" 3795 T = QualType(); 3796 break; 3797 // These types are never variably-modified. 3798 case Type::Builtin: 3799 case Type::Complex: 3800 case Type::Vector: 3801 case Type::ExtVector: 3802 case Type::Record: 3803 case Type::Enum: 3804 case Type::Elaborated: 3805 case Type::TemplateSpecialization: 3806 case Type::ObjCObject: 3807 case Type::ObjCInterface: 3808 case Type::ObjCObjectPointer: 3809 case Type::Pipe: 3810 llvm_unreachable("type class is never variably-modified!"); 3811 case Type::Adjusted: 3812 T = cast<AdjustedType>(Ty)->getOriginalType(); 3813 break; 3814 case Type::Decayed: 3815 T = cast<DecayedType>(Ty)->getPointeeType(); 3816 break; 3817 case Type::Pointer: 3818 T = cast<PointerType>(Ty)->getPointeeType(); 3819 break; 3820 case Type::BlockPointer: 3821 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3822 break; 3823 case Type::LValueReference: 3824 case Type::RValueReference: 3825 T = cast<ReferenceType>(Ty)->getPointeeType(); 3826 break; 3827 case Type::MemberPointer: 3828 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3829 break; 3830 case Type::ConstantArray: 3831 case Type::IncompleteArray: 3832 // Losing element qualification here is fine. 3833 T = cast<ArrayType>(Ty)->getElementType(); 3834 break; 3835 case Type::VariableArray: { 3836 // Losing element qualification here is fine. 3837 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3838 3839 // Unknown size indication requires no size computation. 3840 // Otherwise, evaluate and record it. 3841 if (auto Size = VAT->getSizeExpr()) { 3842 if (!CSI->isVLATypeCaptured(VAT)) { 3843 RecordDecl *CapRecord = nullptr; 3844 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3845 CapRecord = LSI->Lambda; 3846 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3847 CapRecord = CRSI->TheRecordDecl; 3848 } 3849 if (CapRecord) { 3850 auto ExprLoc = Size->getExprLoc(); 3851 auto SizeType = Context.getSizeType(); 3852 // Build the non-static data member. 3853 auto Field = 3854 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3855 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3856 /*BW*/ nullptr, /*Mutable*/ false, 3857 /*InitStyle*/ ICIS_NoInit); 3858 Field->setImplicit(true); 3859 Field->setAccess(AS_private); 3860 Field->setCapturedVLAType(VAT); 3861 CapRecord->addDecl(Field); 3862 3863 CSI->addVLATypeCapture(ExprLoc, SizeType); 3864 } 3865 } 3866 } 3867 T = VAT->getElementType(); 3868 break; 3869 } 3870 case Type::FunctionProto: 3871 case Type::FunctionNoProto: 3872 T = cast<FunctionType>(Ty)->getReturnType(); 3873 break; 3874 case Type::Paren: 3875 case Type::TypeOf: 3876 case Type::UnaryTransform: 3877 case Type::Attributed: 3878 case Type::SubstTemplateTypeParm: 3879 case Type::PackExpansion: 3880 // Keep walking after single level desugaring. 3881 T = T.getSingleStepDesugaredType(Context); 3882 break; 3883 case Type::Typedef: 3884 T = cast<TypedefType>(Ty)->desugar(); 3885 break; 3886 case Type::Decltype: 3887 T = cast<DecltypeType>(Ty)->desugar(); 3888 break; 3889 case Type::Auto: 3890 T = cast<AutoType>(Ty)->getDeducedType(); 3891 break; 3892 case Type::TypeOfExpr: 3893 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3894 break; 3895 case Type::Atomic: 3896 T = cast<AtomicType>(Ty)->getValueType(); 3897 break; 3898 } 3899 } while (!T.isNull() && T->isVariablyModifiedType()); 3900 } 3901 3902 /// \brief Build a sizeof or alignof expression given a type operand. 3903 ExprResult 3904 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3905 SourceLocation OpLoc, 3906 UnaryExprOrTypeTrait ExprKind, 3907 SourceRange R) { 3908 if (!TInfo) 3909 return ExprError(); 3910 3911 QualType T = TInfo->getType(); 3912 3913 if (!T->isDependentType() && 3914 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3915 return ExprError(); 3916 3917 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3918 if (auto *TT = T->getAs<TypedefType>()) { 3919 for (auto I = FunctionScopes.rbegin(), 3920 E = std::prev(FunctionScopes.rend()); 3921 I != E; ++I) { 3922 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3923 if (CSI == nullptr) 3924 break; 3925 DeclContext *DC = nullptr; 3926 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3927 DC = LSI->CallOperator; 3928 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3929 DC = CRSI->TheCapturedDecl; 3930 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3931 DC = BSI->TheDecl; 3932 if (DC) { 3933 if (DC->containsDecl(TT->getDecl())) 3934 break; 3935 captureVariablyModifiedType(Context, T, CSI); 3936 } 3937 } 3938 } 3939 } 3940 3941 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3942 return new (Context) UnaryExprOrTypeTraitExpr( 3943 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3944 } 3945 3946 /// \brief Build a sizeof or alignof expression given an expression 3947 /// operand. 3948 ExprResult 3949 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3950 UnaryExprOrTypeTrait ExprKind) { 3951 ExprResult PE = CheckPlaceholderExpr(E); 3952 if (PE.isInvalid()) 3953 return ExprError(); 3954 3955 E = PE.get(); 3956 3957 // Verify that the operand is valid. 3958 bool isInvalid = false; 3959 if (E->isTypeDependent()) { 3960 // Delay type-checking for type-dependent expressions. 3961 } else if (ExprKind == UETT_AlignOf) { 3962 isInvalid = CheckAlignOfExpr(*this, E); 3963 } else if (ExprKind == UETT_VecStep) { 3964 isInvalid = CheckVecStepExpr(E); 3965 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3966 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3967 isInvalid = true; 3968 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3969 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3970 isInvalid = true; 3971 } else { 3972 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3973 } 3974 3975 if (isInvalid) 3976 return ExprError(); 3977 3978 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3979 PE = TransformToPotentiallyEvaluated(E); 3980 if (PE.isInvalid()) return ExprError(); 3981 E = PE.get(); 3982 } 3983 3984 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3985 return new (Context) UnaryExprOrTypeTraitExpr( 3986 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3987 } 3988 3989 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3990 /// expr and the same for @c alignof and @c __alignof 3991 /// Note that the ArgRange is invalid if isType is false. 3992 ExprResult 3993 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3994 UnaryExprOrTypeTrait ExprKind, bool IsType, 3995 void *TyOrEx, SourceRange ArgRange) { 3996 // If error parsing type, ignore. 3997 if (!TyOrEx) return ExprError(); 3998 3999 if (IsType) { 4000 TypeSourceInfo *TInfo; 4001 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4002 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4003 } 4004 4005 Expr *ArgEx = (Expr *)TyOrEx; 4006 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4007 return Result; 4008 } 4009 4010 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4011 bool IsReal) { 4012 if (V.get()->isTypeDependent()) 4013 return S.Context.DependentTy; 4014 4015 // _Real and _Imag are only l-values for normal l-values. 4016 if (V.get()->getObjectKind() != OK_Ordinary) { 4017 V = S.DefaultLvalueConversion(V.get()); 4018 if (V.isInvalid()) 4019 return QualType(); 4020 } 4021 4022 // These operators return the element type of a complex type. 4023 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4024 return CT->getElementType(); 4025 4026 // Otherwise they pass through real integer and floating point types here. 4027 if (V.get()->getType()->isArithmeticType()) 4028 return V.get()->getType(); 4029 4030 // Test for placeholders. 4031 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4032 if (PR.isInvalid()) return QualType(); 4033 if (PR.get() != V.get()) { 4034 V = PR; 4035 return CheckRealImagOperand(S, V, Loc, IsReal); 4036 } 4037 4038 // Reject anything else. 4039 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4040 << (IsReal ? "__real" : "__imag"); 4041 return QualType(); 4042 } 4043 4044 4045 4046 ExprResult 4047 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4048 tok::TokenKind Kind, Expr *Input) { 4049 UnaryOperatorKind Opc; 4050 switch (Kind) { 4051 default: llvm_unreachable("Unknown unary op!"); 4052 case tok::plusplus: Opc = UO_PostInc; break; 4053 case tok::minusminus: Opc = UO_PostDec; break; 4054 } 4055 4056 // Since this might is a postfix expression, get rid of ParenListExprs. 4057 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4058 if (Result.isInvalid()) return ExprError(); 4059 Input = Result.get(); 4060 4061 return BuildUnaryOp(S, OpLoc, Opc, Input); 4062 } 4063 4064 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4065 /// 4066 /// \return true on error 4067 static bool checkArithmeticOnObjCPointer(Sema &S, 4068 SourceLocation opLoc, 4069 Expr *op) { 4070 assert(op->getType()->isObjCObjectPointerType()); 4071 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4072 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4073 return false; 4074 4075 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4076 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4077 << op->getSourceRange(); 4078 return true; 4079 } 4080 4081 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4082 auto *BaseNoParens = Base->IgnoreParens(); 4083 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4084 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4085 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4086 } 4087 4088 ExprResult 4089 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4090 Expr *idx, SourceLocation rbLoc) { 4091 if (base && !base->getType().isNull() && 4092 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4093 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4094 /*Length=*/nullptr, rbLoc); 4095 4096 // Since this might be a postfix expression, get rid of ParenListExprs. 4097 if (isa<ParenListExpr>(base)) { 4098 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4099 if (result.isInvalid()) return ExprError(); 4100 base = result.get(); 4101 } 4102 4103 // Handle any non-overload placeholder types in the base and index 4104 // expressions. We can't handle overloads here because the other 4105 // operand might be an overloadable type, in which case the overload 4106 // resolution for the operator overload should get the first crack 4107 // at the overload. 4108 bool IsMSPropertySubscript = false; 4109 if (base->getType()->isNonOverloadPlaceholderType()) { 4110 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4111 if (!IsMSPropertySubscript) { 4112 ExprResult result = CheckPlaceholderExpr(base); 4113 if (result.isInvalid()) 4114 return ExprError(); 4115 base = result.get(); 4116 } 4117 } 4118 if (idx->getType()->isNonOverloadPlaceholderType()) { 4119 ExprResult result = CheckPlaceholderExpr(idx); 4120 if (result.isInvalid()) return ExprError(); 4121 idx = result.get(); 4122 } 4123 4124 // Build an unanalyzed expression if either operand is type-dependent. 4125 if (getLangOpts().CPlusPlus && 4126 (base->isTypeDependent() || idx->isTypeDependent())) { 4127 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4128 VK_LValue, OK_Ordinary, rbLoc); 4129 } 4130 4131 // MSDN, property (C++) 4132 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4133 // This attribute can also be used in the declaration of an empty array in a 4134 // class or structure definition. For example: 4135 // __declspec(property(get=GetX, put=PutX)) int x[]; 4136 // The above statement indicates that x[] can be used with one or more array 4137 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4138 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4139 if (IsMSPropertySubscript) { 4140 // Build MS property subscript expression if base is MS property reference 4141 // or MS property subscript. 4142 return new (Context) MSPropertySubscriptExpr( 4143 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4144 } 4145 4146 // Use C++ overloaded-operator rules if either operand has record 4147 // type. The spec says to do this if either type is *overloadable*, 4148 // but enum types can't declare subscript operators or conversion 4149 // operators, so there's nothing interesting for overload resolution 4150 // to do if there aren't any record types involved. 4151 // 4152 // ObjC pointers have their own subscripting logic that is not tied 4153 // to overload resolution and so should not take this path. 4154 if (getLangOpts().CPlusPlus && 4155 (base->getType()->isRecordType() || 4156 (!base->getType()->isObjCObjectPointerType() && 4157 idx->getType()->isRecordType()))) { 4158 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4159 } 4160 4161 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4162 } 4163 4164 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4165 Expr *LowerBound, 4166 SourceLocation ColonLoc, Expr *Length, 4167 SourceLocation RBLoc) { 4168 if (Base->getType()->isPlaceholderType() && 4169 !Base->getType()->isSpecificPlaceholderType( 4170 BuiltinType::OMPArraySection)) { 4171 ExprResult Result = CheckPlaceholderExpr(Base); 4172 if (Result.isInvalid()) 4173 return ExprError(); 4174 Base = Result.get(); 4175 } 4176 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4177 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4178 if (Result.isInvalid()) 4179 return ExprError(); 4180 Result = DefaultLvalueConversion(Result.get()); 4181 if (Result.isInvalid()) 4182 return ExprError(); 4183 LowerBound = Result.get(); 4184 } 4185 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4186 ExprResult Result = CheckPlaceholderExpr(Length); 4187 if (Result.isInvalid()) 4188 return ExprError(); 4189 Result = DefaultLvalueConversion(Result.get()); 4190 if (Result.isInvalid()) 4191 return ExprError(); 4192 Length = Result.get(); 4193 } 4194 4195 // Build an unanalyzed expression if either operand is type-dependent. 4196 if (Base->isTypeDependent() || 4197 (LowerBound && 4198 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4199 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4200 return new (Context) 4201 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4202 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4203 } 4204 4205 // Perform default conversions. 4206 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4207 QualType ResultTy; 4208 if (OriginalTy->isAnyPointerType()) { 4209 ResultTy = OriginalTy->getPointeeType(); 4210 } else if (OriginalTy->isArrayType()) { 4211 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4212 } else { 4213 return ExprError( 4214 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4215 << Base->getSourceRange()); 4216 } 4217 // C99 6.5.2.1p1 4218 if (LowerBound) { 4219 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4220 LowerBound); 4221 if (Res.isInvalid()) 4222 return ExprError(Diag(LowerBound->getExprLoc(), 4223 diag::err_omp_typecheck_section_not_integer) 4224 << 0 << LowerBound->getSourceRange()); 4225 LowerBound = Res.get(); 4226 4227 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4228 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4229 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4230 << 0 << LowerBound->getSourceRange(); 4231 } 4232 if (Length) { 4233 auto Res = 4234 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4235 if (Res.isInvalid()) 4236 return ExprError(Diag(Length->getExprLoc(), 4237 diag::err_omp_typecheck_section_not_integer) 4238 << 1 << Length->getSourceRange()); 4239 Length = Res.get(); 4240 4241 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4242 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4243 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4244 << 1 << Length->getSourceRange(); 4245 } 4246 4247 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4248 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4249 // type. Note that functions are not objects, and that (in C99 parlance) 4250 // incomplete types are not object types. 4251 if (ResultTy->isFunctionType()) { 4252 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4253 << ResultTy << Base->getSourceRange(); 4254 return ExprError(); 4255 } 4256 4257 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4258 diag::err_omp_section_incomplete_type, Base)) 4259 return ExprError(); 4260 4261 if (LowerBound) { 4262 llvm::APSInt LowerBoundValue; 4263 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4264 // OpenMP 4.0, [2.4 Array Sections] 4265 // The lower-bound and length must evaluate to non-negative integers. 4266 if (LowerBoundValue.isNegative()) { 4267 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4268 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4269 << LowerBound->getSourceRange(); 4270 return ExprError(); 4271 } 4272 } 4273 } 4274 4275 if (Length) { 4276 llvm::APSInt LengthValue; 4277 if (Length->EvaluateAsInt(LengthValue, Context)) { 4278 // OpenMP 4.0, [2.4 Array Sections] 4279 // The lower-bound and length must evaluate to non-negative integers. 4280 if (LengthValue.isNegative()) { 4281 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4282 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4283 << Length->getSourceRange(); 4284 return ExprError(); 4285 } 4286 } 4287 } else if (ColonLoc.isValid() && 4288 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4289 !OriginalTy->isVariableArrayType()))) { 4290 // OpenMP 4.0, [2.4 Array Sections] 4291 // When the size of the array dimension is not known, the length must be 4292 // specified explicitly. 4293 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4294 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4295 return ExprError(); 4296 } 4297 4298 if (!Base->getType()->isSpecificPlaceholderType( 4299 BuiltinType::OMPArraySection)) { 4300 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4301 if (Result.isInvalid()) 4302 return ExprError(); 4303 Base = Result.get(); 4304 } 4305 return new (Context) 4306 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4307 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4308 } 4309 4310 ExprResult 4311 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4312 Expr *Idx, SourceLocation RLoc) { 4313 Expr *LHSExp = Base; 4314 Expr *RHSExp = Idx; 4315 4316 // Perform default conversions. 4317 if (!LHSExp->getType()->getAs<VectorType>()) { 4318 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4319 if (Result.isInvalid()) 4320 return ExprError(); 4321 LHSExp = Result.get(); 4322 } 4323 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4324 if (Result.isInvalid()) 4325 return ExprError(); 4326 RHSExp = Result.get(); 4327 4328 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4329 ExprValueKind VK = VK_LValue; 4330 ExprObjectKind OK = OK_Ordinary; 4331 4332 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4333 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4334 // in the subscript position. As a result, we need to derive the array base 4335 // and index from the expression types. 4336 Expr *BaseExpr, *IndexExpr; 4337 QualType ResultType; 4338 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4339 BaseExpr = LHSExp; 4340 IndexExpr = RHSExp; 4341 ResultType = Context.DependentTy; 4342 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4343 BaseExpr = LHSExp; 4344 IndexExpr = RHSExp; 4345 ResultType = PTy->getPointeeType(); 4346 } else if (const ObjCObjectPointerType *PTy = 4347 LHSTy->getAs<ObjCObjectPointerType>()) { 4348 BaseExpr = LHSExp; 4349 IndexExpr = RHSExp; 4350 4351 // Use custom logic if this should be the pseudo-object subscript 4352 // expression. 4353 if (!LangOpts.isSubscriptPointerArithmetic()) 4354 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4355 nullptr); 4356 4357 ResultType = PTy->getPointeeType(); 4358 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4359 // Handle the uncommon case of "123[Ptr]". 4360 BaseExpr = RHSExp; 4361 IndexExpr = LHSExp; 4362 ResultType = PTy->getPointeeType(); 4363 } else if (const ObjCObjectPointerType *PTy = 4364 RHSTy->getAs<ObjCObjectPointerType>()) { 4365 // Handle the uncommon case of "123[Ptr]". 4366 BaseExpr = RHSExp; 4367 IndexExpr = LHSExp; 4368 ResultType = PTy->getPointeeType(); 4369 if (!LangOpts.isSubscriptPointerArithmetic()) { 4370 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4371 << ResultType << BaseExpr->getSourceRange(); 4372 return ExprError(); 4373 } 4374 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4375 BaseExpr = LHSExp; // vectors: V[123] 4376 IndexExpr = RHSExp; 4377 VK = LHSExp->getValueKind(); 4378 if (VK != VK_RValue) 4379 OK = OK_VectorComponent; 4380 4381 // FIXME: need to deal with const... 4382 ResultType = VTy->getElementType(); 4383 } else if (LHSTy->isArrayType()) { 4384 // If we see an array that wasn't promoted by 4385 // DefaultFunctionArrayLvalueConversion, it must be an array that 4386 // wasn't promoted because of the C90 rule that doesn't 4387 // allow promoting non-lvalue arrays. Warn, then 4388 // force the promotion here. 4389 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4390 LHSExp->getSourceRange(); 4391 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4392 CK_ArrayToPointerDecay).get(); 4393 LHSTy = LHSExp->getType(); 4394 4395 BaseExpr = LHSExp; 4396 IndexExpr = RHSExp; 4397 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4398 } else if (RHSTy->isArrayType()) { 4399 // Same as previous, except for 123[f().a] case 4400 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4401 RHSExp->getSourceRange(); 4402 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4403 CK_ArrayToPointerDecay).get(); 4404 RHSTy = RHSExp->getType(); 4405 4406 BaseExpr = RHSExp; 4407 IndexExpr = LHSExp; 4408 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4409 } else { 4410 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4411 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4412 } 4413 // C99 6.5.2.1p1 4414 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4415 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4416 << IndexExpr->getSourceRange()); 4417 4418 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4419 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4420 && !IndexExpr->isTypeDependent()) 4421 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4422 4423 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4424 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4425 // type. Note that Functions are not objects, and that (in C99 parlance) 4426 // incomplete types are not object types. 4427 if (ResultType->isFunctionType()) { 4428 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4429 << ResultType << BaseExpr->getSourceRange(); 4430 return ExprError(); 4431 } 4432 4433 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4434 // GNU extension: subscripting on pointer to void 4435 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4436 << BaseExpr->getSourceRange(); 4437 4438 // C forbids expressions of unqualified void type from being l-values. 4439 // See IsCForbiddenLValueType. 4440 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4441 } else if (!ResultType->isDependentType() && 4442 RequireCompleteType(LLoc, ResultType, 4443 diag::err_subscript_incomplete_type, BaseExpr)) 4444 return ExprError(); 4445 4446 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4447 !ResultType.isCForbiddenLValueType()); 4448 4449 return new (Context) 4450 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4451 } 4452 4453 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4454 FunctionDecl *FD, 4455 ParmVarDecl *Param) { 4456 if (Param->hasUnparsedDefaultArg()) { 4457 Diag(CallLoc, 4458 diag::err_use_of_default_argument_to_function_declared_later) << 4459 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4460 Diag(UnparsedDefaultArgLocs[Param], 4461 diag::note_default_argument_declared_here); 4462 return ExprError(); 4463 } 4464 4465 if (Param->hasUninstantiatedDefaultArg()) { 4466 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4467 4468 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4469 Param); 4470 4471 // Instantiate the expression. 4472 MultiLevelTemplateArgumentList MutiLevelArgList 4473 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4474 4475 InstantiatingTemplate Inst(*this, CallLoc, Param, 4476 MutiLevelArgList.getInnermost()); 4477 if (Inst.isInvalid()) 4478 return ExprError(); 4479 4480 ExprResult Result; 4481 { 4482 // C++ [dcl.fct.default]p5: 4483 // The names in the [default argument] expression are bound, and 4484 // the semantic constraints are checked, at the point where the 4485 // default argument expression appears. 4486 ContextRAII SavedContext(*this, FD); 4487 LocalInstantiationScope Local(*this); 4488 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4489 } 4490 if (Result.isInvalid()) 4491 return ExprError(); 4492 4493 // Check the expression as an initializer for the parameter. 4494 InitializedEntity Entity 4495 = InitializedEntity::InitializeParameter(Context, Param); 4496 InitializationKind Kind 4497 = InitializationKind::CreateCopy(Param->getLocation(), 4498 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4499 Expr *ResultE = Result.getAs<Expr>(); 4500 4501 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4502 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4503 if (Result.isInvalid()) 4504 return ExprError(); 4505 4506 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4507 Param->getOuterLocStart()); 4508 if (Result.isInvalid()) 4509 return ExprError(); 4510 4511 // Remember the instantiated default argument. 4512 Param->setDefaultArg(Result.getAs<Expr>()); 4513 if (ASTMutationListener *L = getASTMutationListener()) { 4514 L->DefaultArgumentInstantiated(Param); 4515 } 4516 } 4517 4518 // If the default expression creates temporaries, we need to 4519 // push them to the current stack of expression temporaries so they'll 4520 // be properly destroyed. 4521 // FIXME: We should really be rebuilding the default argument with new 4522 // bound temporaries; see the comment in PR5810. 4523 // We don't need to do that with block decls, though, because 4524 // blocks in default argument expression can never capture anything. 4525 if (isa<ExprWithCleanups>(Param->getInit())) { 4526 // Set the "needs cleanups" bit regardless of whether there are 4527 // any explicit objects. 4528 ExprNeedsCleanups = true; 4529 4530 // Append all the objects to the cleanup list. Right now, this 4531 // should always be a no-op, because blocks in default argument 4532 // expressions should never be able to capture anything. 4533 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4534 "default argument expression has capturing blocks?"); 4535 } 4536 4537 // We already type-checked the argument, so we know it works. 4538 // Just mark all of the declarations in this potentially-evaluated expression 4539 // as being "referenced". 4540 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4541 /*SkipLocalVariables=*/true); 4542 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4543 } 4544 4545 4546 Sema::VariadicCallType 4547 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4548 Expr *Fn) { 4549 if (Proto && Proto->isVariadic()) { 4550 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4551 return VariadicConstructor; 4552 else if (Fn && Fn->getType()->isBlockPointerType()) 4553 return VariadicBlock; 4554 else if (FDecl) { 4555 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4556 if (Method->isInstance()) 4557 return VariadicMethod; 4558 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4559 return VariadicMethod; 4560 return VariadicFunction; 4561 } 4562 return VariadicDoesNotApply; 4563 } 4564 4565 namespace { 4566 class FunctionCallCCC : public FunctionCallFilterCCC { 4567 public: 4568 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4569 unsigned NumArgs, MemberExpr *ME) 4570 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4571 FunctionName(FuncName) {} 4572 4573 bool ValidateCandidate(const TypoCorrection &candidate) override { 4574 if (!candidate.getCorrectionSpecifier() || 4575 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4576 return false; 4577 } 4578 4579 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4580 } 4581 4582 private: 4583 const IdentifierInfo *const FunctionName; 4584 }; 4585 } 4586 4587 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4588 FunctionDecl *FDecl, 4589 ArrayRef<Expr *> Args) { 4590 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4591 DeclarationName FuncName = FDecl->getDeclName(); 4592 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4593 4594 if (TypoCorrection Corrected = S.CorrectTypo( 4595 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4596 S.getScopeForContext(S.CurContext), nullptr, 4597 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4598 Args.size(), ME), 4599 Sema::CTK_ErrorRecovery)) { 4600 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4601 if (Corrected.isOverloaded()) { 4602 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4603 OverloadCandidateSet::iterator Best; 4604 for (NamedDecl *CD : Corrected) { 4605 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4606 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4607 OCS); 4608 } 4609 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4610 case OR_Success: 4611 ND = Best->FoundDecl; 4612 Corrected.setCorrectionDecl(ND); 4613 break; 4614 default: 4615 break; 4616 } 4617 } 4618 ND = ND->getUnderlyingDecl(); 4619 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4620 return Corrected; 4621 } 4622 } 4623 return TypoCorrection(); 4624 } 4625 4626 /// ConvertArgumentsForCall - Converts the arguments specified in 4627 /// Args/NumArgs to the parameter types of the function FDecl with 4628 /// function prototype Proto. Call is the call expression itself, and 4629 /// Fn is the function expression. For a C++ member function, this 4630 /// routine does not attempt to convert the object argument. Returns 4631 /// true if the call is ill-formed. 4632 bool 4633 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4634 FunctionDecl *FDecl, 4635 const FunctionProtoType *Proto, 4636 ArrayRef<Expr *> Args, 4637 SourceLocation RParenLoc, 4638 bool IsExecConfig) { 4639 // Bail out early if calling a builtin with custom typechecking. 4640 if (FDecl) 4641 if (unsigned ID = FDecl->getBuiltinID()) 4642 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4643 return false; 4644 4645 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4646 // assignment, to the types of the corresponding parameter, ... 4647 unsigned NumParams = Proto->getNumParams(); 4648 bool Invalid = false; 4649 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4650 unsigned FnKind = Fn->getType()->isBlockPointerType() 4651 ? 1 /* block */ 4652 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4653 : 0 /* function */); 4654 4655 // If too few arguments are available (and we don't have default 4656 // arguments for the remaining parameters), don't make the call. 4657 if (Args.size() < NumParams) { 4658 if (Args.size() < MinArgs) { 4659 TypoCorrection TC; 4660 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4661 unsigned diag_id = 4662 MinArgs == NumParams && !Proto->isVariadic() 4663 ? diag::err_typecheck_call_too_few_args_suggest 4664 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4665 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4666 << static_cast<unsigned>(Args.size()) 4667 << TC.getCorrectionRange()); 4668 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4669 Diag(RParenLoc, 4670 MinArgs == NumParams && !Proto->isVariadic() 4671 ? diag::err_typecheck_call_too_few_args_one 4672 : diag::err_typecheck_call_too_few_args_at_least_one) 4673 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4674 else 4675 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4676 ? diag::err_typecheck_call_too_few_args 4677 : diag::err_typecheck_call_too_few_args_at_least) 4678 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4679 << Fn->getSourceRange(); 4680 4681 // Emit the location of the prototype. 4682 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4683 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4684 << FDecl; 4685 4686 return true; 4687 } 4688 Call->setNumArgs(Context, NumParams); 4689 } 4690 4691 // If too many are passed and not variadic, error on the extras and drop 4692 // them. 4693 if (Args.size() > NumParams) { 4694 if (!Proto->isVariadic()) { 4695 TypoCorrection TC; 4696 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4697 unsigned diag_id = 4698 MinArgs == NumParams && !Proto->isVariadic() 4699 ? diag::err_typecheck_call_too_many_args_suggest 4700 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4701 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4702 << static_cast<unsigned>(Args.size()) 4703 << TC.getCorrectionRange()); 4704 } else if (NumParams == 1 && FDecl && 4705 FDecl->getParamDecl(0)->getDeclName()) 4706 Diag(Args[NumParams]->getLocStart(), 4707 MinArgs == NumParams 4708 ? diag::err_typecheck_call_too_many_args_one 4709 : diag::err_typecheck_call_too_many_args_at_most_one) 4710 << FnKind << FDecl->getParamDecl(0) 4711 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4712 << SourceRange(Args[NumParams]->getLocStart(), 4713 Args.back()->getLocEnd()); 4714 else 4715 Diag(Args[NumParams]->getLocStart(), 4716 MinArgs == NumParams 4717 ? diag::err_typecheck_call_too_many_args 4718 : diag::err_typecheck_call_too_many_args_at_most) 4719 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4720 << Fn->getSourceRange() 4721 << SourceRange(Args[NumParams]->getLocStart(), 4722 Args.back()->getLocEnd()); 4723 4724 // Emit the location of the prototype. 4725 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4726 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4727 << FDecl; 4728 4729 // This deletes the extra arguments. 4730 Call->setNumArgs(Context, NumParams); 4731 return true; 4732 } 4733 } 4734 SmallVector<Expr *, 8> AllArgs; 4735 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4736 4737 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4738 Proto, 0, Args, AllArgs, CallType); 4739 if (Invalid) 4740 return true; 4741 unsigned TotalNumArgs = AllArgs.size(); 4742 for (unsigned i = 0; i < TotalNumArgs; ++i) 4743 Call->setArg(i, AllArgs[i]); 4744 4745 return false; 4746 } 4747 4748 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4749 const FunctionProtoType *Proto, 4750 unsigned FirstParam, ArrayRef<Expr *> Args, 4751 SmallVectorImpl<Expr *> &AllArgs, 4752 VariadicCallType CallType, bool AllowExplicit, 4753 bool IsListInitialization) { 4754 unsigned NumParams = Proto->getNumParams(); 4755 bool Invalid = false; 4756 size_t ArgIx = 0; 4757 // Continue to check argument types (even if we have too few/many args). 4758 for (unsigned i = FirstParam; i < NumParams; i++) { 4759 QualType ProtoArgType = Proto->getParamType(i); 4760 4761 Expr *Arg; 4762 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4763 if (ArgIx < Args.size()) { 4764 Arg = Args[ArgIx++]; 4765 4766 if (RequireCompleteType(Arg->getLocStart(), 4767 ProtoArgType, 4768 diag::err_call_incomplete_argument, Arg)) 4769 return true; 4770 4771 // Strip the unbridged-cast placeholder expression off, if applicable. 4772 bool CFAudited = false; 4773 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4774 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4775 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4776 Arg = stripARCUnbridgedCast(Arg); 4777 else if (getLangOpts().ObjCAutoRefCount && 4778 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4779 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4780 CFAudited = true; 4781 4782 InitializedEntity Entity = 4783 Param ? InitializedEntity::InitializeParameter(Context, Param, 4784 ProtoArgType) 4785 : InitializedEntity::InitializeParameter( 4786 Context, ProtoArgType, Proto->isParamConsumed(i)); 4787 4788 // Remember that parameter belongs to a CF audited API. 4789 if (CFAudited) 4790 Entity.setParameterCFAudited(); 4791 4792 ExprResult ArgE = PerformCopyInitialization( 4793 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4794 if (ArgE.isInvalid()) 4795 return true; 4796 4797 Arg = ArgE.getAs<Expr>(); 4798 } else { 4799 assert(Param && "can't use default arguments without a known callee"); 4800 4801 ExprResult ArgExpr = 4802 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4803 if (ArgExpr.isInvalid()) 4804 return true; 4805 4806 Arg = ArgExpr.getAs<Expr>(); 4807 } 4808 4809 // Check for array bounds violations for each argument to the call. This 4810 // check only triggers warnings when the argument isn't a more complex Expr 4811 // with its own checking, such as a BinaryOperator. 4812 CheckArrayAccess(Arg); 4813 4814 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4815 CheckStaticArrayArgument(CallLoc, Param, Arg); 4816 4817 AllArgs.push_back(Arg); 4818 } 4819 4820 // If this is a variadic call, handle args passed through "...". 4821 if (CallType != VariadicDoesNotApply) { 4822 // Assume that extern "C" functions with variadic arguments that 4823 // return __unknown_anytype aren't *really* variadic. 4824 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4825 FDecl->isExternC()) { 4826 for (Expr *A : Args.slice(ArgIx)) { 4827 QualType paramType; // ignored 4828 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4829 Invalid |= arg.isInvalid(); 4830 AllArgs.push_back(arg.get()); 4831 } 4832 4833 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4834 } else { 4835 for (Expr *A : Args.slice(ArgIx)) { 4836 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4837 Invalid |= Arg.isInvalid(); 4838 AllArgs.push_back(Arg.get()); 4839 } 4840 } 4841 4842 // Check for array bounds violations. 4843 for (Expr *A : Args.slice(ArgIx)) 4844 CheckArrayAccess(A); 4845 } 4846 return Invalid; 4847 } 4848 4849 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4850 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4851 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4852 TL = DTL.getOriginalLoc(); 4853 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4854 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4855 << ATL.getLocalSourceRange(); 4856 } 4857 4858 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4859 /// array parameter, check that it is non-null, and that if it is formed by 4860 /// array-to-pointer decay, the underlying array is sufficiently large. 4861 /// 4862 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4863 /// array type derivation, then for each call to the function, the value of the 4864 /// corresponding actual argument shall provide access to the first element of 4865 /// an array with at least as many elements as specified by the size expression. 4866 void 4867 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4868 ParmVarDecl *Param, 4869 const Expr *ArgExpr) { 4870 // Static array parameters are not supported in C++. 4871 if (!Param || getLangOpts().CPlusPlus) 4872 return; 4873 4874 QualType OrigTy = Param->getOriginalType(); 4875 4876 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4877 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4878 return; 4879 4880 if (ArgExpr->isNullPointerConstant(Context, 4881 Expr::NPC_NeverValueDependent)) { 4882 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4883 DiagnoseCalleeStaticArrayParam(*this, Param); 4884 return; 4885 } 4886 4887 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4888 if (!CAT) 4889 return; 4890 4891 const ConstantArrayType *ArgCAT = 4892 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4893 if (!ArgCAT) 4894 return; 4895 4896 if (ArgCAT->getSize().ult(CAT->getSize())) { 4897 Diag(CallLoc, diag::warn_static_array_too_small) 4898 << ArgExpr->getSourceRange() 4899 << (unsigned) ArgCAT->getSize().getZExtValue() 4900 << (unsigned) CAT->getSize().getZExtValue(); 4901 DiagnoseCalleeStaticArrayParam(*this, Param); 4902 } 4903 } 4904 4905 /// Given a function expression of unknown-any type, try to rebuild it 4906 /// to have a function type. 4907 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4908 4909 /// Is the given type a placeholder that we need to lower out 4910 /// immediately during argument processing? 4911 static bool isPlaceholderToRemoveAsArg(QualType type) { 4912 // Placeholders are never sugared. 4913 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4914 if (!placeholder) return false; 4915 4916 switch (placeholder->getKind()) { 4917 // Ignore all the non-placeholder types. 4918 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4919 case BuiltinType::Id: 4920 #include "clang/Basic/OpenCLImageTypes.def" 4921 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4922 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4923 #include "clang/AST/BuiltinTypes.def" 4924 return false; 4925 4926 // We cannot lower out overload sets; they might validly be resolved 4927 // by the call machinery. 4928 case BuiltinType::Overload: 4929 return false; 4930 4931 // Unbridged casts in ARC can be handled in some call positions and 4932 // should be left in place. 4933 case BuiltinType::ARCUnbridgedCast: 4934 return false; 4935 4936 // Pseudo-objects should be converted as soon as possible. 4937 case BuiltinType::PseudoObject: 4938 return true; 4939 4940 // The debugger mode could theoretically but currently does not try 4941 // to resolve unknown-typed arguments based on known parameter types. 4942 case BuiltinType::UnknownAny: 4943 return true; 4944 4945 // These are always invalid as call arguments and should be reported. 4946 case BuiltinType::BoundMember: 4947 case BuiltinType::BuiltinFn: 4948 case BuiltinType::OMPArraySection: 4949 return true; 4950 4951 } 4952 llvm_unreachable("bad builtin type kind"); 4953 } 4954 4955 /// Check an argument list for placeholders that we won't try to 4956 /// handle later. 4957 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4958 // Apply this processing to all the arguments at once instead of 4959 // dying at the first failure. 4960 bool hasInvalid = false; 4961 for (size_t i = 0, e = args.size(); i != e; i++) { 4962 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4963 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4964 if (result.isInvalid()) hasInvalid = true; 4965 else args[i] = result.get(); 4966 } else if (hasInvalid) { 4967 (void)S.CorrectDelayedTyposInExpr(args[i]); 4968 } 4969 } 4970 return hasInvalid; 4971 } 4972 4973 /// If a builtin function has a pointer argument with no explicit address 4974 /// space, then it should be able to accept a pointer to any address 4975 /// space as input. In order to do this, we need to replace the 4976 /// standard builtin declaration with one that uses the same address space 4977 /// as the call. 4978 /// 4979 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4980 /// it does not contain any pointer arguments without 4981 /// an address space qualifer. Otherwise the rewritten 4982 /// FunctionDecl is returned. 4983 /// TODO: Handle pointer return types. 4984 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4985 const FunctionDecl *FDecl, 4986 MultiExprArg ArgExprs) { 4987 4988 QualType DeclType = FDecl->getType(); 4989 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4990 4991 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4992 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4993 return nullptr; 4994 4995 bool NeedsNewDecl = false; 4996 unsigned i = 0; 4997 SmallVector<QualType, 8> OverloadParams; 4998 4999 for (QualType ParamType : FT->param_types()) { 5000 5001 // Convert array arguments to pointer to simplify type lookup. 5002 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 5003 QualType ArgType = Arg->getType(); 5004 if (!ParamType->isPointerType() || 5005 ParamType.getQualifiers().hasAddressSpace() || 5006 !ArgType->isPointerType() || 5007 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5008 OverloadParams.push_back(ParamType); 5009 continue; 5010 } 5011 5012 NeedsNewDecl = true; 5013 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5014 5015 QualType PointeeType = ParamType->getPointeeType(); 5016 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5017 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5018 } 5019 5020 if (!NeedsNewDecl) 5021 return nullptr; 5022 5023 FunctionProtoType::ExtProtoInfo EPI; 5024 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5025 OverloadParams, EPI); 5026 DeclContext *Parent = Context.getTranslationUnitDecl(); 5027 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5028 FDecl->getLocation(), 5029 FDecl->getLocation(), 5030 FDecl->getIdentifier(), 5031 OverloadTy, 5032 /*TInfo=*/nullptr, 5033 SC_Extern, false, 5034 /*hasPrototype=*/true); 5035 SmallVector<ParmVarDecl*, 16> Params; 5036 FT = cast<FunctionProtoType>(OverloadTy); 5037 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5038 QualType ParamType = FT->getParamType(i); 5039 ParmVarDecl *Parm = 5040 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5041 SourceLocation(), nullptr, ParamType, 5042 /*TInfo=*/nullptr, SC_None, nullptr); 5043 Parm->setScopeInfo(0, i); 5044 Params.push_back(Parm); 5045 } 5046 OverloadDecl->setParams(Params); 5047 return OverloadDecl; 5048 } 5049 5050 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5051 std::size_t NumArgs) { 5052 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5053 /*PartialOverloading=*/false)) 5054 return Callee->isVariadic(); 5055 return Callee->getMinRequiredArguments() <= NumArgs; 5056 } 5057 5058 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5059 /// This provides the location of the left/right parens and a list of comma 5060 /// locations. 5061 ExprResult 5062 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5063 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5064 Expr *ExecConfig, bool IsExecConfig) { 5065 // Since this might be a postfix expression, get rid of ParenListExprs. 5066 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 5067 if (Result.isInvalid()) return ExprError(); 5068 Fn = Result.get(); 5069 5070 if (checkArgsForPlaceholders(*this, ArgExprs)) 5071 return ExprError(); 5072 5073 if (getLangOpts().CPlusPlus) { 5074 // If this is a pseudo-destructor expression, build the call immediately. 5075 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5076 if (!ArgExprs.empty()) { 5077 // Pseudo-destructor calls should not have any arguments. 5078 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5079 << FixItHint::CreateRemoval( 5080 SourceRange(ArgExprs.front()->getLocStart(), 5081 ArgExprs.back()->getLocEnd())); 5082 } 5083 5084 return new (Context) 5085 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5086 } 5087 if (Fn->getType() == Context.PseudoObjectTy) { 5088 ExprResult result = CheckPlaceholderExpr(Fn); 5089 if (result.isInvalid()) return ExprError(); 5090 Fn = result.get(); 5091 } 5092 5093 // Determine whether this is a dependent call inside a C++ template, 5094 // in which case we won't do any semantic analysis now. 5095 bool Dependent = false; 5096 if (Fn->isTypeDependent()) 5097 Dependent = true; 5098 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5099 Dependent = true; 5100 5101 if (Dependent) { 5102 if (ExecConfig) { 5103 return new (Context) CUDAKernelCallExpr( 5104 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5105 Context.DependentTy, VK_RValue, RParenLoc); 5106 } else { 5107 return new (Context) CallExpr( 5108 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5109 } 5110 } 5111 5112 // Determine whether this is a call to an object (C++ [over.call.object]). 5113 if (Fn->getType()->isRecordType()) 5114 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 5115 RParenLoc); 5116 5117 if (Fn->getType() == Context.UnknownAnyTy) { 5118 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5119 if (result.isInvalid()) return ExprError(); 5120 Fn = result.get(); 5121 } 5122 5123 if (Fn->getType() == Context.BoundMemberTy) { 5124 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5125 } 5126 } 5127 5128 // Check for overloaded calls. This can happen even in C due to extensions. 5129 if (Fn->getType() == Context.OverloadTy) { 5130 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5131 5132 // We aren't supposed to apply this logic for if there's an '&' involved. 5133 if (!find.HasFormOfMemberPointer) { 5134 OverloadExpr *ovl = find.Expression; 5135 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5136 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 5137 RParenLoc, ExecConfig, 5138 /*AllowTypoCorrection=*/true, 5139 find.IsAddressOfOperand); 5140 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5141 } 5142 } 5143 5144 // If we're directly calling a function, get the appropriate declaration. 5145 if (Fn->getType() == Context.UnknownAnyTy) { 5146 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5147 if (result.isInvalid()) return ExprError(); 5148 Fn = result.get(); 5149 } 5150 5151 Expr *NakedFn = Fn->IgnoreParens(); 5152 5153 bool CallingNDeclIndirectly = false; 5154 NamedDecl *NDecl = nullptr; 5155 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5156 if (UnOp->getOpcode() == UO_AddrOf) { 5157 CallingNDeclIndirectly = true; 5158 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5159 } 5160 } 5161 5162 if (isa<DeclRefExpr>(NakedFn)) { 5163 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5164 5165 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5166 if (FDecl && FDecl->getBuiltinID()) { 5167 // Rewrite the function decl for this builtin by replacing parameters 5168 // with no explicit address space with the address space of the arguments 5169 // in ArgExprs. 5170 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5171 NDecl = FDecl; 5172 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 5173 SourceLocation(), FDecl, false, 5174 SourceLocation(), FDecl->getType(), 5175 Fn->getValueKind(), FDecl); 5176 } 5177 } 5178 } else if (isa<MemberExpr>(NakedFn)) 5179 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5180 5181 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5182 if (CallingNDeclIndirectly && 5183 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5184 Fn->getLocStart())) 5185 return ExprError(); 5186 5187 // CheckEnableIf assumes that the we're passing in a sane number of args for 5188 // FD, but that doesn't always hold true here. This is because, in some 5189 // cases, we'll emit a diag about an ill-formed function call, but then 5190 // we'll continue on as if the function call wasn't ill-formed. So, if the 5191 // number of args looks incorrect, don't do enable_if checks; we should've 5192 // already emitted an error about the bad call. 5193 if (FD->hasAttr<EnableIfAttr>() && 5194 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5195 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5196 Diag(Fn->getLocStart(), 5197 isa<CXXMethodDecl>(FD) ? 5198 diag::err_ovl_no_viable_member_function_in_call : 5199 diag::err_ovl_no_viable_function_in_call) 5200 << FD << FD->getSourceRange(); 5201 Diag(FD->getLocation(), 5202 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5203 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5204 } 5205 } 5206 } 5207 5208 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5209 ExecConfig, IsExecConfig); 5210 } 5211 5212 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5213 /// 5214 /// __builtin_astype( value, dst type ) 5215 /// 5216 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5217 SourceLocation BuiltinLoc, 5218 SourceLocation RParenLoc) { 5219 ExprValueKind VK = VK_RValue; 5220 ExprObjectKind OK = OK_Ordinary; 5221 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5222 QualType SrcTy = E->getType(); 5223 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5224 return ExprError(Diag(BuiltinLoc, 5225 diag::err_invalid_astype_of_different_size) 5226 << DstTy 5227 << SrcTy 5228 << E->getSourceRange()); 5229 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5230 } 5231 5232 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5233 /// provided arguments. 5234 /// 5235 /// __builtin_convertvector( value, dst type ) 5236 /// 5237 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5238 SourceLocation BuiltinLoc, 5239 SourceLocation RParenLoc) { 5240 TypeSourceInfo *TInfo; 5241 GetTypeFromParser(ParsedDestTy, &TInfo); 5242 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5243 } 5244 5245 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5246 /// i.e. an expression not of \p OverloadTy. The expression should 5247 /// unary-convert to an expression of function-pointer or 5248 /// block-pointer type. 5249 /// 5250 /// \param NDecl the declaration being called, if available 5251 ExprResult 5252 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5253 SourceLocation LParenLoc, 5254 ArrayRef<Expr *> Args, 5255 SourceLocation RParenLoc, 5256 Expr *Config, bool IsExecConfig) { 5257 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5258 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5259 5260 // Functions with 'interrupt' attribute cannot be called directly. 5261 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5262 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5263 return ExprError(); 5264 } 5265 5266 // Promote the function operand. 5267 // We special-case function promotion here because we only allow promoting 5268 // builtin functions to function pointers in the callee of a call. 5269 ExprResult Result; 5270 if (BuiltinID && 5271 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5272 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5273 CK_BuiltinFnToFnPtr).get(); 5274 } else { 5275 Result = CallExprUnaryConversions(Fn); 5276 } 5277 if (Result.isInvalid()) 5278 return ExprError(); 5279 Fn = Result.get(); 5280 5281 // Make the call expr early, before semantic checks. This guarantees cleanup 5282 // of arguments and function on error. 5283 CallExpr *TheCall; 5284 if (Config) 5285 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5286 cast<CallExpr>(Config), Args, 5287 Context.BoolTy, VK_RValue, 5288 RParenLoc); 5289 else 5290 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5291 VK_RValue, RParenLoc); 5292 5293 if (!getLangOpts().CPlusPlus) { 5294 // C cannot always handle TypoExpr nodes in builtin calls and direct 5295 // function calls as their argument checking don't necessarily handle 5296 // dependent types properly, so make sure any TypoExprs have been 5297 // dealt with. 5298 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5299 if (!Result.isUsable()) return ExprError(); 5300 TheCall = dyn_cast<CallExpr>(Result.get()); 5301 if (!TheCall) return Result; 5302 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5303 } 5304 5305 // Bail out early if calling a builtin with custom typechecking. 5306 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5307 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5308 5309 retry: 5310 const FunctionType *FuncT; 5311 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5312 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5313 // have type pointer to function". 5314 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5315 if (!FuncT) 5316 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5317 << Fn->getType() << Fn->getSourceRange()); 5318 } else if (const BlockPointerType *BPT = 5319 Fn->getType()->getAs<BlockPointerType>()) { 5320 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5321 } else { 5322 // Handle calls to expressions of unknown-any type. 5323 if (Fn->getType() == Context.UnknownAnyTy) { 5324 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5325 if (rewrite.isInvalid()) return ExprError(); 5326 Fn = rewrite.get(); 5327 TheCall->setCallee(Fn); 5328 goto retry; 5329 } 5330 5331 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5332 << Fn->getType() << Fn->getSourceRange()); 5333 } 5334 5335 if (getLangOpts().CUDA) { 5336 if (Config) { 5337 // CUDA: Kernel calls must be to global functions 5338 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5339 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5340 << FDecl->getName() << Fn->getSourceRange()); 5341 5342 // CUDA: Kernel function must have 'void' return type 5343 if (!FuncT->getReturnType()->isVoidType()) 5344 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5345 << Fn->getType() << Fn->getSourceRange()); 5346 } else { 5347 // CUDA: Calls to global functions must be configured 5348 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5349 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5350 << FDecl->getName() << Fn->getSourceRange()); 5351 } 5352 } 5353 5354 // Check for a valid return type 5355 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5356 FDecl)) 5357 return ExprError(); 5358 5359 // We know the result type of the call, set it. 5360 TheCall->setType(FuncT->getCallResultType(Context)); 5361 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5362 5363 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5364 if (Proto) { 5365 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5366 IsExecConfig)) 5367 return ExprError(); 5368 } else { 5369 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5370 5371 if (FDecl) { 5372 // Check if we have too few/too many template arguments, based 5373 // on our knowledge of the function definition. 5374 const FunctionDecl *Def = nullptr; 5375 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5376 Proto = Def->getType()->getAs<FunctionProtoType>(); 5377 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5378 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5379 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5380 } 5381 5382 // If the function we're calling isn't a function prototype, but we have 5383 // a function prototype from a prior declaratiom, use that prototype. 5384 if (!FDecl->hasPrototype()) 5385 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5386 } 5387 5388 // Promote the arguments (C99 6.5.2.2p6). 5389 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5390 Expr *Arg = Args[i]; 5391 5392 if (Proto && i < Proto->getNumParams()) { 5393 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5394 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5395 ExprResult ArgE = 5396 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5397 if (ArgE.isInvalid()) 5398 return true; 5399 5400 Arg = ArgE.getAs<Expr>(); 5401 5402 } else { 5403 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5404 5405 if (ArgE.isInvalid()) 5406 return true; 5407 5408 Arg = ArgE.getAs<Expr>(); 5409 } 5410 5411 if (RequireCompleteType(Arg->getLocStart(), 5412 Arg->getType(), 5413 diag::err_call_incomplete_argument, Arg)) 5414 return ExprError(); 5415 5416 TheCall->setArg(i, Arg); 5417 } 5418 } 5419 5420 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5421 if (!Method->isStatic()) 5422 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5423 << Fn->getSourceRange()); 5424 5425 // Check for sentinels 5426 if (NDecl) 5427 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5428 5429 // Do special checking on direct calls to functions. 5430 if (FDecl) { 5431 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5432 return ExprError(); 5433 5434 if (BuiltinID) 5435 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5436 } else if (NDecl) { 5437 if (CheckPointerCall(NDecl, TheCall, Proto)) 5438 return ExprError(); 5439 } else { 5440 if (CheckOtherCall(TheCall, Proto)) 5441 return ExprError(); 5442 } 5443 5444 return MaybeBindToTemporary(TheCall); 5445 } 5446 5447 ExprResult 5448 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5449 SourceLocation RParenLoc, Expr *InitExpr) { 5450 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5451 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5452 5453 TypeSourceInfo *TInfo; 5454 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5455 if (!TInfo) 5456 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5457 5458 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5459 } 5460 5461 ExprResult 5462 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5463 SourceLocation RParenLoc, Expr *LiteralExpr) { 5464 QualType literalType = TInfo->getType(); 5465 5466 if (literalType->isArrayType()) { 5467 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5468 diag::err_illegal_decl_array_incomplete_type, 5469 SourceRange(LParenLoc, 5470 LiteralExpr->getSourceRange().getEnd()))) 5471 return ExprError(); 5472 if (literalType->isVariableArrayType()) 5473 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5474 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5475 } else if (!literalType->isDependentType() && 5476 RequireCompleteType(LParenLoc, literalType, 5477 diag::err_typecheck_decl_incomplete_type, 5478 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5479 return ExprError(); 5480 5481 InitializedEntity Entity 5482 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5483 InitializationKind Kind 5484 = InitializationKind::CreateCStyleCast(LParenLoc, 5485 SourceRange(LParenLoc, RParenLoc), 5486 /*InitList=*/true); 5487 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5488 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5489 &literalType); 5490 if (Result.isInvalid()) 5491 return ExprError(); 5492 LiteralExpr = Result.get(); 5493 5494 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5495 if (isFileScope && 5496 !LiteralExpr->isTypeDependent() && 5497 !LiteralExpr->isValueDependent() && 5498 !literalType->isDependentType()) { // 6.5.2.5p3 5499 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5500 return ExprError(); 5501 } 5502 5503 // In C, compound literals are l-values for some reason. 5504 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5505 5506 return MaybeBindToTemporary( 5507 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5508 VK, LiteralExpr, isFileScope)); 5509 } 5510 5511 ExprResult 5512 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5513 SourceLocation RBraceLoc) { 5514 // Immediately handle non-overload placeholders. Overloads can be 5515 // resolved contextually, but everything else here can't. 5516 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5517 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5518 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5519 5520 // Ignore failures; dropping the entire initializer list because 5521 // of one failure would be terrible for indexing/etc. 5522 if (result.isInvalid()) continue; 5523 5524 InitArgList[I] = result.get(); 5525 } 5526 } 5527 5528 // Semantic analysis for initializers is done by ActOnDeclarator() and 5529 // CheckInitializer() - it requires knowledge of the object being intialized. 5530 5531 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5532 RBraceLoc); 5533 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5534 return E; 5535 } 5536 5537 /// Do an explicit extend of the given block pointer if we're in ARC. 5538 void Sema::maybeExtendBlockObject(ExprResult &E) { 5539 assert(E.get()->getType()->isBlockPointerType()); 5540 assert(E.get()->isRValue()); 5541 5542 // Only do this in an r-value context. 5543 if (!getLangOpts().ObjCAutoRefCount) return; 5544 5545 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5546 CK_ARCExtendBlockObject, E.get(), 5547 /*base path*/ nullptr, VK_RValue); 5548 ExprNeedsCleanups = true; 5549 } 5550 5551 /// Prepare a conversion of the given expression to an ObjC object 5552 /// pointer type. 5553 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5554 QualType type = E.get()->getType(); 5555 if (type->isObjCObjectPointerType()) { 5556 return CK_BitCast; 5557 } else if (type->isBlockPointerType()) { 5558 maybeExtendBlockObject(E); 5559 return CK_BlockPointerToObjCPointerCast; 5560 } else { 5561 assert(type->isPointerType()); 5562 return CK_CPointerToObjCPointerCast; 5563 } 5564 } 5565 5566 /// Prepares for a scalar cast, performing all the necessary stages 5567 /// except the final cast and returning the kind required. 5568 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5569 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5570 // Also, callers should have filtered out the invalid cases with 5571 // pointers. Everything else should be possible. 5572 5573 QualType SrcTy = Src.get()->getType(); 5574 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5575 return CK_NoOp; 5576 5577 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5578 case Type::STK_MemberPointer: 5579 llvm_unreachable("member pointer type in C"); 5580 5581 case Type::STK_CPointer: 5582 case Type::STK_BlockPointer: 5583 case Type::STK_ObjCObjectPointer: 5584 switch (DestTy->getScalarTypeKind()) { 5585 case Type::STK_CPointer: { 5586 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5587 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5588 if (SrcAS != DestAS) 5589 return CK_AddressSpaceConversion; 5590 return CK_BitCast; 5591 } 5592 case Type::STK_BlockPointer: 5593 return (SrcKind == Type::STK_BlockPointer 5594 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5595 case Type::STK_ObjCObjectPointer: 5596 if (SrcKind == Type::STK_ObjCObjectPointer) 5597 return CK_BitCast; 5598 if (SrcKind == Type::STK_CPointer) 5599 return CK_CPointerToObjCPointerCast; 5600 maybeExtendBlockObject(Src); 5601 return CK_BlockPointerToObjCPointerCast; 5602 case Type::STK_Bool: 5603 return CK_PointerToBoolean; 5604 case Type::STK_Integral: 5605 return CK_PointerToIntegral; 5606 case Type::STK_Floating: 5607 case Type::STK_FloatingComplex: 5608 case Type::STK_IntegralComplex: 5609 case Type::STK_MemberPointer: 5610 llvm_unreachable("illegal cast from pointer"); 5611 } 5612 llvm_unreachable("Should have returned before this"); 5613 5614 case Type::STK_Bool: // casting from bool is like casting from an integer 5615 case Type::STK_Integral: 5616 switch (DestTy->getScalarTypeKind()) { 5617 case Type::STK_CPointer: 5618 case Type::STK_ObjCObjectPointer: 5619 case Type::STK_BlockPointer: 5620 if (Src.get()->isNullPointerConstant(Context, 5621 Expr::NPC_ValueDependentIsNull)) 5622 return CK_NullToPointer; 5623 return CK_IntegralToPointer; 5624 case Type::STK_Bool: 5625 return CK_IntegralToBoolean; 5626 case Type::STK_Integral: 5627 return CK_IntegralCast; 5628 case Type::STK_Floating: 5629 return CK_IntegralToFloating; 5630 case Type::STK_IntegralComplex: 5631 Src = ImpCastExprToType(Src.get(), 5632 DestTy->castAs<ComplexType>()->getElementType(), 5633 CK_IntegralCast); 5634 return CK_IntegralRealToComplex; 5635 case Type::STK_FloatingComplex: 5636 Src = ImpCastExprToType(Src.get(), 5637 DestTy->castAs<ComplexType>()->getElementType(), 5638 CK_IntegralToFloating); 5639 return CK_FloatingRealToComplex; 5640 case Type::STK_MemberPointer: 5641 llvm_unreachable("member pointer type in C"); 5642 } 5643 llvm_unreachable("Should have returned before this"); 5644 5645 case Type::STK_Floating: 5646 switch (DestTy->getScalarTypeKind()) { 5647 case Type::STK_Floating: 5648 return CK_FloatingCast; 5649 case Type::STK_Bool: 5650 return CK_FloatingToBoolean; 5651 case Type::STK_Integral: 5652 return CK_FloatingToIntegral; 5653 case Type::STK_FloatingComplex: 5654 Src = ImpCastExprToType(Src.get(), 5655 DestTy->castAs<ComplexType>()->getElementType(), 5656 CK_FloatingCast); 5657 return CK_FloatingRealToComplex; 5658 case Type::STK_IntegralComplex: 5659 Src = ImpCastExprToType(Src.get(), 5660 DestTy->castAs<ComplexType>()->getElementType(), 5661 CK_FloatingToIntegral); 5662 return CK_IntegralRealToComplex; 5663 case Type::STK_CPointer: 5664 case Type::STK_ObjCObjectPointer: 5665 case Type::STK_BlockPointer: 5666 llvm_unreachable("valid float->pointer cast?"); 5667 case Type::STK_MemberPointer: 5668 llvm_unreachable("member pointer type in C"); 5669 } 5670 llvm_unreachable("Should have returned before this"); 5671 5672 case Type::STK_FloatingComplex: 5673 switch (DestTy->getScalarTypeKind()) { 5674 case Type::STK_FloatingComplex: 5675 return CK_FloatingComplexCast; 5676 case Type::STK_IntegralComplex: 5677 return CK_FloatingComplexToIntegralComplex; 5678 case Type::STK_Floating: { 5679 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5680 if (Context.hasSameType(ET, DestTy)) 5681 return CK_FloatingComplexToReal; 5682 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5683 return CK_FloatingCast; 5684 } 5685 case Type::STK_Bool: 5686 return CK_FloatingComplexToBoolean; 5687 case Type::STK_Integral: 5688 Src = ImpCastExprToType(Src.get(), 5689 SrcTy->castAs<ComplexType>()->getElementType(), 5690 CK_FloatingComplexToReal); 5691 return CK_FloatingToIntegral; 5692 case Type::STK_CPointer: 5693 case Type::STK_ObjCObjectPointer: 5694 case Type::STK_BlockPointer: 5695 llvm_unreachable("valid complex float->pointer cast?"); 5696 case Type::STK_MemberPointer: 5697 llvm_unreachable("member pointer type in C"); 5698 } 5699 llvm_unreachable("Should have returned before this"); 5700 5701 case Type::STK_IntegralComplex: 5702 switch (DestTy->getScalarTypeKind()) { 5703 case Type::STK_FloatingComplex: 5704 return CK_IntegralComplexToFloatingComplex; 5705 case Type::STK_IntegralComplex: 5706 return CK_IntegralComplexCast; 5707 case Type::STK_Integral: { 5708 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5709 if (Context.hasSameType(ET, DestTy)) 5710 return CK_IntegralComplexToReal; 5711 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5712 return CK_IntegralCast; 5713 } 5714 case Type::STK_Bool: 5715 return CK_IntegralComplexToBoolean; 5716 case Type::STK_Floating: 5717 Src = ImpCastExprToType(Src.get(), 5718 SrcTy->castAs<ComplexType>()->getElementType(), 5719 CK_IntegralComplexToReal); 5720 return CK_IntegralToFloating; 5721 case Type::STK_CPointer: 5722 case Type::STK_ObjCObjectPointer: 5723 case Type::STK_BlockPointer: 5724 llvm_unreachable("valid complex int->pointer cast?"); 5725 case Type::STK_MemberPointer: 5726 llvm_unreachable("member pointer type in C"); 5727 } 5728 llvm_unreachable("Should have returned before this"); 5729 } 5730 5731 llvm_unreachable("Unhandled scalar cast"); 5732 } 5733 5734 static bool breakDownVectorType(QualType type, uint64_t &len, 5735 QualType &eltType) { 5736 // Vectors are simple. 5737 if (const VectorType *vecType = type->getAs<VectorType>()) { 5738 len = vecType->getNumElements(); 5739 eltType = vecType->getElementType(); 5740 assert(eltType->isScalarType()); 5741 return true; 5742 } 5743 5744 // We allow lax conversion to and from non-vector types, but only if 5745 // they're real types (i.e. non-complex, non-pointer scalar types). 5746 if (!type->isRealType()) return false; 5747 5748 len = 1; 5749 eltType = type; 5750 return true; 5751 } 5752 5753 /// Are the two types lax-compatible vector types? That is, given 5754 /// that one of them is a vector, do they have equal storage sizes, 5755 /// where the storage size is the number of elements times the element 5756 /// size? 5757 /// 5758 /// This will also return false if either of the types is neither a 5759 /// vector nor a real type. 5760 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5761 assert(destTy->isVectorType() || srcTy->isVectorType()); 5762 5763 // Disallow lax conversions between scalars and ExtVectors (these 5764 // conversions are allowed for other vector types because common headers 5765 // depend on them). Most scalar OP ExtVector cases are handled by the 5766 // splat path anyway, which does what we want (convert, not bitcast). 5767 // What this rules out for ExtVectors is crazy things like char4*float. 5768 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5769 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5770 5771 uint64_t srcLen, destLen; 5772 QualType srcEltTy, destEltTy; 5773 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5774 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5775 5776 // ASTContext::getTypeSize will return the size rounded up to a 5777 // power of 2, so instead of using that, we need to use the raw 5778 // element size multiplied by the element count. 5779 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5780 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5781 5782 return (srcLen * srcEltSize == destLen * destEltSize); 5783 } 5784 5785 /// Is this a legal conversion between two types, one of which is 5786 /// known to be a vector type? 5787 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5788 assert(destTy->isVectorType() || srcTy->isVectorType()); 5789 5790 if (!Context.getLangOpts().LaxVectorConversions) 5791 return false; 5792 return areLaxCompatibleVectorTypes(srcTy, destTy); 5793 } 5794 5795 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5796 CastKind &Kind) { 5797 assert(VectorTy->isVectorType() && "Not a vector type!"); 5798 5799 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5800 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5801 return Diag(R.getBegin(), 5802 Ty->isVectorType() ? 5803 diag::err_invalid_conversion_between_vectors : 5804 diag::err_invalid_conversion_between_vector_and_integer) 5805 << VectorTy << Ty << R; 5806 } else 5807 return Diag(R.getBegin(), 5808 diag::err_invalid_conversion_between_vector_and_scalar) 5809 << VectorTy << Ty << R; 5810 5811 Kind = CK_BitCast; 5812 return false; 5813 } 5814 5815 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5816 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5817 5818 if (DestElemTy == SplattedExpr->getType()) 5819 return SplattedExpr; 5820 5821 assert(DestElemTy->isFloatingType() || 5822 DestElemTy->isIntegralOrEnumerationType()); 5823 5824 CastKind CK; 5825 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5826 // OpenCL requires that we convert `true` boolean expressions to -1, but 5827 // only when splatting vectors. 5828 if (DestElemTy->isFloatingType()) { 5829 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5830 // in two steps: boolean to signed integral, then to floating. 5831 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5832 CK_BooleanToSignedIntegral); 5833 SplattedExpr = CastExprRes.get(); 5834 CK = CK_IntegralToFloating; 5835 } else { 5836 CK = CK_BooleanToSignedIntegral; 5837 } 5838 } else { 5839 ExprResult CastExprRes = SplattedExpr; 5840 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5841 if (CastExprRes.isInvalid()) 5842 return ExprError(); 5843 SplattedExpr = CastExprRes.get(); 5844 } 5845 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5846 } 5847 5848 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5849 Expr *CastExpr, CastKind &Kind) { 5850 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5851 5852 QualType SrcTy = CastExpr->getType(); 5853 5854 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5855 // an ExtVectorType. 5856 // In OpenCL, casts between vectors of different types are not allowed. 5857 // (See OpenCL 6.2). 5858 if (SrcTy->isVectorType()) { 5859 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5860 || (getLangOpts().OpenCL && 5861 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5862 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5863 << DestTy << SrcTy << R; 5864 return ExprError(); 5865 } 5866 Kind = CK_BitCast; 5867 return CastExpr; 5868 } 5869 5870 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5871 // conversion will take place first from scalar to elt type, and then 5872 // splat from elt type to vector. 5873 if (SrcTy->isPointerType()) 5874 return Diag(R.getBegin(), 5875 diag::err_invalid_conversion_between_vector_and_scalar) 5876 << DestTy << SrcTy << R; 5877 5878 Kind = CK_VectorSplat; 5879 return prepareVectorSplat(DestTy, CastExpr); 5880 } 5881 5882 ExprResult 5883 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5884 Declarator &D, ParsedType &Ty, 5885 SourceLocation RParenLoc, Expr *CastExpr) { 5886 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5887 "ActOnCastExpr(): missing type or expr"); 5888 5889 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5890 if (D.isInvalidType()) 5891 return ExprError(); 5892 5893 if (getLangOpts().CPlusPlus) { 5894 // Check that there are no default arguments (C++ only). 5895 CheckExtraCXXDefaultArguments(D); 5896 } else { 5897 // Make sure any TypoExprs have been dealt with. 5898 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5899 if (!Res.isUsable()) 5900 return ExprError(); 5901 CastExpr = Res.get(); 5902 } 5903 5904 checkUnusedDeclAttributes(D); 5905 5906 QualType castType = castTInfo->getType(); 5907 Ty = CreateParsedType(castType, castTInfo); 5908 5909 bool isVectorLiteral = false; 5910 5911 // Check for an altivec or OpenCL literal, 5912 // i.e. all the elements are integer constants. 5913 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5914 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5915 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5916 && castType->isVectorType() && (PE || PLE)) { 5917 if (PLE && PLE->getNumExprs() == 0) { 5918 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5919 return ExprError(); 5920 } 5921 if (PE || PLE->getNumExprs() == 1) { 5922 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5923 if (!E->getType()->isVectorType()) 5924 isVectorLiteral = true; 5925 } 5926 else 5927 isVectorLiteral = true; 5928 } 5929 5930 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5931 // then handle it as such. 5932 if (isVectorLiteral) 5933 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5934 5935 // If the Expr being casted is a ParenListExpr, handle it specially. 5936 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5937 // sequence of BinOp comma operators. 5938 if (isa<ParenListExpr>(CastExpr)) { 5939 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5940 if (Result.isInvalid()) return ExprError(); 5941 CastExpr = Result.get(); 5942 } 5943 5944 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5945 !getSourceManager().isInSystemMacro(LParenLoc)) 5946 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5947 5948 CheckTollFreeBridgeCast(castType, CastExpr); 5949 5950 CheckObjCBridgeRelatedCast(castType, CastExpr); 5951 5952 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5953 } 5954 5955 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5956 SourceLocation RParenLoc, Expr *E, 5957 TypeSourceInfo *TInfo) { 5958 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5959 "Expected paren or paren list expression"); 5960 5961 Expr **exprs; 5962 unsigned numExprs; 5963 Expr *subExpr; 5964 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5965 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5966 LiteralLParenLoc = PE->getLParenLoc(); 5967 LiteralRParenLoc = PE->getRParenLoc(); 5968 exprs = PE->getExprs(); 5969 numExprs = PE->getNumExprs(); 5970 } else { // isa<ParenExpr> by assertion at function entrance 5971 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5972 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5973 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5974 exprs = &subExpr; 5975 numExprs = 1; 5976 } 5977 5978 QualType Ty = TInfo->getType(); 5979 assert(Ty->isVectorType() && "Expected vector type"); 5980 5981 SmallVector<Expr *, 8> initExprs; 5982 const VectorType *VTy = Ty->getAs<VectorType>(); 5983 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5984 5985 // '(...)' form of vector initialization in AltiVec: the number of 5986 // initializers must be one or must match the size of the vector. 5987 // If a single value is specified in the initializer then it will be 5988 // replicated to all the components of the vector 5989 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5990 // The number of initializers must be one or must match the size of the 5991 // vector. If a single value is specified in the initializer then it will 5992 // be replicated to all the components of the vector 5993 if (numExprs == 1) { 5994 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5995 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5996 if (Literal.isInvalid()) 5997 return ExprError(); 5998 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5999 PrepareScalarCast(Literal, ElemTy)); 6000 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6001 } 6002 else if (numExprs < numElems) { 6003 Diag(E->getExprLoc(), 6004 diag::err_incorrect_number_of_vector_initializers); 6005 return ExprError(); 6006 } 6007 else 6008 initExprs.append(exprs, exprs + numExprs); 6009 } 6010 else { 6011 // For OpenCL, when the number of initializers is a single value, 6012 // it will be replicated to all components of the vector. 6013 if (getLangOpts().OpenCL && 6014 VTy->getVectorKind() == VectorType::GenericVector && 6015 numExprs == 1) { 6016 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6017 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6018 if (Literal.isInvalid()) 6019 return ExprError(); 6020 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6021 PrepareScalarCast(Literal, ElemTy)); 6022 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6023 } 6024 6025 initExprs.append(exprs, exprs + numExprs); 6026 } 6027 // FIXME: This means that pretty-printing the final AST will produce curly 6028 // braces instead of the original commas. 6029 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6030 initExprs, LiteralRParenLoc); 6031 initE->setType(Ty); 6032 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6033 } 6034 6035 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6036 /// the ParenListExpr into a sequence of comma binary operators. 6037 ExprResult 6038 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6039 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6040 if (!E) 6041 return OrigExpr; 6042 6043 ExprResult Result(E->getExpr(0)); 6044 6045 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6046 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6047 E->getExpr(i)); 6048 6049 if (Result.isInvalid()) return ExprError(); 6050 6051 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6052 } 6053 6054 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6055 SourceLocation R, 6056 MultiExprArg Val) { 6057 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6058 return expr; 6059 } 6060 6061 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6062 /// constant and the other is not a pointer. Returns true if a diagnostic is 6063 /// emitted. 6064 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6065 SourceLocation QuestionLoc) { 6066 Expr *NullExpr = LHSExpr; 6067 Expr *NonPointerExpr = RHSExpr; 6068 Expr::NullPointerConstantKind NullKind = 6069 NullExpr->isNullPointerConstant(Context, 6070 Expr::NPC_ValueDependentIsNotNull); 6071 6072 if (NullKind == Expr::NPCK_NotNull) { 6073 NullExpr = RHSExpr; 6074 NonPointerExpr = LHSExpr; 6075 NullKind = 6076 NullExpr->isNullPointerConstant(Context, 6077 Expr::NPC_ValueDependentIsNotNull); 6078 } 6079 6080 if (NullKind == Expr::NPCK_NotNull) 6081 return false; 6082 6083 if (NullKind == Expr::NPCK_ZeroExpression) 6084 return false; 6085 6086 if (NullKind == Expr::NPCK_ZeroLiteral) { 6087 // In this case, check to make sure that we got here from a "NULL" 6088 // string in the source code. 6089 NullExpr = NullExpr->IgnoreParenImpCasts(); 6090 SourceLocation loc = NullExpr->getExprLoc(); 6091 if (!findMacroSpelling(loc, "NULL")) 6092 return false; 6093 } 6094 6095 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6096 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6097 << NonPointerExpr->getType() << DiagType 6098 << NonPointerExpr->getSourceRange(); 6099 return true; 6100 } 6101 6102 /// \brief Return false if the condition expression is valid, true otherwise. 6103 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6104 QualType CondTy = Cond->getType(); 6105 6106 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6107 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6108 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6109 << CondTy << Cond->getSourceRange(); 6110 return true; 6111 } 6112 6113 // C99 6.5.15p2 6114 if (CondTy->isScalarType()) return false; 6115 6116 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6117 << CondTy << Cond->getSourceRange(); 6118 return true; 6119 } 6120 6121 /// \brief Handle when one or both operands are void type. 6122 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6123 ExprResult &RHS) { 6124 Expr *LHSExpr = LHS.get(); 6125 Expr *RHSExpr = RHS.get(); 6126 6127 if (!LHSExpr->getType()->isVoidType()) 6128 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6129 << RHSExpr->getSourceRange(); 6130 if (!RHSExpr->getType()->isVoidType()) 6131 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6132 << LHSExpr->getSourceRange(); 6133 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6134 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6135 return S.Context.VoidTy; 6136 } 6137 6138 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6139 /// true otherwise. 6140 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6141 QualType PointerTy) { 6142 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6143 !NullExpr.get()->isNullPointerConstant(S.Context, 6144 Expr::NPC_ValueDependentIsNull)) 6145 return true; 6146 6147 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6148 return false; 6149 } 6150 6151 /// \brief Checks compatibility between two pointers and return the resulting 6152 /// type. 6153 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6154 ExprResult &RHS, 6155 SourceLocation Loc) { 6156 QualType LHSTy = LHS.get()->getType(); 6157 QualType RHSTy = RHS.get()->getType(); 6158 6159 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6160 // Two identical pointers types are always compatible. 6161 return LHSTy; 6162 } 6163 6164 QualType lhptee, rhptee; 6165 6166 // Get the pointee types. 6167 bool IsBlockPointer = false; 6168 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6169 lhptee = LHSBTy->getPointeeType(); 6170 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6171 IsBlockPointer = true; 6172 } else { 6173 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6174 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6175 } 6176 6177 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6178 // differently qualified versions of compatible types, the result type is 6179 // a pointer to an appropriately qualified version of the composite 6180 // type. 6181 6182 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6183 // clause doesn't make sense for our extensions. E.g. address space 2 should 6184 // be incompatible with address space 3: they may live on different devices or 6185 // anything. 6186 Qualifiers lhQual = lhptee.getQualifiers(); 6187 Qualifiers rhQual = rhptee.getQualifiers(); 6188 6189 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6190 lhQual.removeCVRQualifiers(); 6191 rhQual.removeCVRQualifiers(); 6192 6193 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6194 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6195 6196 // For OpenCL: 6197 // 1. If LHS and RHS types match exactly and: 6198 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6199 // (b) AS overlap => generate addrspacecast 6200 // (c) AS don't overlap => give an error 6201 // 2. if LHS and RHS types don't match: 6202 // (a) AS match => use standard C rules, generate bitcast 6203 // (b) AS overlap => generate addrspacecast instead of bitcast 6204 // (c) AS don't overlap => give an error 6205 6206 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6207 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6208 6209 // OpenCL cases 1c, 2a, 2b, and 2c. 6210 if (CompositeTy.isNull()) { 6211 // In this situation, we assume void* type. No especially good 6212 // reason, but this is what gcc does, and we do have to pick 6213 // to get a consistent AST. 6214 QualType incompatTy; 6215 if (S.getLangOpts().OpenCL) { 6216 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6217 // spaces is disallowed. 6218 unsigned ResultAddrSpace; 6219 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6220 // Cases 2a and 2b. 6221 ResultAddrSpace = lhQual.getAddressSpace(); 6222 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6223 // Cases 2a and 2b. 6224 ResultAddrSpace = rhQual.getAddressSpace(); 6225 } else { 6226 // Cases 1c and 2c. 6227 S.Diag(Loc, 6228 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6229 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6230 << RHS.get()->getSourceRange(); 6231 return QualType(); 6232 } 6233 6234 // Continue handling cases 2a and 2b. 6235 incompatTy = S.Context.getPointerType( 6236 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6237 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6238 (lhQual.getAddressSpace() != ResultAddrSpace) 6239 ? CK_AddressSpaceConversion /* 2b */ 6240 : CK_BitCast /* 2a */); 6241 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6242 (rhQual.getAddressSpace() != ResultAddrSpace) 6243 ? CK_AddressSpaceConversion /* 2b */ 6244 : CK_BitCast /* 2a */); 6245 } else { 6246 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6247 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6248 << RHS.get()->getSourceRange(); 6249 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6250 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6251 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6252 } 6253 return incompatTy; 6254 } 6255 6256 // The pointer types are compatible. 6257 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6258 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6259 if (IsBlockPointer) 6260 ResultTy = S.Context.getBlockPointerType(ResultTy); 6261 else { 6262 // Cases 1a and 1b for OpenCL. 6263 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6264 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6265 ? CK_BitCast /* 1a */ 6266 : CK_AddressSpaceConversion /* 1b */; 6267 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6268 ? CK_BitCast /* 1a */ 6269 : CK_AddressSpaceConversion /* 1b */; 6270 ResultTy = S.Context.getPointerType(ResultTy); 6271 } 6272 6273 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6274 // if the target type does not change. 6275 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6276 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6277 return ResultTy; 6278 } 6279 6280 /// \brief Return the resulting type when the operands are both block pointers. 6281 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6282 ExprResult &LHS, 6283 ExprResult &RHS, 6284 SourceLocation Loc) { 6285 QualType LHSTy = LHS.get()->getType(); 6286 QualType RHSTy = RHS.get()->getType(); 6287 6288 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6289 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6290 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6291 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6292 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6293 return destType; 6294 } 6295 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6296 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6297 << RHS.get()->getSourceRange(); 6298 return QualType(); 6299 } 6300 6301 // We have 2 block pointer types. 6302 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6303 } 6304 6305 /// \brief Return the resulting type when the operands are both pointers. 6306 static QualType 6307 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6308 ExprResult &RHS, 6309 SourceLocation Loc) { 6310 // get the pointer types 6311 QualType LHSTy = LHS.get()->getType(); 6312 QualType RHSTy = RHS.get()->getType(); 6313 6314 // get the "pointed to" types 6315 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6316 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6317 6318 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6319 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6320 // Figure out necessary qualifiers (C99 6.5.15p6) 6321 QualType destPointee 6322 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6323 QualType destType = S.Context.getPointerType(destPointee); 6324 // Add qualifiers if necessary. 6325 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6326 // Promote to void*. 6327 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6328 return destType; 6329 } 6330 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6331 QualType destPointee 6332 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6333 QualType destType = S.Context.getPointerType(destPointee); 6334 // Add qualifiers if necessary. 6335 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6336 // Promote to void*. 6337 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6338 return destType; 6339 } 6340 6341 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6342 } 6343 6344 /// \brief Return false if the first expression is not an integer and the second 6345 /// expression is not a pointer, true otherwise. 6346 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6347 Expr* PointerExpr, SourceLocation Loc, 6348 bool IsIntFirstExpr) { 6349 if (!PointerExpr->getType()->isPointerType() || 6350 !Int.get()->getType()->isIntegerType()) 6351 return false; 6352 6353 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6354 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6355 6356 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6357 << Expr1->getType() << Expr2->getType() 6358 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6359 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6360 CK_IntegralToPointer); 6361 return true; 6362 } 6363 6364 /// \brief Simple conversion between integer and floating point types. 6365 /// 6366 /// Used when handling the OpenCL conditional operator where the 6367 /// condition is a vector while the other operands are scalar. 6368 /// 6369 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6370 /// types are either integer or floating type. Between the two 6371 /// operands, the type with the higher rank is defined as the "result 6372 /// type". The other operand needs to be promoted to the same type. No 6373 /// other type promotion is allowed. We cannot use 6374 /// UsualArithmeticConversions() for this purpose, since it always 6375 /// promotes promotable types. 6376 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6377 ExprResult &RHS, 6378 SourceLocation QuestionLoc) { 6379 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6380 if (LHS.isInvalid()) 6381 return QualType(); 6382 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6383 if (RHS.isInvalid()) 6384 return QualType(); 6385 6386 // For conversion purposes, we ignore any qualifiers. 6387 // For example, "const float" and "float" are equivalent. 6388 QualType LHSType = 6389 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6390 QualType RHSType = 6391 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6392 6393 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6394 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6395 << LHSType << LHS.get()->getSourceRange(); 6396 return QualType(); 6397 } 6398 6399 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6400 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6401 << RHSType << RHS.get()->getSourceRange(); 6402 return QualType(); 6403 } 6404 6405 // If both types are identical, no conversion is needed. 6406 if (LHSType == RHSType) 6407 return LHSType; 6408 6409 // Now handle "real" floating types (i.e. float, double, long double). 6410 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6411 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6412 /*IsCompAssign = */ false); 6413 6414 // Finally, we have two differing integer types. 6415 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6416 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6417 } 6418 6419 /// \brief Convert scalar operands to a vector that matches the 6420 /// condition in length. 6421 /// 6422 /// Used when handling the OpenCL conditional operator where the 6423 /// condition is a vector while the other operands are scalar. 6424 /// 6425 /// We first compute the "result type" for the scalar operands 6426 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6427 /// into a vector of that type where the length matches the condition 6428 /// vector type. s6.11.6 requires that the element types of the result 6429 /// and the condition must have the same number of bits. 6430 static QualType 6431 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6432 QualType CondTy, SourceLocation QuestionLoc) { 6433 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6434 if (ResTy.isNull()) return QualType(); 6435 6436 const VectorType *CV = CondTy->getAs<VectorType>(); 6437 assert(CV); 6438 6439 // Determine the vector result type 6440 unsigned NumElements = CV->getNumElements(); 6441 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6442 6443 // Ensure that all types have the same number of bits 6444 if (S.Context.getTypeSize(CV->getElementType()) 6445 != S.Context.getTypeSize(ResTy)) { 6446 // Since VectorTy is created internally, it does not pretty print 6447 // with an OpenCL name. Instead, we just print a description. 6448 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6449 SmallString<64> Str; 6450 llvm::raw_svector_ostream OS(Str); 6451 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6452 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6453 << CondTy << OS.str(); 6454 return QualType(); 6455 } 6456 6457 // Convert operands to the vector result type 6458 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6459 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6460 6461 return VectorTy; 6462 } 6463 6464 /// \brief Return false if this is a valid OpenCL condition vector 6465 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6466 SourceLocation QuestionLoc) { 6467 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6468 // integral type. 6469 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6470 assert(CondTy); 6471 QualType EleTy = CondTy->getElementType(); 6472 if (EleTy->isIntegerType()) return false; 6473 6474 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6475 << Cond->getType() << Cond->getSourceRange(); 6476 return true; 6477 } 6478 6479 /// \brief Return false if the vector condition type and the vector 6480 /// result type are compatible. 6481 /// 6482 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6483 /// number of elements, and their element types have the same number 6484 /// of bits. 6485 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6486 SourceLocation QuestionLoc) { 6487 const VectorType *CV = CondTy->getAs<VectorType>(); 6488 const VectorType *RV = VecResTy->getAs<VectorType>(); 6489 assert(CV && RV); 6490 6491 if (CV->getNumElements() != RV->getNumElements()) { 6492 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6493 << CondTy << VecResTy; 6494 return true; 6495 } 6496 6497 QualType CVE = CV->getElementType(); 6498 QualType RVE = RV->getElementType(); 6499 6500 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6501 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6502 << CondTy << VecResTy; 6503 return true; 6504 } 6505 6506 return false; 6507 } 6508 6509 /// \brief Return the resulting type for the conditional operator in 6510 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6511 /// s6.3.i) when the condition is a vector type. 6512 static QualType 6513 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6514 ExprResult &LHS, ExprResult &RHS, 6515 SourceLocation QuestionLoc) { 6516 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6517 if (Cond.isInvalid()) 6518 return QualType(); 6519 QualType CondTy = Cond.get()->getType(); 6520 6521 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6522 return QualType(); 6523 6524 // If either operand is a vector then find the vector type of the 6525 // result as specified in OpenCL v1.1 s6.3.i. 6526 if (LHS.get()->getType()->isVectorType() || 6527 RHS.get()->getType()->isVectorType()) { 6528 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6529 /*isCompAssign*/false, 6530 /*AllowBothBool*/true, 6531 /*AllowBoolConversions*/false); 6532 if (VecResTy.isNull()) return QualType(); 6533 // The result type must match the condition type as specified in 6534 // OpenCL v1.1 s6.11.6. 6535 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6536 return QualType(); 6537 return VecResTy; 6538 } 6539 6540 // Both operands are scalar. 6541 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6542 } 6543 6544 /// \brief Return true if the Expr is block type 6545 static bool checkBlockType(Sema &S, const Expr *E) { 6546 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6547 QualType Ty = CE->getCallee()->getType(); 6548 if (Ty->isBlockPointerType()) { 6549 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6550 return true; 6551 } 6552 } 6553 return false; 6554 } 6555 6556 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6557 /// In that case, LHS = cond. 6558 /// C99 6.5.15 6559 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6560 ExprResult &RHS, ExprValueKind &VK, 6561 ExprObjectKind &OK, 6562 SourceLocation QuestionLoc) { 6563 6564 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6565 if (!LHSResult.isUsable()) return QualType(); 6566 LHS = LHSResult; 6567 6568 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6569 if (!RHSResult.isUsable()) return QualType(); 6570 RHS = RHSResult; 6571 6572 // C++ is sufficiently different to merit its own checker. 6573 if (getLangOpts().CPlusPlus) 6574 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6575 6576 VK = VK_RValue; 6577 OK = OK_Ordinary; 6578 6579 // The OpenCL operator with a vector condition is sufficiently 6580 // different to merit its own checker. 6581 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6582 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6583 6584 // First, check the condition. 6585 Cond = UsualUnaryConversions(Cond.get()); 6586 if (Cond.isInvalid()) 6587 return QualType(); 6588 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6589 return QualType(); 6590 6591 // Now check the two expressions. 6592 if (LHS.get()->getType()->isVectorType() || 6593 RHS.get()->getType()->isVectorType()) 6594 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6595 /*AllowBothBool*/true, 6596 /*AllowBoolConversions*/false); 6597 6598 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6599 if (LHS.isInvalid() || RHS.isInvalid()) 6600 return QualType(); 6601 6602 QualType LHSTy = LHS.get()->getType(); 6603 QualType RHSTy = RHS.get()->getType(); 6604 6605 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6606 // selection operator (?:). 6607 if (getLangOpts().OpenCL && 6608 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6609 return QualType(); 6610 } 6611 6612 // If both operands have arithmetic type, do the usual arithmetic conversions 6613 // to find a common type: C99 6.5.15p3,5. 6614 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6615 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6616 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6617 6618 return ResTy; 6619 } 6620 6621 // If both operands are the same structure or union type, the result is that 6622 // type. 6623 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6624 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6625 if (LHSRT->getDecl() == RHSRT->getDecl()) 6626 // "If both the operands have structure or union type, the result has 6627 // that type." This implies that CV qualifiers are dropped. 6628 return LHSTy.getUnqualifiedType(); 6629 // FIXME: Type of conditional expression must be complete in C mode. 6630 } 6631 6632 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6633 // The following || allows only one side to be void (a GCC-ism). 6634 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6635 return checkConditionalVoidType(*this, LHS, RHS); 6636 } 6637 6638 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6639 // the type of the other operand." 6640 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6641 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6642 6643 // All objective-c pointer type analysis is done here. 6644 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6645 QuestionLoc); 6646 if (LHS.isInvalid() || RHS.isInvalid()) 6647 return QualType(); 6648 if (!compositeType.isNull()) 6649 return compositeType; 6650 6651 6652 // Handle block pointer types. 6653 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6654 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6655 QuestionLoc); 6656 6657 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6658 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6659 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6660 QuestionLoc); 6661 6662 // GCC compatibility: soften pointer/integer mismatch. Note that 6663 // null pointers have been filtered out by this point. 6664 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6665 /*isIntFirstExpr=*/true)) 6666 return RHSTy; 6667 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6668 /*isIntFirstExpr=*/false)) 6669 return LHSTy; 6670 6671 // Emit a better diagnostic if one of the expressions is a null pointer 6672 // constant and the other is not a pointer type. In this case, the user most 6673 // likely forgot to take the address of the other expression. 6674 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6675 return QualType(); 6676 6677 // Otherwise, the operands are not compatible. 6678 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6679 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6680 << RHS.get()->getSourceRange(); 6681 return QualType(); 6682 } 6683 6684 /// FindCompositeObjCPointerType - Helper method to find composite type of 6685 /// two objective-c pointer types of the two input expressions. 6686 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6687 SourceLocation QuestionLoc) { 6688 QualType LHSTy = LHS.get()->getType(); 6689 QualType RHSTy = RHS.get()->getType(); 6690 6691 // Handle things like Class and struct objc_class*. Here we case the result 6692 // to the pseudo-builtin, because that will be implicitly cast back to the 6693 // redefinition type if an attempt is made to access its fields. 6694 if (LHSTy->isObjCClassType() && 6695 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6696 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6697 return LHSTy; 6698 } 6699 if (RHSTy->isObjCClassType() && 6700 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6701 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6702 return RHSTy; 6703 } 6704 // And the same for struct objc_object* / id 6705 if (LHSTy->isObjCIdType() && 6706 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6707 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6708 return LHSTy; 6709 } 6710 if (RHSTy->isObjCIdType() && 6711 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6712 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6713 return RHSTy; 6714 } 6715 // And the same for struct objc_selector* / SEL 6716 if (Context.isObjCSelType(LHSTy) && 6717 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6718 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6719 return LHSTy; 6720 } 6721 if (Context.isObjCSelType(RHSTy) && 6722 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6723 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6724 return RHSTy; 6725 } 6726 // Check constraints for Objective-C object pointers types. 6727 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6728 6729 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6730 // Two identical object pointer types are always compatible. 6731 return LHSTy; 6732 } 6733 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6734 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6735 QualType compositeType = LHSTy; 6736 6737 // If both operands are interfaces and either operand can be 6738 // assigned to the other, use that type as the composite 6739 // type. This allows 6740 // xxx ? (A*) a : (B*) b 6741 // where B is a subclass of A. 6742 // 6743 // Additionally, as for assignment, if either type is 'id' 6744 // allow silent coercion. Finally, if the types are 6745 // incompatible then make sure to use 'id' as the composite 6746 // type so the result is acceptable for sending messages to. 6747 6748 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6749 // It could return the composite type. 6750 if (!(compositeType = 6751 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6752 // Nothing more to do. 6753 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6754 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6755 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6756 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6757 } else if ((LHSTy->isObjCQualifiedIdType() || 6758 RHSTy->isObjCQualifiedIdType()) && 6759 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6760 // Need to handle "id<xx>" explicitly. 6761 // GCC allows qualified id and any Objective-C type to devolve to 6762 // id. Currently localizing to here until clear this should be 6763 // part of ObjCQualifiedIdTypesAreCompatible. 6764 compositeType = Context.getObjCIdType(); 6765 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6766 compositeType = Context.getObjCIdType(); 6767 } else { 6768 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6769 << LHSTy << RHSTy 6770 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6771 QualType incompatTy = Context.getObjCIdType(); 6772 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6773 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6774 return incompatTy; 6775 } 6776 // The object pointer types are compatible. 6777 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6778 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6779 return compositeType; 6780 } 6781 // Check Objective-C object pointer types and 'void *' 6782 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6783 if (getLangOpts().ObjCAutoRefCount) { 6784 // ARC forbids the implicit conversion of object pointers to 'void *', 6785 // so these types are not compatible. 6786 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6787 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6788 LHS = RHS = true; 6789 return QualType(); 6790 } 6791 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6792 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6793 QualType destPointee 6794 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6795 QualType destType = Context.getPointerType(destPointee); 6796 // Add qualifiers if necessary. 6797 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6798 // Promote to void*. 6799 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6800 return destType; 6801 } 6802 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6803 if (getLangOpts().ObjCAutoRefCount) { 6804 // ARC forbids the implicit conversion of object pointers to 'void *', 6805 // so these types are not compatible. 6806 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6807 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6808 LHS = RHS = true; 6809 return QualType(); 6810 } 6811 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6812 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6813 QualType destPointee 6814 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6815 QualType destType = Context.getPointerType(destPointee); 6816 // Add qualifiers if necessary. 6817 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6818 // Promote to void*. 6819 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6820 return destType; 6821 } 6822 return QualType(); 6823 } 6824 6825 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6826 /// ParenRange in parentheses. 6827 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6828 const PartialDiagnostic &Note, 6829 SourceRange ParenRange) { 6830 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6831 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6832 EndLoc.isValid()) { 6833 Self.Diag(Loc, Note) 6834 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6835 << FixItHint::CreateInsertion(EndLoc, ")"); 6836 } else { 6837 // We can't display the parentheses, so just show the bare note. 6838 Self.Diag(Loc, Note) << ParenRange; 6839 } 6840 } 6841 6842 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6843 return BinaryOperator::isAdditiveOp(Opc) || 6844 BinaryOperator::isMultiplicativeOp(Opc) || 6845 BinaryOperator::isShiftOp(Opc); 6846 } 6847 6848 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6849 /// expression, either using a built-in or overloaded operator, 6850 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6851 /// expression. 6852 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6853 Expr **RHSExprs) { 6854 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6855 E = E->IgnoreImpCasts(); 6856 E = E->IgnoreConversionOperator(); 6857 E = E->IgnoreImpCasts(); 6858 6859 // Built-in binary operator. 6860 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6861 if (IsArithmeticOp(OP->getOpcode())) { 6862 *Opcode = OP->getOpcode(); 6863 *RHSExprs = OP->getRHS(); 6864 return true; 6865 } 6866 } 6867 6868 // Overloaded operator. 6869 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6870 if (Call->getNumArgs() != 2) 6871 return false; 6872 6873 // Make sure this is really a binary operator that is safe to pass into 6874 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6875 OverloadedOperatorKind OO = Call->getOperator(); 6876 if (OO < OO_Plus || OO > OO_Arrow || 6877 OO == OO_PlusPlus || OO == OO_MinusMinus) 6878 return false; 6879 6880 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6881 if (IsArithmeticOp(OpKind)) { 6882 *Opcode = OpKind; 6883 *RHSExprs = Call->getArg(1); 6884 return true; 6885 } 6886 } 6887 6888 return false; 6889 } 6890 6891 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6892 /// or is a logical expression such as (x==y) which has int type, but is 6893 /// commonly interpreted as boolean. 6894 static bool ExprLooksBoolean(Expr *E) { 6895 E = E->IgnoreParenImpCasts(); 6896 6897 if (E->getType()->isBooleanType()) 6898 return true; 6899 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6900 return OP->isComparisonOp() || OP->isLogicalOp(); 6901 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6902 return OP->getOpcode() == UO_LNot; 6903 if (E->getType()->isPointerType()) 6904 return true; 6905 6906 return false; 6907 } 6908 6909 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6910 /// and binary operator are mixed in a way that suggests the programmer assumed 6911 /// the conditional operator has higher precedence, for example: 6912 /// "int x = a + someBinaryCondition ? 1 : 2". 6913 static void DiagnoseConditionalPrecedence(Sema &Self, 6914 SourceLocation OpLoc, 6915 Expr *Condition, 6916 Expr *LHSExpr, 6917 Expr *RHSExpr) { 6918 BinaryOperatorKind CondOpcode; 6919 Expr *CondRHS; 6920 6921 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6922 return; 6923 if (!ExprLooksBoolean(CondRHS)) 6924 return; 6925 6926 // The condition is an arithmetic binary expression, with a right- 6927 // hand side that looks boolean, so warn. 6928 6929 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6930 << Condition->getSourceRange() 6931 << BinaryOperator::getOpcodeStr(CondOpcode); 6932 6933 SuggestParentheses(Self, OpLoc, 6934 Self.PDiag(diag::note_precedence_silence) 6935 << BinaryOperator::getOpcodeStr(CondOpcode), 6936 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6937 6938 SuggestParentheses(Self, OpLoc, 6939 Self.PDiag(diag::note_precedence_conditional_first), 6940 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6941 } 6942 6943 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6944 /// in the case of a the GNU conditional expr extension. 6945 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6946 SourceLocation ColonLoc, 6947 Expr *CondExpr, Expr *LHSExpr, 6948 Expr *RHSExpr) { 6949 if (!getLangOpts().CPlusPlus) { 6950 // C cannot handle TypoExpr nodes in the condition because it 6951 // doesn't handle dependent types properly, so make sure any TypoExprs have 6952 // been dealt with before checking the operands. 6953 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6954 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 6955 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 6956 6957 if (!CondResult.isUsable()) 6958 return ExprError(); 6959 6960 if (LHSExpr) { 6961 if (!LHSResult.isUsable()) 6962 return ExprError(); 6963 } 6964 6965 if (!RHSResult.isUsable()) 6966 return ExprError(); 6967 6968 CondExpr = CondResult.get(); 6969 LHSExpr = LHSResult.get(); 6970 RHSExpr = RHSResult.get(); 6971 } 6972 6973 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6974 // was the condition. 6975 OpaqueValueExpr *opaqueValue = nullptr; 6976 Expr *commonExpr = nullptr; 6977 if (!LHSExpr) { 6978 commonExpr = CondExpr; 6979 // Lower out placeholder types first. This is important so that we don't 6980 // try to capture a placeholder. This happens in few cases in C++; such 6981 // as Objective-C++'s dictionary subscripting syntax. 6982 if (commonExpr->hasPlaceholderType()) { 6983 ExprResult result = CheckPlaceholderExpr(commonExpr); 6984 if (!result.isUsable()) return ExprError(); 6985 commonExpr = result.get(); 6986 } 6987 // We usually want to apply unary conversions *before* saving, except 6988 // in the special case of a C++ l-value conditional. 6989 if (!(getLangOpts().CPlusPlus 6990 && !commonExpr->isTypeDependent() 6991 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6992 && commonExpr->isGLValue() 6993 && commonExpr->isOrdinaryOrBitFieldObject() 6994 && RHSExpr->isOrdinaryOrBitFieldObject() 6995 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6996 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6997 if (commonRes.isInvalid()) 6998 return ExprError(); 6999 commonExpr = commonRes.get(); 7000 } 7001 7002 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7003 commonExpr->getType(), 7004 commonExpr->getValueKind(), 7005 commonExpr->getObjectKind(), 7006 commonExpr); 7007 LHSExpr = CondExpr = opaqueValue; 7008 } 7009 7010 ExprValueKind VK = VK_RValue; 7011 ExprObjectKind OK = OK_Ordinary; 7012 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7013 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7014 VK, OK, QuestionLoc); 7015 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7016 RHS.isInvalid()) 7017 return ExprError(); 7018 7019 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7020 RHS.get()); 7021 7022 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7023 7024 if (!commonExpr) 7025 return new (Context) 7026 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7027 RHS.get(), result, VK, OK); 7028 7029 return new (Context) BinaryConditionalOperator( 7030 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7031 ColonLoc, result, VK, OK); 7032 } 7033 7034 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7035 // being closely modeled after the C99 spec:-). The odd characteristic of this 7036 // routine is it effectively iqnores the qualifiers on the top level pointee. 7037 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7038 // FIXME: add a couple examples in this comment. 7039 static Sema::AssignConvertType 7040 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7041 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7042 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7043 7044 // get the "pointed to" type (ignoring qualifiers at the top level) 7045 const Type *lhptee, *rhptee; 7046 Qualifiers lhq, rhq; 7047 std::tie(lhptee, lhq) = 7048 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7049 std::tie(rhptee, rhq) = 7050 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7051 7052 Sema::AssignConvertType ConvTy = Sema::Compatible; 7053 7054 // C99 6.5.16.1p1: This following citation is common to constraints 7055 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7056 // qualifiers of the type *pointed to* by the right; 7057 7058 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7059 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7060 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7061 // Ignore lifetime for further calculation. 7062 lhq.removeObjCLifetime(); 7063 rhq.removeObjCLifetime(); 7064 } 7065 7066 if (!lhq.compatiblyIncludes(rhq)) { 7067 // Treat address-space mismatches as fatal. TODO: address subspaces 7068 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7069 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7070 7071 // It's okay to add or remove GC or lifetime qualifiers when converting to 7072 // and from void*. 7073 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7074 .compatiblyIncludes( 7075 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7076 && (lhptee->isVoidType() || rhptee->isVoidType())) 7077 ; // keep old 7078 7079 // Treat lifetime mismatches as fatal. 7080 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7081 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7082 7083 // For GCC compatibility, other qualifier mismatches are treated 7084 // as still compatible in C. 7085 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7086 } 7087 7088 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7089 // incomplete type and the other is a pointer to a qualified or unqualified 7090 // version of void... 7091 if (lhptee->isVoidType()) { 7092 if (rhptee->isIncompleteOrObjectType()) 7093 return ConvTy; 7094 7095 // As an extension, we allow cast to/from void* to function pointer. 7096 assert(rhptee->isFunctionType()); 7097 return Sema::FunctionVoidPointer; 7098 } 7099 7100 if (rhptee->isVoidType()) { 7101 if (lhptee->isIncompleteOrObjectType()) 7102 return ConvTy; 7103 7104 // As an extension, we allow cast to/from void* to function pointer. 7105 assert(lhptee->isFunctionType()); 7106 return Sema::FunctionVoidPointer; 7107 } 7108 7109 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7110 // unqualified versions of compatible types, ... 7111 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7112 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7113 // Check if the pointee types are compatible ignoring the sign. 7114 // We explicitly check for char so that we catch "char" vs 7115 // "unsigned char" on systems where "char" is unsigned. 7116 if (lhptee->isCharType()) 7117 ltrans = S.Context.UnsignedCharTy; 7118 else if (lhptee->hasSignedIntegerRepresentation()) 7119 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7120 7121 if (rhptee->isCharType()) 7122 rtrans = S.Context.UnsignedCharTy; 7123 else if (rhptee->hasSignedIntegerRepresentation()) 7124 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7125 7126 if (ltrans == rtrans) { 7127 // Types are compatible ignoring the sign. Qualifier incompatibility 7128 // takes priority over sign incompatibility because the sign 7129 // warning can be disabled. 7130 if (ConvTy != Sema::Compatible) 7131 return ConvTy; 7132 7133 return Sema::IncompatiblePointerSign; 7134 } 7135 7136 // If we are a multi-level pointer, it's possible that our issue is simply 7137 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7138 // the eventual target type is the same and the pointers have the same 7139 // level of indirection, this must be the issue. 7140 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7141 do { 7142 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7143 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7144 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7145 7146 if (lhptee == rhptee) 7147 return Sema::IncompatibleNestedPointerQualifiers; 7148 } 7149 7150 // General pointer incompatibility takes priority over qualifiers. 7151 return Sema::IncompatiblePointer; 7152 } 7153 if (!S.getLangOpts().CPlusPlus && 7154 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7155 return Sema::IncompatiblePointer; 7156 return ConvTy; 7157 } 7158 7159 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7160 /// block pointer types are compatible or whether a block and normal pointer 7161 /// are compatible. It is more restrict than comparing two function pointer 7162 // types. 7163 static Sema::AssignConvertType 7164 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7165 QualType RHSType) { 7166 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7167 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7168 7169 QualType lhptee, rhptee; 7170 7171 // get the "pointed to" type (ignoring qualifiers at the top level) 7172 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7173 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7174 7175 // In C++, the types have to match exactly. 7176 if (S.getLangOpts().CPlusPlus) 7177 return Sema::IncompatibleBlockPointer; 7178 7179 Sema::AssignConvertType ConvTy = Sema::Compatible; 7180 7181 // For blocks we enforce that qualifiers are identical. 7182 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7183 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7184 7185 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7186 return Sema::IncompatibleBlockPointer; 7187 7188 return ConvTy; 7189 } 7190 7191 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7192 /// for assignment compatibility. 7193 static Sema::AssignConvertType 7194 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7195 QualType RHSType) { 7196 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7197 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7198 7199 if (LHSType->isObjCBuiltinType()) { 7200 // Class is not compatible with ObjC object pointers. 7201 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7202 !RHSType->isObjCQualifiedClassType()) 7203 return Sema::IncompatiblePointer; 7204 return Sema::Compatible; 7205 } 7206 if (RHSType->isObjCBuiltinType()) { 7207 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7208 !LHSType->isObjCQualifiedClassType()) 7209 return Sema::IncompatiblePointer; 7210 return Sema::Compatible; 7211 } 7212 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7213 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7214 7215 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7216 // make an exception for id<P> 7217 !LHSType->isObjCQualifiedIdType()) 7218 return Sema::CompatiblePointerDiscardsQualifiers; 7219 7220 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7221 return Sema::Compatible; 7222 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7223 return Sema::IncompatibleObjCQualifiedId; 7224 return Sema::IncompatiblePointer; 7225 } 7226 7227 Sema::AssignConvertType 7228 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7229 QualType LHSType, QualType RHSType) { 7230 // Fake up an opaque expression. We don't actually care about what 7231 // cast operations are required, so if CheckAssignmentConstraints 7232 // adds casts to this they'll be wasted, but fortunately that doesn't 7233 // usually happen on valid code. 7234 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7235 ExprResult RHSPtr = &RHSExpr; 7236 CastKind K = CK_Invalid; 7237 7238 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7239 } 7240 7241 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7242 /// has code to accommodate several GCC extensions when type checking 7243 /// pointers. Here are some objectionable examples that GCC considers warnings: 7244 /// 7245 /// int a, *pint; 7246 /// short *pshort; 7247 /// struct foo *pfoo; 7248 /// 7249 /// pint = pshort; // warning: assignment from incompatible pointer type 7250 /// a = pint; // warning: assignment makes integer from pointer without a cast 7251 /// pint = a; // warning: assignment makes pointer from integer without a cast 7252 /// pint = pfoo; // warning: assignment from incompatible pointer type 7253 /// 7254 /// As a result, the code for dealing with pointers is more complex than the 7255 /// C99 spec dictates. 7256 /// 7257 /// Sets 'Kind' for any result kind except Incompatible. 7258 Sema::AssignConvertType 7259 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7260 CastKind &Kind, bool ConvertRHS) { 7261 QualType RHSType = RHS.get()->getType(); 7262 QualType OrigLHSType = LHSType; 7263 7264 // Get canonical types. We're not formatting these types, just comparing 7265 // them. 7266 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7267 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7268 7269 // Common case: no conversion required. 7270 if (LHSType == RHSType) { 7271 Kind = CK_NoOp; 7272 return Compatible; 7273 } 7274 7275 // If we have an atomic type, try a non-atomic assignment, then just add an 7276 // atomic qualification step. 7277 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7278 Sema::AssignConvertType result = 7279 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7280 if (result != Compatible) 7281 return result; 7282 if (Kind != CK_NoOp && ConvertRHS) 7283 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7284 Kind = CK_NonAtomicToAtomic; 7285 return Compatible; 7286 } 7287 7288 // If the left-hand side is a reference type, then we are in a 7289 // (rare!) case where we've allowed the use of references in C, 7290 // e.g., as a parameter type in a built-in function. In this case, 7291 // just make sure that the type referenced is compatible with the 7292 // right-hand side type. The caller is responsible for adjusting 7293 // LHSType so that the resulting expression does not have reference 7294 // type. 7295 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7296 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7297 Kind = CK_LValueBitCast; 7298 return Compatible; 7299 } 7300 return Incompatible; 7301 } 7302 7303 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7304 // to the same ExtVector type. 7305 if (LHSType->isExtVectorType()) { 7306 if (RHSType->isExtVectorType()) 7307 return Incompatible; 7308 if (RHSType->isArithmeticType()) { 7309 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7310 if (ConvertRHS) 7311 RHS = prepareVectorSplat(LHSType, RHS.get()); 7312 Kind = CK_VectorSplat; 7313 return Compatible; 7314 } 7315 } 7316 7317 // Conversions to or from vector type. 7318 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7319 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7320 // Allow assignments of an AltiVec vector type to an equivalent GCC 7321 // vector type and vice versa 7322 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7323 Kind = CK_BitCast; 7324 return Compatible; 7325 } 7326 7327 // If we are allowing lax vector conversions, and LHS and RHS are both 7328 // vectors, the total size only needs to be the same. This is a bitcast; 7329 // no bits are changed but the result type is different. 7330 if (isLaxVectorConversion(RHSType, LHSType)) { 7331 Kind = CK_BitCast; 7332 return IncompatibleVectors; 7333 } 7334 } 7335 return Incompatible; 7336 } 7337 7338 // Arithmetic conversions. 7339 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7340 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7341 if (ConvertRHS) 7342 Kind = PrepareScalarCast(RHS, LHSType); 7343 return Compatible; 7344 } 7345 7346 // Conversions to normal pointers. 7347 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7348 // U* -> T* 7349 if (isa<PointerType>(RHSType)) { 7350 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7351 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7352 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7353 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7354 } 7355 7356 // int -> T* 7357 if (RHSType->isIntegerType()) { 7358 Kind = CK_IntegralToPointer; // FIXME: null? 7359 return IntToPointer; 7360 } 7361 7362 // C pointers are not compatible with ObjC object pointers, 7363 // with two exceptions: 7364 if (isa<ObjCObjectPointerType>(RHSType)) { 7365 // - conversions to void* 7366 if (LHSPointer->getPointeeType()->isVoidType()) { 7367 Kind = CK_BitCast; 7368 return Compatible; 7369 } 7370 7371 // - conversions from 'Class' to the redefinition type 7372 if (RHSType->isObjCClassType() && 7373 Context.hasSameType(LHSType, 7374 Context.getObjCClassRedefinitionType())) { 7375 Kind = CK_BitCast; 7376 return Compatible; 7377 } 7378 7379 Kind = CK_BitCast; 7380 return IncompatiblePointer; 7381 } 7382 7383 // U^ -> void* 7384 if (RHSType->getAs<BlockPointerType>()) { 7385 if (LHSPointer->getPointeeType()->isVoidType()) { 7386 Kind = CK_BitCast; 7387 return Compatible; 7388 } 7389 } 7390 7391 return Incompatible; 7392 } 7393 7394 // Conversions to block pointers. 7395 if (isa<BlockPointerType>(LHSType)) { 7396 // U^ -> T^ 7397 if (RHSType->isBlockPointerType()) { 7398 Kind = CK_BitCast; 7399 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7400 } 7401 7402 // int or null -> T^ 7403 if (RHSType->isIntegerType()) { 7404 Kind = CK_IntegralToPointer; // FIXME: null 7405 return IntToBlockPointer; 7406 } 7407 7408 // id -> T^ 7409 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7410 Kind = CK_AnyPointerToBlockPointerCast; 7411 return Compatible; 7412 } 7413 7414 // void* -> T^ 7415 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7416 if (RHSPT->getPointeeType()->isVoidType()) { 7417 Kind = CK_AnyPointerToBlockPointerCast; 7418 return Compatible; 7419 } 7420 7421 return Incompatible; 7422 } 7423 7424 // Conversions to Objective-C pointers. 7425 if (isa<ObjCObjectPointerType>(LHSType)) { 7426 // A* -> B* 7427 if (RHSType->isObjCObjectPointerType()) { 7428 Kind = CK_BitCast; 7429 Sema::AssignConvertType result = 7430 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7431 if (getLangOpts().ObjCAutoRefCount && 7432 result == Compatible && 7433 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7434 result = IncompatibleObjCWeakRef; 7435 return result; 7436 } 7437 7438 // int or null -> A* 7439 if (RHSType->isIntegerType()) { 7440 Kind = CK_IntegralToPointer; // FIXME: null 7441 return IntToPointer; 7442 } 7443 7444 // In general, C pointers are not compatible with ObjC object pointers, 7445 // with two exceptions: 7446 if (isa<PointerType>(RHSType)) { 7447 Kind = CK_CPointerToObjCPointerCast; 7448 7449 // - conversions from 'void*' 7450 if (RHSType->isVoidPointerType()) { 7451 return Compatible; 7452 } 7453 7454 // - conversions to 'Class' from its redefinition type 7455 if (LHSType->isObjCClassType() && 7456 Context.hasSameType(RHSType, 7457 Context.getObjCClassRedefinitionType())) { 7458 return Compatible; 7459 } 7460 7461 return IncompatiblePointer; 7462 } 7463 7464 // Only under strict condition T^ is compatible with an Objective-C pointer. 7465 if (RHSType->isBlockPointerType() && 7466 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7467 if (ConvertRHS) 7468 maybeExtendBlockObject(RHS); 7469 Kind = CK_BlockPointerToObjCPointerCast; 7470 return Compatible; 7471 } 7472 7473 return Incompatible; 7474 } 7475 7476 // Conversions from pointers that are not covered by the above. 7477 if (isa<PointerType>(RHSType)) { 7478 // T* -> _Bool 7479 if (LHSType == Context.BoolTy) { 7480 Kind = CK_PointerToBoolean; 7481 return Compatible; 7482 } 7483 7484 // T* -> int 7485 if (LHSType->isIntegerType()) { 7486 Kind = CK_PointerToIntegral; 7487 return PointerToInt; 7488 } 7489 7490 return Incompatible; 7491 } 7492 7493 // Conversions from Objective-C pointers that are not covered by the above. 7494 if (isa<ObjCObjectPointerType>(RHSType)) { 7495 // T* -> _Bool 7496 if (LHSType == Context.BoolTy) { 7497 Kind = CK_PointerToBoolean; 7498 return Compatible; 7499 } 7500 7501 // T* -> int 7502 if (LHSType->isIntegerType()) { 7503 Kind = CK_PointerToIntegral; 7504 return PointerToInt; 7505 } 7506 7507 return Incompatible; 7508 } 7509 7510 // struct A -> struct B 7511 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7512 if (Context.typesAreCompatible(LHSType, RHSType)) { 7513 Kind = CK_NoOp; 7514 return Compatible; 7515 } 7516 } 7517 7518 return Incompatible; 7519 } 7520 7521 /// \brief Constructs a transparent union from an expression that is 7522 /// used to initialize the transparent union. 7523 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7524 ExprResult &EResult, QualType UnionType, 7525 FieldDecl *Field) { 7526 // Build an initializer list that designates the appropriate member 7527 // of the transparent union. 7528 Expr *E = EResult.get(); 7529 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7530 E, SourceLocation()); 7531 Initializer->setType(UnionType); 7532 Initializer->setInitializedFieldInUnion(Field); 7533 7534 // Build a compound literal constructing a value of the transparent 7535 // union type from this initializer list. 7536 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7537 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7538 VK_RValue, Initializer, false); 7539 } 7540 7541 Sema::AssignConvertType 7542 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7543 ExprResult &RHS) { 7544 QualType RHSType = RHS.get()->getType(); 7545 7546 // If the ArgType is a Union type, we want to handle a potential 7547 // transparent_union GCC extension. 7548 const RecordType *UT = ArgType->getAsUnionType(); 7549 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7550 return Incompatible; 7551 7552 // The field to initialize within the transparent union. 7553 RecordDecl *UD = UT->getDecl(); 7554 FieldDecl *InitField = nullptr; 7555 // It's compatible if the expression matches any of the fields. 7556 for (auto *it : UD->fields()) { 7557 if (it->getType()->isPointerType()) { 7558 // If the transparent union contains a pointer type, we allow: 7559 // 1) void pointer 7560 // 2) null pointer constant 7561 if (RHSType->isPointerType()) 7562 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7563 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7564 InitField = it; 7565 break; 7566 } 7567 7568 if (RHS.get()->isNullPointerConstant(Context, 7569 Expr::NPC_ValueDependentIsNull)) { 7570 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7571 CK_NullToPointer); 7572 InitField = it; 7573 break; 7574 } 7575 } 7576 7577 CastKind Kind = CK_Invalid; 7578 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7579 == Compatible) { 7580 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7581 InitField = it; 7582 break; 7583 } 7584 } 7585 7586 if (!InitField) 7587 return Incompatible; 7588 7589 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7590 return Compatible; 7591 } 7592 7593 Sema::AssignConvertType 7594 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7595 bool Diagnose, 7596 bool DiagnoseCFAudited, 7597 bool ConvertRHS) { 7598 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7599 // we can't avoid *all* modifications at the moment, so we need some somewhere 7600 // to put the updated value. 7601 ExprResult LocalRHS = CallerRHS; 7602 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7603 7604 if (getLangOpts().CPlusPlus) { 7605 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7606 // C++ 5.17p3: If the left operand is not of class type, the 7607 // expression is implicitly converted (C++ 4) to the 7608 // cv-unqualified type of the left operand. 7609 ExprResult Res; 7610 if (Diagnose) { 7611 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7612 AA_Assigning); 7613 } else { 7614 ImplicitConversionSequence ICS = 7615 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7616 /*SuppressUserConversions=*/false, 7617 /*AllowExplicit=*/false, 7618 /*InOverloadResolution=*/false, 7619 /*CStyle=*/false, 7620 /*AllowObjCWritebackConversion=*/false); 7621 if (ICS.isFailure()) 7622 return Incompatible; 7623 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7624 ICS, AA_Assigning); 7625 } 7626 if (Res.isInvalid()) 7627 return Incompatible; 7628 Sema::AssignConvertType result = Compatible; 7629 if (getLangOpts().ObjCAutoRefCount && 7630 !CheckObjCARCUnavailableWeakConversion(LHSType, 7631 RHS.get()->getType())) 7632 result = IncompatibleObjCWeakRef; 7633 RHS = Res; 7634 return result; 7635 } 7636 7637 // FIXME: Currently, we fall through and treat C++ classes like C 7638 // structures. 7639 // FIXME: We also fall through for atomics; not sure what should 7640 // happen there, though. 7641 } else if (RHS.get()->getType() == Context.OverloadTy) { 7642 // As a set of extensions to C, we support overloading on functions. These 7643 // functions need to be resolved here. 7644 DeclAccessPair DAP; 7645 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7646 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7647 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7648 else 7649 return Incompatible; 7650 } 7651 7652 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7653 // a null pointer constant. 7654 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7655 LHSType->isBlockPointerType()) && 7656 RHS.get()->isNullPointerConstant(Context, 7657 Expr::NPC_ValueDependentIsNull)) { 7658 if (Diagnose || ConvertRHS) { 7659 CastKind Kind; 7660 CXXCastPath Path; 7661 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7662 /*IgnoreBaseAccess=*/false, Diagnose); 7663 if (ConvertRHS) 7664 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7665 } 7666 return Compatible; 7667 } 7668 7669 // This check seems unnatural, however it is necessary to ensure the proper 7670 // conversion of functions/arrays. If the conversion were done for all 7671 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7672 // expressions that suppress this implicit conversion (&, sizeof). 7673 // 7674 // Suppress this for references: C++ 8.5.3p5. 7675 if (!LHSType->isReferenceType()) { 7676 // FIXME: We potentially allocate here even if ConvertRHS is false. 7677 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7678 if (RHS.isInvalid()) 7679 return Incompatible; 7680 } 7681 7682 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7683 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7684 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7685 if (PDecl && !PDecl->hasDefinition()) { 7686 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7687 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7688 } 7689 } 7690 7691 CastKind Kind = CK_Invalid; 7692 Sema::AssignConvertType result = 7693 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7694 7695 // C99 6.5.16.1p2: The value of the right operand is converted to the 7696 // type of the assignment expression. 7697 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7698 // so that we can use references in built-in functions even in C. 7699 // The getNonReferenceType() call makes sure that the resulting expression 7700 // does not have reference type. 7701 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7702 QualType Ty = LHSType.getNonLValueExprType(Context); 7703 Expr *E = RHS.get(); 7704 7705 // Check for various Objective-C errors. If we are not reporting 7706 // diagnostics and just checking for errors, e.g., during overload 7707 // resolution, return Incompatible to indicate the failure. 7708 if (getLangOpts().ObjCAutoRefCount && 7709 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7710 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7711 if (!Diagnose) 7712 return Incompatible; 7713 } 7714 if (getLangOpts().ObjC1 && 7715 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7716 E->getType(), E, Diagnose) || 7717 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7718 if (!Diagnose) 7719 return Incompatible; 7720 // Replace the expression with a corrected version and continue so we 7721 // can find further errors. 7722 RHS = E; 7723 return Compatible; 7724 } 7725 7726 if (ConvertRHS) 7727 RHS = ImpCastExprToType(E, Ty, Kind); 7728 } 7729 return result; 7730 } 7731 7732 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7733 ExprResult &RHS) { 7734 Diag(Loc, diag::err_typecheck_invalid_operands) 7735 << LHS.get()->getType() << RHS.get()->getType() 7736 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7737 return QualType(); 7738 } 7739 7740 /// Try to convert a value of non-vector type to a vector type by converting 7741 /// the type to the element type of the vector and then performing a splat. 7742 /// If the language is OpenCL, we only use conversions that promote scalar 7743 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7744 /// for float->int. 7745 /// 7746 /// \param scalar - if non-null, actually perform the conversions 7747 /// \return true if the operation fails (but without diagnosing the failure) 7748 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7749 QualType scalarTy, 7750 QualType vectorEltTy, 7751 QualType vectorTy) { 7752 // The conversion to apply to the scalar before splatting it, 7753 // if necessary. 7754 CastKind scalarCast = CK_Invalid; 7755 7756 if (vectorEltTy->isIntegralType(S.Context)) { 7757 if (!scalarTy->isIntegralType(S.Context)) 7758 return true; 7759 if (S.getLangOpts().OpenCL && 7760 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7761 return true; 7762 scalarCast = CK_IntegralCast; 7763 } else if (vectorEltTy->isRealFloatingType()) { 7764 if (scalarTy->isRealFloatingType()) { 7765 if (S.getLangOpts().OpenCL && 7766 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7767 return true; 7768 scalarCast = CK_FloatingCast; 7769 } 7770 else if (scalarTy->isIntegralType(S.Context)) 7771 scalarCast = CK_IntegralToFloating; 7772 else 7773 return true; 7774 } else { 7775 return true; 7776 } 7777 7778 // Adjust scalar if desired. 7779 if (scalar) { 7780 if (scalarCast != CK_Invalid) 7781 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7782 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7783 } 7784 return false; 7785 } 7786 7787 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7788 SourceLocation Loc, bool IsCompAssign, 7789 bool AllowBothBool, 7790 bool AllowBoolConversions) { 7791 if (!IsCompAssign) { 7792 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7793 if (LHS.isInvalid()) 7794 return QualType(); 7795 } 7796 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7797 if (RHS.isInvalid()) 7798 return QualType(); 7799 7800 // For conversion purposes, we ignore any qualifiers. 7801 // For example, "const float" and "float" are equivalent. 7802 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7803 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7804 7805 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7806 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7807 assert(LHSVecType || RHSVecType); 7808 7809 // AltiVec-style "vector bool op vector bool" combinations are allowed 7810 // for some operators but not others. 7811 if (!AllowBothBool && 7812 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7813 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7814 return InvalidOperands(Loc, LHS, RHS); 7815 7816 // If the vector types are identical, return. 7817 if (Context.hasSameType(LHSType, RHSType)) 7818 return LHSType; 7819 7820 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7821 if (LHSVecType && RHSVecType && 7822 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7823 if (isa<ExtVectorType>(LHSVecType)) { 7824 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7825 return LHSType; 7826 } 7827 7828 if (!IsCompAssign) 7829 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7830 return RHSType; 7831 } 7832 7833 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7834 // can be mixed, with the result being the non-bool type. The non-bool 7835 // operand must have integer element type. 7836 if (AllowBoolConversions && LHSVecType && RHSVecType && 7837 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7838 (Context.getTypeSize(LHSVecType->getElementType()) == 7839 Context.getTypeSize(RHSVecType->getElementType()))) { 7840 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7841 LHSVecType->getElementType()->isIntegerType() && 7842 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7843 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7844 return LHSType; 7845 } 7846 if (!IsCompAssign && 7847 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7848 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7849 RHSVecType->getElementType()->isIntegerType()) { 7850 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7851 return RHSType; 7852 } 7853 } 7854 7855 // If there's an ext-vector type and a scalar, try to convert the scalar to 7856 // the vector element type and splat. 7857 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7858 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7859 LHSVecType->getElementType(), LHSType)) 7860 return LHSType; 7861 } 7862 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7863 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7864 LHSType, RHSVecType->getElementType(), 7865 RHSType)) 7866 return RHSType; 7867 } 7868 7869 // If we're allowing lax vector conversions, only the total (data) size needs 7870 // to be the same. If one of the types is scalar, the result is always the 7871 // vector type. Don't allow this if the scalar operand is an lvalue. 7872 QualType VecType = LHSVecType ? LHSType : RHSType; 7873 QualType ScalarType = LHSVecType ? RHSType : LHSType; 7874 ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS; 7875 if (isLaxVectorConversion(ScalarType, VecType) && 7876 !ScalarExpr->get()->isLValue()) { 7877 *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast); 7878 return VecType; 7879 } 7880 7881 // Okay, the expression is invalid. 7882 7883 // If there's a non-vector, non-real operand, diagnose that. 7884 if ((!RHSVecType && !RHSType->isRealType()) || 7885 (!LHSVecType && !LHSType->isRealType())) { 7886 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7887 << LHSType << RHSType 7888 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7889 return QualType(); 7890 } 7891 7892 // OpenCL V1.1 6.2.6.p1: 7893 // If the operands are of more than one vector type, then an error shall 7894 // occur. Implicit conversions between vector types are not permitted, per 7895 // section 6.2.1. 7896 if (getLangOpts().OpenCL && 7897 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7898 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7899 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7900 << RHSType; 7901 return QualType(); 7902 } 7903 7904 // Otherwise, use the generic diagnostic. 7905 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7906 << LHSType << RHSType 7907 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7908 return QualType(); 7909 } 7910 7911 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7912 // expression. These are mainly cases where the null pointer is used as an 7913 // integer instead of a pointer. 7914 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7915 SourceLocation Loc, bool IsCompare) { 7916 // The canonical way to check for a GNU null is with isNullPointerConstant, 7917 // but we use a bit of a hack here for speed; this is a relatively 7918 // hot path, and isNullPointerConstant is slow. 7919 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7920 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7921 7922 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7923 7924 // Avoid analyzing cases where the result will either be invalid (and 7925 // diagnosed as such) or entirely valid and not something to warn about. 7926 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7927 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7928 return; 7929 7930 // Comparison operations would not make sense with a null pointer no matter 7931 // what the other expression is. 7932 if (!IsCompare) { 7933 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7934 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7935 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7936 return; 7937 } 7938 7939 // The rest of the operations only make sense with a null pointer 7940 // if the other expression is a pointer. 7941 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7942 NonNullType->canDecayToPointerType()) 7943 return; 7944 7945 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7946 << LHSNull /* LHS is NULL */ << NonNullType 7947 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7948 } 7949 7950 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7951 ExprResult &RHS, 7952 SourceLocation Loc, bool IsDiv) { 7953 // Check for division/remainder by zero. 7954 llvm::APSInt RHSValue; 7955 if (!RHS.get()->isValueDependent() && 7956 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7957 S.DiagRuntimeBehavior(Loc, RHS.get(), 7958 S.PDiag(diag::warn_remainder_division_by_zero) 7959 << IsDiv << RHS.get()->getSourceRange()); 7960 } 7961 7962 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7963 SourceLocation Loc, 7964 bool IsCompAssign, bool IsDiv) { 7965 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7966 7967 if (LHS.get()->getType()->isVectorType() || 7968 RHS.get()->getType()->isVectorType()) 7969 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7970 /*AllowBothBool*/getLangOpts().AltiVec, 7971 /*AllowBoolConversions*/false); 7972 7973 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7974 if (LHS.isInvalid() || RHS.isInvalid()) 7975 return QualType(); 7976 7977 7978 if (compType.isNull() || !compType->isArithmeticType()) 7979 return InvalidOperands(Loc, LHS, RHS); 7980 if (IsDiv) 7981 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7982 return compType; 7983 } 7984 7985 QualType Sema::CheckRemainderOperands( 7986 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7987 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7988 7989 if (LHS.get()->getType()->isVectorType() || 7990 RHS.get()->getType()->isVectorType()) { 7991 if (LHS.get()->getType()->hasIntegerRepresentation() && 7992 RHS.get()->getType()->hasIntegerRepresentation()) 7993 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7994 /*AllowBothBool*/getLangOpts().AltiVec, 7995 /*AllowBoolConversions*/false); 7996 return InvalidOperands(Loc, LHS, RHS); 7997 } 7998 7999 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8000 if (LHS.isInvalid() || RHS.isInvalid()) 8001 return QualType(); 8002 8003 if (compType.isNull() || !compType->isIntegerType()) 8004 return InvalidOperands(Loc, LHS, RHS); 8005 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8006 return compType; 8007 } 8008 8009 /// \brief Diagnose invalid arithmetic on two void pointers. 8010 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8011 Expr *LHSExpr, Expr *RHSExpr) { 8012 S.Diag(Loc, S.getLangOpts().CPlusPlus 8013 ? diag::err_typecheck_pointer_arith_void_type 8014 : diag::ext_gnu_void_ptr) 8015 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8016 << RHSExpr->getSourceRange(); 8017 } 8018 8019 /// \brief Diagnose invalid arithmetic on a void pointer. 8020 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8021 Expr *Pointer) { 8022 S.Diag(Loc, S.getLangOpts().CPlusPlus 8023 ? diag::err_typecheck_pointer_arith_void_type 8024 : diag::ext_gnu_void_ptr) 8025 << 0 /* one pointer */ << Pointer->getSourceRange(); 8026 } 8027 8028 /// \brief Diagnose invalid arithmetic on two function pointers. 8029 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8030 Expr *LHS, Expr *RHS) { 8031 assert(LHS->getType()->isAnyPointerType()); 8032 assert(RHS->getType()->isAnyPointerType()); 8033 S.Diag(Loc, S.getLangOpts().CPlusPlus 8034 ? diag::err_typecheck_pointer_arith_function_type 8035 : diag::ext_gnu_ptr_func_arith) 8036 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8037 // We only show the second type if it differs from the first. 8038 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8039 RHS->getType()) 8040 << RHS->getType()->getPointeeType() 8041 << LHS->getSourceRange() << RHS->getSourceRange(); 8042 } 8043 8044 /// \brief Diagnose invalid arithmetic on a function pointer. 8045 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8046 Expr *Pointer) { 8047 assert(Pointer->getType()->isAnyPointerType()); 8048 S.Diag(Loc, S.getLangOpts().CPlusPlus 8049 ? diag::err_typecheck_pointer_arith_function_type 8050 : diag::ext_gnu_ptr_func_arith) 8051 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8052 << 0 /* one pointer, so only one type */ 8053 << Pointer->getSourceRange(); 8054 } 8055 8056 /// \brief Emit error if Operand is incomplete pointer type 8057 /// 8058 /// \returns True if pointer has incomplete type 8059 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8060 Expr *Operand) { 8061 QualType ResType = Operand->getType(); 8062 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8063 ResType = ResAtomicType->getValueType(); 8064 8065 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8066 QualType PointeeTy = ResType->getPointeeType(); 8067 return S.RequireCompleteType(Loc, PointeeTy, 8068 diag::err_typecheck_arithmetic_incomplete_type, 8069 PointeeTy, Operand->getSourceRange()); 8070 } 8071 8072 /// \brief Check the validity of an arithmetic pointer operand. 8073 /// 8074 /// If the operand has pointer type, this code will check for pointer types 8075 /// which are invalid in arithmetic operations. These will be diagnosed 8076 /// appropriately, including whether or not the use is supported as an 8077 /// extension. 8078 /// 8079 /// \returns True when the operand is valid to use (even if as an extension). 8080 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8081 Expr *Operand) { 8082 QualType ResType = Operand->getType(); 8083 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8084 ResType = ResAtomicType->getValueType(); 8085 8086 if (!ResType->isAnyPointerType()) return true; 8087 8088 QualType PointeeTy = ResType->getPointeeType(); 8089 if (PointeeTy->isVoidType()) { 8090 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8091 return !S.getLangOpts().CPlusPlus; 8092 } 8093 if (PointeeTy->isFunctionType()) { 8094 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8095 return !S.getLangOpts().CPlusPlus; 8096 } 8097 8098 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8099 8100 return true; 8101 } 8102 8103 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8104 /// operands. 8105 /// 8106 /// This routine will diagnose any invalid arithmetic on pointer operands much 8107 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8108 /// for emitting a single diagnostic even for operations where both LHS and RHS 8109 /// are (potentially problematic) pointers. 8110 /// 8111 /// \returns True when the operand is valid to use (even if as an extension). 8112 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8113 Expr *LHSExpr, Expr *RHSExpr) { 8114 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8115 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8116 if (!isLHSPointer && !isRHSPointer) return true; 8117 8118 QualType LHSPointeeTy, RHSPointeeTy; 8119 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8120 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8121 8122 // if both are pointers check if operation is valid wrt address spaces 8123 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8124 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8125 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8126 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8127 S.Diag(Loc, 8128 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8129 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8130 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8131 return false; 8132 } 8133 } 8134 8135 // Check for arithmetic on pointers to incomplete types. 8136 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8137 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8138 if (isLHSVoidPtr || isRHSVoidPtr) { 8139 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8140 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8141 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8142 8143 return !S.getLangOpts().CPlusPlus; 8144 } 8145 8146 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8147 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8148 if (isLHSFuncPtr || isRHSFuncPtr) { 8149 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8150 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8151 RHSExpr); 8152 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8153 8154 return !S.getLangOpts().CPlusPlus; 8155 } 8156 8157 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8158 return false; 8159 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8160 return false; 8161 8162 return true; 8163 } 8164 8165 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8166 /// literal. 8167 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8168 Expr *LHSExpr, Expr *RHSExpr) { 8169 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8170 Expr* IndexExpr = RHSExpr; 8171 if (!StrExpr) { 8172 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8173 IndexExpr = LHSExpr; 8174 } 8175 8176 bool IsStringPlusInt = StrExpr && 8177 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8178 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8179 return; 8180 8181 llvm::APSInt index; 8182 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8183 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8184 if (index.isNonNegative() && 8185 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8186 index.isUnsigned())) 8187 return; 8188 } 8189 8190 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8191 Self.Diag(OpLoc, diag::warn_string_plus_int) 8192 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8193 8194 // Only print a fixit for "str" + int, not for int + "str". 8195 if (IndexExpr == RHSExpr) { 8196 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8197 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8198 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8199 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8200 << FixItHint::CreateInsertion(EndLoc, "]"); 8201 } else 8202 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8203 } 8204 8205 /// \brief Emit a warning when adding a char literal to a string. 8206 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8207 Expr *LHSExpr, Expr *RHSExpr) { 8208 const Expr *StringRefExpr = LHSExpr; 8209 const CharacterLiteral *CharExpr = 8210 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8211 8212 if (!CharExpr) { 8213 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8214 StringRefExpr = RHSExpr; 8215 } 8216 8217 if (!CharExpr || !StringRefExpr) 8218 return; 8219 8220 const QualType StringType = StringRefExpr->getType(); 8221 8222 // Return if not a PointerType. 8223 if (!StringType->isAnyPointerType()) 8224 return; 8225 8226 // Return if not a CharacterType. 8227 if (!StringType->getPointeeType()->isAnyCharacterType()) 8228 return; 8229 8230 ASTContext &Ctx = Self.getASTContext(); 8231 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8232 8233 const QualType CharType = CharExpr->getType(); 8234 if (!CharType->isAnyCharacterType() && 8235 CharType->isIntegerType() && 8236 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8237 Self.Diag(OpLoc, diag::warn_string_plus_char) 8238 << DiagRange << Ctx.CharTy; 8239 } else { 8240 Self.Diag(OpLoc, diag::warn_string_plus_char) 8241 << DiagRange << CharExpr->getType(); 8242 } 8243 8244 // Only print a fixit for str + char, not for char + str. 8245 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8246 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8247 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8248 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8249 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8250 << FixItHint::CreateInsertion(EndLoc, "]"); 8251 } else { 8252 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8253 } 8254 } 8255 8256 /// \brief Emit error when two pointers are incompatible. 8257 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8258 Expr *LHSExpr, Expr *RHSExpr) { 8259 assert(LHSExpr->getType()->isAnyPointerType()); 8260 assert(RHSExpr->getType()->isAnyPointerType()); 8261 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8262 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8263 << RHSExpr->getSourceRange(); 8264 } 8265 8266 // C99 6.5.6 8267 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8268 SourceLocation Loc, BinaryOperatorKind Opc, 8269 QualType* CompLHSTy) { 8270 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8271 8272 if (LHS.get()->getType()->isVectorType() || 8273 RHS.get()->getType()->isVectorType()) { 8274 QualType compType = CheckVectorOperands( 8275 LHS, RHS, Loc, CompLHSTy, 8276 /*AllowBothBool*/getLangOpts().AltiVec, 8277 /*AllowBoolConversions*/getLangOpts().ZVector); 8278 if (CompLHSTy) *CompLHSTy = compType; 8279 return compType; 8280 } 8281 8282 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8283 if (LHS.isInvalid() || RHS.isInvalid()) 8284 return QualType(); 8285 8286 // Diagnose "string literal" '+' int and string '+' "char literal". 8287 if (Opc == BO_Add) { 8288 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8289 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8290 } 8291 8292 // handle the common case first (both operands are arithmetic). 8293 if (!compType.isNull() && compType->isArithmeticType()) { 8294 if (CompLHSTy) *CompLHSTy = compType; 8295 return compType; 8296 } 8297 8298 // Type-checking. Ultimately the pointer's going to be in PExp; 8299 // note that we bias towards the LHS being the pointer. 8300 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8301 8302 bool isObjCPointer; 8303 if (PExp->getType()->isPointerType()) { 8304 isObjCPointer = false; 8305 } else if (PExp->getType()->isObjCObjectPointerType()) { 8306 isObjCPointer = true; 8307 } else { 8308 std::swap(PExp, IExp); 8309 if (PExp->getType()->isPointerType()) { 8310 isObjCPointer = false; 8311 } else if (PExp->getType()->isObjCObjectPointerType()) { 8312 isObjCPointer = true; 8313 } else { 8314 return InvalidOperands(Loc, LHS, RHS); 8315 } 8316 } 8317 assert(PExp->getType()->isAnyPointerType()); 8318 8319 if (!IExp->getType()->isIntegerType()) 8320 return InvalidOperands(Loc, LHS, RHS); 8321 8322 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8323 return QualType(); 8324 8325 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8326 return QualType(); 8327 8328 // Check array bounds for pointer arithemtic 8329 CheckArrayAccess(PExp, IExp); 8330 8331 if (CompLHSTy) { 8332 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8333 if (LHSTy.isNull()) { 8334 LHSTy = LHS.get()->getType(); 8335 if (LHSTy->isPromotableIntegerType()) 8336 LHSTy = Context.getPromotedIntegerType(LHSTy); 8337 } 8338 *CompLHSTy = LHSTy; 8339 } 8340 8341 return PExp->getType(); 8342 } 8343 8344 // C99 6.5.6 8345 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8346 SourceLocation Loc, 8347 QualType* CompLHSTy) { 8348 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8349 8350 if (LHS.get()->getType()->isVectorType() || 8351 RHS.get()->getType()->isVectorType()) { 8352 QualType compType = CheckVectorOperands( 8353 LHS, RHS, Loc, CompLHSTy, 8354 /*AllowBothBool*/getLangOpts().AltiVec, 8355 /*AllowBoolConversions*/getLangOpts().ZVector); 8356 if (CompLHSTy) *CompLHSTy = compType; 8357 return compType; 8358 } 8359 8360 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8361 if (LHS.isInvalid() || RHS.isInvalid()) 8362 return QualType(); 8363 8364 // Enforce type constraints: C99 6.5.6p3. 8365 8366 // Handle the common case first (both operands are arithmetic). 8367 if (!compType.isNull() && compType->isArithmeticType()) { 8368 if (CompLHSTy) *CompLHSTy = compType; 8369 return compType; 8370 } 8371 8372 // Either ptr - int or ptr - ptr. 8373 if (LHS.get()->getType()->isAnyPointerType()) { 8374 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8375 8376 // Diagnose bad cases where we step over interface counts. 8377 if (LHS.get()->getType()->isObjCObjectPointerType() && 8378 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8379 return QualType(); 8380 8381 // The result type of a pointer-int computation is the pointer type. 8382 if (RHS.get()->getType()->isIntegerType()) { 8383 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8384 return QualType(); 8385 8386 // Check array bounds for pointer arithemtic 8387 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8388 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8389 8390 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8391 return LHS.get()->getType(); 8392 } 8393 8394 // Handle pointer-pointer subtractions. 8395 if (const PointerType *RHSPTy 8396 = RHS.get()->getType()->getAs<PointerType>()) { 8397 QualType rpointee = RHSPTy->getPointeeType(); 8398 8399 if (getLangOpts().CPlusPlus) { 8400 // Pointee types must be the same: C++ [expr.add] 8401 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8402 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8403 } 8404 } else { 8405 // Pointee types must be compatible C99 6.5.6p3 8406 if (!Context.typesAreCompatible( 8407 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8408 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8409 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8410 return QualType(); 8411 } 8412 } 8413 8414 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8415 LHS.get(), RHS.get())) 8416 return QualType(); 8417 8418 // The pointee type may have zero size. As an extension, a structure or 8419 // union may have zero size or an array may have zero length. In this 8420 // case subtraction does not make sense. 8421 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8422 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8423 if (ElementSize.isZero()) { 8424 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8425 << rpointee.getUnqualifiedType() 8426 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8427 } 8428 } 8429 8430 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8431 return Context.getPointerDiffType(); 8432 } 8433 } 8434 8435 return InvalidOperands(Loc, LHS, RHS); 8436 } 8437 8438 static bool isScopedEnumerationType(QualType T) { 8439 if (const EnumType *ET = T->getAs<EnumType>()) 8440 return ET->getDecl()->isScoped(); 8441 return false; 8442 } 8443 8444 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8445 SourceLocation Loc, BinaryOperatorKind Opc, 8446 QualType LHSType) { 8447 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8448 // so skip remaining warnings as we don't want to modify values within Sema. 8449 if (S.getLangOpts().OpenCL) 8450 return; 8451 8452 llvm::APSInt Right; 8453 // Check right/shifter operand 8454 if (RHS.get()->isValueDependent() || 8455 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8456 return; 8457 8458 if (Right.isNegative()) { 8459 S.DiagRuntimeBehavior(Loc, RHS.get(), 8460 S.PDiag(diag::warn_shift_negative) 8461 << RHS.get()->getSourceRange()); 8462 return; 8463 } 8464 llvm::APInt LeftBits(Right.getBitWidth(), 8465 S.Context.getTypeSize(LHS.get()->getType())); 8466 if (Right.uge(LeftBits)) { 8467 S.DiagRuntimeBehavior(Loc, RHS.get(), 8468 S.PDiag(diag::warn_shift_gt_typewidth) 8469 << RHS.get()->getSourceRange()); 8470 return; 8471 } 8472 if (Opc != BO_Shl) 8473 return; 8474 8475 // When left shifting an ICE which is signed, we can check for overflow which 8476 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8477 // integers have defined behavior modulo one more than the maximum value 8478 // representable in the result type, so never warn for those. 8479 llvm::APSInt Left; 8480 if (LHS.get()->isValueDependent() || 8481 LHSType->hasUnsignedIntegerRepresentation() || 8482 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8483 return; 8484 8485 // If LHS does not have a signed type and non-negative value 8486 // then, the behavior is undefined. Warn about it. 8487 if (Left.isNegative()) { 8488 S.DiagRuntimeBehavior(Loc, LHS.get(), 8489 S.PDiag(diag::warn_shift_lhs_negative) 8490 << LHS.get()->getSourceRange()); 8491 return; 8492 } 8493 8494 llvm::APInt ResultBits = 8495 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8496 if (LeftBits.uge(ResultBits)) 8497 return; 8498 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8499 Result = Result.shl(Right); 8500 8501 // Print the bit representation of the signed integer as an unsigned 8502 // hexadecimal number. 8503 SmallString<40> HexResult; 8504 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8505 8506 // If we are only missing a sign bit, this is less likely to result in actual 8507 // bugs -- if the result is cast back to an unsigned type, it will have the 8508 // expected value. Thus we place this behind a different warning that can be 8509 // turned off separately if needed. 8510 if (LeftBits == ResultBits - 1) { 8511 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8512 << HexResult << LHSType 8513 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8514 return; 8515 } 8516 8517 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8518 << HexResult.str() << Result.getMinSignedBits() << LHSType 8519 << Left.getBitWidth() << LHS.get()->getSourceRange() 8520 << RHS.get()->getSourceRange(); 8521 } 8522 8523 /// \brief Return the resulting type when an OpenCL vector is shifted 8524 /// by a scalar or vector shift amount. 8525 static QualType checkOpenCLVectorShift(Sema &S, 8526 ExprResult &LHS, ExprResult &RHS, 8527 SourceLocation Loc, bool IsCompAssign) { 8528 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8529 if (!LHS.get()->getType()->isVectorType()) { 8530 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8531 << RHS.get()->getType() << LHS.get()->getType() 8532 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8533 return QualType(); 8534 } 8535 8536 if (!IsCompAssign) { 8537 LHS = S.UsualUnaryConversions(LHS.get()); 8538 if (LHS.isInvalid()) return QualType(); 8539 } 8540 8541 RHS = S.UsualUnaryConversions(RHS.get()); 8542 if (RHS.isInvalid()) return QualType(); 8543 8544 QualType LHSType = LHS.get()->getType(); 8545 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8546 QualType LHSEleType = LHSVecTy->getElementType(); 8547 8548 // Note that RHS might not be a vector. 8549 QualType RHSType = RHS.get()->getType(); 8550 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8551 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8552 8553 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8554 if (!LHSEleType->isIntegerType()) { 8555 S.Diag(Loc, diag::err_typecheck_expect_int) 8556 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8557 return QualType(); 8558 } 8559 8560 if (!RHSEleType->isIntegerType()) { 8561 S.Diag(Loc, diag::err_typecheck_expect_int) 8562 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8563 return QualType(); 8564 } 8565 8566 if (RHSVecTy) { 8567 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8568 // are applied component-wise. So if RHS is a vector, then ensure 8569 // that the number of elements is the same as LHS... 8570 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8571 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8572 << LHS.get()->getType() << RHS.get()->getType() 8573 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8574 return QualType(); 8575 } 8576 } else { 8577 // ...else expand RHS to match the number of elements in LHS. 8578 QualType VecTy = 8579 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8580 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8581 } 8582 8583 return LHSType; 8584 } 8585 8586 // C99 6.5.7 8587 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8588 SourceLocation Loc, BinaryOperatorKind Opc, 8589 bool IsCompAssign) { 8590 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8591 8592 // Vector shifts promote their scalar inputs to vector type. 8593 if (LHS.get()->getType()->isVectorType() || 8594 RHS.get()->getType()->isVectorType()) { 8595 if (LangOpts.OpenCL) 8596 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8597 if (LangOpts.ZVector) { 8598 // The shift operators for the z vector extensions work basically 8599 // like OpenCL shifts, except that neither the LHS nor the RHS is 8600 // allowed to be a "vector bool". 8601 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8602 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8603 return InvalidOperands(Loc, LHS, RHS); 8604 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8605 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8606 return InvalidOperands(Loc, LHS, RHS); 8607 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8608 } 8609 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8610 /*AllowBothBool*/true, 8611 /*AllowBoolConversions*/false); 8612 } 8613 8614 // Shifts don't perform usual arithmetic conversions, they just do integer 8615 // promotions on each operand. C99 6.5.7p3 8616 8617 // For the LHS, do usual unary conversions, but then reset them away 8618 // if this is a compound assignment. 8619 ExprResult OldLHS = LHS; 8620 LHS = UsualUnaryConversions(LHS.get()); 8621 if (LHS.isInvalid()) 8622 return QualType(); 8623 QualType LHSType = LHS.get()->getType(); 8624 if (IsCompAssign) LHS = OldLHS; 8625 8626 // The RHS is simpler. 8627 RHS = UsualUnaryConversions(RHS.get()); 8628 if (RHS.isInvalid()) 8629 return QualType(); 8630 QualType RHSType = RHS.get()->getType(); 8631 8632 // C99 6.5.7p2: Each of the operands shall have integer type. 8633 if (!LHSType->hasIntegerRepresentation() || 8634 !RHSType->hasIntegerRepresentation()) 8635 return InvalidOperands(Loc, LHS, RHS); 8636 8637 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8638 // hasIntegerRepresentation() above instead of this. 8639 if (isScopedEnumerationType(LHSType) || 8640 isScopedEnumerationType(RHSType)) { 8641 return InvalidOperands(Loc, LHS, RHS); 8642 } 8643 // Sanity-check shift operands 8644 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8645 8646 // "The type of the result is that of the promoted left operand." 8647 return LHSType; 8648 } 8649 8650 static bool IsWithinTemplateSpecialization(Decl *D) { 8651 if (DeclContext *DC = D->getDeclContext()) { 8652 if (isa<ClassTemplateSpecializationDecl>(DC)) 8653 return true; 8654 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8655 return FD->isFunctionTemplateSpecialization(); 8656 } 8657 return false; 8658 } 8659 8660 /// If two different enums are compared, raise a warning. 8661 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8662 Expr *RHS) { 8663 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8664 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8665 8666 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8667 if (!LHSEnumType) 8668 return; 8669 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8670 if (!RHSEnumType) 8671 return; 8672 8673 // Ignore anonymous enums. 8674 if (!LHSEnumType->getDecl()->getIdentifier()) 8675 return; 8676 if (!RHSEnumType->getDecl()->getIdentifier()) 8677 return; 8678 8679 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8680 return; 8681 8682 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8683 << LHSStrippedType << RHSStrippedType 8684 << LHS->getSourceRange() << RHS->getSourceRange(); 8685 } 8686 8687 /// \brief Diagnose bad pointer comparisons. 8688 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8689 ExprResult &LHS, ExprResult &RHS, 8690 bool IsError) { 8691 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8692 : diag::ext_typecheck_comparison_of_distinct_pointers) 8693 << LHS.get()->getType() << RHS.get()->getType() 8694 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8695 } 8696 8697 /// \brief Returns false if the pointers are converted to a composite type, 8698 /// true otherwise. 8699 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8700 ExprResult &LHS, ExprResult &RHS) { 8701 // C++ [expr.rel]p2: 8702 // [...] Pointer conversions (4.10) and qualification 8703 // conversions (4.4) are performed on pointer operands (or on 8704 // a pointer operand and a null pointer constant) to bring 8705 // them to their composite pointer type. [...] 8706 // 8707 // C++ [expr.eq]p1 uses the same notion for (in)equality 8708 // comparisons of pointers. 8709 8710 // C++ [expr.eq]p2: 8711 // In addition, pointers to members can be compared, or a pointer to 8712 // member and a null pointer constant. Pointer to member conversions 8713 // (4.11) and qualification conversions (4.4) are performed to bring 8714 // them to a common type. If one operand is a null pointer constant, 8715 // the common type is the type of the other operand. Otherwise, the 8716 // common type is a pointer to member type similar (4.4) to the type 8717 // of one of the operands, with a cv-qualification signature (4.4) 8718 // that is the union of the cv-qualification signatures of the operand 8719 // types. 8720 8721 QualType LHSType = LHS.get()->getType(); 8722 QualType RHSType = RHS.get()->getType(); 8723 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8724 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8725 8726 bool NonStandardCompositeType = false; 8727 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8728 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8729 if (T.isNull()) { 8730 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8731 return true; 8732 } 8733 8734 if (NonStandardCompositeType) 8735 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8736 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8737 << RHS.get()->getSourceRange(); 8738 8739 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8740 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8741 return false; 8742 } 8743 8744 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8745 ExprResult &LHS, 8746 ExprResult &RHS, 8747 bool IsError) { 8748 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8749 : diag::ext_typecheck_comparison_of_fptr_to_void) 8750 << LHS.get()->getType() << RHS.get()->getType() 8751 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8752 } 8753 8754 static bool isObjCObjectLiteral(ExprResult &E) { 8755 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8756 case Stmt::ObjCArrayLiteralClass: 8757 case Stmt::ObjCDictionaryLiteralClass: 8758 case Stmt::ObjCStringLiteralClass: 8759 case Stmt::ObjCBoxedExprClass: 8760 return true; 8761 default: 8762 // Note that ObjCBoolLiteral is NOT an object literal! 8763 return false; 8764 } 8765 } 8766 8767 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8768 const ObjCObjectPointerType *Type = 8769 LHS->getType()->getAs<ObjCObjectPointerType>(); 8770 8771 // If this is not actually an Objective-C object, bail out. 8772 if (!Type) 8773 return false; 8774 8775 // Get the LHS object's interface type. 8776 QualType InterfaceType = Type->getPointeeType(); 8777 8778 // If the RHS isn't an Objective-C object, bail out. 8779 if (!RHS->getType()->isObjCObjectPointerType()) 8780 return false; 8781 8782 // Try to find the -isEqual: method. 8783 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8784 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8785 InterfaceType, 8786 /*instance=*/true); 8787 if (!Method) { 8788 if (Type->isObjCIdType()) { 8789 // For 'id', just check the global pool. 8790 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8791 /*receiverId=*/true); 8792 } else { 8793 // Check protocols. 8794 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8795 /*instance=*/true); 8796 } 8797 } 8798 8799 if (!Method) 8800 return false; 8801 8802 QualType T = Method->parameters()[0]->getType(); 8803 if (!T->isObjCObjectPointerType()) 8804 return false; 8805 8806 QualType R = Method->getReturnType(); 8807 if (!R->isScalarType()) 8808 return false; 8809 8810 return true; 8811 } 8812 8813 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8814 FromE = FromE->IgnoreParenImpCasts(); 8815 switch (FromE->getStmtClass()) { 8816 default: 8817 break; 8818 case Stmt::ObjCStringLiteralClass: 8819 // "string literal" 8820 return LK_String; 8821 case Stmt::ObjCArrayLiteralClass: 8822 // "array literal" 8823 return LK_Array; 8824 case Stmt::ObjCDictionaryLiteralClass: 8825 // "dictionary literal" 8826 return LK_Dictionary; 8827 case Stmt::BlockExprClass: 8828 return LK_Block; 8829 case Stmt::ObjCBoxedExprClass: { 8830 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8831 switch (Inner->getStmtClass()) { 8832 case Stmt::IntegerLiteralClass: 8833 case Stmt::FloatingLiteralClass: 8834 case Stmt::CharacterLiteralClass: 8835 case Stmt::ObjCBoolLiteralExprClass: 8836 case Stmt::CXXBoolLiteralExprClass: 8837 // "numeric literal" 8838 return LK_Numeric; 8839 case Stmt::ImplicitCastExprClass: { 8840 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8841 // Boolean literals can be represented by implicit casts. 8842 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8843 return LK_Numeric; 8844 break; 8845 } 8846 default: 8847 break; 8848 } 8849 return LK_Boxed; 8850 } 8851 } 8852 return LK_None; 8853 } 8854 8855 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8856 ExprResult &LHS, ExprResult &RHS, 8857 BinaryOperator::Opcode Opc){ 8858 Expr *Literal; 8859 Expr *Other; 8860 if (isObjCObjectLiteral(LHS)) { 8861 Literal = LHS.get(); 8862 Other = RHS.get(); 8863 } else { 8864 Literal = RHS.get(); 8865 Other = LHS.get(); 8866 } 8867 8868 // Don't warn on comparisons against nil. 8869 Other = Other->IgnoreParenCasts(); 8870 if (Other->isNullPointerConstant(S.getASTContext(), 8871 Expr::NPC_ValueDependentIsNotNull)) 8872 return; 8873 8874 // This should be kept in sync with warn_objc_literal_comparison. 8875 // LK_String should always be after the other literals, since it has its own 8876 // warning flag. 8877 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8878 assert(LiteralKind != Sema::LK_Block); 8879 if (LiteralKind == Sema::LK_None) { 8880 llvm_unreachable("Unknown Objective-C object literal kind"); 8881 } 8882 8883 if (LiteralKind == Sema::LK_String) 8884 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8885 << Literal->getSourceRange(); 8886 else 8887 S.Diag(Loc, diag::warn_objc_literal_comparison) 8888 << LiteralKind << Literal->getSourceRange(); 8889 8890 if (BinaryOperator::isEqualityOp(Opc) && 8891 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8892 SourceLocation Start = LHS.get()->getLocStart(); 8893 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 8894 CharSourceRange OpRange = 8895 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 8896 8897 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8898 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8899 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8900 << FixItHint::CreateInsertion(End, "]"); 8901 } 8902 } 8903 8904 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8905 ExprResult &RHS, 8906 SourceLocation Loc, 8907 BinaryOperatorKind Opc) { 8908 // Check that left hand side is !something. 8909 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8910 if (!UO || UO->getOpcode() != UO_LNot) return; 8911 8912 // Only check if the right hand side is non-bool arithmetic type. 8913 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8914 8915 // Make sure that the something in !something is not bool. 8916 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8917 if (SubExpr->isKnownToHaveBooleanValue()) return; 8918 8919 // Emit warning. 8920 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8921 << Loc; 8922 8923 // First note suggest !(x < y) 8924 SourceLocation FirstOpen = SubExpr->getLocStart(); 8925 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8926 FirstClose = S.getLocForEndOfToken(FirstClose); 8927 if (FirstClose.isInvalid()) 8928 FirstOpen = SourceLocation(); 8929 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8930 << FixItHint::CreateInsertion(FirstOpen, "(") 8931 << FixItHint::CreateInsertion(FirstClose, ")"); 8932 8933 // Second note suggests (!x) < y 8934 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8935 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8936 SecondClose = S.getLocForEndOfToken(SecondClose); 8937 if (SecondClose.isInvalid()) 8938 SecondOpen = SourceLocation(); 8939 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8940 << FixItHint::CreateInsertion(SecondOpen, "(") 8941 << FixItHint::CreateInsertion(SecondClose, ")"); 8942 } 8943 8944 // Get the decl for a simple expression: a reference to a variable, 8945 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8946 static ValueDecl *getCompareDecl(Expr *E) { 8947 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8948 return DR->getDecl(); 8949 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8950 if (Ivar->isFreeIvar()) 8951 return Ivar->getDecl(); 8952 } 8953 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8954 if (Mem->isImplicitAccess()) 8955 return Mem->getMemberDecl(); 8956 } 8957 return nullptr; 8958 } 8959 8960 // C99 6.5.8, C++ [expr.rel] 8961 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8962 SourceLocation Loc, BinaryOperatorKind Opc, 8963 bool IsRelational) { 8964 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8965 8966 // Handle vector comparisons separately. 8967 if (LHS.get()->getType()->isVectorType() || 8968 RHS.get()->getType()->isVectorType()) 8969 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8970 8971 QualType LHSType = LHS.get()->getType(); 8972 QualType RHSType = RHS.get()->getType(); 8973 8974 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8975 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8976 8977 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8978 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 8979 8980 if (!LHSType->hasFloatingRepresentation() && 8981 !(LHSType->isBlockPointerType() && IsRelational) && 8982 !LHS.get()->getLocStart().isMacroID() && 8983 !RHS.get()->getLocStart().isMacroID() && 8984 ActiveTemplateInstantiations.empty()) { 8985 // For non-floating point types, check for self-comparisons of the form 8986 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8987 // often indicate logic errors in the program. 8988 // 8989 // NOTE: Don't warn about comparison expressions resulting from macro 8990 // expansion. Also don't warn about comparisons which are only self 8991 // comparisons within a template specialization. The warnings should catch 8992 // obvious cases in the definition of the template anyways. The idea is to 8993 // warn when the typed comparison operator will always evaluate to the same 8994 // result. 8995 ValueDecl *DL = getCompareDecl(LHSStripped); 8996 ValueDecl *DR = getCompareDecl(RHSStripped); 8997 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8998 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8999 << 0 // self- 9000 << (Opc == BO_EQ 9001 || Opc == BO_LE 9002 || Opc == BO_GE)); 9003 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9004 !DL->getType()->isReferenceType() && 9005 !DR->getType()->isReferenceType()) { 9006 // what is it always going to eval to? 9007 char always_evals_to; 9008 switch(Opc) { 9009 case BO_EQ: // e.g. array1 == array2 9010 always_evals_to = 0; // false 9011 break; 9012 case BO_NE: // e.g. array1 != array2 9013 always_evals_to = 1; // true 9014 break; 9015 default: 9016 // best we can say is 'a constant' 9017 always_evals_to = 2; // e.g. array1 <= array2 9018 break; 9019 } 9020 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9021 << 1 // array 9022 << always_evals_to); 9023 } 9024 9025 if (isa<CastExpr>(LHSStripped)) 9026 LHSStripped = LHSStripped->IgnoreParenCasts(); 9027 if (isa<CastExpr>(RHSStripped)) 9028 RHSStripped = RHSStripped->IgnoreParenCasts(); 9029 9030 // Warn about comparisons against a string constant (unless the other 9031 // operand is null), the user probably wants strcmp. 9032 Expr *literalString = nullptr; 9033 Expr *literalStringStripped = nullptr; 9034 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9035 !RHSStripped->isNullPointerConstant(Context, 9036 Expr::NPC_ValueDependentIsNull)) { 9037 literalString = LHS.get(); 9038 literalStringStripped = LHSStripped; 9039 } else if ((isa<StringLiteral>(RHSStripped) || 9040 isa<ObjCEncodeExpr>(RHSStripped)) && 9041 !LHSStripped->isNullPointerConstant(Context, 9042 Expr::NPC_ValueDependentIsNull)) { 9043 literalString = RHS.get(); 9044 literalStringStripped = RHSStripped; 9045 } 9046 9047 if (literalString) { 9048 DiagRuntimeBehavior(Loc, nullptr, 9049 PDiag(diag::warn_stringcompare) 9050 << isa<ObjCEncodeExpr>(literalStringStripped) 9051 << literalString->getSourceRange()); 9052 } 9053 } 9054 9055 // C99 6.5.8p3 / C99 6.5.9p4 9056 UsualArithmeticConversions(LHS, RHS); 9057 if (LHS.isInvalid() || RHS.isInvalid()) 9058 return QualType(); 9059 9060 LHSType = LHS.get()->getType(); 9061 RHSType = RHS.get()->getType(); 9062 9063 // The result of comparisons is 'bool' in C++, 'int' in C. 9064 QualType ResultTy = Context.getLogicalOperationType(); 9065 9066 if (IsRelational) { 9067 if (LHSType->isRealType() && RHSType->isRealType()) 9068 return ResultTy; 9069 } else { 9070 // Check for comparisons of floating point operands using != and ==. 9071 if (LHSType->hasFloatingRepresentation()) 9072 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9073 9074 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9075 return ResultTy; 9076 } 9077 9078 const Expr::NullPointerConstantKind LHSNullKind = 9079 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9080 const Expr::NullPointerConstantKind RHSNullKind = 9081 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9082 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9083 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9084 9085 if (!IsRelational && LHSIsNull != RHSIsNull) { 9086 bool IsEquality = Opc == BO_EQ; 9087 if (RHSIsNull) 9088 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9089 RHS.get()->getSourceRange()); 9090 else 9091 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9092 LHS.get()->getSourceRange()); 9093 } 9094 9095 // All of the following pointer-related warnings are GCC extensions, except 9096 // when handling null pointer constants. 9097 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9098 QualType LCanPointeeTy = 9099 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9100 QualType RCanPointeeTy = 9101 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9102 9103 if (getLangOpts().CPlusPlus) { 9104 if (LCanPointeeTy == RCanPointeeTy) 9105 return ResultTy; 9106 if (!IsRelational && 9107 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9108 // Valid unless comparison between non-null pointer and function pointer 9109 // This is a gcc extension compatibility comparison. 9110 // In a SFINAE context, we treat this as a hard error to maintain 9111 // conformance with the C++ standard. 9112 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9113 && !LHSIsNull && !RHSIsNull) { 9114 diagnoseFunctionPointerToVoidComparison( 9115 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9116 9117 if (isSFINAEContext()) 9118 return QualType(); 9119 9120 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9121 return ResultTy; 9122 } 9123 } 9124 9125 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9126 return QualType(); 9127 else 9128 return ResultTy; 9129 } 9130 // C99 6.5.9p2 and C99 6.5.8p2 9131 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9132 RCanPointeeTy.getUnqualifiedType())) { 9133 // Valid unless a relational comparison of function pointers 9134 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9135 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9136 << LHSType << RHSType << LHS.get()->getSourceRange() 9137 << RHS.get()->getSourceRange(); 9138 } 9139 } else if (!IsRelational && 9140 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9141 // Valid unless comparison between non-null pointer and function pointer 9142 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9143 && !LHSIsNull && !RHSIsNull) 9144 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9145 /*isError*/false); 9146 } else { 9147 // Invalid 9148 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9149 } 9150 if (LCanPointeeTy != RCanPointeeTy) { 9151 // Treat NULL constant as a special case in OpenCL. 9152 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9153 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9154 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9155 Diag(Loc, 9156 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9157 << LHSType << RHSType << 0 /* comparison */ 9158 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9159 } 9160 } 9161 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9162 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9163 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9164 : CK_BitCast; 9165 if (LHSIsNull && !RHSIsNull) 9166 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9167 else 9168 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9169 } 9170 return ResultTy; 9171 } 9172 9173 if (getLangOpts().CPlusPlus) { 9174 // Comparison of nullptr_t with itself. 9175 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9176 return ResultTy; 9177 9178 // Comparison of pointers with null pointer constants and equality 9179 // comparisons of member pointers to null pointer constants. 9180 if (RHSIsNull && 9181 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9182 (!IsRelational && 9183 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9184 RHS = ImpCastExprToType(RHS.get(), LHSType, 9185 LHSType->isMemberPointerType() 9186 ? CK_NullToMemberPointer 9187 : CK_NullToPointer); 9188 return ResultTy; 9189 } 9190 if (LHSIsNull && 9191 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9192 (!IsRelational && 9193 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9194 LHS = ImpCastExprToType(LHS.get(), RHSType, 9195 RHSType->isMemberPointerType() 9196 ? CK_NullToMemberPointer 9197 : CK_NullToPointer); 9198 return ResultTy; 9199 } 9200 9201 // Comparison of member pointers. 9202 if (!IsRelational && 9203 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9204 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9205 return QualType(); 9206 else 9207 return ResultTy; 9208 } 9209 9210 // Handle scoped enumeration types specifically, since they don't promote 9211 // to integers. 9212 if (LHS.get()->getType()->isEnumeralType() && 9213 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9214 RHS.get()->getType())) 9215 return ResultTy; 9216 } 9217 9218 // Handle block pointer types. 9219 if (!IsRelational && LHSType->isBlockPointerType() && 9220 RHSType->isBlockPointerType()) { 9221 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9222 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9223 9224 if (!LHSIsNull && !RHSIsNull && 9225 !Context.typesAreCompatible(lpointee, rpointee)) { 9226 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9227 << LHSType << RHSType << LHS.get()->getSourceRange() 9228 << RHS.get()->getSourceRange(); 9229 } 9230 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9231 return ResultTy; 9232 } 9233 9234 // Allow block pointers to be compared with null pointer constants. 9235 if (!IsRelational 9236 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9237 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9238 if (!LHSIsNull && !RHSIsNull) { 9239 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9240 ->getPointeeType()->isVoidType()) 9241 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9242 ->getPointeeType()->isVoidType()))) 9243 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9244 << LHSType << RHSType << LHS.get()->getSourceRange() 9245 << RHS.get()->getSourceRange(); 9246 } 9247 if (LHSIsNull && !RHSIsNull) 9248 LHS = ImpCastExprToType(LHS.get(), RHSType, 9249 RHSType->isPointerType() ? CK_BitCast 9250 : CK_AnyPointerToBlockPointerCast); 9251 else 9252 RHS = ImpCastExprToType(RHS.get(), LHSType, 9253 LHSType->isPointerType() ? CK_BitCast 9254 : CK_AnyPointerToBlockPointerCast); 9255 return ResultTy; 9256 } 9257 9258 if (LHSType->isObjCObjectPointerType() || 9259 RHSType->isObjCObjectPointerType()) { 9260 const PointerType *LPT = LHSType->getAs<PointerType>(); 9261 const PointerType *RPT = RHSType->getAs<PointerType>(); 9262 if (LPT || RPT) { 9263 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9264 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9265 9266 if (!LPtrToVoid && !RPtrToVoid && 9267 !Context.typesAreCompatible(LHSType, RHSType)) { 9268 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9269 /*isError*/false); 9270 } 9271 if (LHSIsNull && !RHSIsNull) { 9272 Expr *E = LHS.get(); 9273 if (getLangOpts().ObjCAutoRefCount) 9274 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9275 LHS = ImpCastExprToType(E, RHSType, 9276 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9277 } 9278 else { 9279 Expr *E = RHS.get(); 9280 if (getLangOpts().ObjCAutoRefCount) 9281 CheckObjCARCConversion(SourceRange(), LHSType, E, 9282 CCK_ImplicitConversion, /*Diagnose=*/true, 9283 /*DiagnoseCFAudited=*/false, Opc); 9284 RHS = ImpCastExprToType(E, LHSType, 9285 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9286 } 9287 return ResultTy; 9288 } 9289 if (LHSType->isObjCObjectPointerType() && 9290 RHSType->isObjCObjectPointerType()) { 9291 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9292 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9293 /*isError*/false); 9294 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9295 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9296 9297 if (LHSIsNull && !RHSIsNull) 9298 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9299 else 9300 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9301 return ResultTy; 9302 } 9303 } 9304 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9305 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9306 unsigned DiagID = 0; 9307 bool isError = false; 9308 if (LangOpts.DebuggerSupport) { 9309 // Under a debugger, allow the comparison of pointers to integers, 9310 // since users tend to want to compare addresses. 9311 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9312 (RHSIsNull && RHSType->isIntegerType())) { 9313 if (IsRelational && !getLangOpts().CPlusPlus) 9314 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9315 } else if (IsRelational && !getLangOpts().CPlusPlus) 9316 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9317 else if (getLangOpts().CPlusPlus) { 9318 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9319 isError = true; 9320 } else 9321 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9322 9323 if (DiagID) { 9324 Diag(Loc, DiagID) 9325 << LHSType << RHSType << LHS.get()->getSourceRange() 9326 << RHS.get()->getSourceRange(); 9327 if (isError) 9328 return QualType(); 9329 } 9330 9331 if (LHSType->isIntegerType()) 9332 LHS = ImpCastExprToType(LHS.get(), RHSType, 9333 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9334 else 9335 RHS = ImpCastExprToType(RHS.get(), LHSType, 9336 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9337 return ResultTy; 9338 } 9339 9340 // Handle block pointers. 9341 if (!IsRelational && RHSIsNull 9342 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9343 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9344 return ResultTy; 9345 } 9346 if (!IsRelational && LHSIsNull 9347 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9348 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9349 return ResultTy; 9350 } 9351 9352 return InvalidOperands(Loc, LHS, RHS); 9353 } 9354 9355 9356 // Return a signed type that is of identical size and number of elements. 9357 // For floating point vectors, return an integer type of identical size 9358 // and number of elements. 9359 QualType Sema::GetSignedVectorType(QualType V) { 9360 const VectorType *VTy = V->getAs<VectorType>(); 9361 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9362 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9363 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9364 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9365 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9366 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9367 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9368 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9369 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9370 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9371 "Unhandled vector element size in vector compare"); 9372 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9373 } 9374 9375 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9376 /// operates on extended vector types. Instead of producing an IntTy result, 9377 /// like a scalar comparison, a vector comparison produces a vector of integer 9378 /// types. 9379 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9380 SourceLocation Loc, 9381 bool IsRelational) { 9382 // Check to make sure we're operating on vectors of the same type and width, 9383 // Allowing one side to be a scalar of element type. 9384 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9385 /*AllowBothBool*/true, 9386 /*AllowBoolConversions*/getLangOpts().ZVector); 9387 if (vType.isNull()) 9388 return vType; 9389 9390 QualType LHSType = LHS.get()->getType(); 9391 9392 // If AltiVec, the comparison results in a numeric type, i.e. 9393 // bool for C++, int for C 9394 if (getLangOpts().AltiVec && 9395 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9396 return Context.getLogicalOperationType(); 9397 9398 // For non-floating point types, check for self-comparisons of the form 9399 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9400 // often indicate logic errors in the program. 9401 if (!LHSType->hasFloatingRepresentation() && 9402 ActiveTemplateInstantiations.empty()) { 9403 if (DeclRefExpr* DRL 9404 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9405 if (DeclRefExpr* DRR 9406 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9407 if (DRL->getDecl() == DRR->getDecl()) 9408 DiagRuntimeBehavior(Loc, nullptr, 9409 PDiag(diag::warn_comparison_always) 9410 << 0 // self- 9411 << 2 // "a constant" 9412 ); 9413 } 9414 9415 // Check for comparisons of floating point operands using != and ==. 9416 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9417 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9418 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9419 } 9420 9421 // Return a signed type for the vector. 9422 return GetSignedVectorType(vType); 9423 } 9424 9425 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9426 SourceLocation Loc) { 9427 // Ensure that either both operands are of the same vector type, or 9428 // one operand is of a vector type and the other is of its element type. 9429 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9430 /*AllowBothBool*/true, 9431 /*AllowBoolConversions*/false); 9432 if (vType.isNull()) 9433 return InvalidOperands(Loc, LHS, RHS); 9434 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9435 vType->hasFloatingRepresentation()) 9436 return InvalidOperands(Loc, LHS, RHS); 9437 9438 return GetSignedVectorType(LHS.get()->getType()); 9439 } 9440 9441 inline QualType Sema::CheckBitwiseOperands( 9442 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9443 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9444 9445 if (LHS.get()->getType()->isVectorType() || 9446 RHS.get()->getType()->isVectorType()) { 9447 if (LHS.get()->getType()->hasIntegerRepresentation() && 9448 RHS.get()->getType()->hasIntegerRepresentation()) 9449 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9450 /*AllowBothBool*/true, 9451 /*AllowBoolConversions*/getLangOpts().ZVector); 9452 return InvalidOperands(Loc, LHS, RHS); 9453 } 9454 9455 ExprResult LHSResult = LHS, RHSResult = RHS; 9456 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9457 IsCompAssign); 9458 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9459 return QualType(); 9460 LHS = LHSResult.get(); 9461 RHS = RHSResult.get(); 9462 9463 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9464 return compType; 9465 return InvalidOperands(Loc, LHS, RHS); 9466 } 9467 9468 // C99 6.5.[13,14] 9469 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9470 SourceLocation Loc, 9471 BinaryOperatorKind Opc) { 9472 // Check vector operands differently. 9473 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9474 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9475 9476 // Diagnose cases where the user write a logical and/or but probably meant a 9477 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9478 // is a constant. 9479 if (LHS.get()->getType()->isIntegerType() && 9480 !LHS.get()->getType()->isBooleanType() && 9481 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9482 // Don't warn in macros or template instantiations. 9483 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9484 // If the RHS can be constant folded, and if it constant folds to something 9485 // that isn't 0 or 1 (which indicate a potential logical operation that 9486 // happened to fold to true/false) then warn. 9487 // Parens on the RHS are ignored. 9488 llvm::APSInt Result; 9489 if (RHS.get()->EvaluateAsInt(Result, Context)) 9490 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9491 !RHS.get()->getExprLoc().isMacroID()) || 9492 (Result != 0 && Result != 1)) { 9493 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9494 << RHS.get()->getSourceRange() 9495 << (Opc == BO_LAnd ? "&&" : "||"); 9496 // Suggest replacing the logical operator with the bitwise version 9497 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9498 << (Opc == BO_LAnd ? "&" : "|") 9499 << FixItHint::CreateReplacement(SourceRange( 9500 Loc, getLocForEndOfToken(Loc)), 9501 Opc == BO_LAnd ? "&" : "|"); 9502 if (Opc == BO_LAnd) 9503 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9504 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9505 << FixItHint::CreateRemoval( 9506 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9507 RHS.get()->getLocEnd())); 9508 } 9509 } 9510 9511 if (!Context.getLangOpts().CPlusPlus) { 9512 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9513 // not operate on the built-in scalar and vector float types. 9514 if (Context.getLangOpts().OpenCL && 9515 Context.getLangOpts().OpenCLVersion < 120) { 9516 if (LHS.get()->getType()->isFloatingType() || 9517 RHS.get()->getType()->isFloatingType()) 9518 return InvalidOperands(Loc, LHS, RHS); 9519 } 9520 9521 LHS = UsualUnaryConversions(LHS.get()); 9522 if (LHS.isInvalid()) 9523 return QualType(); 9524 9525 RHS = UsualUnaryConversions(RHS.get()); 9526 if (RHS.isInvalid()) 9527 return QualType(); 9528 9529 if (!LHS.get()->getType()->isScalarType() || 9530 !RHS.get()->getType()->isScalarType()) 9531 return InvalidOperands(Loc, LHS, RHS); 9532 9533 return Context.IntTy; 9534 } 9535 9536 // The following is safe because we only use this method for 9537 // non-overloadable operands. 9538 9539 // C++ [expr.log.and]p1 9540 // C++ [expr.log.or]p1 9541 // The operands are both contextually converted to type bool. 9542 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9543 if (LHSRes.isInvalid()) 9544 return InvalidOperands(Loc, LHS, RHS); 9545 LHS = LHSRes; 9546 9547 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9548 if (RHSRes.isInvalid()) 9549 return InvalidOperands(Loc, LHS, RHS); 9550 RHS = RHSRes; 9551 9552 // C++ [expr.log.and]p2 9553 // C++ [expr.log.or]p2 9554 // The result is a bool. 9555 return Context.BoolTy; 9556 } 9557 9558 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9559 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9560 if (!ME) return false; 9561 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9562 ObjCMessageExpr *Base = 9563 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9564 if (!Base) return false; 9565 return Base->getMethodDecl() != nullptr; 9566 } 9567 9568 /// Is the given expression (which must be 'const') a reference to a 9569 /// variable which was originally non-const, but which has become 9570 /// 'const' due to being captured within a block? 9571 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9572 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9573 assert(E->isLValue() && E->getType().isConstQualified()); 9574 E = E->IgnoreParens(); 9575 9576 // Must be a reference to a declaration from an enclosing scope. 9577 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9578 if (!DRE) return NCCK_None; 9579 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9580 9581 // The declaration must be a variable which is not declared 'const'. 9582 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9583 if (!var) return NCCK_None; 9584 if (var->getType().isConstQualified()) return NCCK_None; 9585 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9586 9587 // Decide whether the first capture was for a block or a lambda. 9588 DeclContext *DC = S.CurContext, *Prev = nullptr; 9589 while (DC != var->getDeclContext()) { 9590 Prev = DC; 9591 DC = DC->getParent(); 9592 } 9593 // Unless we have an init-capture, we've gone one step too far. 9594 if (!var->isInitCapture()) 9595 DC = Prev; 9596 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9597 } 9598 9599 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9600 Ty = Ty.getNonReferenceType(); 9601 if (IsDereference && Ty->isPointerType()) 9602 Ty = Ty->getPointeeType(); 9603 return !Ty.isConstQualified(); 9604 } 9605 9606 /// Emit the "read-only variable not assignable" error and print notes to give 9607 /// more information about why the variable is not assignable, such as pointing 9608 /// to the declaration of a const variable, showing that a method is const, or 9609 /// that the function is returning a const reference. 9610 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9611 SourceLocation Loc) { 9612 // Update err_typecheck_assign_const and note_typecheck_assign_const 9613 // when this enum is changed. 9614 enum { 9615 ConstFunction, 9616 ConstVariable, 9617 ConstMember, 9618 ConstMethod, 9619 ConstUnknown, // Keep as last element 9620 }; 9621 9622 SourceRange ExprRange = E->getSourceRange(); 9623 9624 // Only emit one error on the first const found. All other consts will emit 9625 // a note to the error. 9626 bool DiagnosticEmitted = false; 9627 9628 // Track if the current expression is the result of a derefence, and if the 9629 // next checked expression is the result of a derefence. 9630 bool IsDereference = false; 9631 bool NextIsDereference = false; 9632 9633 // Loop to process MemberExpr chains. 9634 while (true) { 9635 IsDereference = NextIsDereference; 9636 NextIsDereference = false; 9637 9638 E = E->IgnoreParenImpCasts(); 9639 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9640 NextIsDereference = ME->isArrow(); 9641 const ValueDecl *VD = ME->getMemberDecl(); 9642 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9643 // Mutable fields can be modified even if the class is const. 9644 if (Field->isMutable()) { 9645 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9646 break; 9647 } 9648 9649 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9650 if (!DiagnosticEmitted) { 9651 S.Diag(Loc, diag::err_typecheck_assign_const) 9652 << ExprRange << ConstMember << false /*static*/ << Field 9653 << Field->getType(); 9654 DiagnosticEmitted = true; 9655 } 9656 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9657 << ConstMember << false /*static*/ << Field << Field->getType() 9658 << Field->getSourceRange(); 9659 } 9660 E = ME->getBase(); 9661 continue; 9662 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9663 if (VDecl->getType().isConstQualified()) { 9664 if (!DiagnosticEmitted) { 9665 S.Diag(Loc, diag::err_typecheck_assign_const) 9666 << ExprRange << ConstMember << true /*static*/ << VDecl 9667 << VDecl->getType(); 9668 DiagnosticEmitted = true; 9669 } 9670 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9671 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9672 << VDecl->getSourceRange(); 9673 } 9674 // Static fields do not inherit constness from parents. 9675 break; 9676 } 9677 break; 9678 } // End MemberExpr 9679 break; 9680 } 9681 9682 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9683 // Function calls 9684 const FunctionDecl *FD = CE->getDirectCallee(); 9685 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9686 if (!DiagnosticEmitted) { 9687 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9688 << ConstFunction << FD; 9689 DiagnosticEmitted = true; 9690 } 9691 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9692 diag::note_typecheck_assign_const) 9693 << ConstFunction << FD << FD->getReturnType() 9694 << FD->getReturnTypeSourceRange(); 9695 } 9696 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9697 // Point to variable declaration. 9698 if (const ValueDecl *VD = DRE->getDecl()) { 9699 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9700 if (!DiagnosticEmitted) { 9701 S.Diag(Loc, diag::err_typecheck_assign_const) 9702 << ExprRange << ConstVariable << VD << VD->getType(); 9703 DiagnosticEmitted = true; 9704 } 9705 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9706 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9707 } 9708 } 9709 } else if (isa<CXXThisExpr>(E)) { 9710 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9711 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9712 if (MD->isConst()) { 9713 if (!DiagnosticEmitted) { 9714 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9715 << ConstMethod << MD; 9716 DiagnosticEmitted = true; 9717 } 9718 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9719 << ConstMethod << MD << MD->getSourceRange(); 9720 } 9721 } 9722 } 9723 } 9724 9725 if (DiagnosticEmitted) 9726 return; 9727 9728 // Can't determine a more specific message, so display the generic error. 9729 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9730 } 9731 9732 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9733 /// emit an error and return true. If so, return false. 9734 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9735 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9736 SourceLocation OrigLoc = Loc; 9737 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9738 &Loc); 9739 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9740 IsLV = Expr::MLV_InvalidMessageExpression; 9741 if (IsLV == Expr::MLV_Valid) 9742 return false; 9743 9744 unsigned DiagID = 0; 9745 bool NeedType = false; 9746 switch (IsLV) { // C99 6.5.16p2 9747 case Expr::MLV_ConstQualified: 9748 // Use a specialized diagnostic when we're assigning to an object 9749 // from an enclosing function or block. 9750 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9751 if (NCCK == NCCK_Block) 9752 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9753 else 9754 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9755 break; 9756 } 9757 9758 // In ARC, use some specialized diagnostics for occasions where we 9759 // infer 'const'. These are always pseudo-strong variables. 9760 if (S.getLangOpts().ObjCAutoRefCount) { 9761 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9762 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9763 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9764 9765 // Use the normal diagnostic if it's pseudo-__strong but the 9766 // user actually wrote 'const'. 9767 if (var->isARCPseudoStrong() && 9768 (!var->getTypeSourceInfo() || 9769 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9770 // There are two pseudo-strong cases: 9771 // - self 9772 ObjCMethodDecl *method = S.getCurMethodDecl(); 9773 if (method && var == method->getSelfDecl()) 9774 DiagID = method->isClassMethod() 9775 ? diag::err_typecheck_arc_assign_self_class_method 9776 : diag::err_typecheck_arc_assign_self; 9777 9778 // - fast enumeration variables 9779 else 9780 DiagID = diag::err_typecheck_arr_assign_enumeration; 9781 9782 SourceRange Assign; 9783 if (Loc != OrigLoc) 9784 Assign = SourceRange(OrigLoc, OrigLoc); 9785 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9786 // We need to preserve the AST regardless, so migration tool 9787 // can do its job. 9788 return false; 9789 } 9790 } 9791 } 9792 9793 // If none of the special cases above are triggered, then this is a 9794 // simple const assignment. 9795 if (DiagID == 0) { 9796 DiagnoseConstAssignment(S, E, Loc); 9797 return true; 9798 } 9799 9800 break; 9801 case Expr::MLV_ConstAddrSpace: 9802 DiagnoseConstAssignment(S, E, Loc); 9803 return true; 9804 case Expr::MLV_ArrayType: 9805 case Expr::MLV_ArrayTemporary: 9806 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9807 NeedType = true; 9808 break; 9809 case Expr::MLV_NotObjectType: 9810 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9811 NeedType = true; 9812 break; 9813 case Expr::MLV_LValueCast: 9814 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9815 break; 9816 case Expr::MLV_Valid: 9817 llvm_unreachable("did not take early return for MLV_Valid"); 9818 case Expr::MLV_InvalidExpression: 9819 case Expr::MLV_MemberFunction: 9820 case Expr::MLV_ClassTemporary: 9821 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9822 break; 9823 case Expr::MLV_IncompleteType: 9824 case Expr::MLV_IncompleteVoidType: 9825 return S.RequireCompleteType(Loc, E->getType(), 9826 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9827 case Expr::MLV_DuplicateVectorComponents: 9828 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9829 break; 9830 case Expr::MLV_NoSetterProperty: 9831 llvm_unreachable("readonly properties should be processed differently"); 9832 case Expr::MLV_InvalidMessageExpression: 9833 DiagID = diag::error_readonly_message_assignment; 9834 break; 9835 case Expr::MLV_SubObjCPropertySetting: 9836 DiagID = diag::error_no_subobject_property_setting; 9837 break; 9838 } 9839 9840 SourceRange Assign; 9841 if (Loc != OrigLoc) 9842 Assign = SourceRange(OrigLoc, OrigLoc); 9843 if (NeedType) 9844 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9845 else 9846 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9847 return true; 9848 } 9849 9850 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9851 SourceLocation Loc, 9852 Sema &Sema) { 9853 // C / C++ fields 9854 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9855 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9856 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9857 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9858 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9859 } 9860 9861 // Objective-C instance variables 9862 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9863 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9864 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9865 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9866 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9867 if (RL && RR && RL->getDecl() == RR->getDecl()) 9868 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9869 } 9870 } 9871 9872 // C99 6.5.16.1 9873 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9874 SourceLocation Loc, 9875 QualType CompoundType) { 9876 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9877 9878 // Verify that LHS is a modifiable lvalue, and emit error if not. 9879 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9880 return QualType(); 9881 9882 QualType LHSType = LHSExpr->getType(); 9883 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9884 CompoundType; 9885 AssignConvertType ConvTy; 9886 if (CompoundType.isNull()) { 9887 Expr *RHSCheck = RHS.get(); 9888 9889 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9890 9891 QualType LHSTy(LHSType); 9892 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9893 if (RHS.isInvalid()) 9894 return QualType(); 9895 // Special case of NSObject attributes on c-style pointer types. 9896 if (ConvTy == IncompatiblePointer && 9897 ((Context.isObjCNSObjectType(LHSType) && 9898 RHSType->isObjCObjectPointerType()) || 9899 (Context.isObjCNSObjectType(RHSType) && 9900 LHSType->isObjCObjectPointerType()))) 9901 ConvTy = Compatible; 9902 9903 if (ConvTy == Compatible && 9904 LHSType->isObjCObjectType()) 9905 Diag(Loc, diag::err_objc_object_assignment) 9906 << LHSType; 9907 9908 // If the RHS is a unary plus or minus, check to see if they = and + are 9909 // right next to each other. If so, the user may have typo'd "x =+ 4" 9910 // instead of "x += 4". 9911 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9912 RHSCheck = ICE->getSubExpr(); 9913 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9914 if ((UO->getOpcode() == UO_Plus || 9915 UO->getOpcode() == UO_Minus) && 9916 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9917 // Only if the two operators are exactly adjacent. 9918 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9919 // And there is a space or other character before the subexpr of the 9920 // unary +/-. We don't want to warn on "x=-1". 9921 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9922 UO->getSubExpr()->getLocStart().isFileID()) { 9923 Diag(Loc, diag::warn_not_compound_assign) 9924 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9925 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9926 } 9927 } 9928 9929 if (ConvTy == Compatible) { 9930 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9931 // Warn about retain cycles where a block captures the LHS, but 9932 // not if the LHS is a simple variable into which the block is 9933 // being stored...unless that variable can be captured by reference! 9934 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9935 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9936 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9937 checkRetainCycles(LHSExpr, RHS.get()); 9938 9939 // It is safe to assign a weak reference into a strong variable. 9940 // Although this code can still have problems: 9941 // id x = self.weakProp; 9942 // id y = self.weakProp; 9943 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9944 // paths through the function. This should be revisited if 9945 // -Wrepeated-use-of-weak is made flow-sensitive. 9946 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9947 RHS.get()->getLocStart())) 9948 getCurFunction()->markSafeWeakUse(RHS.get()); 9949 9950 } else if (getLangOpts().ObjCAutoRefCount) { 9951 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9952 } 9953 } 9954 } else { 9955 // Compound assignment "x += y" 9956 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9957 } 9958 9959 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9960 RHS.get(), AA_Assigning)) 9961 return QualType(); 9962 9963 CheckForNullPointerDereference(*this, LHSExpr); 9964 9965 // C99 6.5.16p3: The type of an assignment expression is the type of the 9966 // left operand unless the left operand has qualified type, in which case 9967 // it is the unqualified version of the type of the left operand. 9968 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9969 // is converted to the type of the assignment expression (above). 9970 // C++ 5.17p1: the type of the assignment expression is that of its left 9971 // operand. 9972 return (getLangOpts().CPlusPlus 9973 ? LHSType : LHSType.getUnqualifiedType()); 9974 } 9975 9976 // Only ignore explicit casts to void. 9977 static bool IgnoreCommaOperand(const Expr *E) { 9978 E = E->IgnoreParens(); 9979 9980 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 9981 if (CE->getCastKind() == CK_ToVoid) { 9982 return true; 9983 } 9984 } 9985 9986 return false; 9987 } 9988 9989 // Look for instances where it is likely the comma operator is confused with 9990 // another operator. There is a whitelist of acceptable expressions for the 9991 // left hand side of the comma operator, otherwise emit a warning. 9992 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 9993 // No warnings in macros 9994 if (Loc.isMacroID()) 9995 return; 9996 9997 // Don't warn in template instantiations. 9998 if (!ActiveTemplateInstantiations.empty()) 9999 return; 10000 10001 // Scope isn't fine-grained enough to whitelist the specific cases, so 10002 // instead, skip more than needed, then call back into here with the 10003 // CommaVisitor in SemaStmt.cpp. 10004 // The whitelisted locations are the initialization and increment portions 10005 // of a for loop. The additional checks are on the condition of 10006 // if statements, do/while loops, and for loops. 10007 const unsigned ForIncrementFlags = 10008 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10009 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10010 const unsigned ScopeFlags = getCurScope()->getFlags(); 10011 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10012 (ScopeFlags & ForInitFlags) == ForInitFlags) 10013 return; 10014 10015 // If there are multiple comma operators used together, get the RHS of the 10016 // of the comma operator as the LHS. 10017 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10018 if (BO->getOpcode() != BO_Comma) 10019 break; 10020 LHS = BO->getRHS(); 10021 } 10022 10023 // Only allow some expressions on LHS to not warn. 10024 if (IgnoreCommaOperand(LHS)) 10025 return; 10026 10027 Diag(Loc, diag::warn_comma_operator); 10028 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10029 << LHS->getSourceRange() 10030 << FixItHint::CreateInsertion(LHS->getLocStart(), 10031 LangOpts.CPlusPlus ? "static_cast<void>(" 10032 : "(void)(") 10033 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10034 ")"); 10035 } 10036 10037 // C99 6.5.17 10038 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10039 SourceLocation Loc) { 10040 LHS = S.CheckPlaceholderExpr(LHS.get()); 10041 RHS = S.CheckPlaceholderExpr(RHS.get()); 10042 if (LHS.isInvalid() || RHS.isInvalid()) 10043 return QualType(); 10044 10045 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10046 // operands, but not unary promotions. 10047 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10048 10049 // So we treat the LHS as a ignored value, and in C++ we allow the 10050 // containing site to determine what should be done with the RHS. 10051 LHS = S.IgnoredValueConversions(LHS.get()); 10052 if (LHS.isInvalid()) 10053 return QualType(); 10054 10055 S.DiagnoseUnusedExprResult(LHS.get()); 10056 10057 if (!S.getLangOpts().CPlusPlus) { 10058 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10059 if (RHS.isInvalid()) 10060 return QualType(); 10061 if (!RHS.get()->getType()->isVoidType()) 10062 S.RequireCompleteType(Loc, RHS.get()->getType(), 10063 diag::err_incomplete_type); 10064 } 10065 10066 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10067 S.DiagnoseCommaOperator(LHS.get(), Loc); 10068 10069 return RHS.get()->getType(); 10070 } 10071 10072 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10073 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10074 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10075 ExprValueKind &VK, 10076 ExprObjectKind &OK, 10077 SourceLocation OpLoc, 10078 bool IsInc, bool IsPrefix) { 10079 if (Op->isTypeDependent()) 10080 return S.Context.DependentTy; 10081 10082 QualType ResType = Op->getType(); 10083 // Atomic types can be used for increment / decrement where the non-atomic 10084 // versions can, so ignore the _Atomic() specifier for the purpose of 10085 // checking. 10086 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10087 ResType = ResAtomicType->getValueType(); 10088 10089 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10090 10091 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10092 // Decrement of bool is not allowed. 10093 if (!IsInc) { 10094 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10095 return QualType(); 10096 } 10097 // Increment of bool sets it to true, but is deprecated. 10098 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10099 : diag::warn_increment_bool) 10100 << Op->getSourceRange(); 10101 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10102 // Error on enum increments and decrements in C++ mode 10103 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10104 return QualType(); 10105 } else if (ResType->isRealType()) { 10106 // OK! 10107 } else if (ResType->isPointerType()) { 10108 // C99 6.5.2.4p2, 6.5.6p2 10109 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10110 return QualType(); 10111 } else if (ResType->isObjCObjectPointerType()) { 10112 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10113 // Otherwise, we just need a complete type. 10114 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10115 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10116 return QualType(); 10117 } else if (ResType->isAnyComplexType()) { 10118 // C99 does not support ++/-- on complex types, we allow as an extension. 10119 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10120 << ResType << Op->getSourceRange(); 10121 } else if (ResType->isPlaceholderType()) { 10122 ExprResult PR = S.CheckPlaceholderExpr(Op); 10123 if (PR.isInvalid()) return QualType(); 10124 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10125 IsInc, IsPrefix); 10126 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10127 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10128 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10129 (ResType->getAs<VectorType>()->getVectorKind() != 10130 VectorType::AltiVecBool)) { 10131 // The z vector extensions allow ++ and -- for non-bool vectors. 10132 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10133 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10134 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10135 } else { 10136 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10137 << ResType << int(IsInc) << Op->getSourceRange(); 10138 return QualType(); 10139 } 10140 // At this point, we know we have a real, complex or pointer type. 10141 // Now make sure the operand is a modifiable lvalue. 10142 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10143 return QualType(); 10144 // In C++, a prefix increment is the same type as the operand. Otherwise 10145 // (in C or with postfix), the increment is the unqualified type of the 10146 // operand. 10147 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10148 VK = VK_LValue; 10149 OK = Op->getObjectKind(); 10150 return ResType; 10151 } else { 10152 VK = VK_RValue; 10153 return ResType.getUnqualifiedType(); 10154 } 10155 } 10156 10157 10158 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10159 /// This routine allows us to typecheck complex/recursive expressions 10160 /// where the declaration is needed for type checking. We only need to 10161 /// handle cases when the expression references a function designator 10162 /// or is an lvalue. Here are some examples: 10163 /// - &(x) => x 10164 /// - &*****f => f for f a function designator. 10165 /// - &s.xx => s 10166 /// - &s.zz[1].yy -> s, if zz is an array 10167 /// - *(x + 1) -> x, if x is an array 10168 /// - &"123"[2] -> 0 10169 /// - & __real__ x -> x 10170 static ValueDecl *getPrimaryDecl(Expr *E) { 10171 switch (E->getStmtClass()) { 10172 case Stmt::DeclRefExprClass: 10173 return cast<DeclRefExpr>(E)->getDecl(); 10174 case Stmt::MemberExprClass: 10175 // If this is an arrow operator, the address is an offset from 10176 // the base's value, so the object the base refers to is 10177 // irrelevant. 10178 if (cast<MemberExpr>(E)->isArrow()) 10179 return nullptr; 10180 // Otherwise, the expression refers to a part of the base 10181 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10182 case Stmt::ArraySubscriptExprClass: { 10183 // FIXME: This code shouldn't be necessary! We should catch the implicit 10184 // promotion of register arrays earlier. 10185 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10186 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10187 if (ICE->getSubExpr()->getType()->isArrayType()) 10188 return getPrimaryDecl(ICE->getSubExpr()); 10189 } 10190 return nullptr; 10191 } 10192 case Stmt::UnaryOperatorClass: { 10193 UnaryOperator *UO = cast<UnaryOperator>(E); 10194 10195 switch(UO->getOpcode()) { 10196 case UO_Real: 10197 case UO_Imag: 10198 case UO_Extension: 10199 return getPrimaryDecl(UO->getSubExpr()); 10200 default: 10201 return nullptr; 10202 } 10203 } 10204 case Stmt::ParenExprClass: 10205 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10206 case Stmt::ImplicitCastExprClass: 10207 // If the result of an implicit cast is an l-value, we care about 10208 // the sub-expression; otherwise, the result here doesn't matter. 10209 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10210 default: 10211 return nullptr; 10212 } 10213 } 10214 10215 namespace { 10216 enum { 10217 AO_Bit_Field = 0, 10218 AO_Vector_Element = 1, 10219 AO_Property_Expansion = 2, 10220 AO_Register_Variable = 3, 10221 AO_No_Error = 4 10222 }; 10223 } 10224 /// \brief Diagnose invalid operand for address of operations. 10225 /// 10226 /// \param Type The type of operand which cannot have its address taken. 10227 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10228 Expr *E, unsigned Type) { 10229 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10230 } 10231 10232 /// CheckAddressOfOperand - The operand of & must be either a function 10233 /// designator or an lvalue designating an object. If it is an lvalue, the 10234 /// object cannot be declared with storage class register or be a bit field. 10235 /// Note: The usual conversions are *not* applied to the operand of the & 10236 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10237 /// In C++, the operand might be an overloaded function name, in which case 10238 /// we allow the '&' but retain the overloaded-function type. 10239 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10240 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10241 if (PTy->getKind() == BuiltinType::Overload) { 10242 Expr *E = OrigOp.get()->IgnoreParens(); 10243 if (!isa<OverloadExpr>(E)) { 10244 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10245 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10246 << OrigOp.get()->getSourceRange(); 10247 return QualType(); 10248 } 10249 10250 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10251 if (isa<UnresolvedMemberExpr>(Ovl)) 10252 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10253 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10254 << OrigOp.get()->getSourceRange(); 10255 return QualType(); 10256 } 10257 10258 return Context.OverloadTy; 10259 } 10260 10261 if (PTy->getKind() == BuiltinType::UnknownAny) 10262 return Context.UnknownAnyTy; 10263 10264 if (PTy->getKind() == BuiltinType::BoundMember) { 10265 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10266 << OrigOp.get()->getSourceRange(); 10267 return QualType(); 10268 } 10269 10270 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10271 if (OrigOp.isInvalid()) return QualType(); 10272 } 10273 10274 if (OrigOp.get()->isTypeDependent()) 10275 return Context.DependentTy; 10276 10277 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10278 10279 // Make sure to ignore parentheses in subsequent checks 10280 Expr *op = OrigOp.get()->IgnoreParens(); 10281 10282 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10283 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10284 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10285 return QualType(); 10286 } 10287 10288 if (getLangOpts().C99) { 10289 // Implement C99-only parts of addressof rules. 10290 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10291 if (uOp->getOpcode() == UO_Deref) 10292 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10293 // (assuming the deref expression is valid). 10294 return uOp->getSubExpr()->getType(); 10295 } 10296 // Technically, there should be a check for array subscript 10297 // expressions here, but the result of one is always an lvalue anyway. 10298 } 10299 ValueDecl *dcl = getPrimaryDecl(op); 10300 10301 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10302 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10303 op->getLocStart())) 10304 return QualType(); 10305 10306 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10307 unsigned AddressOfError = AO_No_Error; 10308 10309 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10310 bool sfinae = (bool)isSFINAEContext(); 10311 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10312 : diag::ext_typecheck_addrof_temporary) 10313 << op->getType() << op->getSourceRange(); 10314 if (sfinae) 10315 return QualType(); 10316 // Materialize the temporary as an lvalue so that we can take its address. 10317 OrigOp = op = new (Context) 10318 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10319 } else if (isa<ObjCSelectorExpr>(op)) { 10320 return Context.getPointerType(op->getType()); 10321 } else if (lval == Expr::LV_MemberFunction) { 10322 // If it's an instance method, make a member pointer. 10323 // The expression must have exactly the form &A::foo. 10324 10325 // If the underlying expression isn't a decl ref, give up. 10326 if (!isa<DeclRefExpr>(op)) { 10327 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10328 << OrigOp.get()->getSourceRange(); 10329 return QualType(); 10330 } 10331 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10332 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10333 10334 // The id-expression was parenthesized. 10335 if (OrigOp.get() != DRE) { 10336 Diag(OpLoc, diag::err_parens_pointer_member_function) 10337 << OrigOp.get()->getSourceRange(); 10338 10339 // The method was named without a qualifier. 10340 } else if (!DRE->getQualifier()) { 10341 if (MD->getParent()->getName().empty()) 10342 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10343 << op->getSourceRange(); 10344 else { 10345 SmallString<32> Str; 10346 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10347 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10348 << op->getSourceRange() 10349 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10350 } 10351 } 10352 10353 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10354 if (isa<CXXDestructorDecl>(MD)) 10355 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10356 10357 QualType MPTy = Context.getMemberPointerType( 10358 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10359 // Under the MS ABI, lock down the inheritance model now. 10360 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10361 (void)isCompleteType(OpLoc, MPTy); 10362 return MPTy; 10363 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10364 // C99 6.5.3.2p1 10365 // The operand must be either an l-value or a function designator 10366 if (!op->getType()->isFunctionType()) { 10367 // Use a special diagnostic for loads from property references. 10368 if (isa<PseudoObjectExpr>(op)) { 10369 AddressOfError = AO_Property_Expansion; 10370 } else { 10371 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10372 << op->getType() << op->getSourceRange(); 10373 return QualType(); 10374 } 10375 } 10376 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10377 // The operand cannot be a bit-field 10378 AddressOfError = AO_Bit_Field; 10379 } else if (op->getObjectKind() == OK_VectorComponent) { 10380 // The operand cannot be an element of a vector 10381 AddressOfError = AO_Vector_Element; 10382 } else if (dcl) { // C99 6.5.3.2p1 10383 // We have an lvalue with a decl. Make sure the decl is not declared 10384 // with the register storage-class specifier. 10385 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10386 // in C++ it is not error to take address of a register 10387 // variable (c++03 7.1.1P3) 10388 if (vd->getStorageClass() == SC_Register && 10389 !getLangOpts().CPlusPlus) { 10390 AddressOfError = AO_Register_Variable; 10391 } 10392 } else if (isa<MSPropertyDecl>(dcl)) { 10393 AddressOfError = AO_Property_Expansion; 10394 } else if (isa<FunctionTemplateDecl>(dcl)) { 10395 return Context.OverloadTy; 10396 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10397 // Okay: we can take the address of a field. 10398 // Could be a pointer to member, though, if there is an explicit 10399 // scope qualifier for the class. 10400 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10401 DeclContext *Ctx = dcl->getDeclContext(); 10402 if (Ctx && Ctx->isRecord()) { 10403 if (dcl->getType()->isReferenceType()) { 10404 Diag(OpLoc, 10405 diag::err_cannot_form_pointer_to_member_of_reference_type) 10406 << dcl->getDeclName() << dcl->getType(); 10407 return QualType(); 10408 } 10409 10410 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10411 Ctx = Ctx->getParent(); 10412 10413 QualType MPTy = Context.getMemberPointerType( 10414 op->getType(), 10415 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10416 // Under the MS ABI, lock down the inheritance model now. 10417 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10418 (void)isCompleteType(OpLoc, MPTy); 10419 return MPTy; 10420 } 10421 } 10422 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10423 llvm_unreachable("Unknown/unexpected decl type"); 10424 } 10425 10426 if (AddressOfError != AO_No_Error) { 10427 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10428 return QualType(); 10429 } 10430 10431 if (lval == Expr::LV_IncompleteVoidType) { 10432 // Taking the address of a void variable is technically illegal, but we 10433 // allow it in cases which are otherwise valid. 10434 // Example: "extern void x; void* y = &x;". 10435 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10436 } 10437 10438 // If the operand has type "type", the result has type "pointer to type". 10439 if (op->getType()->isObjCObjectType()) 10440 return Context.getObjCObjectPointerType(op->getType()); 10441 10442 // OpenCL v2.0 s6.12.5 - The unary operators & cannot be used with a block. 10443 if (getLangOpts().OpenCL && OrigOp.get()->getType()->isBlockPointerType()) { 10444 Diag(OpLoc, diag::err_typecheck_unary_expr) << OrigOp.get()->getType() 10445 << op->getSourceRange(); 10446 return QualType(); 10447 } 10448 10449 return Context.getPointerType(op->getType()); 10450 } 10451 10452 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10453 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10454 if (!DRE) 10455 return; 10456 const Decl *D = DRE->getDecl(); 10457 if (!D) 10458 return; 10459 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10460 if (!Param) 10461 return; 10462 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10463 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10464 return; 10465 if (FunctionScopeInfo *FD = S.getCurFunction()) 10466 if (!FD->ModifiedNonNullParams.count(Param)) 10467 FD->ModifiedNonNullParams.insert(Param); 10468 } 10469 10470 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10471 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10472 SourceLocation OpLoc) { 10473 if (Op->isTypeDependent()) 10474 return S.Context.DependentTy; 10475 10476 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10477 if (ConvResult.isInvalid()) 10478 return QualType(); 10479 Op = ConvResult.get(); 10480 QualType OpTy = Op->getType(); 10481 QualType Result; 10482 10483 if (isa<CXXReinterpretCastExpr>(Op)) { 10484 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10485 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10486 Op->getSourceRange()); 10487 } 10488 10489 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10490 { 10491 Result = PT->getPointeeType(); 10492 // OpenCL v2.0 s6.12.5 - The unary operators * cannot be used with a block. 10493 if (S.getLangOpts().OpenCLVersion >= 200 && Result->isBlockPointerType()) { 10494 S.Diag(OpLoc, diag::err_opencl_dereferencing) << OpTy 10495 << Op->getSourceRange(); 10496 return QualType(); 10497 } 10498 } 10499 else if (const ObjCObjectPointerType *OPT = 10500 OpTy->getAs<ObjCObjectPointerType>()) 10501 Result = OPT->getPointeeType(); 10502 else { 10503 ExprResult PR = S.CheckPlaceholderExpr(Op); 10504 if (PR.isInvalid()) return QualType(); 10505 if (PR.get() != Op) 10506 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10507 } 10508 10509 if (Result.isNull()) { 10510 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10511 << OpTy << Op->getSourceRange(); 10512 return QualType(); 10513 } 10514 10515 // Note that per both C89 and C99, indirection is always legal, even if Result 10516 // is an incomplete type or void. It would be possible to warn about 10517 // dereferencing a void pointer, but it's completely well-defined, and such a 10518 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10519 // for pointers to 'void' but is fine for any other pointer type: 10520 // 10521 // C++ [expr.unary.op]p1: 10522 // [...] the expression to which [the unary * operator] is applied shall 10523 // be a pointer to an object type, or a pointer to a function type 10524 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10525 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10526 << OpTy << Op->getSourceRange(); 10527 10528 // Dereferences are usually l-values... 10529 VK = VK_LValue; 10530 10531 // ...except that certain expressions are never l-values in C. 10532 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10533 VK = VK_RValue; 10534 10535 return Result; 10536 } 10537 10538 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10539 BinaryOperatorKind Opc; 10540 switch (Kind) { 10541 default: llvm_unreachable("Unknown binop!"); 10542 case tok::periodstar: Opc = BO_PtrMemD; break; 10543 case tok::arrowstar: Opc = BO_PtrMemI; break; 10544 case tok::star: Opc = BO_Mul; break; 10545 case tok::slash: Opc = BO_Div; break; 10546 case tok::percent: Opc = BO_Rem; break; 10547 case tok::plus: Opc = BO_Add; break; 10548 case tok::minus: Opc = BO_Sub; break; 10549 case tok::lessless: Opc = BO_Shl; break; 10550 case tok::greatergreater: Opc = BO_Shr; break; 10551 case tok::lessequal: Opc = BO_LE; break; 10552 case tok::less: Opc = BO_LT; break; 10553 case tok::greaterequal: Opc = BO_GE; break; 10554 case tok::greater: Opc = BO_GT; break; 10555 case tok::exclaimequal: Opc = BO_NE; break; 10556 case tok::equalequal: Opc = BO_EQ; break; 10557 case tok::amp: Opc = BO_And; break; 10558 case tok::caret: Opc = BO_Xor; break; 10559 case tok::pipe: Opc = BO_Or; break; 10560 case tok::ampamp: Opc = BO_LAnd; break; 10561 case tok::pipepipe: Opc = BO_LOr; break; 10562 case tok::equal: Opc = BO_Assign; break; 10563 case tok::starequal: Opc = BO_MulAssign; break; 10564 case tok::slashequal: Opc = BO_DivAssign; break; 10565 case tok::percentequal: Opc = BO_RemAssign; break; 10566 case tok::plusequal: Opc = BO_AddAssign; break; 10567 case tok::minusequal: Opc = BO_SubAssign; break; 10568 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10569 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10570 case tok::ampequal: Opc = BO_AndAssign; break; 10571 case tok::caretequal: Opc = BO_XorAssign; break; 10572 case tok::pipeequal: Opc = BO_OrAssign; break; 10573 case tok::comma: Opc = BO_Comma; break; 10574 } 10575 return Opc; 10576 } 10577 10578 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10579 tok::TokenKind Kind) { 10580 UnaryOperatorKind Opc; 10581 switch (Kind) { 10582 default: llvm_unreachable("Unknown unary op!"); 10583 case tok::plusplus: Opc = UO_PreInc; break; 10584 case tok::minusminus: Opc = UO_PreDec; break; 10585 case tok::amp: Opc = UO_AddrOf; break; 10586 case tok::star: Opc = UO_Deref; break; 10587 case tok::plus: Opc = UO_Plus; break; 10588 case tok::minus: Opc = UO_Minus; break; 10589 case tok::tilde: Opc = UO_Not; break; 10590 case tok::exclaim: Opc = UO_LNot; break; 10591 case tok::kw___real: Opc = UO_Real; break; 10592 case tok::kw___imag: Opc = UO_Imag; break; 10593 case tok::kw___extension__: Opc = UO_Extension; break; 10594 } 10595 return Opc; 10596 } 10597 10598 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10599 /// This warning is only emitted for builtin assignment operations. It is also 10600 /// suppressed in the event of macro expansions. 10601 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10602 SourceLocation OpLoc) { 10603 if (!S.ActiveTemplateInstantiations.empty()) 10604 return; 10605 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10606 return; 10607 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10608 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10609 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10610 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10611 if (!LHSDeclRef || !RHSDeclRef || 10612 LHSDeclRef->getLocation().isMacroID() || 10613 RHSDeclRef->getLocation().isMacroID()) 10614 return; 10615 const ValueDecl *LHSDecl = 10616 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10617 const ValueDecl *RHSDecl = 10618 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10619 if (LHSDecl != RHSDecl) 10620 return; 10621 if (LHSDecl->getType().isVolatileQualified()) 10622 return; 10623 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10624 if (RefTy->getPointeeType().isVolatileQualified()) 10625 return; 10626 10627 S.Diag(OpLoc, diag::warn_self_assignment) 10628 << LHSDeclRef->getType() 10629 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10630 } 10631 10632 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10633 /// is usually indicative of introspection within the Objective-C pointer. 10634 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10635 SourceLocation OpLoc) { 10636 if (!S.getLangOpts().ObjC1) 10637 return; 10638 10639 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10640 const Expr *LHS = L.get(); 10641 const Expr *RHS = R.get(); 10642 10643 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10644 ObjCPointerExpr = LHS; 10645 OtherExpr = RHS; 10646 } 10647 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10648 ObjCPointerExpr = RHS; 10649 OtherExpr = LHS; 10650 } 10651 10652 // This warning is deliberately made very specific to reduce false 10653 // positives with logic that uses '&' for hashing. This logic mainly 10654 // looks for code trying to introspect into tagged pointers, which 10655 // code should generally never do. 10656 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10657 unsigned Diag = diag::warn_objc_pointer_masking; 10658 // Determine if we are introspecting the result of performSelectorXXX. 10659 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10660 // Special case messages to -performSelector and friends, which 10661 // can return non-pointer values boxed in a pointer value. 10662 // Some clients may wish to silence warnings in this subcase. 10663 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10664 Selector S = ME->getSelector(); 10665 StringRef SelArg0 = S.getNameForSlot(0); 10666 if (SelArg0.startswith("performSelector")) 10667 Diag = diag::warn_objc_pointer_masking_performSelector; 10668 } 10669 10670 S.Diag(OpLoc, Diag) 10671 << ObjCPointerExpr->getSourceRange(); 10672 } 10673 } 10674 10675 static NamedDecl *getDeclFromExpr(Expr *E) { 10676 if (!E) 10677 return nullptr; 10678 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10679 return DRE->getDecl(); 10680 if (auto *ME = dyn_cast<MemberExpr>(E)) 10681 return ME->getMemberDecl(); 10682 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10683 return IRE->getDecl(); 10684 return nullptr; 10685 } 10686 10687 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10688 /// operator @p Opc at location @c TokLoc. This routine only supports 10689 /// built-in operations; ActOnBinOp handles overloaded operators. 10690 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10691 BinaryOperatorKind Opc, 10692 Expr *LHSExpr, Expr *RHSExpr) { 10693 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10694 // The syntax only allows initializer lists on the RHS of assignment, 10695 // so we don't need to worry about accepting invalid code for 10696 // non-assignment operators. 10697 // C++11 5.17p9: 10698 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10699 // of x = {} is x = T(). 10700 InitializationKind Kind = 10701 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10702 InitializedEntity Entity = 10703 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10704 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10705 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10706 if (Init.isInvalid()) 10707 return Init; 10708 RHSExpr = Init.get(); 10709 } 10710 10711 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10712 QualType ResultTy; // Result type of the binary operator. 10713 // The following two variables are used for compound assignment operators 10714 QualType CompLHSTy; // Type of LHS after promotions for computation 10715 QualType CompResultTy; // Type of computation result 10716 ExprValueKind VK = VK_RValue; 10717 ExprObjectKind OK = OK_Ordinary; 10718 10719 if (!getLangOpts().CPlusPlus) { 10720 // C cannot handle TypoExpr nodes on either side of a binop because it 10721 // doesn't handle dependent types properly, so make sure any TypoExprs have 10722 // been dealt with before checking the operands. 10723 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10724 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10725 if (Opc != BO_Assign) 10726 return ExprResult(E); 10727 // Avoid correcting the RHS to the same Expr as the LHS. 10728 Decl *D = getDeclFromExpr(E); 10729 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10730 }); 10731 if (!LHS.isUsable() || !RHS.isUsable()) 10732 return ExprError(); 10733 } 10734 10735 if (getLangOpts().OpenCL) { 10736 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10737 // the ATOMIC_VAR_INIT macro. 10738 if (LHSExpr->getType()->isAtomicType() || 10739 RHSExpr->getType()->isAtomicType()) { 10740 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10741 if (BO_Assign == Opc) 10742 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10743 else 10744 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10745 return ExprError(); 10746 } 10747 } 10748 10749 switch (Opc) { 10750 case BO_Assign: 10751 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10752 if (getLangOpts().CPlusPlus && 10753 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10754 VK = LHS.get()->getValueKind(); 10755 OK = LHS.get()->getObjectKind(); 10756 } 10757 if (!ResultTy.isNull()) { 10758 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10759 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10760 } 10761 RecordModifiableNonNullParam(*this, LHS.get()); 10762 break; 10763 case BO_PtrMemD: 10764 case BO_PtrMemI: 10765 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10766 Opc == BO_PtrMemI); 10767 break; 10768 case BO_Mul: 10769 case BO_Div: 10770 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10771 Opc == BO_Div); 10772 break; 10773 case BO_Rem: 10774 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10775 break; 10776 case BO_Add: 10777 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10778 break; 10779 case BO_Sub: 10780 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10781 break; 10782 case BO_Shl: 10783 case BO_Shr: 10784 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10785 break; 10786 case BO_LE: 10787 case BO_LT: 10788 case BO_GE: 10789 case BO_GT: 10790 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10791 break; 10792 case BO_EQ: 10793 case BO_NE: 10794 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10795 break; 10796 case BO_And: 10797 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10798 case BO_Xor: 10799 case BO_Or: 10800 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10801 break; 10802 case BO_LAnd: 10803 case BO_LOr: 10804 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10805 break; 10806 case BO_MulAssign: 10807 case BO_DivAssign: 10808 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10809 Opc == BO_DivAssign); 10810 CompLHSTy = CompResultTy; 10811 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10812 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10813 break; 10814 case BO_RemAssign: 10815 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10816 CompLHSTy = CompResultTy; 10817 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10818 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10819 break; 10820 case BO_AddAssign: 10821 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10822 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10823 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10824 break; 10825 case BO_SubAssign: 10826 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10827 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10828 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10829 break; 10830 case BO_ShlAssign: 10831 case BO_ShrAssign: 10832 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10833 CompLHSTy = CompResultTy; 10834 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10835 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10836 break; 10837 case BO_AndAssign: 10838 case BO_OrAssign: // fallthrough 10839 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10840 case BO_XorAssign: 10841 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10842 CompLHSTy = CompResultTy; 10843 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10844 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10845 break; 10846 case BO_Comma: 10847 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10848 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10849 VK = RHS.get()->getValueKind(); 10850 OK = RHS.get()->getObjectKind(); 10851 } 10852 break; 10853 } 10854 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10855 return ExprError(); 10856 10857 // Check for array bounds violations for both sides of the BinaryOperator 10858 CheckArrayAccess(LHS.get()); 10859 CheckArrayAccess(RHS.get()); 10860 10861 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10862 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10863 &Context.Idents.get("object_setClass"), 10864 SourceLocation(), LookupOrdinaryName); 10865 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10866 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 10867 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10868 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10869 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10870 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10871 } 10872 else 10873 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10874 } 10875 else if (const ObjCIvarRefExpr *OIRE = 10876 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10877 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10878 10879 if (CompResultTy.isNull()) 10880 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10881 OK, OpLoc, FPFeatures.fp_contract); 10882 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10883 OK_ObjCProperty) { 10884 VK = VK_LValue; 10885 OK = LHS.get()->getObjectKind(); 10886 } 10887 return new (Context) CompoundAssignOperator( 10888 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10889 OpLoc, FPFeatures.fp_contract); 10890 } 10891 10892 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10893 /// operators are mixed in a way that suggests that the programmer forgot that 10894 /// comparison operators have higher precedence. The most typical example of 10895 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10896 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10897 SourceLocation OpLoc, Expr *LHSExpr, 10898 Expr *RHSExpr) { 10899 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10900 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10901 10902 // Check that one of the sides is a comparison operator and the other isn't. 10903 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10904 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10905 if (isLeftComp == isRightComp) 10906 return; 10907 10908 // Bitwise operations are sometimes used as eager logical ops. 10909 // Don't diagnose this. 10910 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10911 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10912 if (isLeftBitwise || isRightBitwise) 10913 return; 10914 10915 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10916 OpLoc) 10917 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10918 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10919 SourceRange ParensRange = isLeftComp ? 10920 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10921 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10922 10923 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10924 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10925 SuggestParentheses(Self, OpLoc, 10926 Self.PDiag(diag::note_precedence_silence) << OpStr, 10927 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10928 SuggestParentheses(Self, OpLoc, 10929 Self.PDiag(diag::note_precedence_bitwise_first) 10930 << BinaryOperator::getOpcodeStr(Opc), 10931 ParensRange); 10932 } 10933 10934 /// \brief It accepts a '&&' expr that is inside a '||' one. 10935 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10936 /// in parentheses. 10937 static void 10938 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10939 BinaryOperator *Bop) { 10940 assert(Bop->getOpcode() == BO_LAnd); 10941 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10942 << Bop->getSourceRange() << OpLoc; 10943 SuggestParentheses(Self, Bop->getOperatorLoc(), 10944 Self.PDiag(diag::note_precedence_silence) 10945 << Bop->getOpcodeStr(), 10946 Bop->getSourceRange()); 10947 } 10948 10949 /// \brief Returns true if the given expression can be evaluated as a constant 10950 /// 'true'. 10951 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10952 bool Res; 10953 return !E->isValueDependent() && 10954 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10955 } 10956 10957 /// \brief Returns true if the given expression can be evaluated as a constant 10958 /// 'false'. 10959 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10960 bool Res; 10961 return !E->isValueDependent() && 10962 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10963 } 10964 10965 /// \brief Look for '&&' in the left hand of a '||' expr. 10966 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10967 Expr *LHSExpr, Expr *RHSExpr) { 10968 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10969 if (Bop->getOpcode() == BO_LAnd) { 10970 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10971 if (EvaluatesAsFalse(S, RHSExpr)) 10972 return; 10973 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10974 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10975 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10976 } else if (Bop->getOpcode() == BO_LOr) { 10977 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10978 // If it's "a || b && 1 || c" we didn't warn earlier for 10979 // "a || b && 1", but warn now. 10980 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10981 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10982 } 10983 } 10984 } 10985 } 10986 10987 /// \brief Look for '&&' in the right hand of a '||' expr. 10988 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10989 Expr *LHSExpr, Expr *RHSExpr) { 10990 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10991 if (Bop->getOpcode() == BO_LAnd) { 10992 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10993 if (EvaluatesAsFalse(S, LHSExpr)) 10994 return; 10995 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10996 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10997 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10998 } 10999 } 11000 } 11001 11002 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11003 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11004 /// the '&' expression in parentheses. 11005 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11006 SourceLocation OpLoc, Expr *SubExpr) { 11007 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11008 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11009 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11010 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11011 << Bop->getSourceRange() << OpLoc; 11012 SuggestParentheses(S, Bop->getOperatorLoc(), 11013 S.PDiag(diag::note_precedence_silence) 11014 << Bop->getOpcodeStr(), 11015 Bop->getSourceRange()); 11016 } 11017 } 11018 } 11019 11020 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11021 Expr *SubExpr, StringRef Shift) { 11022 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11023 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11024 StringRef Op = Bop->getOpcodeStr(); 11025 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11026 << Bop->getSourceRange() << OpLoc << Shift << Op; 11027 SuggestParentheses(S, Bop->getOperatorLoc(), 11028 S.PDiag(diag::note_precedence_silence) << Op, 11029 Bop->getSourceRange()); 11030 } 11031 } 11032 } 11033 11034 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11035 Expr *LHSExpr, Expr *RHSExpr) { 11036 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11037 if (!OCE) 11038 return; 11039 11040 FunctionDecl *FD = OCE->getDirectCallee(); 11041 if (!FD || !FD->isOverloadedOperator()) 11042 return; 11043 11044 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11045 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11046 return; 11047 11048 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11049 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11050 << (Kind == OO_LessLess); 11051 SuggestParentheses(S, OCE->getOperatorLoc(), 11052 S.PDiag(diag::note_precedence_silence) 11053 << (Kind == OO_LessLess ? "<<" : ">>"), 11054 OCE->getSourceRange()); 11055 SuggestParentheses(S, OpLoc, 11056 S.PDiag(diag::note_evaluate_comparison_first), 11057 SourceRange(OCE->getArg(1)->getLocStart(), 11058 RHSExpr->getLocEnd())); 11059 } 11060 11061 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11062 /// precedence. 11063 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11064 SourceLocation OpLoc, Expr *LHSExpr, 11065 Expr *RHSExpr){ 11066 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11067 if (BinaryOperator::isBitwiseOp(Opc)) 11068 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11069 11070 // Diagnose "arg1 & arg2 | arg3" 11071 if ((Opc == BO_Or || Opc == BO_Xor) && 11072 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11073 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11074 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11075 } 11076 11077 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11078 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11079 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11080 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11081 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11082 } 11083 11084 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11085 || Opc == BO_Shr) { 11086 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11087 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11088 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11089 } 11090 11091 // Warn on overloaded shift operators and comparisons, such as: 11092 // cout << 5 == 4; 11093 if (BinaryOperator::isComparisonOp(Opc)) 11094 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11095 } 11096 11097 // Binary Operators. 'Tok' is the token for the operator. 11098 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11099 tok::TokenKind Kind, 11100 Expr *LHSExpr, Expr *RHSExpr) { 11101 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11102 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11103 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11104 11105 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11106 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11107 11108 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11109 } 11110 11111 /// Build an overloaded binary operator expression in the given scope. 11112 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11113 BinaryOperatorKind Opc, 11114 Expr *LHS, Expr *RHS) { 11115 // Find all of the overloaded operators visible from this 11116 // point. We perform both an operator-name lookup from the local 11117 // scope and an argument-dependent lookup based on the types of 11118 // the arguments. 11119 UnresolvedSet<16> Functions; 11120 OverloadedOperatorKind OverOp 11121 = BinaryOperator::getOverloadedOperator(Opc); 11122 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11123 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11124 RHS->getType(), Functions); 11125 11126 // Build the (potentially-overloaded, potentially-dependent) 11127 // binary operation. 11128 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11129 } 11130 11131 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11132 BinaryOperatorKind Opc, 11133 Expr *LHSExpr, Expr *RHSExpr) { 11134 // We want to end up calling one of checkPseudoObjectAssignment 11135 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11136 // both expressions are overloadable or either is type-dependent), 11137 // or CreateBuiltinBinOp (in any other case). We also want to get 11138 // any placeholder types out of the way. 11139 11140 // Handle pseudo-objects in the LHS. 11141 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11142 // Assignments with a pseudo-object l-value need special analysis. 11143 if (pty->getKind() == BuiltinType::PseudoObject && 11144 BinaryOperator::isAssignmentOp(Opc)) 11145 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11146 11147 // Don't resolve overloads if the other type is overloadable. 11148 if (pty->getKind() == BuiltinType::Overload) { 11149 // We can't actually test that if we still have a placeholder, 11150 // though. Fortunately, none of the exceptions we see in that 11151 // code below are valid when the LHS is an overload set. Note 11152 // that an overload set can be dependently-typed, but it never 11153 // instantiates to having an overloadable type. 11154 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11155 if (resolvedRHS.isInvalid()) return ExprError(); 11156 RHSExpr = resolvedRHS.get(); 11157 11158 if (RHSExpr->isTypeDependent() || 11159 RHSExpr->getType()->isOverloadableType()) 11160 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11161 } 11162 11163 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11164 if (LHS.isInvalid()) return ExprError(); 11165 LHSExpr = LHS.get(); 11166 } 11167 11168 // Handle pseudo-objects in the RHS. 11169 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11170 // An overload in the RHS can potentially be resolved by the type 11171 // being assigned to. 11172 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11173 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11174 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11175 11176 if (LHSExpr->getType()->isOverloadableType()) 11177 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11178 11179 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11180 } 11181 11182 // Don't resolve overloads if the other type is overloadable. 11183 if (pty->getKind() == BuiltinType::Overload && 11184 LHSExpr->getType()->isOverloadableType()) 11185 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11186 11187 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11188 if (!resolvedRHS.isUsable()) return ExprError(); 11189 RHSExpr = resolvedRHS.get(); 11190 } 11191 11192 if (getLangOpts().CPlusPlus) { 11193 // If either expression is type-dependent, always build an 11194 // overloaded op. 11195 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11196 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11197 11198 // Otherwise, build an overloaded op if either expression has an 11199 // overloadable type. 11200 if (LHSExpr->getType()->isOverloadableType() || 11201 RHSExpr->getType()->isOverloadableType()) 11202 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11203 } 11204 11205 // Build a built-in binary operation. 11206 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11207 } 11208 11209 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11210 UnaryOperatorKind Opc, 11211 Expr *InputExpr) { 11212 ExprResult Input = InputExpr; 11213 ExprValueKind VK = VK_RValue; 11214 ExprObjectKind OK = OK_Ordinary; 11215 QualType resultType; 11216 if (getLangOpts().OpenCL) { 11217 // The only legal unary operation for atomics is '&'. 11218 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 11219 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11220 << InputExpr->getType() 11221 << Input.get()->getSourceRange()); 11222 } 11223 } 11224 switch (Opc) { 11225 case UO_PreInc: 11226 case UO_PreDec: 11227 case UO_PostInc: 11228 case UO_PostDec: 11229 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11230 OpLoc, 11231 Opc == UO_PreInc || 11232 Opc == UO_PostInc, 11233 Opc == UO_PreInc || 11234 Opc == UO_PreDec); 11235 break; 11236 case UO_AddrOf: 11237 resultType = CheckAddressOfOperand(Input, OpLoc); 11238 RecordModifiableNonNullParam(*this, InputExpr); 11239 break; 11240 case UO_Deref: { 11241 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11242 if (Input.isInvalid()) return ExprError(); 11243 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11244 break; 11245 } 11246 case UO_Plus: 11247 case UO_Minus: 11248 Input = UsualUnaryConversions(Input.get()); 11249 if (Input.isInvalid()) return ExprError(); 11250 resultType = Input.get()->getType(); 11251 if (resultType->isDependentType()) 11252 break; 11253 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11254 break; 11255 else if (resultType->isVectorType() && 11256 // The z vector extensions don't allow + or - with bool vectors. 11257 (!Context.getLangOpts().ZVector || 11258 resultType->getAs<VectorType>()->getVectorKind() != 11259 VectorType::AltiVecBool)) 11260 break; 11261 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11262 Opc == UO_Plus && 11263 resultType->isPointerType()) 11264 break; 11265 11266 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11267 << resultType << Input.get()->getSourceRange()); 11268 11269 case UO_Not: // bitwise complement 11270 Input = UsualUnaryConversions(Input.get()); 11271 if (Input.isInvalid()) 11272 return ExprError(); 11273 resultType = Input.get()->getType(); 11274 if (resultType->isDependentType()) 11275 break; 11276 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11277 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11278 // C99 does not support '~' for complex conjugation. 11279 Diag(OpLoc, diag::ext_integer_complement_complex) 11280 << resultType << Input.get()->getSourceRange(); 11281 else if (resultType->hasIntegerRepresentation()) 11282 break; 11283 else if (resultType->isExtVectorType()) { 11284 if (Context.getLangOpts().OpenCL) { 11285 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11286 // on vector float types. 11287 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11288 if (!T->isIntegerType()) 11289 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11290 << resultType << Input.get()->getSourceRange()); 11291 } 11292 break; 11293 } else { 11294 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11295 << resultType << Input.get()->getSourceRange()); 11296 } 11297 break; 11298 11299 case UO_LNot: // logical negation 11300 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11301 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11302 if (Input.isInvalid()) return ExprError(); 11303 resultType = Input.get()->getType(); 11304 11305 // Though we still have to promote half FP to float... 11306 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11307 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11308 resultType = Context.FloatTy; 11309 } 11310 11311 if (resultType->isDependentType()) 11312 break; 11313 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11314 // C99 6.5.3.3p1: ok, fallthrough; 11315 if (Context.getLangOpts().CPlusPlus) { 11316 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11317 // operand contextually converted to bool. 11318 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11319 ScalarTypeToBooleanCastKind(resultType)); 11320 } else if (Context.getLangOpts().OpenCL && 11321 Context.getLangOpts().OpenCLVersion < 120) { 11322 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11323 // operate on scalar float types. 11324 if (!resultType->isIntegerType()) 11325 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11326 << resultType << Input.get()->getSourceRange()); 11327 } 11328 } else if (resultType->isExtVectorType()) { 11329 if (Context.getLangOpts().OpenCL && 11330 Context.getLangOpts().OpenCLVersion < 120) { 11331 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11332 // operate on vector float types. 11333 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11334 if (!T->isIntegerType()) 11335 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11336 << resultType << Input.get()->getSourceRange()); 11337 } 11338 // Vector logical not returns the signed variant of the operand type. 11339 resultType = GetSignedVectorType(resultType); 11340 break; 11341 } else { 11342 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11343 << resultType << Input.get()->getSourceRange()); 11344 } 11345 11346 // LNot always has type int. C99 6.5.3.3p5. 11347 // In C++, it's bool. C++ 5.3.1p8 11348 resultType = Context.getLogicalOperationType(); 11349 break; 11350 case UO_Real: 11351 case UO_Imag: 11352 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11353 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11354 // complex l-values to ordinary l-values and all other values to r-values. 11355 if (Input.isInvalid()) return ExprError(); 11356 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11357 if (Input.get()->getValueKind() != VK_RValue && 11358 Input.get()->getObjectKind() == OK_Ordinary) 11359 VK = Input.get()->getValueKind(); 11360 } else if (!getLangOpts().CPlusPlus) { 11361 // In C, a volatile scalar is read by __imag. In C++, it is not. 11362 Input = DefaultLvalueConversion(Input.get()); 11363 } 11364 break; 11365 case UO_Extension: 11366 case UO_Coawait: 11367 resultType = Input.get()->getType(); 11368 VK = Input.get()->getValueKind(); 11369 OK = Input.get()->getObjectKind(); 11370 break; 11371 } 11372 if (resultType.isNull() || Input.isInvalid()) 11373 return ExprError(); 11374 11375 // Check for array bounds violations in the operand of the UnaryOperator, 11376 // except for the '*' and '&' operators that have to be handled specially 11377 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11378 // that are explicitly defined as valid by the standard). 11379 if (Opc != UO_AddrOf && Opc != UO_Deref) 11380 CheckArrayAccess(Input.get()); 11381 11382 return new (Context) 11383 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11384 } 11385 11386 /// \brief Determine whether the given expression is a qualified member 11387 /// access expression, of a form that could be turned into a pointer to member 11388 /// with the address-of operator. 11389 static bool isQualifiedMemberAccess(Expr *E) { 11390 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11391 if (!DRE->getQualifier()) 11392 return false; 11393 11394 ValueDecl *VD = DRE->getDecl(); 11395 if (!VD->isCXXClassMember()) 11396 return false; 11397 11398 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11399 return true; 11400 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11401 return Method->isInstance(); 11402 11403 return false; 11404 } 11405 11406 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11407 if (!ULE->getQualifier()) 11408 return false; 11409 11410 for (NamedDecl *D : ULE->decls()) { 11411 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11412 if (Method->isInstance()) 11413 return true; 11414 } else { 11415 // Overload set does not contain methods. 11416 break; 11417 } 11418 } 11419 11420 return false; 11421 } 11422 11423 return false; 11424 } 11425 11426 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11427 UnaryOperatorKind Opc, Expr *Input) { 11428 // First things first: handle placeholders so that the 11429 // overloaded-operator check considers the right type. 11430 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11431 // Increment and decrement of pseudo-object references. 11432 if (pty->getKind() == BuiltinType::PseudoObject && 11433 UnaryOperator::isIncrementDecrementOp(Opc)) 11434 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11435 11436 // extension is always a builtin operator. 11437 if (Opc == UO_Extension) 11438 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11439 11440 // & gets special logic for several kinds of placeholder. 11441 // The builtin code knows what to do. 11442 if (Opc == UO_AddrOf && 11443 (pty->getKind() == BuiltinType::Overload || 11444 pty->getKind() == BuiltinType::UnknownAny || 11445 pty->getKind() == BuiltinType::BoundMember)) 11446 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11447 11448 // Anything else needs to be handled now. 11449 ExprResult Result = CheckPlaceholderExpr(Input); 11450 if (Result.isInvalid()) return ExprError(); 11451 Input = Result.get(); 11452 } 11453 11454 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11455 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11456 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11457 // Find all of the overloaded operators visible from this 11458 // point. We perform both an operator-name lookup from the local 11459 // scope and an argument-dependent lookup based on the types of 11460 // the arguments. 11461 UnresolvedSet<16> Functions; 11462 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11463 if (S && OverOp != OO_None) 11464 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11465 Functions); 11466 11467 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11468 } 11469 11470 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11471 } 11472 11473 // Unary Operators. 'Tok' is the token for the operator. 11474 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11475 tok::TokenKind Op, Expr *Input) { 11476 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11477 } 11478 11479 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11480 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11481 LabelDecl *TheDecl) { 11482 TheDecl->markUsed(Context); 11483 // Create the AST node. The address of a label always has type 'void*'. 11484 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11485 Context.getPointerType(Context.VoidTy)); 11486 } 11487 11488 /// Given the last statement in a statement-expression, check whether 11489 /// the result is a producing expression (like a call to an 11490 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11491 /// release out of the full-expression. Otherwise, return null. 11492 /// Cannot fail. 11493 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11494 // Should always be wrapped with one of these. 11495 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11496 if (!cleanups) return nullptr; 11497 11498 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11499 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11500 return nullptr; 11501 11502 // Splice out the cast. This shouldn't modify any interesting 11503 // features of the statement. 11504 Expr *producer = cast->getSubExpr(); 11505 assert(producer->getType() == cast->getType()); 11506 assert(producer->getValueKind() == cast->getValueKind()); 11507 cleanups->setSubExpr(producer); 11508 return cleanups; 11509 } 11510 11511 void Sema::ActOnStartStmtExpr() { 11512 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11513 } 11514 11515 void Sema::ActOnStmtExprError() { 11516 // Note that function is also called by TreeTransform when leaving a 11517 // StmtExpr scope without rebuilding anything. 11518 11519 DiscardCleanupsInEvaluationContext(); 11520 PopExpressionEvaluationContext(); 11521 } 11522 11523 ExprResult 11524 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11525 SourceLocation RPLoc) { // "({..})" 11526 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11527 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11528 11529 if (hasAnyUnrecoverableErrorsInThisFunction()) 11530 DiscardCleanupsInEvaluationContext(); 11531 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11532 PopExpressionEvaluationContext(); 11533 11534 // FIXME: there are a variety of strange constraints to enforce here, for 11535 // example, it is not possible to goto into a stmt expression apparently. 11536 // More semantic analysis is needed. 11537 11538 // If there are sub-stmts in the compound stmt, take the type of the last one 11539 // as the type of the stmtexpr. 11540 QualType Ty = Context.VoidTy; 11541 bool StmtExprMayBindToTemp = false; 11542 if (!Compound->body_empty()) { 11543 Stmt *LastStmt = Compound->body_back(); 11544 LabelStmt *LastLabelStmt = nullptr; 11545 // If LastStmt is a label, skip down through into the body. 11546 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11547 LastLabelStmt = Label; 11548 LastStmt = Label->getSubStmt(); 11549 } 11550 11551 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11552 // Do function/array conversion on the last expression, but not 11553 // lvalue-to-rvalue. However, initialize an unqualified type. 11554 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11555 if (LastExpr.isInvalid()) 11556 return ExprError(); 11557 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11558 11559 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11560 // In ARC, if the final expression ends in a consume, splice 11561 // the consume out and bind it later. In the alternate case 11562 // (when dealing with a retainable type), the result 11563 // initialization will create a produce. In both cases the 11564 // result will be +1, and we'll need to balance that out with 11565 // a bind. 11566 if (Expr *rebuiltLastStmt 11567 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11568 LastExpr = rebuiltLastStmt; 11569 } else { 11570 LastExpr = PerformCopyInitialization( 11571 InitializedEntity::InitializeResult(LPLoc, 11572 Ty, 11573 false), 11574 SourceLocation(), 11575 LastExpr); 11576 } 11577 11578 if (LastExpr.isInvalid()) 11579 return ExprError(); 11580 if (LastExpr.get() != nullptr) { 11581 if (!LastLabelStmt) 11582 Compound->setLastStmt(LastExpr.get()); 11583 else 11584 LastLabelStmt->setSubStmt(LastExpr.get()); 11585 StmtExprMayBindToTemp = true; 11586 } 11587 } 11588 } 11589 } 11590 11591 // FIXME: Check that expression type is complete/non-abstract; statement 11592 // expressions are not lvalues. 11593 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11594 if (StmtExprMayBindToTemp) 11595 return MaybeBindToTemporary(ResStmtExpr); 11596 return ResStmtExpr; 11597 } 11598 11599 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11600 TypeSourceInfo *TInfo, 11601 ArrayRef<OffsetOfComponent> Components, 11602 SourceLocation RParenLoc) { 11603 QualType ArgTy = TInfo->getType(); 11604 bool Dependent = ArgTy->isDependentType(); 11605 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11606 11607 // We must have at least one component that refers to the type, and the first 11608 // one is known to be a field designator. Verify that the ArgTy represents 11609 // a struct/union/class. 11610 if (!Dependent && !ArgTy->isRecordType()) 11611 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11612 << ArgTy << TypeRange); 11613 11614 // Type must be complete per C99 7.17p3 because a declaring a variable 11615 // with an incomplete type would be ill-formed. 11616 if (!Dependent 11617 && RequireCompleteType(BuiltinLoc, ArgTy, 11618 diag::err_offsetof_incomplete_type, TypeRange)) 11619 return ExprError(); 11620 11621 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11622 // GCC extension, diagnose them. 11623 // FIXME: This diagnostic isn't actually visible because the location is in 11624 // a system header! 11625 if (Components.size() != 1) 11626 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11627 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11628 11629 bool DidWarnAboutNonPOD = false; 11630 QualType CurrentType = ArgTy; 11631 SmallVector<OffsetOfNode, 4> Comps; 11632 SmallVector<Expr*, 4> Exprs; 11633 for (const OffsetOfComponent &OC : Components) { 11634 if (OC.isBrackets) { 11635 // Offset of an array sub-field. TODO: Should we allow vector elements? 11636 if (!CurrentType->isDependentType()) { 11637 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11638 if(!AT) 11639 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11640 << CurrentType); 11641 CurrentType = AT->getElementType(); 11642 } else 11643 CurrentType = Context.DependentTy; 11644 11645 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11646 if (IdxRval.isInvalid()) 11647 return ExprError(); 11648 Expr *Idx = IdxRval.get(); 11649 11650 // The expression must be an integral expression. 11651 // FIXME: An integral constant expression? 11652 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11653 !Idx->getType()->isIntegerType()) 11654 return ExprError(Diag(Idx->getLocStart(), 11655 diag::err_typecheck_subscript_not_integer) 11656 << Idx->getSourceRange()); 11657 11658 // Record this array index. 11659 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11660 Exprs.push_back(Idx); 11661 continue; 11662 } 11663 11664 // Offset of a field. 11665 if (CurrentType->isDependentType()) { 11666 // We have the offset of a field, but we can't look into the dependent 11667 // type. Just record the identifier of the field. 11668 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11669 CurrentType = Context.DependentTy; 11670 continue; 11671 } 11672 11673 // We need to have a complete type to look into. 11674 if (RequireCompleteType(OC.LocStart, CurrentType, 11675 diag::err_offsetof_incomplete_type)) 11676 return ExprError(); 11677 11678 // Look for the designated field. 11679 const RecordType *RC = CurrentType->getAs<RecordType>(); 11680 if (!RC) 11681 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11682 << CurrentType); 11683 RecordDecl *RD = RC->getDecl(); 11684 11685 // C++ [lib.support.types]p5: 11686 // The macro offsetof accepts a restricted set of type arguments in this 11687 // International Standard. type shall be a POD structure or a POD union 11688 // (clause 9). 11689 // C++11 [support.types]p4: 11690 // If type is not a standard-layout class (Clause 9), the results are 11691 // undefined. 11692 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11693 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11694 unsigned DiagID = 11695 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11696 : diag::ext_offsetof_non_pod_type; 11697 11698 if (!IsSafe && !DidWarnAboutNonPOD && 11699 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11700 PDiag(DiagID) 11701 << SourceRange(Components[0].LocStart, OC.LocEnd) 11702 << CurrentType)) 11703 DidWarnAboutNonPOD = true; 11704 } 11705 11706 // Look for the field. 11707 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11708 LookupQualifiedName(R, RD); 11709 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11710 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11711 if (!MemberDecl) { 11712 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11713 MemberDecl = IndirectMemberDecl->getAnonField(); 11714 } 11715 11716 if (!MemberDecl) 11717 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11718 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11719 OC.LocEnd)); 11720 11721 // C99 7.17p3: 11722 // (If the specified member is a bit-field, the behavior is undefined.) 11723 // 11724 // We diagnose this as an error. 11725 if (MemberDecl->isBitField()) { 11726 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11727 << MemberDecl->getDeclName() 11728 << SourceRange(BuiltinLoc, RParenLoc); 11729 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11730 return ExprError(); 11731 } 11732 11733 RecordDecl *Parent = MemberDecl->getParent(); 11734 if (IndirectMemberDecl) 11735 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11736 11737 // If the member was found in a base class, introduce OffsetOfNodes for 11738 // the base class indirections. 11739 CXXBasePaths Paths; 11740 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11741 Paths)) { 11742 if (Paths.getDetectedVirtual()) { 11743 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11744 << MemberDecl->getDeclName() 11745 << SourceRange(BuiltinLoc, RParenLoc); 11746 return ExprError(); 11747 } 11748 11749 CXXBasePath &Path = Paths.front(); 11750 for (const CXXBasePathElement &B : Path) 11751 Comps.push_back(OffsetOfNode(B.Base)); 11752 } 11753 11754 if (IndirectMemberDecl) { 11755 for (auto *FI : IndirectMemberDecl->chain()) { 11756 assert(isa<FieldDecl>(FI)); 11757 Comps.push_back(OffsetOfNode(OC.LocStart, 11758 cast<FieldDecl>(FI), OC.LocEnd)); 11759 } 11760 } else 11761 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11762 11763 CurrentType = MemberDecl->getType().getNonReferenceType(); 11764 } 11765 11766 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11767 Comps, Exprs, RParenLoc); 11768 } 11769 11770 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11771 SourceLocation BuiltinLoc, 11772 SourceLocation TypeLoc, 11773 ParsedType ParsedArgTy, 11774 ArrayRef<OffsetOfComponent> Components, 11775 SourceLocation RParenLoc) { 11776 11777 TypeSourceInfo *ArgTInfo; 11778 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11779 if (ArgTy.isNull()) 11780 return ExprError(); 11781 11782 if (!ArgTInfo) 11783 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11784 11785 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11786 } 11787 11788 11789 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11790 Expr *CondExpr, 11791 Expr *LHSExpr, Expr *RHSExpr, 11792 SourceLocation RPLoc) { 11793 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11794 11795 ExprValueKind VK = VK_RValue; 11796 ExprObjectKind OK = OK_Ordinary; 11797 QualType resType; 11798 bool ValueDependent = false; 11799 bool CondIsTrue = false; 11800 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11801 resType = Context.DependentTy; 11802 ValueDependent = true; 11803 } else { 11804 // The conditional expression is required to be a constant expression. 11805 llvm::APSInt condEval(32); 11806 ExprResult CondICE 11807 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11808 diag::err_typecheck_choose_expr_requires_constant, false); 11809 if (CondICE.isInvalid()) 11810 return ExprError(); 11811 CondExpr = CondICE.get(); 11812 CondIsTrue = condEval.getZExtValue(); 11813 11814 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11815 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11816 11817 resType = ActiveExpr->getType(); 11818 ValueDependent = ActiveExpr->isValueDependent(); 11819 VK = ActiveExpr->getValueKind(); 11820 OK = ActiveExpr->getObjectKind(); 11821 } 11822 11823 return new (Context) 11824 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11825 CondIsTrue, resType->isDependentType(), ValueDependent); 11826 } 11827 11828 //===----------------------------------------------------------------------===// 11829 // Clang Extensions. 11830 //===----------------------------------------------------------------------===// 11831 11832 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11833 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11834 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11835 11836 if (LangOpts.CPlusPlus) { 11837 Decl *ManglingContextDecl; 11838 if (MangleNumberingContext *MCtx = 11839 getCurrentMangleNumberContext(Block->getDeclContext(), 11840 ManglingContextDecl)) { 11841 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11842 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11843 } 11844 } 11845 11846 PushBlockScope(CurScope, Block); 11847 CurContext->addDecl(Block); 11848 if (CurScope) 11849 PushDeclContext(CurScope, Block); 11850 else 11851 CurContext = Block; 11852 11853 getCurBlock()->HasImplicitReturnType = true; 11854 11855 // Enter a new evaluation context to insulate the block from any 11856 // cleanups from the enclosing full-expression. 11857 PushExpressionEvaluationContext(PotentiallyEvaluated); 11858 } 11859 11860 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11861 Scope *CurScope) { 11862 assert(ParamInfo.getIdentifier() == nullptr && 11863 "block-id should have no identifier!"); 11864 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11865 BlockScopeInfo *CurBlock = getCurBlock(); 11866 11867 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11868 QualType T = Sig->getType(); 11869 11870 // FIXME: We should allow unexpanded parameter packs here, but that would, 11871 // in turn, make the block expression contain unexpanded parameter packs. 11872 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11873 // Drop the parameters. 11874 FunctionProtoType::ExtProtoInfo EPI; 11875 EPI.HasTrailingReturn = false; 11876 EPI.TypeQuals |= DeclSpec::TQ_const; 11877 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11878 Sig = Context.getTrivialTypeSourceInfo(T); 11879 } 11880 11881 // GetTypeForDeclarator always produces a function type for a block 11882 // literal signature. Furthermore, it is always a FunctionProtoType 11883 // unless the function was written with a typedef. 11884 assert(T->isFunctionType() && 11885 "GetTypeForDeclarator made a non-function block signature"); 11886 11887 // Look for an explicit signature in that function type. 11888 FunctionProtoTypeLoc ExplicitSignature; 11889 11890 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11891 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11892 11893 // Check whether that explicit signature was synthesized by 11894 // GetTypeForDeclarator. If so, don't save that as part of the 11895 // written signature. 11896 if (ExplicitSignature.getLocalRangeBegin() == 11897 ExplicitSignature.getLocalRangeEnd()) { 11898 // This would be much cheaper if we stored TypeLocs instead of 11899 // TypeSourceInfos. 11900 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11901 unsigned Size = Result.getFullDataSize(); 11902 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11903 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11904 11905 ExplicitSignature = FunctionProtoTypeLoc(); 11906 } 11907 } 11908 11909 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11910 CurBlock->FunctionType = T; 11911 11912 const FunctionType *Fn = T->getAs<FunctionType>(); 11913 QualType RetTy = Fn->getReturnType(); 11914 bool isVariadic = 11915 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11916 11917 CurBlock->TheDecl->setIsVariadic(isVariadic); 11918 11919 // Context.DependentTy is used as a placeholder for a missing block 11920 // return type. TODO: what should we do with declarators like: 11921 // ^ * { ... } 11922 // If the answer is "apply template argument deduction".... 11923 if (RetTy != Context.DependentTy) { 11924 CurBlock->ReturnType = RetTy; 11925 CurBlock->TheDecl->setBlockMissingReturnType(false); 11926 CurBlock->HasImplicitReturnType = false; 11927 } 11928 11929 // Push block parameters from the declarator if we had them. 11930 SmallVector<ParmVarDecl*, 8> Params; 11931 if (ExplicitSignature) { 11932 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11933 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11934 if (Param->getIdentifier() == nullptr && 11935 !Param->isImplicit() && 11936 !Param->isInvalidDecl() && 11937 !getLangOpts().CPlusPlus) 11938 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11939 Params.push_back(Param); 11940 } 11941 11942 // Fake up parameter variables if we have a typedef, like 11943 // ^ fntype { ... } 11944 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11945 for (const auto &I : Fn->param_types()) { 11946 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11947 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11948 Params.push_back(Param); 11949 } 11950 } 11951 11952 // Set the parameters on the block decl. 11953 if (!Params.empty()) { 11954 CurBlock->TheDecl->setParams(Params); 11955 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11956 CurBlock->TheDecl->param_end(), 11957 /*CheckParameterNames=*/false); 11958 } 11959 11960 // Finally we can process decl attributes. 11961 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11962 11963 // Put the parameter variables in scope. 11964 for (auto AI : CurBlock->TheDecl->params()) { 11965 AI->setOwningFunction(CurBlock->TheDecl); 11966 11967 // If this has an identifier, add it to the scope stack. 11968 if (AI->getIdentifier()) { 11969 CheckShadow(CurBlock->TheScope, AI); 11970 11971 PushOnScopeChains(AI, CurBlock->TheScope); 11972 } 11973 } 11974 } 11975 11976 /// ActOnBlockError - If there is an error parsing a block, this callback 11977 /// is invoked to pop the information about the block from the action impl. 11978 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11979 // Leave the expression-evaluation context. 11980 DiscardCleanupsInEvaluationContext(); 11981 PopExpressionEvaluationContext(); 11982 11983 // Pop off CurBlock, handle nested blocks. 11984 PopDeclContext(); 11985 PopFunctionScopeInfo(); 11986 } 11987 11988 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11989 /// literal was successfully completed. ^(int x){...} 11990 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11991 Stmt *Body, Scope *CurScope) { 11992 // If blocks are disabled, emit an error. 11993 if (!LangOpts.Blocks) 11994 Diag(CaretLoc, diag::err_blocks_disable); 11995 11996 // Leave the expression-evaluation context. 11997 if (hasAnyUnrecoverableErrorsInThisFunction()) 11998 DiscardCleanupsInEvaluationContext(); 11999 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 12000 PopExpressionEvaluationContext(); 12001 12002 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12003 12004 if (BSI->HasImplicitReturnType) 12005 deduceClosureReturnType(*BSI); 12006 12007 PopDeclContext(); 12008 12009 QualType RetTy = Context.VoidTy; 12010 if (!BSI->ReturnType.isNull()) 12011 RetTy = BSI->ReturnType; 12012 12013 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12014 QualType BlockTy; 12015 12016 // Set the captured variables on the block. 12017 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12018 SmallVector<BlockDecl::Capture, 4> Captures; 12019 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12020 if (Cap.isThisCapture()) 12021 continue; 12022 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12023 Cap.isNested(), Cap.getInitExpr()); 12024 Captures.push_back(NewCap); 12025 } 12026 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12027 12028 // If the user wrote a function type in some form, try to use that. 12029 if (!BSI->FunctionType.isNull()) { 12030 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12031 12032 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12033 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12034 12035 // Turn protoless block types into nullary block types. 12036 if (isa<FunctionNoProtoType>(FTy)) { 12037 FunctionProtoType::ExtProtoInfo EPI; 12038 EPI.ExtInfo = Ext; 12039 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12040 12041 // Otherwise, if we don't need to change anything about the function type, 12042 // preserve its sugar structure. 12043 } else if (FTy->getReturnType() == RetTy && 12044 (!NoReturn || FTy->getNoReturnAttr())) { 12045 BlockTy = BSI->FunctionType; 12046 12047 // Otherwise, make the minimal modifications to the function type. 12048 } else { 12049 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12050 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12051 EPI.TypeQuals = 0; // FIXME: silently? 12052 EPI.ExtInfo = Ext; 12053 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12054 } 12055 12056 // If we don't have a function type, just build one from nothing. 12057 } else { 12058 FunctionProtoType::ExtProtoInfo EPI; 12059 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12060 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12061 } 12062 12063 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 12064 BSI->TheDecl->param_end()); 12065 BlockTy = Context.getBlockPointerType(BlockTy); 12066 12067 // If needed, diagnose invalid gotos and switches in the block. 12068 if (getCurFunction()->NeedsScopeChecking() && 12069 !PP.isCodeCompletionEnabled()) 12070 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12071 12072 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12073 12074 // Try to apply the named return value optimization. We have to check again 12075 // if we can do this, though, because blocks keep return statements around 12076 // to deduce an implicit return type. 12077 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12078 !BSI->TheDecl->isDependentContext()) 12079 computeNRVO(Body, BSI); 12080 12081 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12082 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12083 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12084 12085 // If the block isn't obviously global, i.e. it captures anything at 12086 // all, then we need to do a few things in the surrounding context: 12087 if (Result->getBlockDecl()->hasCaptures()) { 12088 // First, this expression has a new cleanup object. 12089 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12090 ExprNeedsCleanups = true; 12091 12092 // It also gets a branch-protected scope if any of the captured 12093 // variables needs destruction. 12094 for (const auto &CI : Result->getBlockDecl()->captures()) { 12095 const VarDecl *var = CI.getVariable(); 12096 if (var->getType().isDestructedType() != QualType::DK_none) { 12097 getCurFunction()->setHasBranchProtectedScope(); 12098 break; 12099 } 12100 } 12101 } 12102 12103 return Result; 12104 } 12105 12106 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12107 SourceLocation RPLoc) { 12108 TypeSourceInfo *TInfo; 12109 GetTypeFromParser(Ty, &TInfo); 12110 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12111 } 12112 12113 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12114 Expr *E, TypeSourceInfo *TInfo, 12115 SourceLocation RPLoc) { 12116 Expr *OrigExpr = E; 12117 bool IsMS = false; 12118 12119 // CUDA device code does not support varargs. 12120 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12121 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12122 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12123 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12124 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12125 } 12126 } 12127 12128 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12129 // as Microsoft ABI on an actual Microsoft platform, where 12130 // __builtin_ms_va_list and __builtin_va_list are the same.) 12131 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12132 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12133 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12134 if (Context.hasSameType(MSVaListType, E->getType())) { 12135 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12136 return ExprError(); 12137 IsMS = true; 12138 } 12139 } 12140 12141 // Get the va_list type 12142 QualType VaListType = Context.getBuiltinVaListType(); 12143 if (!IsMS) { 12144 if (VaListType->isArrayType()) { 12145 // Deal with implicit array decay; for example, on x86-64, 12146 // va_list is an array, but it's supposed to decay to 12147 // a pointer for va_arg. 12148 VaListType = Context.getArrayDecayedType(VaListType); 12149 // Make sure the input expression also decays appropriately. 12150 ExprResult Result = UsualUnaryConversions(E); 12151 if (Result.isInvalid()) 12152 return ExprError(); 12153 E = Result.get(); 12154 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12155 // If va_list is a record type and we are compiling in C++ mode, 12156 // check the argument using reference binding. 12157 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12158 Context, Context.getLValueReferenceType(VaListType), false); 12159 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12160 if (Init.isInvalid()) 12161 return ExprError(); 12162 E = Init.getAs<Expr>(); 12163 } else { 12164 // Otherwise, the va_list argument must be an l-value because 12165 // it is modified by va_arg. 12166 if (!E->isTypeDependent() && 12167 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12168 return ExprError(); 12169 } 12170 } 12171 12172 if (!IsMS && !E->isTypeDependent() && 12173 !Context.hasSameType(VaListType, E->getType())) 12174 return ExprError(Diag(E->getLocStart(), 12175 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12176 << OrigExpr->getType() << E->getSourceRange()); 12177 12178 if (!TInfo->getType()->isDependentType()) { 12179 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12180 diag::err_second_parameter_to_va_arg_incomplete, 12181 TInfo->getTypeLoc())) 12182 return ExprError(); 12183 12184 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12185 TInfo->getType(), 12186 diag::err_second_parameter_to_va_arg_abstract, 12187 TInfo->getTypeLoc())) 12188 return ExprError(); 12189 12190 if (!TInfo->getType().isPODType(Context)) { 12191 Diag(TInfo->getTypeLoc().getBeginLoc(), 12192 TInfo->getType()->isObjCLifetimeType() 12193 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12194 : diag::warn_second_parameter_to_va_arg_not_pod) 12195 << TInfo->getType() 12196 << TInfo->getTypeLoc().getSourceRange(); 12197 } 12198 12199 // Check for va_arg where arguments of the given type will be promoted 12200 // (i.e. this va_arg is guaranteed to have undefined behavior). 12201 QualType PromoteType; 12202 if (TInfo->getType()->isPromotableIntegerType()) { 12203 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12204 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12205 PromoteType = QualType(); 12206 } 12207 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12208 PromoteType = Context.DoubleTy; 12209 if (!PromoteType.isNull()) 12210 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12211 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12212 << TInfo->getType() 12213 << PromoteType 12214 << TInfo->getTypeLoc().getSourceRange()); 12215 } 12216 12217 QualType T = TInfo->getType().getNonLValueExprType(Context); 12218 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12219 } 12220 12221 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12222 // The type of __null will be int or long, depending on the size of 12223 // pointers on the target. 12224 QualType Ty; 12225 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12226 if (pw == Context.getTargetInfo().getIntWidth()) 12227 Ty = Context.IntTy; 12228 else if (pw == Context.getTargetInfo().getLongWidth()) 12229 Ty = Context.LongTy; 12230 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12231 Ty = Context.LongLongTy; 12232 else { 12233 llvm_unreachable("I don't know size of pointer!"); 12234 } 12235 12236 return new (Context) GNUNullExpr(Ty, TokenLoc); 12237 } 12238 12239 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12240 bool Diagnose) { 12241 if (!getLangOpts().ObjC1) 12242 return false; 12243 12244 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12245 if (!PT) 12246 return false; 12247 12248 if (!PT->isObjCIdType()) { 12249 // Check if the destination is the 'NSString' interface. 12250 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12251 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12252 return false; 12253 } 12254 12255 // Ignore any parens, implicit casts (should only be 12256 // array-to-pointer decays), and not-so-opaque values. The last is 12257 // important for making this trigger for property assignments. 12258 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12259 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12260 if (OV->getSourceExpr()) 12261 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12262 12263 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12264 if (!SL || !SL->isAscii()) 12265 return false; 12266 if (Diagnose) { 12267 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12268 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12269 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12270 } 12271 return true; 12272 } 12273 12274 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12275 const Expr *SrcExpr) { 12276 if (!DstType->isFunctionPointerType() || 12277 !SrcExpr->getType()->isFunctionType()) 12278 return false; 12279 12280 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12281 if (!DRE) 12282 return false; 12283 12284 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12285 if (!FD) 12286 return false; 12287 12288 return !S.checkAddressOfFunctionIsAvailable(FD, 12289 /*Complain=*/true, 12290 SrcExpr->getLocStart()); 12291 } 12292 12293 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12294 SourceLocation Loc, 12295 QualType DstType, QualType SrcType, 12296 Expr *SrcExpr, AssignmentAction Action, 12297 bool *Complained) { 12298 if (Complained) 12299 *Complained = false; 12300 12301 // Decode the result (notice that AST's are still created for extensions). 12302 bool CheckInferredResultType = false; 12303 bool isInvalid = false; 12304 unsigned DiagKind = 0; 12305 FixItHint Hint; 12306 ConversionFixItGenerator ConvHints; 12307 bool MayHaveConvFixit = false; 12308 bool MayHaveFunctionDiff = false; 12309 const ObjCInterfaceDecl *IFace = nullptr; 12310 const ObjCProtocolDecl *PDecl = nullptr; 12311 12312 switch (ConvTy) { 12313 case Compatible: 12314 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12315 return false; 12316 12317 case PointerToInt: 12318 DiagKind = diag::ext_typecheck_convert_pointer_int; 12319 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12320 MayHaveConvFixit = true; 12321 break; 12322 case IntToPointer: 12323 DiagKind = diag::ext_typecheck_convert_int_pointer; 12324 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12325 MayHaveConvFixit = true; 12326 break; 12327 case IncompatiblePointer: 12328 DiagKind = 12329 (Action == AA_Passing_CFAudited ? 12330 diag::err_arc_typecheck_convert_incompatible_pointer : 12331 diag::ext_typecheck_convert_incompatible_pointer); 12332 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12333 SrcType->isObjCObjectPointerType(); 12334 if (Hint.isNull() && !CheckInferredResultType) { 12335 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12336 } 12337 else if (CheckInferredResultType) { 12338 SrcType = SrcType.getUnqualifiedType(); 12339 DstType = DstType.getUnqualifiedType(); 12340 } 12341 MayHaveConvFixit = true; 12342 break; 12343 case IncompatiblePointerSign: 12344 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12345 break; 12346 case FunctionVoidPointer: 12347 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12348 break; 12349 case IncompatiblePointerDiscardsQualifiers: { 12350 // Perform array-to-pointer decay if necessary. 12351 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12352 12353 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12354 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12355 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12356 DiagKind = diag::err_typecheck_incompatible_address_space; 12357 break; 12358 12359 12360 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12361 DiagKind = diag::err_typecheck_incompatible_ownership; 12362 break; 12363 } 12364 12365 llvm_unreachable("unknown error case for discarding qualifiers!"); 12366 // fallthrough 12367 } 12368 case CompatiblePointerDiscardsQualifiers: 12369 // If the qualifiers lost were because we were applying the 12370 // (deprecated) C++ conversion from a string literal to a char* 12371 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12372 // Ideally, this check would be performed in 12373 // checkPointerTypesForAssignment. However, that would require a 12374 // bit of refactoring (so that the second argument is an 12375 // expression, rather than a type), which should be done as part 12376 // of a larger effort to fix checkPointerTypesForAssignment for 12377 // C++ semantics. 12378 if (getLangOpts().CPlusPlus && 12379 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12380 return false; 12381 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12382 break; 12383 case IncompatibleNestedPointerQualifiers: 12384 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12385 break; 12386 case IntToBlockPointer: 12387 DiagKind = diag::err_int_to_block_pointer; 12388 break; 12389 case IncompatibleBlockPointer: 12390 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12391 break; 12392 case IncompatibleObjCQualifiedId: { 12393 if (SrcType->isObjCQualifiedIdType()) { 12394 const ObjCObjectPointerType *srcOPT = 12395 SrcType->getAs<ObjCObjectPointerType>(); 12396 for (auto *srcProto : srcOPT->quals()) { 12397 PDecl = srcProto; 12398 break; 12399 } 12400 if (const ObjCInterfaceType *IFaceT = 12401 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12402 IFace = IFaceT->getDecl(); 12403 } 12404 else if (DstType->isObjCQualifiedIdType()) { 12405 const ObjCObjectPointerType *dstOPT = 12406 DstType->getAs<ObjCObjectPointerType>(); 12407 for (auto *dstProto : dstOPT->quals()) { 12408 PDecl = dstProto; 12409 break; 12410 } 12411 if (const ObjCInterfaceType *IFaceT = 12412 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12413 IFace = IFaceT->getDecl(); 12414 } 12415 DiagKind = diag::warn_incompatible_qualified_id; 12416 break; 12417 } 12418 case IncompatibleVectors: 12419 DiagKind = diag::warn_incompatible_vectors; 12420 break; 12421 case IncompatibleObjCWeakRef: 12422 DiagKind = diag::err_arc_weak_unavailable_assign; 12423 break; 12424 case Incompatible: 12425 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12426 if (Complained) 12427 *Complained = true; 12428 return true; 12429 } 12430 12431 DiagKind = diag::err_typecheck_convert_incompatible; 12432 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12433 MayHaveConvFixit = true; 12434 isInvalid = true; 12435 MayHaveFunctionDiff = true; 12436 break; 12437 } 12438 12439 QualType FirstType, SecondType; 12440 switch (Action) { 12441 case AA_Assigning: 12442 case AA_Initializing: 12443 // The destination type comes first. 12444 FirstType = DstType; 12445 SecondType = SrcType; 12446 break; 12447 12448 case AA_Returning: 12449 case AA_Passing: 12450 case AA_Passing_CFAudited: 12451 case AA_Converting: 12452 case AA_Sending: 12453 case AA_Casting: 12454 // The source type comes first. 12455 FirstType = SrcType; 12456 SecondType = DstType; 12457 break; 12458 } 12459 12460 PartialDiagnostic FDiag = PDiag(DiagKind); 12461 if (Action == AA_Passing_CFAudited) 12462 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12463 else 12464 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12465 12466 // If we can fix the conversion, suggest the FixIts. 12467 assert(ConvHints.isNull() || Hint.isNull()); 12468 if (!ConvHints.isNull()) { 12469 for (FixItHint &H : ConvHints.Hints) 12470 FDiag << H; 12471 } else { 12472 FDiag << Hint; 12473 } 12474 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12475 12476 if (MayHaveFunctionDiff) 12477 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12478 12479 Diag(Loc, FDiag); 12480 if (DiagKind == diag::warn_incompatible_qualified_id && 12481 PDecl && IFace && !IFace->hasDefinition()) 12482 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12483 << IFace->getName() << PDecl->getName(); 12484 12485 if (SecondType == Context.OverloadTy) 12486 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12487 FirstType, /*TakingAddress=*/true); 12488 12489 if (CheckInferredResultType) 12490 EmitRelatedResultTypeNote(SrcExpr); 12491 12492 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12493 EmitRelatedResultTypeNoteForReturn(DstType); 12494 12495 if (Complained) 12496 *Complained = true; 12497 return isInvalid; 12498 } 12499 12500 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12501 llvm::APSInt *Result) { 12502 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12503 public: 12504 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12505 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12506 } 12507 } Diagnoser; 12508 12509 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12510 } 12511 12512 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12513 llvm::APSInt *Result, 12514 unsigned DiagID, 12515 bool AllowFold) { 12516 class IDDiagnoser : public VerifyICEDiagnoser { 12517 unsigned DiagID; 12518 12519 public: 12520 IDDiagnoser(unsigned DiagID) 12521 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12522 12523 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12524 S.Diag(Loc, DiagID) << SR; 12525 } 12526 } Diagnoser(DiagID); 12527 12528 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12529 } 12530 12531 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12532 SourceRange SR) { 12533 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12534 } 12535 12536 ExprResult 12537 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12538 VerifyICEDiagnoser &Diagnoser, 12539 bool AllowFold) { 12540 SourceLocation DiagLoc = E->getLocStart(); 12541 12542 if (getLangOpts().CPlusPlus11) { 12543 // C++11 [expr.const]p5: 12544 // If an expression of literal class type is used in a context where an 12545 // integral constant expression is required, then that class type shall 12546 // have a single non-explicit conversion function to an integral or 12547 // unscoped enumeration type 12548 ExprResult Converted; 12549 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12550 public: 12551 CXX11ConvertDiagnoser(bool Silent) 12552 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12553 Silent, true) {} 12554 12555 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12556 QualType T) override { 12557 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12558 } 12559 12560 SemaDiagnosticBuilder diagnoseIncomplete( 12561 Sema &S, SourceLocation Loc, QualType T) override { 12562 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12563 } 12564 12565 SemaDiagnosticBuilder diagnoseExplicitConv( 12566 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12567 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12568 } 12569 12570 SemaDiagnosticBuilder noteExplicitConv( 12571 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12572 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12573 << ConvTy->isEnumeralType() << ConvTy; 12574 } 12575 12576 SemaDiagnosticBuilder diagnoseAmbiguous( 12577 Sema &S, SourceLocation Loc, QualType T) override { 12578 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12579 } 12580 12581 SemaDiagnosticBuilder noteAmbiguous( 12582 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12583 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12584 << ConvTy->isEnumeralType() << ConvTy; 12585 } 12586 12587 SemaDiagnosticBuilder diagnoseConversion( 12588 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12589 llvm_unreachable("conversion functions are permitted"); 12590 } 12591 } ConvertDiagnoser(Diagnoser.Suppress); 12592 12593 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12594 ConvertDiagnoser); 12595 if (Converted.isInvalid()) 12596 return Converted; 12597 E = Converted.get(); 12598 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12599 return ExprError(); 12600 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12601 // An ICE must be of integral or unscoped enumeration type. 12602 if (!Diagnoser.Suppress) 12603 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12604 return ExprError(); 12605 } 12606 12607 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12608 // in the non-ICE case. 12609 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12610 if (Result) 12611 *Result = E->EvaluateKnownConstInt(Context); 12612 return E; 12613 } 12614 12615 Expr::EvalResult EvalResult; 12616 SmallVector<PartialDiagnosticAt, 8> Notes; 12617 EvalResult.Diag = &Notes; 12618 12619 // Try to evaluate the expression, and produce diagnostics explaining why it's 12620 // not a constant expression as a side-effect. 12621 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12622 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12623 12624 // In C++11, we can rely on diagnostics being produced for any expression 12625 // which is not a constant expression. If no diagnostics were produced, then 12626 // this is a constant expression. 12627 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12628 if (Result) 12629 *Result = EvalResult.Val.getInt(); 12630 return E; 12631 } 12632 12633 // If our only note is the usual "invalid subexpression" note, just point 12634 // the caret at its location rather than producing an essentially 12635 // redundant note. 12636 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12637 diag::note_invalid_subexpr_in_const_expr) { 12638 DiagLoc = Notes[0].first; 12639 Notes.clear(); 12640 } 12641 12642 if (!Folded || !AllowFold) { 12643 if (!Diagnoser.Suppress) { 12644 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12645 for (const PartialDiagnosticAt &Note : Notes) 12646 Diag(Note.first, Note.second); 12647 } 12648 12649 return ExprError(); 12650 } 12651 12652 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12653 for (const PartialDiagnosticAt &Note : Notes) 12654 Diag(Note.first, Note.second); 12655 12656 if (Result) 12657 *Result = EvalResult.Val.getInt(); 12658 return E; 12659 } 12660 12661 namespace { 12662 // Handle the case where we conclude a expression which we speculatively 12663 // considered to be unevaluated is actually evaluated. 12664 class TransformToPE : public TreeTransform<TransformToPE> { 12665 typedef TreeTransform<TransformToPE> BaseTransform; 12666 12667 public: 12668 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12669 12670 // Make sure we redo semantic analysis 12671 bool AlwaysRebuild() { return true; } 12672 12673 // Make sure we handle LabelStmts correctly. 12674 // FIXME: This does the right thing, but maybe we need a more general 12675 // fix to TreeTransform? 12676 StmtResult TransformLabelStmt(LabelStmt *S) { 12677 S->getDecl()->setStmt(nullptr); 12678 return BaseTransform::TransformLabelStmt(S); 12679 } 12680 12681 // We need to special-case DeclRefExprs referring to FieldDecls which 12682 // are not part of a member pointer formation; normal TreeTransforming 12683 // doesn't catch this case because of the way we represent them in the AST. 12684 // FIXME: This is a bit ugly; is it really the best way to handle this 12685 // case? 12686 // 12687 // Error on DeclRefExprs referring to FieldDecls. 12688 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12689 if (isa<FieldDecl>(E->getDecl()) && 12690 !SemaRef.isUnevaluatedContext()) 12691 return SemaRef.Diag(E->getLocation(), 12692 diag::err_invalid_non_static_member_use) 12693 << E->getDecl() << E->getSourceRange(); 12694 12695 return BaseTransform::TransformDeclRefExpr(E); 12696 } 12697 12698 // Exception: filter out member pointer formation 12699 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12700 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12701 return E; 12702 12703 return BaseTransform::TransformUnaryOperator(E); 12704 } 12705 12706 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12707 // Lambdas never need to be transformed. 12708 return E; 12709 } 12710 }; 12711 } 12712 12713 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12714 assert(isUnevaluatedContext() && 12715 "Should only transform unevaluated expressions"); 12716 ExprEvalContexts.back().Context = 12717 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12718 if (isUnevaluatedContext()) 12719 return E; 12720 return TransformToPE(*this).TransformExpr(E); 12721 } 12722 12723 void 12724 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12725 Decl *LambdaContextDecl, 12726 bool IsDecltype) { 12727 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12728 ExprNeedsCleanups, LambdaContextDecl, 12729 IsDecltype); 12730 ExprNeedsCleanups = false; 12731 if (!MaybeODRUseExprs.empty()) 12732 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12733 } 12734 12735 void 12736 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12737 ReuseLambdaContextDecl_t, 12738 bool IsDecltype) { 12739 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12740 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12741 } 12742 12743 void Sema::PopExpressionEvaluationContext() { 12744 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12745 unsigned NumTypos = Rec.NumTypos; 12746 12747 if (!Rec.Lambdas.empty()) { 12748 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12749 unsigned D; 12750 if (Rec.isUnevaluated()) { 12751 // C++11 [expr.prim.lambda]p2: 12752 // A lambda-expression shall not appear in an unevaluated operand 12753 // (Clause 5). 12754 D = diag::err_lambda_unevaluated_operand; 12755 } else { 12756 // C++1y [expr.const]p2: 12757 // A conditional-expression e is a core constant expression unless the 12758 // evaluation of e, following the rules of the abstract machine, would 12759 // evaluate [...] a lambda-expression. 12760 D = diag::err_lambda_in_constant_expression; 12761 } 12762 for (const auto *L : Rec.Lambdas) 12763 Diag(L->getLocStart(), D); 12764 } else { 12765 // Mark the capture expressions odr-used. This was deferred 12766 // during lambda expression creation. 12767 for (auto *Lambda : Rec.Lambdas) { 12768 for (auto *C : Lambda->capture_inits()) 12769 MarkDeclarationsReferencedInExpr(C); 12770 } 12771 } 12772 } 12773 12774 // When are coming out of an unevaluated context, clear out any 12775 // temporaries that we may have created as part of the evaluation of 12776 // the expression in that context: they aren't relevant because they 12777 // will never be constructed. 12778 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12779 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12780 ExprCleanupObjects.end()); 12781 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12782 CleanupVarDeclMarking(); 12783 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12784 // Otherwise, merge the contexts together. 12785 } else { 12786 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12787 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12788 Rec.SavedMaybeODRUseExprs.end()); 12789 } 12790 12791 // Pop the current expression evaluation context off the stack. 12792 ExprEvalContexts.pop_back(); 12793 12794 if (!ExprEvalContexts.empty()) 12795 ExprEvalContexts.back().NumTypos += NumTypos; 12796 else 12797 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12798 "last ExpressionEvaluationContextRecord"); 12799 } 12800 12801 void Sema::DiscardCleanupsInEvaluationContext() { 12802 ExprCleanupObjects.erase( 12803 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12804 ExprCleanupObjects.end()); 12805 ExprNeedsCleanups = false; 12806 MaybeODRUseExprs.clear(); 12807 } 12808 12809 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12810 if (!E->getType()->isVariablyModifiedType()) 12811 return E; 12812 return TransformToPotentiallyEvaluated(E); 12813 } 12814 12815 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12816 // Do not mark anything as "used" within a dependent context; wait for 12817 // an instantiation. 12818 if (SemaRef.CurContext->isDependentContext()) 12819 return false; 12820 12821 switch (SemaRef.ExprEvalContexts.back().Context) { 12822 case Sema::Unevaluated: 12823 case Sema::UnevaluatedAbstract: 12824 // We are in an expression that is not potentially evaluated; do nothing. 12825 // (Depending on how you read the standard, we actually do need to do 12826 // something here for null pointer constants, but the standard's 12827 // definition of a null pointer constant is completely crazy.) 12828 return false; 12829 12830 case Sema::ConstantEvaluated: 12831 case Sema::PotentiallyEvaluated: 12832 // We are in a potentially evaluated expression (or a constant-expression 12833 // in C++03); we need to do implicit template instantiation, implicitly 12834 // define class members, and mark most declarations as used. 12835 return true; 12836 12837 case Sema::PotentiallyEvaluatedIfUsed: 12838 // Referenced declarations will only be used if the construct in the 12839 // containing expression is used. 12840 return false; 12841 } 12842 llvm_unreachable("Invalid context"); 12843 } 12844 12845 /// \brief Mark a function referenced, and check whether it is odr-used 12846 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12847 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12848 bool MightBeOdrUse) { 12849 assert(Func && "No function?"); 12850 12851 Func->setReferenced(); 12852 12853 // C++11 [basic.def.odr]p3: 12854 // A function whose name appears as a potentially-evaluated expression is 12855 // odr-used if it is the unique lookup result or the selected member of a 12856 // set of overloaded functions [...]. 12857 // 12858 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12859 // can just check that here. Skip the rest of this function if we've already 12860 // marked the function as used. 12861 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 12862 if (Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) { 12863 // C++11 [temp.inst]p3: 12864 // Unless a function template specialization has been explicitly 12865 // instantiated or explicitly specialized, the function template 12866 // specialization is implicitly instantiated when the specialization is 12867 // referenced in a context that requires a function definition to exist. 12868 // 12869 // We consider constexpr function templates to be referenced in a context 12870 // that requires a definition to exist whenever they are referenced. 12871 // 12872 // FIXME: This instantiates constexpr functions too frequently. If this is 12873 // really an unevaluated context (and we're not just in the definition of a 12874 // function template or overload resolution or other cases which we 12875 // incorrectly consider to be unevaluated contexts), and we're not in a 12876 // subexpression which we actually need to evaluate (for instance, a 12877 // template argument, array bound or an expression in a braced-init-list), 12878 // we are not permitted to instantiate this constexpr function definition. 12879 // 12880 // FIXME: This also implicitly defines special members too frequently. They 12881 // are only supposed to be implicitly defined if they are odr-used, but they 12882 // are not odr-used from constant expressions in unevaluated contexts. 12883 // However, they cannot be referenced if they are deleted, and they are 12884 // deleted whenever the implicit definition of the special member would 12885 // fail. 12886 if (!Func->isConstexpr() || Func->getBody()) 12887 return; 12888 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12889 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12890 return; 12891 } 12892 12893 // Note that this declaration has been used. 12894 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12895 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12896 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12897 if (Constructor->isDefaultConstructor()) { 12898 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12899 return; 12900 DefineImplicitDefaultConstructor(Loc, Constructor); 12901 } else if (Constructor->isCopyConstructor()) { 12902 DefineImplicitCopyConstructor(Loc, Constructor); 12903 } else if (Constructor->isMoveConstructor()) { 12904 DefineImplicitMoveConstructor(Loc, Constructor); 12905 } 12906 } else if (Constructor->getInheritedConstructor()) { 12907 DefineInheritingConstructor(Loc, Constructor); 12908 } 12909 } else if (CXXDestructorDecl *Destructor = 12910 dyn_cast<CXXDestructorDecl>(Func)) { 12911 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12912 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12913 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12914 return; 12915 DefineImplicitDestructor(Loc, Destructor); 12916 } 12917 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12918 MarkVTableUsed(Loc, Destructor->getParent()); 12919 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12920 if (MethodDecl->isOverloadedOperator() && 12921 MethodDecl->getOverloadedOperator() == OO_Equal) { 12922 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12923 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12924 if (MethodDecl->isCopyAssignmentOperator()) 12925 DefineImplicitCopyAssignment(Loc, MethodDecl); 12926 else 12927 DefineImplicitMoveAssignment(Loc, MethodDecl); 12928 } 12929 } else if (isa<CXXConversionDecl>(MethodDecl) && 12930 MethodDecl->getParent()->isLambda()) { 12931 CXXConversionDecl *Conversion = 12932 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12933 if (Conversion->isLambdaToBlockPointerConversion()) 12934 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12935 else 12936 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12937 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12938 MarkVTableUsed(Loc, MethodDecl->getParent()); 12939 } 12940 12941 // Recursive functions should be marked when used from another function. 12942 // FIXME: Is this really right? 12943 if (CurContext == Func) return; 12944 12945 // Resolve the exception specification for any function which is 12946 // used: CodeGen will need it. 12947 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12948 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12949 ResolveExceptionSpec(Loc, FPT); 12950 12951 // Implicit instantiation of function templates and member functions of 12952 // class templates. 12953 if (Func->isImplicitlyInstantiable()) { 12954 bool AlreadyInstantiated = false; 12955 SourceLocation PointOfInstantiation = Loc; 12956 if (FunctionTemplateSpecializationInfo *SpecInfo 12957 = Func->getTemplateSpecializationInfo()) { 12958 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12959 SpecInfo->setPointOfInstantiation(Loc); 12960 else if (SpecInfo->getTemplateSpecializationKind() 12961 == TSK_ImplicitInstantiation) { 12962 AlreadyInstantiated = true; 12963 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12964 } 12965 } else if (MemberSpecializationInfo *MSInfo 12966 = Func->getMemberSpecializationInfo()) { 12967 if (MSInfo->getPointOfInstantiation().isInvalid()) 12968 MSInfo->setPointOfInstantiation(Loc); 12969 else if (MSInfo->getTemplateSpecializationKind() 12970 == TSK_ImplicitInstantiation) { 12971 AlreadyInstantiated = true; 12972 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12973 } 12974 } 12975 12976 if (!AlreadyInstantiated || Func->isConstexpr()) { 12977 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12978 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12979 ActiveTemplateInstantiations.size()) 12980 PendingLocalImplicitInstantiations.push_back( 12981 std::make_pair(Func, PointOfInstantiation)); 12982 else if (Func->isConstexpr()) 12983 // Do not defer instantiations of constexpr functions, to avoid the 12984 // expression evaluator needing to call back into Sema if it sees a 12985 // call to such a function. 12986 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12987 else { 12988 PendingInstantiations.push_back(std::make_pair(Func, 12989 PointOfInstantiation)); 12990 // Notify the consumer that a function was implicitly instantiated. 12991 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12992 } 12993 } 12994 } else { 12995 // Walk redefinitions, as some of them may be instantiable. 12996 for (auto i : Func->redecls()) { 12997 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12998 MarkFunctionReferenced(Loc, i, OdrUse); 12999 } 13000 } 13001 13002 if (!OdrUse) return; 13003 13004 // Keep track of used but undefined functions. 13005 if (!Func->isDefined()) { 13006 if (mightHaveNonExternalLinkage(Func)) 13007 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13008 else if (Func->getMostRecentDecl()->isInlined() && 13009 !LangOpts.GNUInline && 13010 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13011 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13012 } 13013 13014 // Normally the most current decl is marked used while processing the use and 13015 // any subsequent decls are marked used by decl merging. This fails with 13016 // template instantiation since marking can happen at the end of the file 13017 // and, because of the two phase lookup, this function is called with at 13018 // decl in the middle of a decl chain. We loop to maintain the invariant 13019 // that once a decl is used, all decls after it are also used. 13020 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 13021 F->markUsed(Context); 13022 if (F == Func) 13023 break; 13024 } 13025 } 13026 13027 static void 13028 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13029 VarDecl *var, DeclContext *DC) { 13030 DeclContext *VarDC = var->getDeclContext(); 13031 13032 // If the parameter still belongs to the translation unit, then 13033 // we're actually just using one parameter in the declaration of 13034 // the next. 13035 if (isa<ParmVarDecl>(var) && 13036 isa<TranslationUnitDecl>(VarDC)) 13037 return; 13038 13039 // For C code, don't diagnose about capture if we're not actually in code 13040 // right now; it's impossible to write a non-constant expression outside of 13041 // function context, so we'll get other (more useful) diagnostics later. 13042 // 13043 // For C++, things get a bit more nasty... it would be nice to suppress this 13044 // diagnostic for certain cases like using a local variable in an array bound 13045 // for a member of a local class, but the correct predicate is not obvious. 13046 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13047 return; 13048 13049 if (isa<CXXMethodDecl>(VarDC) && 13050 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13051 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 13052 << var->getIdentifier(); 13053 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 13054 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 13055 << var->getIdentifier() << fn->getDeclName(); 13056 } else if (isa<BlockDecl>(VarDC)) { 13057 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 13058 << var->getIdentifier(); 13059 } else { 13060 // FIXME: Is there any other context where a local variable can be 13061 // declared? 13062 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 13063 << var->getIdentifier(); 13064 } 13065 13066 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13067 << var->getIdentifier(); 13068 13069 // FIXME: Add additional diagnostic info about class etc. which prevents 13070 // capture. 13071 } 13072 13073 13074 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13075 bool &SubCapturesAreNested, 13076 QualType &CaptureType, 13077 QualType &DeclRefType) { 13078 // Check whether we've already captured it. 13079 if (CSI->CaptureMap.count(Var)) { 13080 // If we found a capture, any subcaptures are nested. 13081 SubCapturesAreNested = true; 13082 13083 // Retrieve the capture type for this variable. 13084 CaptureType = CSI->getCapture(Var).getCaptureType(); 13085 13086 // Compute the type of an expression that refers to this variable. 13087 DeclRefType = CaptureType.getNonReferenceType(); 13088 13089 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13090 // are mutable in the sense that user can change their value - they are 13091 // private instances of the captured declarations. 13092 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13093 if (Cap.isCopyCapture() && 13094 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13095 !(isa<CapturedRegionScopeInfo>(CSI) && 13096 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13097 DeclRefType.addConst(); 13098 return true; 13099 } 13100 return false; 13101 } 13102 13103 // Only block literals, captured statements, and lambda expressions can 13104 // capture; other scopes don't work. 13105 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13106 SourceLocation Loc, 13107 const bool Diagnose, Sema &S) { 13108 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13109 return getLambdaAwareParentOfDeclContext(DC); 13110 else if (Var->hasLocalStorage()) { 13111 if (Diagnose) 13112 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13113 } 13114 return nullptr; 13115 } 13116 13117 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13118 // certain types of variables (unnamed, variably modified types etc.) 13119 // so check for eligibility. 13120 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13121 SourceLocation Loc, 13122 const bool Diagnose, Sema &S) { 13123 13124 bool IsBlock = isa<BlockScopeInfo>(CSI); 13125 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13126 13127 // Lambdas are not allowed to capture unnamed variables 13128 // (e.g. anonymous unions). 13129 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13130 // assuming that's the intent. 13131 if (IsLambda && !Var->getDeclName()) { 13132 if (Diagnose) { 13133 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13134 S.Diag(Var->getLocation(), diag::note_declared_at); 13135 } 13136 return false; 13137 } 13138 13139 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13140 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13141 if (Diagnose) { 13142 S.Diag(Loc, diag::err_ref_vm_type); 13143 S.Diag(Var->getLocation(), diag::note_previous_decl) 13144 << Var->getDeclName(); 13145 } 13146 return false; 13147 } 13148 // Prohibit structs with flexible array members too. 13149 // We cannot capture what is in the tail end of the struct. 13150 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13151 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13152 if (Diagnose) { 13153 if (IsBlock) 13154 S.Diag(Loc, diag::err_ref_flexarray_type); 13155 else 13156 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13157 << Var->getDeclName(); 13158 S.Diag(Var->getLocation(), diag::note_previous_decl) 13159 << Var->getDeclName(); 13160 } 13161 return false; 13162 } 13163 } 13164 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13165 // Lambdas and captured statements are not allowed to capture __block 13166 // variables; they don't support the expected semantics. 13167 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13168 if (Diagnose) { 13169 S.Diag(Loc, diag::err_capture_block_variable) 13170 << Var->getDeclName() << !IsLambda; 13171 S.Diag(Var->getLocation(), diag::note_previous_decl) 13172 << Var->getDeclName(); 13173 } 13174 return false; 13175 } 13176 13177 return true; 13178 } 13179 13180 // Returns true if the capture by block was successful. 13181 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13182 SourceLocation Loc, 13183 const bool BuildAndDiagnose, 13184 QualType &CaptureType, 13185 QualType &DeclRefType, 13186 const bool Nested, 13187 Sema &S) { 13188 Expr *CopyExpr = nullptr; 13189 bool ByRef = false; 13190 13191 // Blocks are not allowed to capture arrays. 13192 if (CaptureType->isArrayType()) { 13193 if (BuildAndDiagnose) { 13194 S.Diag(Loc, diag::err_ref_array_type); 13195 S.Diag(Var->getLocation(), diag::note_previous_decl) 13196 << Var->getDeclName(); 13197 } 13198 return false; 13199 } 13200 13201 // Forbid the block-capture of autoreleasing variables. 13202 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13203 if (BuildAndDiagnose) { 13204 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13205 << /*block*/ 0; 13206 S.Diag(Var->getLocation(), diag::note_previous_decl) 13207 << Var->getDeclName(); 13208 } 13209 return false; 13210 } 13211 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13212 if (HasBlocksAttr || CaptureType->isReferenceType()) { 13213 // Block capture by reference does not change the capture or 13214 // declaration reference types. 13215 ByRef = true; 13216 } else { 13217 // Block capture by copy introduces 'const'. 13218 CaptureType = CaptureType.getNonReferenceType().withConst(); 13219 DeclRefType = CaptureType; 13220 13221 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13222 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13223 // The capture logic needs the destructor, so make sure we mark it. 13224 // Usually this is unnecessary because most local variables have 13225 // their destructors marked at declaration time, but parameters are 13226 // an exception because it's technically only the call site that 13227 // actually requires the destructor. 13228 if (isa<ParmVarDecl>(Var)) 13229 S.FinalizeVarWithDestructor(Var, Record); 13230 13231 // Enter a new evaluation context to insulate the copy 13232 // full-expression. 13233 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13234 13235 // According to the blocks spec, the capture of a variable from 13236 // the stack requires a const copy constructor. This is not true 13237 // of the copy/move done to move a __block variable to the heap. 13238 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13239 DeclRefType.withConst(), 13240 VK_LValue, Loc); 13241 13242 ExprResult Result 13243 = S.PerformCopyInitialization( 13244 InitializedEntity::InitializeBlock(Var->getLocation(), 13245 CaptureType, false), 13246 Loc, DeclRef); 13247 13248 // Build a full-expression copy expression if initialization 13249 // succeeded and used a non-trivial constructor. Recover from 13250 // errors by pretending that the copy isn't necessary. 13251 if (!Result.isInvalid() && 13252 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13253 ->isTrivial()) { 13254 Result = S.MaybeCreateExprWithCleanups(Result); 13255 CopyExpr = Result.get(); 13256 } 13257 } 13258 } 13259 } 13260 13261 // Actually capture the variable. 13262 if (BuildAndDiagnose) 13263 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13264 SourceLocation(), CaptureType, CopyExpr); 13265 13266 return true; 13267 13268 } 13269 13270 13271 /// \brief Capture the given variable in the captured region. 13272 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13273 VarDecl *Var, 13274 SourceLocation Loc, 13275 const bool BuildAndDiagnose, 13276 QualType &CaptureType, 13277 QualType &DeclRefType, 13278 const bool RefersToCapturedVariable, 13279 Sema &S) { 13280 13281 // By default, capture variables by reference. 13282 bool ByRef = true; 13283 // Using an LValue reference type is consistent with Lambdas (see below). 13284 if (S.getLangOpts().OpenMP) { 13285 ByRef = S.IsOpenMPCapturedByRef(Var, RSI); 13286 if (S.IsOpenMPCapturedDecl(Var)) 13287 DeclRefType = DeclRefType.getUnqualifiedType(); 13288 } 13289 13290 if (ByRef) 13291 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13292 else 13293 CaptureType = DeclRefType; 13294 13295 Expr *CopyExpr = nullptr; 13296 if (BuildAndDiagnose) { 13297 // The current implementation assumes that all variables are captured 13298 // by references. Since there is no capture by copy, no expression 13299 // evaluation will be needed. 13300 RecordDecl *RD = RSI->TheRecordDecl; 13301 13302 FieldDecl *Field 13303 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13304 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13305 nullptr, false, ICIS_NoInit); 13306 Field->setImplicit(true); 13307 Field->setAccess(AS_private); 13308 RD->addDecl(Field); 13309 13310 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13311 DeclRefType, VK_LValue, Loc); 13312 Var->setReferenced(true); 13313 Var->markUsed(S.Context); 13314 } 13315 13316 // Actually capture the variable. 13317 if (BuildAndDiagnose) 13318 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13319 SourceLocation(), CaptureType, CopyExpr); 13320 13321 13322 return true; 13323 } 13324 13325 /// \brief Create a field within the lambda class for the variable 13326 /// being captured. 13327 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13328 QualType FieldType, QualType DeclRefType, 13329 SourceLocation Loc, 13330 bool RefersToCapturedVariable) { 13331 CXXRecordDecl *Lambda = LSI->Lambda; 13332 13333 // Build the non-static data member. 13334 FieldDecl *Field 13335 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13336 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13337 nullptr, false, ICIS_NoInit); 13338 Field->setImplicit(true); 13339 Field->setAccess(AS_private); 13340 Lambda->addDecl(Field); 13341 } 13342 13343 /// \brief Capture the given variable in the lambda. 13344 static bool captureInLambda(LambdaScopeInfo *LSI, 13345 VarDecl *Var, 13346 SourceLocation Loc, 13347 const bool BuildAndDiagnose, 13348 QualType &CaptureType, 13349 QualType &DeclRefType, 13350 const bool RefersToCapturedVariable, 13351 const Sema::TryCaptureKind Kind, 13352 SourceLocation EllipsisLoc, 13353 const bool IsTopScope, 13354 Sema &S) { 13355 13356 // Determine whether we are capturing by reference or by value. 13357 bool ByRef = false; 13358 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13359 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13360 } else { 13361 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13362 } 13363 13364 // Compute the type of the field that will capture this variable. 13365 if (ByRef) { 13366 // C++11 [expr.prim.lambda]p15: 13367 // An entity is captured by reference if it is implicitly or 13368 // explicitly captured but not captured by copy. It is 13369 // unspecified whether additional unnamed non-static data 13370 // members are declared in the closure type for entities 13371 // captured by reference. 13372 // 13373 // FIXME: It is not clear whether we want to build an lvalue reference 13374 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13375 // to do the former, while EDG does the latter. Core issue 1249 will 13376 // clarify, but for now we follow GCC because it's a more permissive and 13377 // easily defensible position. 13378 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13379 } else { 13380 // C++11 [expr.prim.lambda]p14: 13381 // For each entity captured by copy, an unnamed non-static 13382 // data member is declared in the closure type. The 13383 // declaration order of these members is unspecified. The type 13384 // of such a data member is the type of the corresponding 13385 // captured entity if the entity is not a reference to an 13386 // object, or the referenced type otherwise. [Note: If the 13387 // captured entity is a reference to a function, the 13388 // corresponding data member is also a reference to a 13389 // function. - end note ] 13390 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13391 if (!RefType->getPointeeType()->isFunctionType()) 13392 CaptureType = RefType->getPointeeType(); 13393 } 13394 13395 // Forbid the lambda copy-capture of autoreleasing variables. 13396 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13397 if (BuildAndDiagnose) { 13398 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13399 S.Diag(Var->getLocation(), diag::note_previous_decl) 13400 << Var->getDeclName(); 13401 } 13402 return false; 13403 } 13404 13405 // Make sure that by-copy captures are of a complete and non-abstract type. 13406 if (BuildAndDiagnose) { 13407 if (!CaptureType->isDependentType() && 13408 S.RequireCompleteType(Loc, CaptureType, 13409 diag::err_capture_of_incomplete_type, 13410 Var->getDeclName())) 13411 return false; 13412 13413 if (S.RequireNonAbstractType(Loc, CaptureType, 13414 diag::err_capture_of_abstract_type)) 13415 return false; 13416 } 13417 } 13418 13419 // Capture this variable in the lambda. 13420 if (BuildAndDiagnose) 13421 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13422 RefersToCapturedVariable); 13423 13424 // Compute the type of a reference to this captured variable. 13425 if (ByRef) 13426 DeclRefType = CaptureType.getNonReferenceType(); 13427 else { 13428 // C++ [expr.prim.lambda]p5: 13429 // The closure type for a lambda-expression has a public inline 13430 // function call operator [...]. This function call operator is 13431 // declared const (9.3.1) if and only if the lambda-expression’s 13432 // parameter-declaration-clause is not followed by mutable. 13433 DeclRefType = CaptureType.getNonReferenceType(); 13434 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13435 DeclRefType.addConst(); 13436 } 13437 13438 // Add the capture. 13439 if (BuildAndDiagnose) 13440 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13441 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13442 13443 return true; 13444 } 13445 13446 bool Sema::tryCaptureVariable( 13447 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13448 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13449 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13450 // An init-capture is notionally from the context surrounding its 13451 // declaration, but its parent DC is the lambda class. 13452 DeclContext *VarDC = Var->getDeclContext(); 13453 if (Var->isInitCapture()) 13454 VarDC = VarDC->getParent(); 13455 13456 DeclContext *DC = CurContext; 13457 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13458 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13459 // We need to sync up the Declaration Context with the 13460 // FunctionScopeIndexToStopAt 13461 if (FunctionScopeIndexToStopAt) { 13462 unsigned FSIndex = FunctionScopes.size() - 1; 13463 while (FSIndex != MaxFunctionScopesIndex) { 13464 DC = getLambdaAwareParentOfDeclContext(DC); 13465 --FSIndex; 13466 } 13467 } 13468 13469 13470 // If the variable is declared in the current context, there is no need to 13471 // capture it. 13472 if (VarDC == DC) return true; 13473 13474 // Capture global variables if it is required to use private copy of this 13475 // variable. 13476 bool IsGlobal = !Var->hasLocalStorage(); 13477 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13478 return true; 13479 13480 // Walk up the stack to determine whether we can capture the variable, 13481 // performing the "simple" checks that don't depend on type. We stop when 13482 // we've either hit the declared scope of the variable or find an existing 13483 // capture of that variable. We start from the innermost capturing-entity 13484 // (the DC) and ensure that all intervening capturing-entities 13485 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13486 // declcontext can either capture the variable or have already captured 13487 // the variable. 13488 CaptureType = Var->getType(); 13489 DeclRefType = CaptureType.getNonReferenceType(); 13490 bool Nested = false; 13491 bool Explicit = (Kind != TryCapture_Implicit); 13492 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13493 unsigned OpenMPLevel = 0; 13494 do { 13495 // Only block literals, captured statements, and lambda expressions can 13496 // capture; other scopes don't work. 13497 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13498 ExprLoc, 13499 BuildAndDiagnose, 13500 *this); 13501 // We need to check for the parent *first* because, if we *have* 13502 // private-captured a global variable, we need to recursively capture it in 13503 // intermediate blocks, lambdas, etc. 13504 if (!ParentDC) { 13505 if (IsGlobal) { 13506 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13507 break; 13508 } 13509 return true; 13510 } 13511 13512 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13513 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13514 13515 13516 // Check whether we've already captured it. 13517 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13518 DeclRefType)) 13519 break; 13520 // If we are instantiating a generic lambda call operator body, 13521 // we do not want to capture new variables. What was captured 13522 // during either a lambdas transformation or initial parsing 13523 // should be used. 13524 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13525 if (BuildAndDiagnose) { 13526 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13527 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13528 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13529 Diag(Var->getLocation(), diag::note_previous_decl) 13530 << Var->getDeclName(); 13531 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13532 } else 13533 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13534 } 13535 return true; 13536 } 13537 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13538 // certain types of variables (unnamed, variably modified types etc.) 13539 // so check for eligibility. 13540 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13541 return true; 13542 13543 // Try to capture variable-length arrays types. 13544 if (Var->getType()->isVariablyModifiedType()) { 13545 // We're going to walk down into the type and look for VLA 13546 // expressions. 13547 QualType QTy = Var->getType(); 13548 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13549 QTy = PVD->getOriginalType(); 13550 captureVariablyModifiedType(Context, QTy, CSI); 13551 } 13552 13553 if (getLangOpts().OpenMP) { 13554 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13555 // OpenMP private variables should not be captured in outer scope, so 13556 // just break here. Similarly, global variables that are captured in a 13557 // target region should not be captured outside the scope of the region. 13558 if (RSI->CapRegionKind == CR_OpenMP) { 13559 auto isTargetCap = isOpenMPTargetCapturedDecl(Var, OpenMPLevel); 13560 // When we detect target captures we are looking from inside the 13561 // target region, therefore we need to propagate the capture from the 13562 // enclosing region. Therefore, the capture is not initially nested. 13563 if (isTargetCap) 13564 FunctionScopesIndex--; 13565 13566 if (isTargetCap || isOpenMPPrivateDecl(Var, OpenMPLevel)) { 13567 Nested = !isTargetCap; 13568 DeclRefType = DeclRefType.getUnqualifiedType(); 13569 CaptureType = Context.getLValueReferenceType(DeclRefType); 13570 break; 13571 } 13572 ++OpenMPLevel; 13573 } 13574 } 13575 } 13576 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13577 // No capture-default, and this is not an explicit capture 13578 // so cannot capture this variable. 13579 if (BuildAndDiagnose) { 13580 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13581 Diag(Var->getLocation(), diag::note_previous_decl) 13582 << Var->getDeclName(); 13583 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13584 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13585 diag::note_lambda_decl); 13586 // FIXME: If we error out because an outer lambda can not implicitly 13587 // capture a variable that an inner lambda explicitly captures, we 13588 // should have the inner lambda do the explicit capture - because 13589 // it makes for cleaner diagnostics later. This would purely be done 13590 // so that the diagnostic does not misleadingly claim that a variable 13591 // can not be captured by a lambda implicitly even though it is captured 13592 // explicitly. Suggestion: 13593 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13594 // at the function head 13595 // - cache the StartingDeclContext - this must be a lambda 13596 // - captureInLambda in the innermost lambda the variable. 13597 } 13598 return true; 13599 } 13600 13601 FunctionScopesIndex--; 13602 DC = ParentDC; 13603 Explicit = false; 13604 } while (!VarDC->Equals(DC)); 13605 13606 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13607 // computing the type of the capture at each step, checking type-specific 13608 // requirements, and adding captures if requested. 13609 // If the variable had already been captured previously, we start capturing 13610 // at the lambda nested within that one. 13611 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13612 ++I) { 13613 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13614 13615 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13616 if (!captureInBlock(BSI, Var, ExprLoc, 13617 BuildAndDiagnose, CaptureType, 13618 DeclRefType, Nested, *this)) 13619 return true; 13620 Nested = true; 13621 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13622 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13623 BuildAndDiagnose, CaptureType, 13624 DeclRefType, Nested, *this)) 13625 return true; 13626 Nested = true; 13627 } else { 13628 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13629 if (!captureInLambda(LSI, Var, ExprLoc, 13630 BuildAndDiagnose, CaptureType, 13631 DeclRefType, Nested, Kind, EllipsisLoc, 13632 /*IsTopScope*/I == N - 1, *this)) 13633 return true; 13634 Nested = true; 13635 } 13636 } 13637 return false; 13638 } 13639 13640 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13641 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13642 QualType CaptureType; 13643 QualType DeclRefType; 13644 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13645 /*BuildAndDiagnose=*/true, CaptureType, 13646 DeclRefType, nullptr); 13647 } 13648 13649 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13650 QualType CaptureType; 13651 QualType DeclRefType; 13652 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13653 /*BuildAndDiagnose=*/false, CaptureType, 13654 DeclRefType, nullptr); 13655 } 13656 13657 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13658 QualType CaptureType; 13659 QualType DeclRefType; 13660 13661 // Determine whether we can capture this variable. 13662 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13663 /*BuildAndDiagnose=*/false, CaptureType, 13664 DeclRefType, nullptr)) 13665 return QualType(); 13666 13667 return DeclRefType; 13668 } 13669 13670 13671 13672 // If either the type of the variable or the initializer is dependent, 13673 // return false. Otherwise, determine whether the variable is a constant 13674 // expression. Use this if you need to know if a variable that might or 13675 // might not be dependent is truly a constant expression. 13676 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13677 ASTContext &Context) { 13678 13679 if (Var->getType()->isDependentType()) 13680 return false; 13681 const VarDecl *DefVD = nullptr; 13682 Var->getAnyInitializer(DefVD); 13683 if (!DefVD) 13684 return false; 13685 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13686 Expr *Init = cast<Expr>(Eval->Value); 13687 if (Init->isValueDependent()) 13688 return false; 13689 return IsVariableAConstantExpression(Var, Context); 13690 } 13691 13692 13693 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13694 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13695 // an object that satisfies the requirements for appearing in a 13696 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13697 // is immediately applied." This function handles the lvalue-to-rvalue 13698 // conversion part. 13699 MaybeODRUseExprs.erase(E->IgnoreParens()); 13700 13701 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13702 // to a variable that is a constant expression, and if so, identify it as 13703 // a reference to a variable that does not involve an odr-use of that 13704 // variable. 13705 if (LambdaScopeInfo *LSI = getCurLambda()) { 13706 Expr *SansParensExpr = E->IgnoreParens(); 13707 VarDecl *Var = nullptr; 13708 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13709 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13710 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13711 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13712 13713 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13714 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13715 } 13716 } 13717 13718 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13719 Res = CorrectDelayedTyposInExpr(Res); 13720 13721 if (!Res.isUsable()) 13722 return Res; 13723 13724 // If a constant-expression is a reference to a variable where we delay 13725 // deciding whether it is an odr-use, just assume we will apply the 13726 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13727 // (a non-type template argument), we have special handling anyway. 13728 UpdateMarkingForLValueToRValue(Res.get()); 13729 return Res; 13730 } 13731 13732 void Sema::CleanupVarDeclMarking() { 13733 for (Expr *E : MaybeODRUseExprs) { 13734 VarDecl *Var; 13735 SourceLocation Loc; 13736 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13737 Var = cast<VarDecl>(DRE->getDecl()); 13738 Loc = DRE->getLocation(); 13739 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13740 Var = cast<VarDecl>(ME->getMemberDecl()); 13741 Loc = ME->getMemberLoc(); 13742 } else { 13743 llvm_unreachable("Unexpected expression"); 13744 } 13745 13746 MarkVarDeclODRUsed(Var, Loc, *this, 13747 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13748 } 13749 13750 MaybeODRUseExprs.clear(); 13751 } 13752 13753 13754 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13755 VarDecl *Var, Expr *E) { 13756 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13757 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13758 Var->setReferenced(); 13759 13760 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13761 bool MarkODRUsed = true; 13762 13763 // If the context is not potentially evaluated, this is not an odr-use and 13764 // does not trigger instantiation. 13765 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13766 if (SemaRef.isUnevaluatedContext()) 13767 return; 13768 13769 // If we don't yet know whether this context is going to end up being an 13770 // evaluated context, and we're referencing a variable from an enclosing 13771 // scope, add a potential capture. 13772 // 13773 // FIXME: Is this necessary? These contexts are only used for default 13774 // arguments, where local variables can't be used. 13775 const bool RefersToEnclosingScope = 13776 (SemaRef.CurContext != Var->getDeclContext() && 13777 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13778 if (RefersToEnclosingScope) { 13779 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13780 // If a variable could potentially be odr-used, defer marking it so 13781 // until we finish analyzing the full expression for any 13782 // lvalue-to-rvalue 13783 // or discarded value conversions that would obviate odr-use. 13784 // Add it to the list of potential captures that will be analyzed 13785 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13786 // unless the variable is a reference that was initialized by a constant 13787 // expression (this will never need to be captured or odr-used). 13788 assert(E && "Capture variable should be used in an expression."); 13789 if (!Var->getType()->isReferenceType() || 13790 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13791 LSI->addPotentialCapture(E->IgnoreParens()); 13792 } 13793 } 13794 13795 if (!isTemplateInstantiation(TSK)) 13796 return; 13797 13798 // Instantiate, but do not mark as odr-used, variable templates. 13799 MarkODRUsed = false; 13800 } 13801 13802 VarTemplateSpecializationDecl *VarSpec = 13803 dyn_cast<VarTemplateSpecializationDecl>(Var); 13804 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13805 "Can't instantiate a partial template specialization."); 13806 13807 // Perform implicit instantiation of static data members, static data member 13808 // templates of class templates, and variable template specializations. Delay 13809 // instantiations of variable templates, except for those that could be used 13810 // in a constant expression. 13811 if (isTemplateInstantiation(TSK)) { 13812 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13813 13814 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13815 if (Var->getPointOfInstantiation().isInvalid()) { 13816 // This is a modification of an existing AST node. Notify listeners. 13817 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13818 L->StaticDataMemberInstantiated(Var); 13819 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13820 // Don't bother trying to instantiate it again, unless we might need 13821 // its initializer before we get to the end of the TU. 13822 TryInstantiating = false; 13823 } 13824 13825 if (Var->getPointOfInstantiation().isInvalid()) 13826 Var->setTemplateSpecializationKind(TSK, Loc); 13827 13828 if (TryInstantiating) { 13829 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13830 bool InstantiationDependent = false; 13831 bool IsNonDependent = 13832 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13833 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13834 : true; 13835 13836 // Do not instantiate specializations that are still type-dependent. 13837 if (IsNonDependent) { 13838 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13839 // Do not defer instantiations of variables which could be used in a 13840 // constant expression. 13841 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13842 } else { 13843 SemaRef.PendingInstantiations 13844 .push_back(std::make_pair(Var, PointOfInstantiation)); 13845 } 13846 } 13847 } 13848 } 13849 13850 if(!MarkODRUsed) return; 13851 13852 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13853 // the requirements for appearing in a constant expression (5.19) and, if 13854 // it is an object, the lvalue-to-rvalue conversion (4.1) 13855 // is immediately applied." We check the first part here, and 13856 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13857 // Note that we use the C++11 definition everywhere because nothing in 13858 // C++03 depends on whether we get the C++03 version correct. The second 13859 // part does not apply to references, since they are not objects. 13860 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13861 // A reference initialized by a constant expression can never be 13862 // odr-used, so simply ignore it. 13863 if (!Var->getType()->isReferenceType()) 13864 SemaRef.MaybeODRUseExprs.insert(E); 13865 } else 13866 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13867 /*MaxFunctionScopeIndex ptr*/ nullptr); 13868 } 13869 13870 /// \brief Mark a variable referenced, and check whether it is odr-used 13871 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13872 /// used directly for normal expressions referring to VarDecl. 13873 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13874 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13875 } 13876 13877 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13878 Decl *D, Expr *E, bool MightBeOdrUse) { 13879 if (SemaRef.isInOpenMPDeclareTargetContext()) 13880 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 13881 13882 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13883 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13884 return; 13885 } 13886 13887 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 13888 13889 // If this is a call to a method via a cast, also mark the method in the 13890 // derived class used in case codegen can devirtualize the call. 13891 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13892 if (!ME) 13893 return; 13894 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13895 if (!MD) 13896 return; 13897 // Only attempt to devirtualize if this is truly a virtual call. 13898 bool IsVirtualCall = MD->isVirtual() && 13899 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13900 if (!IsVirtualCall) 13901 return; 13902 const Expr *Base = ME->getBase(); 13903 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13904 if (!MostDerivedClassDecl) 13905 return; 13906 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13907 if (!DM || DM->isPure()) 13908 return; 13909 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 13910 } 13911 13912 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13913 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13914 // TODO: update this with DR# once a defect report is filed. 13915 // C++11 defect. The address of a pure member should not be an ODR use, even 13916 // if it's a qualified reference. 13917 bool OdrUse = true; 13918 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13919 if (Method->isVirtual()) 13920 OdrUse = false; 13921 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13922 } 13923 13924 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13925 void Sema::MarkMemberReferenced(MemberExpr *E) { 13926 // C++11 [basic.def.odr]p2: 13927 // A non-overloaded function whose name appears as a potentially-evaluated 13928 // expression or a member of a set of candidate functions, if selected by 13929 // overload resolution when referred to from a potentially-evaluated 13930 // expression, is odr-used, unless it is a pure virtual function and its 13931 // name is not explicitly qualified. 13932 bool MightBeOdrUse = true; 13933 if (E->performsVirtualDispatch(getLangOpts())) { 13934 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13935 if (Method->isPure()) 13936 MightBeOdrUse = false; 13937 } 13938 SourceLocation Loc = E->getMemberLoc().isValid() ? 13939 E->getMemberLoc() : E->getLocStart(); 13940 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 13941 } 13942 13943 /// \brief Perform marking for a reference to an arbitrary declaration. It 13944 /// marks the declaration referenced, and performs odr-use checking for 13945 /// functions and variables. This method should not be used when building a 13946 /// normal expression which refers to a variable. 13947 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 13948 bool MightBeOdrUse) { 13949 if (MightBeOdrUse) { 13950 if (auto *VD = dyn_cast<VarDecl>(D)) { 13951 MarkVariableReferenced(Loc, VD); 13952 return; 13953 } 13954 } 13955 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13956 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 13957 return; 13958 } 13959 D->setReferenced(); 13960 } 13961 13962 namespace { 13963 // Mark all of the declarations referenced 13964 // FIXME: Not fully implemented yet! We need to have a better understanding 13965 // of when we're entering 13966 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13967 Sema &S; 13968 SourceLocation Loc; 13969 13970 public: 13971 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13972 13973 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13974 13975 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13976 bool TraverseRecordType(RecordType *T); 13977 }; 13978 } 13979 13980 bool MarkReferencedDecls::TraverseTemplateArgument( 13981 const TemplateArgument &Arg) { 13982 if (Arg.getKind() == TemplateArgument::Declaration) { 13983 if (Decl *D = Arg.getAsDecl()) 13984 S.MarkAnyDeclReferenced(Loc, D, true); 13985 } 13986 13987 return Inherited::TraverseTemplateArgument(Arg); 13988 } 13989 13990 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13991 if (ClassTemplateSpecializationDecl *Spec 13992 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13993 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13994 return TraverseTemplateArguments(Args.data(), Args.size()); 13995 } 13996 13997 return true; 13998 } 13999 14000 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14001 MarkReferencedDecls Marker(*this, Loc); 14002 Marker.TraverseType(Context.getCanonicalType(T)); 14003 } 14004 14005 namespace { 14006 /// \brief Helper class that marks all of the declarations referenced by 14007 /// potentially-evaluated subexpressions as "referenced". 14008 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14009 Sema &S; 14010 bool SkipLocalVariables; 14011 14012 public: 14013 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14014 14015 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14016 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14017 14018 void VisitDeclRefExpr(DeclRefExpr *E) { 14019 // If we were asked not to visit local variables, don't. 14020 if (SkipLocalVariables) { 14021 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14022 if (VD->hasLocalStorage()) 14023 return; 14024 } 14025 14026 S.MarkDeclRefReferenced(E); 14027 } 14028 14029 void VisitMemberExpr(MemberExpr *E) { 14030 S.MarkMemberReferenced(E); 14031 Inherited::VisitMemberExpr(E); 14032 } 14033 14034 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14035 S.MarkFunctionReferenced(E->getLocStart(), 14036 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14037 Visit(E->getSubExpr()); 14038 } 14039 14040 void VisitCXXNewExpr(CXXNewExpr *E) { 14041 if (E->getOperatorNew()) 14042 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14043 if (E->getOperatorDelete()) 14044 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14045 Inherited::VisitCXXNewExpr(E); 14046 } 14047 14048 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14049 if (E->getOperatorDelete()) 14050 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14051 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14052 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14053 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14054 S.MarkFunctionReferenced(E->getLocStart(), 14055 S.LookupDestructor(Record)); 14056 } 14057 14058 Inherited::VisitCXXDeleteExpr(E); 14059 } 14060 14061 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14062 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14063 Inherited::VisitCXXConstructExpr(E); 14064 } 14065 14066 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14067 Visit(E->getExpr()); 14068 } 14069 14070 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14071 Inherited::VisitImplicitCastExpr(E); 14072 14073 if (E->getCastKind() == CK_LValueToRValue) 14074 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14075 } 14076 }; 14077 } 14078 14079 /// \brief Mark any declarations that appear within this expression or any 14080 /// potentially-evaluated subexpressions as "referenced". 14081 /// 14082 /// \param SkipLocalVariables If true, don't mark local variables as 14083 /// 'referenced'. 14084 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14085 bool SkipLocalVariables) { 14086 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14087 } 14088 14089 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14090 /// of the program being compiled. 14091 /// 14092 /// This routine emits the given diagnostic when the code currently being 14093 /// type-checked is "potentially evaluated", meaning that there is a 14094 /// possibility that the code will actually be executable. Code in sizeof() 14095 /// expressions, code used only during overload resolution, etc., are not 14096 /// potentially evaluated. This routine will suppress such diagnostics or, 14097 /// in the absolutely nutty case of potentially potentially evaluated 14098 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14099 /// later. 14100 /// 14101 /// This routine should be used for all diagnostics that describe the run-time 14102 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14103 /// Failure to do so will likely result in spurious diagnostics or failures 14104 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14105 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14106 const PartialDiagnostic &PD) { 14107 switch (ExprEvalContexts.back().Context) { 14108 case Unevaluated: 14109 case UnevaluatedAbstract: 14110 // The argument will never be evaluated, so don't complain. 14111 break; 14112 14113 case ConstantEvaluated: 14114 // Relevant diagnostics should be produced by constant evaluation. 14115 break; 14116 14117 case PotentiallyEvaluated: 14118 case PotentiallyEvaluatedIfUsed: 14119 if (Statement && getCurFunctionOrMethodDecl()) { 14120 FunctionScopes.back()->PossiblyUnreachableDiags. 14121 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14122 } 14123 else 14124 Diag(Loc, PD); 14125 14126 return true; 14127 } 14128 14129 return false; 14130 } 14131 14132 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14133 CallExpr *CE, FunctionDecl *FD) { 14134 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14135 return false; 14136 14137 // If we're inside a decltype's expression, don't check for a valid return 14138 // type or construct temporaries until we know whether this is the last call. 14139 if (ExprEvalContexts.back().IsDecltype) { 14140 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14141 return false; 14142 } 14143 14144 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14145 FunctionDecl *FD; 14146 CallExpr *CE; 14147 14148 public: 14149 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14150 : FD(FD), CE(CE) { } 14151 14152 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14153 if (!FD) { 14154 S.Diag(Loc, diag::err_call_incomplete_return) 14155 << T << CE->getSourceRange(); 14156 return; 14157 } 14158 14159 S.Diag(Loc, diag::err_call_function_incomplete_return) 14160 << CE->getSourceRange() << FD->getDeclName() << T; 14161 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14162 << FD->getDeclName(); 14163 } 14164 } Diagnoser(FD, CE); 14165 14166 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14167 return true; 14168 14169 return false; 14170 } 14171 14172 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14173 // will prevent this condition from triggering, which is what we want. 14174 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14175 SourceLocation Loc; 14176 14177 unsigned diagnostic = diag::warn_condition_is_assignment; 14178 bool IsOrAssign = false; 14179 14180 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14181 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14182 return; 14183 14184 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14185 14186 // Greylist some idioms by putting them into a warning subcategory. 14187 if (ObjCMessageExpr *ME 14188 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14189 Selector Sel = ME->getSelector(); 14190 14191 // self = [<foo> init...] 14192 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14193 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14194 14195 // <foo> = [<bar> nextObject] 14196 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14197 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14198 } 14199 14200 Loc = Op->getOperatorLoc(); 14201 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14202 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14203 return; 14204 14205 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14206 Loc = Op->getOperatorLoc(); 14207 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14208 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14209 else { 14210 // Not an assignment. 14211 return; 14212 } 14213 14214 Diag(Loc, diagnostic) << E->getSourceRange(); 14215 14216 SourceLocation Open = E->getLocStart(); 14217 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14218 Diag(Loc, diag::note_condition_assign_silence) 14219 << FixItHint::CreateInsertion(Open, "(") 14220 << FixItHint::CreateInsertion(Close, ")"); 14221 14222 if (IsOrAssign) 14223 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14224 << FixItHint::CreateReplacement(Loc, "!="); 14225 else 14226 Diag(Loc, diag::note_condition_assign_to_comparison) 14227 << FixItHint::CreateReplacement(Loc, "=="); 14228 } 14229 14230 /// \brief Redundant parentheses over an equality comparison can indicate 14231 /// that the user intended an assignment used as condition. 14232 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14233 // Don't warn if the parens came from a macro. 14234 SourceLocation parenLoc = ParenE->getLocStart(); 14235 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14236 return; 14237 // Don't warn for dependent expressions. 14238 if (ParenE->isTypeDependent()) 14239 return; 14240 14241 Expr *E = ParenE->IgnoreParens(); 14242 14243 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14244 if (opE->getOpcode() == BO_EQ && 14245 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14246 == Expr::MLV_Valid) { 14247 SourceLocation Loc = opE->getOperatorLoc(); 14248 14249 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14250 SourceRange ParenERange = ParenE->getSourceRange(); 14251 Diag(Loc, diag::note_equality_comparison_silence) 14252 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14253 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14254 Diag(Loc, diag::note_equality_comparison_to_assign) 14255 << FixItHint::CreateReplacement(Loc, "="); 14256 } 14257 } 14258 14259 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 14260 DiagnoseAssignmentAsCondition(E); 14261 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14262 DiagnoseEqualityWithExtraParens(parenE); 14263 14264 ExprResult result = CheckPlaceholderExpr(E); 14265 if (result.isInvalid()) return ExprError(); 14266 E = result.get(); 14267 14268 if (!E->isTypeDependent()) { 14269 if (getLangOpts().CPlusPlus) 14270 return CheckCXXBooleanCondition(E); // C++ 6.4p4 14271 14272 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14273 if (ERes.isInvalid()) 14274 return ExprError(); 14275 E = ERes.get(); 14276 14277 QualType T = E->getType(); 14278 if (!T->isScalarType()) { // C99 6.8.4.1p1 14279 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14280 << T << E->getSourceRange(); 14281 return ExprError(); 14282 } 14283 CheckBoolLikeConversion(E, Loc); 14284 } 14285 14286 return E; 14287 } 14288 14289 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 14290 Expr *SubExpr) { 14291 if (!SubExpr) 14292 return ExprError(); 14293 14294 return CheckBooleanCondition(SubExpr, Loc); 14295 } 14296 14297 namespace { 14298 /// A visitor for rebuilding a call to an __unknown_any expression 14299 /// to have an appropriate type. 14300 struct RebuildUnknownAnyFunction 14301 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14302 14303 Sema &S; 14304 14305 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14306 14307 ExprResult VisitStmt(Stmt *S) { 14308 llvm_unreachable("unexpected statement!"); 14309 } 14310 14311 ExprResult VisitExpr(Expr *E) { 14312 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14313 << E->getSourceRange(); 14314 return ExprError(); 14315 } 14316 14317 /// Rebuild an expression which simply semantically wraps another 14318 /// expression which it shares the type and value kind of. 14319 template <class T> ExprResult rebuildSugarExpr(T *E) { 14320 ExprResult SubResult = Visit(E->getSubExpr()); 14321 if (SubResult.isInvalid()) return ExprError(); 14322 14323 Expr *SubExpr = SubResult.get(); 14324 E->setSubExpr(SubExpr); 14325 E->setType(SubExpr->getType()); 14326 E->setValueKind(SubExpr->getValueKind()); 14327 assert(E->getObjectKind() == OK_Ordinary); 14328 return E; 14329 } 14330 14331 ExprResult VisitParenExpr(ParenExpr *E) { 14332 return rebuildSugarExpr(E); 14333 } 14334 14335 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14336 return rebuildSugarExpr(E); 14337 } 14338 14339 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14340 ExprResult SubResult = Visit(E->getSubExpr()); 14341 if (SubResult.isInvalid()) return ExprError(); 14342 14343 Expr *SubExpr = SubResult.get(); 14344 E->setSubExpr(SubExpr); 14345 E->setType(S.Context.getPointerType(SubExpr->getType())); 14346 assert(E->getValueKind() == VK_RValue); 14347 assert(E->getObjectKind() == OK_Ordinary); 14348 return E; 14349 } 14350 14351 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14352 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14353 14354 E->setType(VD->getType()); 14355 14356 assert(E->getValueKind() == VK_RValue); 14357 if (S.getLangOpts().CPlusPlus && 14358 !(isa<CXXMethodDecl>(VD) && 14359 cast<CXXMethodDecl>(VD)->isInstance())) 14360 E->setValueKind(VK_LValue); 14361 14362 return E; 14363 } 14364 14365 ExprResult VisitMemberExpr(MemberExpr *E) { 14366 return resolveDecl(E, E->getMemberDecl()); 14367 } 14368 14369 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14370 return resolveDecl(E, E->getDecl()); 14371 } 14372 }; 14373 } 14374 14375 /// Given a function expression of unknown-any type, try to rebuild it 14376 /// to have a function type. 14377 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14378 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14379 if (Result.isInvalid()) return ExprError(); 14380 return S.DefaultFunctionArrayConversion(Result.get()); 14381 } 14382 14383 namespace { 14384 /// A visitor for rebuilding an expression of type __unknown_anytype 14385 /// into one which resolves the type directly on the referring 14386 /// expression. Strict preservation of the original source 14387 /// structure is not a goal. 14388 struct RebuildUnknownAnyExpr 14389 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14390 14391 Sema &S; 14392 14393 /// The current destination type. 14394 QualType DestType; 14395 14396 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14397 : S(S), DestType(CastType) {} 14398 14399 ExprResult VisitStmt(Stmt *S) { 14400 llvm_unreachable("unexpected statement!"); 14401 } 14402 14403 ExprResult VisitExpr(Expr *E) { 14404 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14405 << E->getSourceRange(); 14406 return ExprError(); 14407 } 14408 14409 ExprResult VisitCallExpr(CallExpr *E); 14410 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14411 14412 /// Rebuild an expression which simply semantically wraps another 14413 /// expression which it shares the type and value kind of. 14414 template <class T> ExprResult rebuildSugarExpr(T *E) { 14415 ExprResult SubResult = Visit(E->getSubExpr()); 14416 if (SubResult.isInvalid()) return ExprError(); 14417 Expr *SubExpr = SubResult.get(); 14418 E->setSubExpr(SubExpr); 14419 E->setType(SubExpr->getType()); 14420 E->setValueKind(SubExpr->getValueKind()); 14421 assert(E->getObjectKind() == OK_Ordinary); 14422 return E; 14423 } 14424 14425 ExprResult VisitParenExpr(ParenExpr *E) { 14426 return rebuildSugarExpr(E); 14427 } 14428 14429 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14430 return rebuildSugarExpr(E); 14431 } 14432 14433 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14434 const PointerType *Ptr = DestType->getAs<PointerType>(); 14435 if (!Ptr) { 14436 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14437 << E->getSourceRange(); 14438 return ExprError(); 14439 } 14440 assert(E->getValueKind() == VK_RValue); 14441 assert(E->getObjectKind() == OK_Ordinary); 14442 E->setType(DestType); 14443 14444 // Build the sub-expression as if it were an object of the pointee type. 14445 DestType = Ptr->getPointeeType(); 14446 ExprResult SubResult = Visit(E->getSubExpr()); 14447 if (SubResult.isInvalid()) return ExprError(); 14448 E->setSubExpr(SubResult.get()); 14449 return E; 14450 } 14451 14452 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14453 14454 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14455 14456 ExprResult VisitMemberExpr(MemberExpr *E) { 14457 return resolveDecl(E, E->getMemberDecl()); 14458 } 14459 14460 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14461 return resolveDecl(E, E->getDecl()); 14462 } 14463 }; 14464 } 14465 14466 /// Rebuilds a call expression which yielded __unknown_anytype. 14467 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14468 Expr *CalleeExpr = E->getCallee(); 14469 14470 enum FnKind { 14471 FK_MemberFunction, 14472 FK_FunctionPointer, 14473 FK_BlockPointer 14474 }; 14475 14476 FnKind Kind; 14477 QualType CalleeType = CalleeExpr->getType(); 14478 if (CalleeType == S.Context.BoundMemberTy) { 14479 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14480 Kind = FK_MemberFunction; 14481 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14482 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14483 CalleeType = Ptr->getPointeeType(); 14484 Kind = FK_FunctionPointer; 14485 } else { 14486 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14487 Kind = FK_BlockPointer; 14488 } 14489 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14490 14491 // Verify that this is a legal result type of a function. 14492 if (DestType->isArrayType() || DestType->isFunctionType()) { 14493 unsigned diagID = diag::err_func_returning_array_function; 14494 if (Kind == FK_BlockPointer) 14495 diagID = diag::err_block_returning_array_function; 14496 14497 S.Diag(E->getExprLoc(), diagID) 14498 << DestType->isFunctionType() << DestType; 14499 return ExprError(); 14500 } 14501 14502 // Otherwise, go ahead and set DestType as the call's result. 14503 E->setType(DestType.getNonLValueExprType(S.Context)); 14504 E->setValueKind(Expr::getValueKindForType(DestType)); 14505 assert(E->getObjectKind() == OK_Ordinary); 14506 14507 // Rebuild the function type, replacing the result type with DestType. 14508 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14509 if (Proto) { 14510 // __unknown_anytype(...) is a special case used by the debugger when 14511 // it has no idea what a function's signature is. 14512 // 14513 // We want to build this call essentially under the K&R 14514 // unprototyped rules, but making a FunctionNoProtoType in C++ 14515 // would foul up all sorts of assumptions. However, we cannot 14516 // simply pass all arguments as variadic arguments, nor can we 14517 // portably just call the function under a non-variadic type; see 14518 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14519 // However, it turns out that in practice it is generally safe to 14520 // call a function declared as "A foo(B,C,D);" under the prototype 14521 // "A foo(B,C,D,...);". The only known exception is with the 14522 // Windows ABI, where any variadic function is implicitly cdecl 14523 // regardless of its normal CC. Therefore we change the parameter 14524 // types to match the types of the arguments. 14525 // 14526 // This is a hack, but it is far superior to moving the 14527 // corresponding target-specific code from IR-gen to Sema/AST. 14528 14529 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14530 SmallVector<QualType, 8> ArgTypes; 14531 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14532 ArgTypes.reserve(E->getNumArgs()); 14533 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14534 Expr *Arg = E->getArg(i); 14535 QualType ArgType = Arg->getType(); 14536 if (E->isLValue()) { 14537 ArgType = S.Context.getLValueReferenceType(ArgType); 14538 } else if (E->isXValue()) { 14539 ArgType = S.Context.getRValueReferenceType(ArgType); 14540 } 14541 ArgTypes.push_back(ArgType); 14542 } 14543 ParamTypes = ArgTypes; 14544 } 14545 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14546 Proto->getExtProtoInfo()); 14547 } else { 14548 DestType = S.Context.getFunctionNoProtoType(DestType, 14549 FnType->getExtInfo()); 14550 } 14551 14552 // Rebuild the appropriate pointer-to-function type. 14553 switch (Kind) { 14554 case FK_MemberFunction: 14555 // Nothing to do. 14556 break; 14557 14558 case FK_FunctionPointer: 14559 DestType = S.Context.getPointerType(DestType); 14560 break; 14561 14562 case FK_BlockPointer: 14563 DestType = S.Context.getBlockPointerType(DestType); 14564 break; 14565 } 14566 14567 // Finally, we can recurse. 14568 ExprResult CalleeResult = Visit(CalleeExpr); 14569 if (!CalleeResult.isUsable()) return ExprError(); 14570 E->setCallee(CalleeResult.get()); 14571 14572 // Bind a temporary if necessary. 14573 return S.MaybeBindToTemporary(E); 14574 } 14575 14576 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14577 // Verify that this is a legal result type of a call. 14578 if (DestType->isArrayType() || DestType->isFunctionType()) { 14579 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14580 << DestType->isFunctionType() << DestType; 14581 return ExprError(); 14582 } 14583 14584 // Rewrite the method result type if available. 14585 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14586 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14587 Method->setReturnType(DestType); 14588 } 14589 14590 // Change the type of the message. 14591 E->setType(DestType.getNonReferenceType()); 14592 E->setValueKind(Expr::getValueKindForType(DestType)); 14593 14594 return S.MaybeBindToTemporary(E); 14595 } 14596 14597 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14598 // The only case we should ever see here is a function-to-pointer decay. 14599 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14600 assert(E->getValueKind() == VK_RValue); 14601 assert(E->getObjectKind() == OK_Ordinary); 14602 14603 E->setType(DestType); 14604 14605 // Rebuild the sub-expression as the pointee (function) type. 14606 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14607 14608 ExprResult Result = Visit(E->getSubExpr()); 14609 if (!Result.isUsable()) return ExprError(); 14610 14611 E->setSubExpr(Result.get()); 14612 return E; 14613 } else if (E->getCastKind() == CK_LValueToRValue) { 14614 assert(E->getValueKind() == VK_RValue); 14615 assert(E->getObjectKind() == OK_Ordinary); 14616 14617 assert(isa<BlockPointerType>(E->getType())); 14618 14619 E->setType(DestType); 14620 14621 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14622 DestType = S.Context.getLValueReferenceType(DestType); 14623 14624 ExprResult Result = Visit(E->getSubExpr()); 14625 if (!Result.isUsable()) return ExprError(); 14626 14627 E->setSubExpr(Result.get()); 14628 return E; 14629 } else { 14630 llvm_unreachable("Unhandled cast type!"); 14631 } 14632 } 14633 14634 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14635 ExprValueKind ValueKind = VK_LValue; 14636 QualType Type = DestType; 14637 14638 // We know how to make this work for certain kinds of decls: 14639 14640 // - functions 14641 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14642 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14643 DestType = Ptr->getPointeeType(); 14644 ExprResult Result = resolveDecl(E, VD); 14645 if (Result.isInvalid()) return ExprError(); 14646 return S.ImpCastExprToType(Result.get(), Type, 14647 CK_FunctionToPointerDecay, VK_RValue); 14648 } 14649 14650 if (!Type->isFunctionType()) { 14651 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14652 << VD << E->getSourceRange(); 14653 return ExprError(); 14654 } 14655 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14656 // We must match the FunctionDecl's type to the hack introduced in 14657 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14658 // type. See the lengthy commentary in that routine. 14659 QualType FDT = FD->getType(); 14660 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14661 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14662 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14663 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14664 SourceLocation Loc = FD->getLocation(); 14665 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14666 FD->getDeclContext(), 14667 Loc, Loc, FD->getNameInfo().getName(), 14668 DestType, FD->getTypeSourceInfo(), 14669 SC_None, false/*isInlineSpecified*/, 14670 FD->hasPrototype(), 14671 false/*isConstexprSpecified*/); 14672 14673 if (FD->getQualifier()) 14674 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14675 14676 SmallVector<ParmVarDecl*, 16> Params; 14677 for (const auto &AI : FT->param_types()) { 14678 ParmVarDecl *Param = 14679 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14680 Param->setScopeInfo(0, Params.size()); 14681 Params.push_back(Param); 14682 } 14683 NewFD->setParams(Params); 14684 DRE->setDecl(NewFD); 14685 VD = DRE->getDecl(); 14686 } 14687 } 14688 14689 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14690 if (MD->isInstance()) { 14691 ValueKind = VK_RValue; 14692 Type = S.Context.BoundMemberTy; 14693 } 14694 14695 // Function references aren't l-values in C. 14696 if (!S.getLangOpts().CPlusPlus) 14697 ValueKind = VK_RValue; 14698 14699 // - variables 14700 } else if (isa<VarDecl>(VD)) { 14701 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14702 Type = RefTy->getPointeeType(); 14703 } else if (Type->isFunctionType()) { 14704 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14705 << VD << E->getSourceRange(); 14706 return ExprError(); 14707 } 14708 14709 // - nothing else 14710 } else { 14711 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14712 << VD << E->getSourceRange(); 14713 return ExprError(); 14714 } 14715 14716 // Modifying the declaration like this is friendly to IR-gen but 14717 // also really dangerous. 14718 VD->setType(DestType); 14719 E->setType(Type); 14720 E->setValueKind(ValueKind); 14721 return E; 14722 } 14723 14724 /// Check a cast of an unknown-any type. We intentionally only 14725 /// trigger this for C-style casts. 14726 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14727 Expr *CastExpr, CastKind &CastKind, 14728 ExprValueKind &VK, CXXCastPath &Path) { 14729 // The type we're casting to must be either void or complete. 14730 if (!CastType->isVoidType() && 14731 RequireCompleteType(TypeRange.getBegin(), CastType, 14732 diag::err_typecheck_cast_to_incomplete)) 14733 return ExprError(); 14734 14735 // Rewrite the casted expression from scratch. 14736 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14737 if (!result.isUsable()) return ExprError(); 14738 14739 CastExpr = result.get(); 14740 VK = CastExpr->getValueKind(); 14741 CastKind = CK_NoOp; 14742 14743 return CastExpr; 14744 } 14745 14746 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14747 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14748 } 14749 14750 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14751 Expr *arg, QualType ¶mType) { 14752 // If the syntactic form of the argument is not an explicit cast of 14753 // any sort, just do default argument promotion. 14754 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14755 if (!castArg) { 14756 ExprResult result = DefaultArgumentPromotion(arg); 14757 if (result.isInvalid()) return ExprError(); 14758 paramType = result.get()->getType(); 14759 return result; 14760 } 14761 14762 // Otherwise, use the type that was written in the explicit cast. 14763 assert(!arg->hasPlaceholderType()); 14764 paramType = castArg->getTypeAsWritten(); 14765 14766 // Copy-initialize a parameter of that type. 14767 InitializedEntity entity = 14768 InitializedEntity::InitializeParameter(Context, paramType, 14769 /*consumed*/ false); 14770 return PerformCopyInitialization(entity, callLoc, arg); 14771 } 14772 14773 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14774 Expr *orig = E; 14775 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14776 while (true) { 14777 E = E->IgnoreParenImpCasts(); 14778 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14779 E = call->getCallee(); 14780 diagID = diag::err_uncasted_call_of_unknown_any; 14781 } else { 14782 break; 14783 } 14784 } 14785 14786 SourceLocation loc; 14787 NamedDecl *d; 14788 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14789 loc = ref->getLocation(); 14790 d = ref->getDecl(); 14791 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14792 loc = mem->getMemberLoc(); 14793 d = mem->getMemberDecl(); 14794 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14795 diagID = diag::err_uncasted_call_of_unknown_any; 14796 loc = msg->getSelectorStartLoc(); 14797 d = msg->getMethodDecl(); 14798 if (!d) { 14799 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14800 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14801 << orig->getSourceRange(); 14802 return ExprError(); 14803 } 14804 } else { 14805 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14806 << E->getSourceRange(); 14807 return ExprError(); 14808 } 14809 14810 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14811 14812 // Never recoverable. 14813 return ExprError(); 14814 } 14815 14816 /// Check for operands with placeholder types and complain if found. 14817 /// Returns true if there was an error and no recovery was possible. 14818 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14819 if (!getLangOpts().CPlusPlus) { 14820 // C cannot handle TypoExpr nodes on either side of a binop because it 14821 // doesn't handle dependent types properly, so make sure any TypoExprs have 14822 // been dealt with before checking the operands. 14823 ExprResult Result = CorrectDelayedTyposInExpr(E); 14824 if (!Result.isUsable()) return ExprError(); 14825 E = Result.get(); 14826 } 14827 14828 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14829 if (!placeholderType) return E; 14830 14831 switch (placeholderType->getKind()) { 14832 14833 // Overloaded expressions. 14834 case BuiltinType::Overload: { 14835 // Try to resolve a single function template specialization. 14836 // This is obligatory. 14837 ExprResult result = E; 14838 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14839 return result; 14840 14841 // If that failed, try to recover with a call. 14842 } else { 14843 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14844 /*complain*/ true); 14845 return result; 14846 } 14847 } 14848 14849 // Bound member functions. 14850 case BuiltinType::BoundMember: { 14851 ExprResult result = E; 14852 const Expr *BME = E->IgnoreParens(); 14853 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14854 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14855 if (isa<CXXPseudoDestructorExpr>(BME)) { 14856 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14857 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14858 if (ME->getMemberNameInfo().getName().getNameKind() == 14859 DeclarationName::CXXDestructorName) 14860 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14861 } 14862 tryToRecoverWithCall(result, PD, 14863 /*complain*/ true); 14864 return result; 14865 } 14866 14867 // ARC unbridged casts. 14868 case BuiltinType::ARCUnbridgedCast: { 14869 Expr *realCast = stripARCUnbridgedCast(E); 14870 diagnoseARCUnbridgedCast(realCast); 14871 return realCast; 14872 } 14873 14874 // Expressions of unknown type. 14875 case BuiltinType::UnknownAny: 14876 return diagnoseUnknownAnyExpr(*this, E); 14877 14878 // Pseudo-objects. 14879 case BuiltinType::PseudoObject: 14880 return checkPseudoObjectRValue(E); 14881 14882 case BuiltinType::BuiltinFn: { 14883 // Accept __noop without parens by implicitly converting it to a call expr. 14884 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14885 if (DRE) { 14886 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14887 if (FD->getBuiltinID() == Builtin::BI__noop) { 14888 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14889 CK_BuiltinFnToFnPtr).get(); 14890 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14891 VK_RValue, SourceLocation()); 14892 } 14893 } 14894 14895 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14896 return ExprError(); 14897 } 14898 14899 // Expressions of unknown type. 14900 case BuiltinType::OMPArraySection: 14901 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14902 return ExprError(); 14903 14904 // Everything else should be impossible. 14905 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 14906 case BuiltinType::Id: 14907 #include "clang/Basic/OpenCLImageTypes.def" 14908 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 14909 #define PLACEHOLDER_TYPE(Id, SingletonId) 14910 #include "clang/AST/BuiltinTypes.def" 14911 break; 14912 } 14913 14914 llvm_unreachable("invalid placeholder type!"); 14915 } 14916 14917 bool Sema::CheckCaseExpression(Expr *E) { 14918 if (E->isTypeDependent()) 14919 return true; 14920 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14921 return E->getType()->isIntegralOrEnumerationType(); 14922 return false; 14923 } 14924 14925 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14926 ExprResult 14927 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14928 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14929 "Unknown Objective-C Boolean value!"); 14930 QualType BoolT = Context.ObjCBuiltinBoolTy; 14931 if (!Context.getBOOLDecl()) { 14932 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14933 Sema::LookupOrdinaryName); 14934 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14935 NamedDecl *ND = Result.getFoundDecl(); 14936 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14937 Context.setBOOLDecl(TD); 14938 } 14939 } 14940 if (Context.getBOOLDecl()) 14941 BoolT = Context.getBOOLType(); 14942 return new (Context) 14943 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14944 } 14945