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) { 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 (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 (D->hasAttr<UnusedAttr>()) { 80 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 81 if (DC && !DC->hasAttr<UnusedAttr>()) 82 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 83 } 84 } 85 86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 87 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 88 if (!OMD) 89 return false; 90 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 91 if (!OID) 92 return false; 93 94 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 95 if (ObjCMethodDecl *CatMeth = 96 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 97 if (!CatMeth->hasAttr<AvailabilityAttr>()) 98 return true; 99 return false; 100 } 101 102 static AvailabilityResult 103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 104 const ObjCInterfaceDecl *UnknownObjCClass, 105 bool ObjCPropertyAccess) { 106 // See if this declaration is unavailable or deprecated. 107 std::string Message; 108 AvailabilityResult Result = D->getAvailability(&Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(&Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(&Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(&Message); 136 } 137 138 const ObjCPropertyDecl *ObjCPDecl = nullptr; 139 if (Result == AR_Deprecated || Result == AR_Unavailable || 140 Result == AR_NotYetIntroduced) { 141 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 142 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 143 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 144 if (PDeclResult == Result) 145 ObjCPDecl = PD; 146 } 147 } 148 } 149 150 switch (Result) { 151 case AR_Available: 152 break; 153 154 case AR_Deprecated: 155 if (S.getCurContextAvailability() != AR_Deprecated) 156 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 157 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 158 ObjCPropertyAccess); 159 break; 160 161 case AR_NotYetIntroduced: { 162 // With strict, the compiler will emit unavailable error. 163 AvailabilityAttr *AA = D->getAttr<AvailabilityAttr>(); 164 if (AA && AA->getStrict() && 165 S.getCurContextAvailability() != AR_NotYetIntroduced) 166 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 167 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 168 ObjCPropertyAccess); 169 170 // Don't do this for enums, they can't be redeclared. 171 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 172 break; 173 174 bool Warn = !AA->isInherited(); 175 // Objective-C method declarations in categories are not modelled as 176 // redeclarations, so manually look for a redeclaration in a category 177 // if necessary. 178 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 179 Warn = false; 180 // In general, D will point to the most recent redeclaration. However, 181 // for `@class A;` decls, this isn't true -- manually go through the 182 // redecl chain in that case. 183 if (Warn && isa<ObjCInterfaceDecl>(D)) 184 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 185 Redecl = Redecl->getPreviousDecl()) 186 if (!Redecl->hasAttr<AvailabilityAttr>() || 187 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 188 Warn = false; 189 190 if (Warn) 191 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 192 UnknownObjCClass, ObjCPDecl, 193 ObjCPropertyAccess); 194 break; 195 } 196 197 case AR_Unavailable: 198 if (S.getCurContextAvailability() != AR_Unavailable) 199 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 200 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 201 ObjCPropertyAccess); 202 break; 203 204 } 205 return Result; 206 } 207 208 /// \brief Emit a note explaining that this function is deleted. 209 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 210 assert(Decl->isDeleted()); 211 212 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 213 214 if (Method && Method->isDeleted() && Method->isDefaulted()) { 215 // If the method was explicitly defaulted, point at that declaration. 216 if (!Method->isImplicit()) 217 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 218 219 // Try to diagnose why this special member function was implicitly 220 // deleted. This might fail, if that reason no longer applies. 221 CXXSpecialMember CSM = getSpecialMember(Method); 222 if (CSM != CXXInvalid) 223 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 224 225 return; 226 } 227 228 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 229 if (CXXConstructorDecl *BaseCD = 230 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 231 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 232 if (BaseCD->isDeleted()) { 233 NoteDeletedFunction(BaseCD); 234 } else { 235 // FIXME: An explanation of why exactly it can't be inherited 236 // would be nice. 237 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 238 } 239 return; 240 } 241 } 242 243 Diag(Decl->getLocation(), diag::note_availability_specified_here) 244 << Decl << true; 245 } 246 247 /// \brief Determine whether a FunctionDecl was ever declared with an 248 /// explicit storage class. 249 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 250 for (auto I : D->redecls()) { 251 if (I->getStorageClass() != SC_None) 252 return true; 253 } 254 return false; 255 } 256 257 /// \brief Check whether we're in an extern inline function and referring to a 258 /// variable or function with internal linkage (C11 6.7.4p3). 259 /// 260 /// This is only a warning because we used to silently accept this code, but 261 /// in many cases it will not behave correctly. This is not enabled in C++ mode 262 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 263 /// and so while there may still be user mistakes, most of the time we can't 264 /// prove that there are errors. 265 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 266 const NamedDecl *D, 267 SourceLocation Loc) { 268 // This is disabled under C++; there are too many ways for this to fire in 269 // contexts where the warning is a false positive, or where it is technically 270 // correct but benign. 271 if (S.getLangOpts().CPlusPlus) 272 return; 273 274 // Check if this is an inlined function or method. 275 FunctionDecl *Current = S.getCurFunctionDecl(); 276 if (!Current) 277 return; 278 if (!Current->isInlined()) 279 return; 280 if (!Current->isExternallyVisible()) 281 return; 282 283 // Check if the decl has internal linkage. 284 if (D->getFormalLinkage() != InternalLinkage) 285 return; 286 287 // Downgrade from ExtWarn to Extension if 288 // (1) the supposedly external inline function is in the main file, 289 // and probably won't be included anywhere else. 290 // (2) the thing we're referencing is a pure function. 291 // (3) the thing we're referencing is another inline function. 292 // This last can give us false negatives, but it's better than warning on 293 // wrappers for simple C library functions. 294 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 295 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 296 if (!DowngradeWarning && UsedFn) 297 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 298 299 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 300 : diag::ext_internal_in_extern_inline) 301 << /*IsVar=*/!UsedFn << D; 302 303 S.MaybeSuggestAddingStaticToDecl(Current); 304 305 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 306 << D; 307 } 308 309 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 310 const FunctionDecl *First = Cur->getFirstDecl(); 311 312 // Suggest "static" on the function, if possible. 313 if (!hasAnyExplicitStorageClass(First)) { 314 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 315 Diag(DeclBegin, diag::note_convert_inline_to_static) 316 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 317 } 318 } 319 320 /// \brief Determine whether the use of this declaration is valid, and 321 /// emit any corresponding diagnostics. 322 /// 323 /// This routine diagnoses various problems with referencing 324 /// declarations that can occur when using a declaration. For example, 325 /// it might warn if a deprecated or unavailable declaration is being 326 /// used, or produce an error (and return true) if a C++0x deleted 327 /// function is being used. 328 /// 329 /// \returns true if there was an error (this declaration cannot be 330 /// referenced), false otherwise. 331 /// 332 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 333 const ObjCInterfaceDecl *UnknownObjCClass, 334 bool ObjCPropertyAccess) { 335 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 336 // If there were any diagnostics suppressed by template argument deduction, 337 // emit them now. 338 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 339 if (Pos != SuppressedDiagnostics.end()) { 340 for (const PartialDiagnosticAt &Suppressed : Pos->second) 341 Diag(Suppressed.first, Suppressed.second); 342 343 // Clear out the list of suppressed diagnostics, so that we don't emit 344 // them again for this specialization. However, we don't obsolete this 345 // entry from the table, because we want to avoid ever emitting these 346 // diagnostics again. 347 Pos->second.clear(); 348 } 349 350 // C++ [basic.start.main]p3: 351 // The function 'main' shall not be used within a program. 352 if (cast<FunctionDecl>(D)->isMain()) 353 Diag(Loc, diag::ext_main_used); 354 } 355 356 // See if this is an auto-typed variable whose initializer we are parsing. 357 if (ParsingInitForAutoVars.count(D)) { 358 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 359 360 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 361 << D->getDeclName() << (unsigned)AT->getKeyword(); 362 return true; 363 } 364 365 // See if this is a deleted function. 366 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 367 if (FD->isDeleted()) { 368 Diag(Loc, diag::err_deleted_function_use); 369 NoteDeletedFunction(FD); 370 return true; 371 } 372 373 // If the function has a deduced return type, and we can't deduce it, 374 // then we can't use it either. 375 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 376 DeduceReturnType(FD, Loc)) 377 return true; 378 } 379 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 380 ObjCPropertyAccess); 381 382 DiagnoseUnusedOfDecl(*this, D, Loc); 383 384 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 385 386 return false; 387 } 388 389 /// \brief Retrieve the message suffix that should be added to a 390 /// diagnostic complaining about the given function being deleted or 391 /// unavailable. 392 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 393 std::string Message; 394 if (FD->getAvailability(&Message)) 395 return ": " + Message; 396 397 return std::string(); 398 } 399 400 /// DiagnoseSentinelCalls - This routine checks whether a call or 401 /// message-send is to a declaration with the sentinel attribute, and 402 /// if so, it checks that the requirements of the sentinel are 403 /// satisfied. 404 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 405 ArrayRef<Expr *> Args) { 406 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 407 if (!attr) 408 return; 409 410 // The number of formal parameters of the declaration. 411 unsigned numFormalParams; 412 413 // The kind of declaration. This is also an index into a %select in 414 // the diagnostic. 415 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 416 417 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 418 numFormalParams = MD->param_size(); 419 calleeType = CT_Method; 420 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 421 numFormalParams = FD->param_size(); 422 calleeType = CT_Function; 423 } else if (isa<VarDecl>(D)) { 424 QualType type = cast<ValueDecl>(D)->getType(); 425 const FunctionType *fn = nullptr; 426 if (const PointerType *ptr = type->getAs<PointerType>()) { 427 fn = ptr->getPointeeType()->getAs<FunctionType>(); 428 if (!fn) return; 429 calleeType = CT_Function; 430 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 431 fn = ptr->getPointeeType()->castAs<FunctionType>(); 432 calleeType = CT_Block; 433 } else { 434 return; 435 } 436 437 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 438 numFormalParams = proto->getNumParams(); 439 } else { 440 numFormalParams = 0; 441 } 442 } else { 443 return; 444 } 445 446 // "nullPos" is the number of formal parameters at the end which 447 // effectively count as part of the variadic arguments. This is 448 // useful if you would prefer to not have *any* formal parameters, 449 // but the language forces you to have at least one. 450 unsigned nullPos = attr->getNullPos(); 451 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 452 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 453 454 // The number of arguments which should follow the sentinel. 455 unsigned numArgsAfterSentinel = attr->getSentinel(); 456 457 // If there aren't enough arguments for all the formal parameters, 458 // the sentinel, and the args after the sentinel, complain. 459 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 460 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 461 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 462 return; 463 } 464 465 // Otherwise, find the sentinel expression. 466 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 467 if (!sentinelExpr) return; 468 if (sentinelExpr->isValueDependent()) return; 469 if (Context.isSentinelNullExpr(sentinelExpr)) return; 470 471 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 472 // or 'NULL' if those are actually defined in the context. Only use 473 // 'nil' for ObjC methods, where it's much more likely that the 474 // variadic arguments form a list of object pointers. 475 SourceLocation MissingNilLoc 476 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 477 std::string NullValue; 478 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 479 NullValue = "nil"; 480 else if (getLangOpts().CPlusPlus11) 481 NullValue = "nullptr"; 482 else if (PP.isMacroDefined("NULL")) 483 NullValue = "NULL"; 484 else 485 NullValue = "(void*) 0"; 486 487 if (MissingNilLoc.isInvalid()) 488 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 489 else 490 Diag(MissingNilLoc, diag::warn_missing_sentinel) 491 << int(calleeType) 492 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 493 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 494 } 495 496 SourceRange Sema::getExprRange(Expr *E) const { 497 return E ? E->getSourceRange() : SourceRange(); 498 } 499 500 //===----------------------------------------------------------------------===// 501 // Standard Promotions and Conversions 502 //===----------------------------------------------------------------------===// 503 504 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 505 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 506 // Handle any placeholder expressions which made it here. 507 if (E->getType()->isPlaceholderType()) { 508 ExprResult result = CheckPlaceholderExpr(E); 509 if (result.isInvalid()) return ExprError(); 510 E = result.get(); 511 } 512 513 QualType Ty = E->getType(); 514 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 515 516 if (Ty->isFunctionType()) { 517 // If we are here, we are not calling a function but taking 518 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 519 if (getLangOpts().OpenCL) { 520 if (Diagnose) 521 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 522 return ExprError(); 523 } 524 525 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 526 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 527 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 528 return ExprError(); 529 530 E = ImpCastExprToType(E, Context.getPointerType(Ty), 531 CK_FunctionToPointerDecay).get(); 532 } else if (Ty->isArrayType()) { 533 // In C90 mode, arrays only promote to pointers if the array expression is 534 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 535 // type 'array of type' is converted to an expression that has type 'pointer 536 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 537 // that has type 'array of type' ...". The relevant change is "an lvalue" 538 // (C90) to "an expression" (C99). 539 // 540 // C++ 4.2p1: 541 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 542 // T" can be converted to an rvalue of type "pointer to T". 543 // 544 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 545 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 546 CK_ArrayToPointerDecay).get(); 547 } 548 return E; 549 } 550 551 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 552 // Check to see if we are dereferencing a null pointer. If so, 553 // and if not volatile-qualified, this is undefined behavior that the 554 // optimizer will delete, so warn about it. People sometimes try to use this 555 // to get a deterministic trap and are surprised by clang's behavior. This 556 // only handles the pattern "*null", which is a very syntactic check. 557 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 558 if (UO->getOpcode() == UO_Deref && 559 UO->getSubExpr()->IgnoreParenCasts()-> 560 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 561 !UO->getType().isVolatileQualified()) { 562 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 563 S.PDiag(diag::warn_indirection_through_null) 564 << UO->getSubExpr()->getSourceRange()); 565 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 566 S.PDiag(diag::note_indirection_through_null)); 567 } 568 } 569 570 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 571 SourceLocation AssignLoc, 572 const Expr* RHS) { 573 const ObjCIvarDecl *IV = OIRE->getDecl(); 574 if (!IV) 575 return; 576 577 DeclarationName MemberName = IV->getDeclName(); 578 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 579 if (!Member || !Member->isStr("isa")) 580 return; 581 582 const Expr *Base = OIRE->getBase(); 583 QualType BaseType = Base->getType(); 584 if (OIRE->isArrow()) 585 BaseType = BaseType->getPointeeType(); 586 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 587 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 588 ObjCInterfaceDecl *ClassDeclared = nullptr; 589 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 590 if (!ClassDeclared->getSuperClass() 591 && (*ClassDeclared->ivar_begin()) == IV) { 592 if (RHS) { 593 NamedDecl *ObjectSetClass = 594 S.LookupSingleName(S.TUScope, 595 &S.Context.Idents.get("object_setClass"), 596 SourceLocation(), S.LookupOrdinaryName); 597 if (ObjectSetClass) { 598 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 599 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 600 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 601 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 602 AssignLoc), ",") << 603 FixItHint::CreateInsertion(RHSLocEnd, ")"); 604 } 605 else 606 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 607 } else { 608 NamedDecl *ObjectGetClass = 609 S.LookupSingleName(S.TUScope, 610 &S.Context.Idents.get("object_getClass"), 611 SourceLocation(), S.LookupOrdinaryName); 612 if (ObjectGetClass) 613 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 614 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 615 FixItHint::CreateReplacement( 616 SourceRange(OIRE->getOpLoc(), 617 OIRE->getLocEnd()), ")"); 618 else 619 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 620 } 621 S.Diag(IV->getLocation(), diag::note_ivar_decl); 622 } 623 } 624 } 625 626 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 627 // Handle any placeholder expressions which made it here. 628 if (E->getType()->isPlaceholderType()) { 629 ExprResult result = CheckPlaceholderExpr(E); 630 if (result.isInvalid()) return ExprError(); 631 E = result.get(); 632 } 633 634 // C++ [conv.lval]p1: 635 // A glvalue of a non-function, non-array type T can be 636 // converted to a prvalue. 637 if (!E->isGLValue()) return E; 638 639 QualType T = E->getType(); 640 assert(!T.isNull() && "r-value conversion on typeless expression?"); 641 642 // We don't want to throw lvalue-to-rvalue casts on top of 643 // expressions of certain types in C++. 644 if (getLangOpts().CPlusPlus && 645 (E->getType() == Context.OverloadTy || 646 T->isDependentType() || 647 T->isRecordType())) 648 return E; 649 650 // The C standard is actually really unclear on this point, and 651 // DR106 tells us what the result should be but not why. It's 652 // generally best to say that void types just doesn't undergo 653 // lvalue-to-rvalue at all. Note that expressions of unqualified 654 // 'void' type are never l-values, but qualified void can be. 655 if (T->isVoidType()) 656 return E; 657 658 // OpenCL usually rejects direct accesses to values of 'half' type. 659 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 660 T->isHalfType()) { 661 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 662 << 0 << T; 663 return ExprError(); 664 } 665 666 CheckForNullPointerDereference(*this, E); 667 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 668 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 669 &Context.Idents.get("object_getClass"), 670 SourceLocation(), LookupOrdinaryName); 671 if (ObjectGetClass) 672 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 673 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 674 FixItHint::CreateReplacement( 675 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 676 else 677 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 678 } 679 else if (const ObjCIvarRefExpr *OIRE = 680 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 681 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 682 683 // C++ [conv.lval]p1: 684 // [...] If T is a non-class type, the type of the prvalue is the 685 // cv-unqualified version of T. Otherwise, the type of the 686 // rvalue is T. 687 // 688 // C99 6.3.2.1p2: 689 // If the lvalue has qualified type, the value has the unqualified 690 // version of the type of the lvalue; otherwise, the value has the 691 // type of the lvalue. 692 if (T.hasQualifiers()) 693 T = T.getUnqualifiedType(); 694 695 // Under the MS ABI, lock down the inheritance model now. 696 if (T->isMemberPointerType() && 697 Context.getTargetInfo().getCXXABI().isMicrosoft()) 698 (void)isCompleteType(E->getExprLoc(), T); 699 700 UpdateMarkingForLValueToRValue(E); 701 702 // Loading a __weak object implicitly retains the value, so we need a cleanup to 703 // balance that. 704 if (getLangOpts().ObjCAutoRefCount && 705 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 706 ExprNeedsCleanups = true; 707 708 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 709 nullptr, VK_RValue); 710 711 // C11 6.3.2.1p2: 712 // ... if the lvalue has atomic type, the value has the non-atomic version 713 // of the type of the lvalue ... 714 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 715 T = Atomic->getValueType().getUnqualifiedType(); 716 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 717 nullptr, VK_RValue); 718 } 719 720 return Res; 721 } 722 723 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 724 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 725 if (Res.isInvalid()) 726 return ExprError(); 727 Res = DefaultLvalueConversion(Res.get()); 728 if (Res.isInvalid()) 729 return ExprError(); 730 return Res; 731 } 732 733 /// CallExprUnaryConversions - a special case of an unary conversion 734 /// performed on a function designator of a call expression. 735 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 736 QualType Ty = E->getType(); 737 ExprResult Res = E; 738 // Only do implicit cast for a function type, but not for a pointer 739 // to function type. 740 if (Ty->isFunctionType()) { 741 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 742 CK_FunctionToPointerDecay).get(); 743 if (Res.isInvalid()) 744 return ExprError(); 745 } 746 Res = DefaultLvalueConversion(Res.get()); 747 if (Res.isInvalid()) 748 return ExprError(); 749 return Res.get(); 750 } 751 752 /// UsualUnaryConversions - Performs various conversions that are common to most 753 /// operators (C99 6.3). The conversions of array and function types are 754 /// sometimes suppressed. For example, the array->pointer conversion doesn't 755 /// apply if the array is an argument to the sizeof or address (&) operators. 756 /// In these instances, this routine should *not* be called. 757 ExprResult Sema::UsualUnaryConversions(Expr *E) { 758 // First, convert to an r-value. 759 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 760 if (Res.isInvalid()) 761 return ExprError(); 762 E = Res.get(); 763 764 QualType Ty = E->getType(); 765 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 766 767 // Half FP have to be promoted to float unless it is natively supported 768 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 769 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 770 771 // Try to perform integral promotions if the object has a theoretically 772 // promotable type. 773 if (Ty->isIntegralOrUnscopedEnumerationType()) { 774 // C99 6.3.1.1p2: 775 // 776 // The following may be used in an expression wherever an int or 777 // unsigned int may be used: 778 // - an object or expression with an integer type whose integer 779 // conversion rank is less than or equal to the rank of int 780 // and unsigned int. 781 // - A bit-field of type _Bool, int, signed int, or unsigned int. 782 // 783 // If an int can represent all values of the original type, the 784 // value is converted to an int; otherwise, it is converted to an 785 // unsigned int. These are called the integer promotions. All 786 // other types are unchanged by the integer promotions. 787 788 QualType PTy = Context.isPromotableBitField(E); 789 if (!PTy.isNull()) { 790 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 791 return E; 792 } 793 if (Ty->isPromotableIntegerType()) { 794 QualType PT = Context.getPromotedIntegerType(Ty); 795 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 796 return E; 797 } 798 } 799 return E; 800 } 801 802 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 803 /// do not have a prototype. Arguments that have type float or __fp16 804 /// are promoted to double. All other argument types are converted by 805 /// UsualUnaryConversions(). 806 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 807 QualType Ty = E->getType(); 808 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 809 810 ExprResult Res = UsualUnaryConversions(E); 811 if (Res.isInvalid()) 812 return ExprError(); 813 E = Res.get(); 814 815 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 816 // double. 817 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 818 if (BTy && (BTy->getKind() == BuiltinType::Half || 819 BTy->getKind() == BuiltinType::Float)) 820 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 821 822 // C++ performs lvalue-to-rvalue conversion as a default argument 823 // promotion, even on class types, but note: 824 // C++11 [conv.lval]p2: 825 // When an lvalue-to-rvalue conversion occurs in an unevaluated 826 // operand or a subexpression thereof the value contained in the 827 // referenced object is not accessed. Otherwise, if the glvalue 828 // has a class type, the conversion copy-initializes a temporary 829 // of type T from the glvalue and the result of the conversion 830 // is a prvalue for the temporary. 831 // FIXME: add some way to gate this entire thing for correctness in 832 // potentially potentially evaluated contexts. 833 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 834 ExprResult Temp = PerformCopyInitialization( 835 InitializedEntity::InitializeTemporary(E->getType()), 836 E->getExprLoc(), E); 837 if (Temp.isInvalid()) 838 return ExprError(); 839 E = Temp.get(); 840 } 841 842 return E; 843 } 844 845 /// Determine the degree of POD-ness for an expression. 846 /// Incomplete types are considered POD, since this check can be performed 847 /// when we're in an unevaluated context. 848 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 849 if (Ty->isIncompleteType()) { 850 // C++11 [expr.call]p7: 851 // After these conversions, if the argument does not have arithmetic, 852 // enumeration, pointer, pointer to member, or class type, the program 853 // is ill-formed. 854 // 855 // Since we've already performed array-to-pointer and function-to-pointer 856 // decay, the only such type in C++ is cv void. This also handles 857 // initializer lists as variadic arguments. 858 if (Ty->isVoidType()) 859 return VAK_Invalid; 860 861 if (Ty->isObjCObjectType()) 862 return VAK_Invalid; 863 return VAK_Valid; 864 } 865 866 if (Ty.isCXX98PODType(Context)) 867 return VAK_Valid; 868 869 // C++11 [expr.call]p7: 870 // Passing a potentially-evaluated argument of class type (Clause 9) 871 // having a non-trivial copy constructor, a non-trivial move constructor, 872 // or a non-trivial destructor, with no corresponding parameter, 873 // is conditionally-supported with implementation-defined semantics. 874 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 875 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 876 if (!Record->hasNonTrivialCopyConstructor() && 877 !Record->hasNonTrivialMoveConstructor() && 878 !Record->hasNonTrivialDestructor()) 879 return VAK_ValidInCXX11; 880 881 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 882 return VAK_Valid; 883 884 if (Ty->isObjCObjectType()) 885 return VAK_Invalid; 886 887 if (getLangOpts().MSVCCompat) 888 return VAK_MSVCUndefined; 889 890 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 891 // permitted to reject them. We should consider doing so. 892 return VAK_Undefined; 893 } 894 895 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 896 // Don't allow one to pass an Objective-C interface to a vararg. 897 const QualType &Ty = E->getType(); 898 VarArgKind VAK = isValidVarArgType(Ty); 899 900 // Complain about passing non-POD types through varargs. 901 switch (VAK) { 902 case VAK_ValidInCXX11: 903 DiagRuntimeBehavior( 904 E->getLocStart(), nullptr, 905 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 906 << Ty << CT); 907 // Fall through. 908 case VAK_Valid: 909 if (Ty->isRecordType()) { 910 // This is unlikely to be what the user intended. If the class has a 911 // 'c_str' member function, the user probably meant to call that. 912 DiagRuntimeBehavior(E->getLocStart(), nullptr, 913 PDiag(diag::warn_pass_class_arg_to_vararg) 914 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 915 } 916 break; 917 918 case VAK_Undefined: 919 case VAK_MSVCUndefined: 920 DiagRuntimeBehavior( 921 E->getLocStart(), nullptr, 922 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 923 << getLangOpts().CPlusPlus11 << Ty << CT); 924 break; 925 926 case VAK_Invalid: 927 if (Ty->isObjCObjectType()) 928 DiagRuntimeBehavior( 929 E->getLocStart(), nullptr, 930 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 931 << Ty << CT); 932 else 933 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 934 << isa<InitListExpr>(E) << Ty << CT; 935 break; 936 } 937 } 938 939 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 940 /// will create a trap if the resulting type is not a POD type. 941 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 942 FunctionDecl *FDecl) { 943 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 944 // Strip the unbridged-cast placeholder expression off, if applicable. 945 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 946 (CT == VariadicMethod || 947 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 948 E = stripARCUnbridgedCast(E); 949 950 // Otherwise, do normal placeholder checking. 951 } else { 952 ExprResult ExprRes = CheckPlaceholderExpr(E); 953 if (ExprRes.isInvalid()) 954 return ExprError(); 955 E = ExprRes.get(); 956 } 957 } 958 959 ExprResult ExprRes = DefaultArgumentPromotion(E); 960 if (ExprRes.isInvalid()) 961 return ExprError(); 962 E = ExprRes.get(); 963 964 // Diagnostics regarding non-POD argument types are 965 // emitted along with format string checking in Sema::CheckFunctionCall(). 966 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 967 // Turn this into a trap. 968 CXXScopeSpec SS; 969 SourceLocation TemplateKWLoc; 970 UnqualifiedId Name; 971 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 972 E->getLocStart()); 973 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 974 Name, true, false); 975 if (TrapFn.isInvalid()) 976 return ExprError(); 977 978 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 979 E->getLocStart(), None, 980 E->getLocEnd()); 981 if (Call.isInvalid()) 982 return ExprError(); 983 984 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 985 Call.get(), E); 986 if (Comma.isInvalid()) 987 return ExprError(); 988 return Comma.get(); 989 } 990 991 if (!getLangOpts().CPlusPlus && 992 RequireCompleteType(E->getExprLoc(), E->getType(), 993 diag::err_call_incomplete_argument)) 994 return ExprError(); 995 996 return E; 997 } 998 999 /// \brief Converts an integer to complex float type. Helper function of 1000 /// UsualArithmeticConversions() 1001 /// 1002 /// \return false if the integer expression is an integer type and is 1003 /// successfully converted to the complex type. 1004 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1005 ExprResult &ComplexExpr, 1006 QualType IntTy, 1007 QualType ComplexTy, 1008 bool SkipCast) { 1009 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1010 if (SkipCast) return false; 1011 if (IntTy->isIntegerType()) { 1012 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1013 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1014 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1015 CK_FloatingRealToComplex); 1016 } else { 1017 assert(IntTy->isComplexIntegerType()); 1018 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1019 CK_IntegralComplexToFloatingComplex); 1020 } 1021 return false; 1022 } 1023 1024 /// \brief Handle arithmetic conversion with complex types. Helper function of 1025 /// UsualArithmeticConversions() 1026 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1027 ExprResult &RHS, QualType LHSType, 1028 QualType RHSType, 1029 bool IsCompAssign) { 1030 // if we have an integer operand, the result is the complex type. 1031 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1032 /*skipCast*/false)) 1033 return LHSType; 1034 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1035 /*skipCast*/IsCompAssign)) 1036 return RHSType; 1037 1038 // This handles complex/complex, complex/float, or float/complex. 1039 // When both operands are complex, the shorter operand is converted to the 1040 // type of the longer, and that is the type of the result. This corresponds 1041 // to what is done when combining two real floating-point operands. 1042 // The fun begins when size promotion occur across type domains. 1043 // From H&S 6.3.4: When one operand is complex and the other is a real 1044 // floating-point type, the less precise type is converted, within it's 1045 // real or complex domain, to the precision of the other type. For example, 1046 // when combining a "long double" with a "double _Complex", the 1047 // "double _Complex" is promoted to "long double _Complex". 1048 1049 // Compute the rank of the two types, regardless of whether they are complex. 1050 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1051 1052 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1053 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1054 QualType LHSElementType = 1055 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1056 QualType RHSElementType = 1057 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1058 1059 QualType ResultType = S.Context.getComplexType(LHSElementType); 1060 if (Order < 0) { 1061 // Promote the precision of the LHS if not an assignment. 1062 ResultType = S.Context.getComplexType(RHSElementType); 1063 if (!IsCompAssign) { 1064 if (LHSComplexType) 1065 LHS = 1066 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1067 else 1068 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1069 } 1070 } else if (Order > 0) { 1071 // Promote the precision of the RHS. 1072 if (RHSComplexType) 1073 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1074 else 1075 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1076 } 1077 return ResultType; 1078 } 1079 1080 /// \brief Hande arithmetic conversion from integer to float. Helper function 1081 /// of UsualArithmeticConversions() 1082 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1083 ExprResult &IntExpr, 1084 QualType FloatTy, QualType IntTy, 1085 bool ConvertFloat, bool ConvertInt) { 1086 if (IntTy->isIntegerType()) { 1087 if (ConvertInt) 1088 // Convert intExpr to the lhs floating point type. 1089 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1090 CK_IntegralToFloating); 1091 return FloatTy; 1092 } 1093 1094 // Convert both sides to the appropriate complex float. 1095 assert(IntTy->isComplexIntegerType()); 1096 QualType result = S.Context.getComplexType(FloatTy); 1097 1098 // _Complex int -> _Complex float 1099 if (ConvertInt) 1100 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1101 CK_IntegralComplexToFloatingComplex); 1102 1103 // float -> _Complex float 1104 if (ConvertFloat) 1105 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1106 CK_FloatingRealToComplex); 1107 1108 return result; 1109 } 1110 1111 /// \brief Handle arithmethic conversion with floating point types. Helper 1112 /// function of UsualArithmeticConversions() 1113 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1114 ExprResult &RHS, QualType LHSType, 1115 QualType RHSType, bool IsCompAssign) { 1116 bool LHSFloat = LHSType->isRealFloatingType(); 1117 bool RHSFloat = RHSType->isRealFloatingType(); 1118 1119 // If we have two real floating types, convert the smaller operand 1120 // to the bigger result. 1121 if (LHSFloat && RHSFloat) { 1122 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1123 if (order > 0) { 1124 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1125 return LHSType; 1126 } 1127 1128 assert(order < 0 && "illegal float comparison"); 1129 if (!IsCompAssign) 1130 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1131 return RHSType; 1132 } 1133 1134 if (LHSFloat) { 1135 // Half FP has to be promoted to float unless it is natively supported 1136 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1137 LHSType = S.Context.FloatTy; 1138 1139 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1140 /*convertFloat=*/!IsCompAssign, 1141 /*convertInt=*/ true); 1142 } 1143 assert(RHSFloat); 1144 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1145 /*convertInt=*/ true, 1146 /*convertFloat=*/!IsCompAssign); 1147 } 1148 1149 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1150 1151 namespace { 1152 /// These helper callbacks are placed in an anonymous namespace to 1153 /// permit their use as function template parameters. 1154 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1155 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1156 } 1157 1158 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1159 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1160 CK_IntegralComplexCast); 1161 } 1162 } 1163 1164 /// \brief Handle integer arithmetic conversions. Helper function of 1165 /// UsualArithmeticConversions() 1166 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1167 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1168 ExprResult &RHS, QualType LHSType, 1169 QualType RHSType, bool IsCompAssign) { 1170 // The rules for this case are in C99 6.3.1.8 1171 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1172 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1173 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1174 if (LHSSigned == RHSSigned) { 1175 // Same signedness; use the higher-ranked type 1176 if (order >= 0) { 1177 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1178 return LHSType; 1179 } else if (!IsCompAssign) 1180 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1181 return RHSType; 1182 } else if (order != (LHSSigned ? 1 : -1)) { 1183 // The unsigned type has greater than or equal rank to the 1184 // signed type, so use the unsigned type 1185 if (RHSSigned) { 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 (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1192 // The two types are different widths; if we are here, that 1193 // means the signed type is larger than the unsigned type, so 1194 // use the signed type. 1195 if (LHSSigned) { 1196 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1197 return LHSType; 1198 } else if (!IsCompAssign) 1199 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1200 return RHSType; 1201 } else { 1202 // The signed type is higher-ranked than the unsigned type, 1203 // but isn't actually any bigger (like unsigned int and long 1204 // on most 32-bit systems). Use the unsigned type corresponding 1205 // to the signed type. 1206 QualType result = 1207 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1208 RHS = (*doRHSCast)(S, RHS.get(), result); 1209 if (!IsCompAssign) 1210 LHS = (*doLHSCast)(S, LHS.get(), result); 1211 return result; 1212 } 1213 } 1214 1215 /// \brief Handle conversions with GCC complex int extension. Helper function 1216 /// of UsualArithmeticConversions() 1217 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1218 ExprResult &RHS, QualType LHSType, 1219 QualType RHSType, 1220 bool IsCompAssign) { 1221 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1222 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1223 1224 if (LHSComplexInt && RHSComplexInt) { 1225 QualType LHSEltType = LHSComplexInt->getElementType(); 1226 QualType RHSEltType = RHSComplexInt->getElementType(); 1227 QualType ScalarType = 1228 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1229 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1230 1231 return S.Context.getComplexType(ScalarType); 1232 } 1233 1234 if (LHSComplexInt) { 1235 QualType LHSEltType = LHSComplexInt->getElementType(); 1236 QualType ScalarType = 1237 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1238 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1239 QualType ComplexType = S.Context.getComplexType(ScalarType); 1240 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1241 CK_IntegralRealToComplex); 1242 1243 return ComplexType; 1244 } 1245 1246 assert(RHSComplexInt); 1247 1248 QualType RHSEltType = RHSComplexInt->getElementType(); 1249 QualType ScalarType = 1250 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1251 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1252 QualType ComplexType = S.Context.getComplexType(ScalarType); 1253 1254 if (!IsCompAssign) 1255 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1256 CK_IntegralRealToComplex); 1257 return ComplexType; 1258 } 1259 1260 /// UsualArithmeticConversions - Performs various conversions that are common to 1261 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1262 /// routine returns the first non-arithmetic type found. The client is 1263 /// responsible for emitting appropriate error diagnostics. 1264 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1265 bool IsCompAssign) { 1266 if (!IsCompAssign) { 1267 LHS = UsualUnaryConversions(LHS.get()); 1268 if (LHS.isInvalid()) 1269 return QualType(); 1270 } 1271 1272 RHS = UsualUnaryConversions(RHS.get()); 1273 if (RHS.isInvalid()) 1274 return QualType(); 1275 1276 // For conversion purposes, we ignore any qualifiers. 1277 // For example, "const float" and "float" are equivalent. 1278 QualType LHSType = 1279 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1280 QualType RHSType = 1281 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1282 1283 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1284 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1285 LHSType = AtomicLHS->getValueType(); 1286 1287 // If both types are identical, no conversion is needed. 1288 if (LHSType == RHSType) 1289 return LHSType; 1290 1291 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1292 // The caller can deal with this (e.g. pointer + int). 1293 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1294 return QualType(); 1295 1296 // Apply unary and bitfield promotions to the LHS's type. 1297 QualType LHSUnpromotedType = LHSType; 1298 if (LHSType->isPromotableIntegerType()) 1299 LHSType = Context.getPromotedIntegerType(LHSType); 1300 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1301 if (!LHSBitfieldPromoteTy.isNull()) 1302 LHSType = LHSBitfieldPromoteTy; 1303 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1304 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1305 1306 // If both types are identical, no conversion is needed. 1307 if (LHSType == RHSType) 1308 return LHSType; 1309 1310 // At this point, we have two different arithmetic types. 1311 1312 // Handle complex types first (C99 6.3.1.8p1). 1313 if (LHSType->isComplexType() || RHSType->isComplexType()) 1314 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1315 IsCompAssign); 1316 1317 // Now handle "real" floating types (i.e. float, double, long double). 1318 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1319 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1320 IsCompAssign); 1321 1322 // Handle GCC complex int extension. 1323 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1324 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1325 IsCompAssign); 1326 1327 // Finally, we have two differing integer types. 1328 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1329 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1330 } 1331 1332 1333 //===----------------------------------------------------------------------===// 1334 // Semantic Analysis for various Expression Types 1335 //===----------------------------------------------------------------------===// 1336 1337 1338 ExprResult 1339 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1340 SourceLocation DefaultLoc, 1341 SourceLocation RParenLoc, 1342 Expr *ControllingExpr, 1343 ArrayRef<ParsedType> ArgTypes, 1344 ArrayRef<Expr *> ArgExprs) { 1345 unsigned NumAssocs = ArgTypes.size(); 1346 assert(NumAssocs == ArgExprs.size()); 1347 1348 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1349 for (unsigned i = 0; i < NumAssocs; ++i) { 1350 if (ArgTypes[i]) 1351 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1352 else 1353 Types[i] = nullptr; 1354 } 1355 1356 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1357 ControllingExpr, 1358 llvm::makeArrayRef(Types, NumAssocs), 1359 ArgExprs); 1360 delete [] Types; 1361 return ER; 1362 } 1363 1364 ExprResult 1365 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1366 SourceLocation DefaultLoc, 1367 SourceLocation RParenLoc, 1368 Expr *ControllingExpr, 1369 ArrayRef<TypeSourceInfo *> Types, 1370 ArrayRef<Expr *> Exprs) { 1371 unsigned NumAssocs = Types.size(); 1372 assert(NumAssocs == Exprs.size()); 1373 1374 // Decay and strip qualifiers for the controlling expression type, and handle 1375 // placeholder type replacement. See committee discussion from WG14 DR423. 1376 { 1377 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1378 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1379 if (R.isInvalid()) 1380 return ExprError(); 1381 ControllingExpr = R.get(); 1382 } 1383 1384 // The controlling expression is an unevaluated operand, so side effects are 1385 // likely unintended. 1386 if (ActiveTemplateInstantiations.empty() && 1387 ControllingExpr->HasSideEffects(Context, false)) 1388 Diag(ControllingExpr->getExprLoc(), 1389 diag::warn_side_effects_unevaluated_context); 1390 1391 bool TypeErrorFound = false, 1392 IsResultDependent = ControllingExpr->isTypeDependent(), 1393 ContainsUnexpandedParameterPack 1394 = ControllingExpr->containsUnexpandedParameterPack(); 1395 1396 for (unsigned i = 0; i < NumAssocs; ++i) { 1397 if (Exprs[i]->containsUnexpandedParameterPack()) 1398 ContainsUnexpandedParameterPack = true; 1399 1400 if (Types[i]) { 1401 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1402 ContainsUnexpandedParameterPack = true; 1403 1404 if (Types[i]->getType()->isDependentType()) { 1405 IsResultDependent = true; 1406 } else { 1407 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1408 // complete object type other than a variably modified type." 1409 unsigned D = 0; 1410 if (Types[i]->getType()->isIncompleteType()) 1411 D = diag::err_assoc_type_incomplete; 1412 else if (!Types[i]->getType()->isObjectType()) 1413 D = diag::err_assoc_type_nonobject; 1414 else if (Types[i]->getType()->isVariablyModifiedType()) 1415 D = diag::err_assoc_type_variably_modified; 1416 1417 if (D != 0) { 1418 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1419 << Types[i]->getTypeLoc().getSourceRange() 1420 << Types[i]->getType(); 1421 TypeErrorFound = true; 1422 } 1423 1424 // C11 6.5.1.1p2 "No two generic associations in the same generic 1425 // selection shall specify compatible types." 1426 for (unsigned j = i+1; j < NumAssocs; ++j) 1427 if (Types[j] && !Types[j]->getType()->isDependentType() && 1428 Context.typesAreCompatible(Types[i]->getType(), 1429 Types[j]->getType())) { 1430 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1431 diag::err_assoc_compatible_types) 1432 << Types[j]->getTypeLoc().getSourceRange() 1433 << Types[j]->getType() 1434 << Types[i]->getType(); 1435 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1436 diag::note_compat_assoc) 1437 << Types[i]->getTypeLoc().getSourceRange() 1438 << Types[i]->getType(); 1439 TypeErrorFound = true; 1440 } 1441 } 1442 } 1443 } 1444 if (TypeErrorFound) 1445 return ExprError(); 1446 1447 // If we determined that the generic selection is result-dependent, don't 1448 // try to compute the result expression. 1449 if (IsResultDependent) 1450 return new (Context) GenericSelectionExpr( 1451 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1452 ContainsUnexpandedParameterPack); 1453 1454 SmallVector<unsigned, 1> CompatIndices; 1455 unsigned DefaultIndex = -1U; 1456 for (unsigned i = 0; i < NumAssocs; ++i) { 1457 if (!Types[i]) 1458 DefaultIndex = i; 1459 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1460 Types[i]->getType())) 1461 CompatIndices.push_back(i); 1462 } 1463 1464 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1465 // type compatible with at most one of the types named in its generic 1466 // association list." 1467 if (CompatIndices.size() > 1) { 1468 // We strip parens here because the controlling expression is typically 1469 // parenthesized in macro definitions. 1470 ControllingExpr = ControllingExpr->IgnoreParens(); 1471 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1472 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1473 << (unsigned) CompatIndices.size(); 1474 for (unsigned I : CompatIndices) { 1475 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1476 diag::note_compat_assoc) 1477 << Types[I]->getTypeLoc().getSourceRange() 1478 << Types[I]->getType(); 1479 } 1480 return ExprError(); 1481 } 1482 1483 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1484 // its controlling expression shall have type compatible with exactly one of 1485 // the types named in its generic association list." 1486 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1487 // We strip parens here because the controlling expression is typically 1488 // parenthesized in macro definitions. 1489 ControllingExpr = ControllingExpr->IgnoreParens(); 1490 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1491 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1492 return ExprError(); 1493 } 1494 1495 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1496 // type name that is compatible with the type of the controlling expression, 1497 // then the result expression of the generic selection is the expression 1498 // in that generic association. Otherwise, the result expression of the 1499 // generic selection is the expression in the default generic association." 1500 unsigned ResultIndex = 1501 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1502 1503 return new (Context) GenericSelectionExpr( 1504 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1505 ContainsUnexpandedParameterPack, ResultIndex); 1506 } 1507 1508 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1509 /// location of the token and the offset of the ud-suffix within it. 1510 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1511 unsigned Offset) { 1512 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1513 S.getLangOpts()); 1514 } 1515 1516 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1517 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1518 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1519 IdentifierInfo *UDSuffix, 1520 SourceLocation UDSuffixLoc, 1521 ArrayRef<Expr*> Args, 1522 SourceLocation LitEndLoc) { 1523 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1524 1525 QualType ArgTy[2]; 1526 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1527 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1528 if (ArgTy[ArgIdx]->isArrayType()) 1529 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1530 } 1531 1532 DeclarationName OpName = 1533 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1534 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1535 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1536 1537 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1538 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1539 /*AllowRaw*/false, /*AllowTemplate*/false, 1540 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1541 return ExprError(); 1542 1543 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1544 } 1545 1546 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1547 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1548 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1549 /// multiple tokens. However, the common case is that StringToks points to one 1550 /// string. 1551 /// 1552 ExprResult 1553 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1554 assert(!StringToks.empty() && "Must have at least one string!"); 1555 1556 StringLiteralParser Literal(StringToks, PP); 1557 if (Literal.hadError) 1558 return ExprError(); 1559 1560 SmallVector<SourceLocation, 4> StringTokLocs; 1561 for (const Token &Tok : StringToks) 1562 StringTokLocs.push_back(Tok.getLocation()); 1563 1564 QualType CharTy = Context.CharTy; 1565 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1566 if (Literal.isWide()) { 1567 CharTy = Context.getWideCharType(); 1568 Kind = StringLiteral::Wide; 1569 } else if (Literal.isUTF8()) { 1570 Kind = StringLiteral::UTF8; 1571 } else if (Literal.isUTF16()) { 1572 CharTy = Context.Char16Ty; 1573 Kind = StringLiteral::UTF16; 1574 } else if (Literal.isUTF32()) { 1575 CharTy = Context.Char32Ty; 1576 Kind = StringLiteral::UTF32; 1577 } else if (Literal.isPascal()) { 1578 CharTy = Context.UnsignedCharTy; 1579 } 1580 1581 QualType CharTyConst = CharTy; 1582 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1583 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1584 CharTyConst.addConst(); 1585 1586 // Get an array type for the string, according to C99 6.4.5. This includes 1587 // the nul terminator character as well as the string length for pascal 1588 // strings. 1589 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1590 llvm::APInt(32, Literal.GetNumStringChars()+1), 1591 ArrayType::Normal, 0); 1592 1593 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1594 if (getLangOpts().OpenCL) { 1595 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1596 } 1597 1598 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1599 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1600 Kind, Literal.Pascal, StrTy, 1601 &StringTokLocs[0], 1602 StringTokLocs.size()); 1603 if (Literal.getUDSuffix().empty()) 1604 return Lit; 1605 1606 // We're building a user-defined literal. 1607 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1608 SourceLocation UDSuffixLoc = 1609 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1610 Literal.getUDSuffixOffset()); 1611 1612 // Make sure we're allowed user-defined literals here. 1613 if (!UDLScope) 1614 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1615 1616 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1617 // operator "" X (str, len) 1618 QualType SizeType = Context.getSizeType(); 1619 1620 DeclarationName OpName = 1621 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1622 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1623 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1624 1625 QualType ArgTy[] = { 1626 Context.getArrayDecayedType(StrTy), SizeType 1627 }; 1628 1629 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1630 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1631 /*AllowRaw*/false, /*AllowTemplate*/false, 1632 /*AllowStringTemplate*/true)) { 1633 1634 case LOLR_Cooked: { 1635 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1636 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1637 StringTokLocs[0]); 1638 Expr *Args[] = { Lit, LenArg }; 1639 1640 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1641 } 1642 1643 case LOLR_StringTemplate: { 1644 TemplateArgumentListInfo ExplicitArgs; 1645 1646 unsigned CharBits = Context.getIntWidth(CharTy); 1647 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1648 llvm::APSInt Value(CharBits, CharIsUnsigned); 1649 1650 TemplateArgument TypeArg(CharTy); 1651 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1652 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1653 1654 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1655 Value = Lit->getCodeUnit(I); 1656 TemplateArgument Arg(Context, Value, CharTy); 1657 TemplateArgumentLocInfo ArgInfo; 1658 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1659 } 1660 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1661 &ExplicitArgs); 1662 } 1663 case LOLR_Raw: 1664 case LOLR_Template: 1665 llvm_unreachable("unexpected literal operator lookup result"); 1666 case LOLR_Error: 1667 return ExprError(); 1668 } 1669 llvm_unreachable("unexpected literal operator lookup result"); 1670 } 1671 1672 ExprResult 1673 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1674 SourceLocation Loc, 1675 const CXXScopeSpec *SS) { 1676 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1677 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1678 } 1679 1680 /// BuildDeclRefExpr - Build an expression that references a 1681 /// declaration that does not require a closure capture. 1682 ExprResult 1683 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1684 const DeclarationNameInfo &NameInfo, 1685 const CXXScopeSpec *SS, NamedDecl *FoundD, 1686 const TemplateArgumentListInfo *TemplateArgs) { 1687 if (getLangOpts().CUDA) 1688 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1689 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1690 if (CheckCUDATarget(Caller, Callee)) { 1691 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1692 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1693 << IdentifyCUDATarget(Caller); 1694 Diag(D->getLocation(), diag::note_previous_decl) 1695 << D->getIdentifier(); 1696 return ExprError(); 1697 } 1698 } 1699 1700 bool RefersToCapturedVariable = 1701 isa<VarDecl>(D) && 1702 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1703 1704 DeclRefExpr *E; 1705 if (isa<VarTemplateSpecializationDecl>(D)) { 1706 VarTemplateSpecializationDecl *VarSpec = 1707 cast<VarTemplateSpecializationDecl>(D); 1708 1709 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1710 : NestedNameSpecifierLoc(), 1711 VarSpec->getTemplateKeywordLoc(), D, 1712 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1713 FoundD, TemplateArgs); 1714 } else { 1715 assert(!TemplateArgs && "No template arguments for non-variable" 1716 " template specialization references"); 1717 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1718 : NestedNameSpecifierLoc(), 1719 SourceLocation(), D, RefersToCapturedVariable, 1720 NameInfo, Ty, VK, FoundD); 1721 } 1722 1723 MarkDeclRefReferenced(E); 1724 1725 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1726 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1727 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1728 recordUseOfEvaluatedWeak(E); 1729 1730 // Just in case we're building an illegal pointer-to-member. 1731 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1732 if (FD && FD->isBitField()) 1733 E->setObjectKind(OK_BitField); 1734 1735 return E; 1736 } 1737 1738 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1739 /// possibly a list of template arguments. 1740 /// 1741 /// If this produces template arguments, it is permitted to call 1742 /// DecomposeTemplateName. 1743 /// 1744 /// This actually loses a lot of source location information for 1745 /// non-standard name kinds; we should consider preserving that in 1746 /// some way. 1747 void 1748 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1749 TemplateArgumentListInfo &Buffer, 1750 DeclarationNameInfo &NameInfo, 1751 const TemplateArgumentListInfo *&TemplateArgs) { 1752 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1753 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1754 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1755 1756 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1757 Id.TemplateId->NumArgs); 1758 translateTemplateArguments(TemplateArgsPtr, Buffer); 1759 1760 TemplateName TName = Id.TemplateId->Template.get(); 1761 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1762 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1763 TemplateArgs = &Buffer; 1764 } else { 1765 NameInfo = GetNameFromUnqualifiedId(Id); 1766 TemplateArgs = nullptr; 1767 } 1768 } 1769 1770 static void emitEmptyLookupTypoDiagnostic( 1771 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1772 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1773 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1774 DeclContext *Ctx = 1775 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1776 if (!TC) { 1777 // Emit a special diagnostic for failed member lookups. 1778 // FIXME: computing the declaration context might fail here (?) 1779 if (Ctx) 1780 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1781 << SS.getRange(); 1782 else 1783 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1784 return; 1785 } 1786 1787 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1788 bool DroppedSpecifier = 1789 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1790 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1791 ? diag::note_implicit_param_decl 1792 : diag::note_previous_decl; 1793 if (!Ctx) 1794 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1795 SemaRef.PDiag(NoteID)); 1796 else 1797 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1798 << Typo << Ctx << DroppedSpecifier 1799 << SS.getRange(), 1800 SemaRef.PDiag(NoteID)); 1801 } 1802 1803 /// Diagnose an empty lookup. 1804 /// 1805 /// \return false if new lookup candidates were found 1806 bool 1807 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1808 std::unique_ptr<CorrectionCandidateCallback> CCC, 1809 TemplateArgumentListInfo *ExplicitTemplateArgs, 1810 ArrayRef<Expr *> Args, TypoExpr **Out) { 1811 DeclarationName Name = R.getLookupName(); 1812 1813 unsigned diagnostic = diag::err_undeclared_var_use; 1814 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1815 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1816 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1817 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1818 diagnostic = diag::err_undeclared_use; 1819 diagnostic_suggest = diag::err_undeclared_use_suggest; 1820 } 1821 1822 // If the original lookup was an unqualified lookup, fake an 1823 // unqualified lookup. This is useful when (for example) the 1824 // original lookup would not have found something because it was a 1825 // dependent name. 1826 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1827 while (DC) { 1828 if (isa<CXXRecordDecl>(DC)) { 1829 LookupQualifiedName(R, DC); 1830 1831 if (!R.empty()) { 1832 // Don't give errors about ambiguities in this lookup. 1833 R.suppressDiagnostics(); 1834 1835 // During a default argument instantiation the CurContext points 1836 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1837 // function parameter list, hence add an explicit check. 1838 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1839 ActiveTemplateInstantiations.back().Kind == 1840 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1841 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1842 bool isInstance = CurMethod && 1843 CurMethod->isInstance() && 1844 DC == CurMethod->getParent() && !isDefaultArgument; 1845 1846 // Give a code modification hint to insert 'this->'. 1847 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1848 // Actually quite difficult! 1849 if (getLangOpts().MSVCCompat) 1850 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1851 if (isInstance) { 1852 Diag(R.getNameLoc(), diagnostic) << Name 1853 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1854 CheckCXXThisCapture(R.getNameLoc()); 1855 } else { 1856 Diag(R.getNameLoc(), diagnostic) << Name; 1857 } 1858 1859 // Do we really want to note all of these? 1860 for (NamedDecl *D : R) 1861 Diag(D->getLocation(), diag::note_dependent_var_use); 1862 1863 // Return true if we are inside a default argument instantiation 1864 // and the found name refers to an instance member function, otherwise 1865 // the function calling DiagnoseEmptyLookup will try to create an 1866 // implicit member call and this is wrong for default argument. 1867 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1868 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1869 return true; 1870 } 1871 1872 // Tell the callee to try to recover. 1873 return false; 1874 } 1875 1876 R.clear(); 1877 } 1878 1879 // In Microsoft mode, if we are performing lookup from within a friend 1880 // function definition declared at class scope then we must set 1881 // DC to the lexical parent to be able to search into the parent 1882 // class. 1883 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1884 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1885 DC->getLexicalParent()->isRecord()) 1886 DC = DC->getLexicalParent(); 1887 else 1888 DC = DC->getParent(); 1889 } 1890 1891 // We didn't find anything, so try to correct for a typo. 1892 TypoCorrection Corrected; 1893 if (S && Out) { 1894 SourceLocation TypoLoc = R.getNameLoc(); 1895 assert(!ExplicitTemplateArgs && 1896 "Diagnosing an empty lookup with explicit template args!"); 1897 *Out = CorrectTypoDelayed( 1898 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1899 [=](const TypoCorrection &TC) { 1900 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1901 diagnostic, diagnostic_suggest); 1902 }, 1903 nullptr, CTK_ErrorRecovery); 1904 if (*Out) 1905 return true; 1906 } else if (S && (Corrected = 1907 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1908 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1909 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1910 bool DroppedSpecifier = 1911 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1912 R.setLookupName(Corrected.getCorrection()); 1913 1914 bool AcceptableWithRecovery = false; 1915 bool AcceptableWithoutRecovery = false; 1916 NamedDecl *ND = Corrected.getFoundDecl(); 1917 if (ND) { 1918 if (Corrected.isOverloaded()) { 1919 OverloadCandidateSet OCS(R.getNameLoc(), 1920 OverloadCandidateSet::CSK_Normal); 1921 OverloadCandidateSet::iterator Best; 1922 for (NamedDecl *CD : Corrected) { 1923 if (FunctionTemplateDecl *FTD = 1924 dyn_cast<FunctionTemplateDecl>(CD)) 1925 AddTemplateOverloadCandidate( 1926 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1927 Args, OCS); 1928 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1929 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1930 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1931 Args, OCS); 1932 } 1933 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1934 case OR_Success: 1935 ND = Best->FoundDecl; 1936 Corrected.setCorrectionDecl(ND); 1937 break; 1938 default: 1939 // FIXME: Arbitrarily pick the first declaration for the note. 1940 Corrected.setCorrectionDecl(ND); 1941 break; 1942 } 1943 } 1944 R.addDecl(ND); 1945 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1946 CXXRecordDecl *Record = nullptr; 1947 if (Corrected.getCorrectionSpecifier()) { 1948 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1949 Record = Ty->getAsCXXRecordDecl(); 1950 } 1951 if (!Record) 1952 Record = cast<CXXRecordDecl>( 1953 ND->getDeclContext()->getRedeclContext()); 1954 R.setNamingClass(Record); 1955 } 1956 1957 auto *UnderlyingND = ND->getUnderlyingDecl(); 1958 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1959 isa<FunctionTemplateDecl>(UnderlyingND); 1960 // FIXME: If we ended up with a typo for a type name or 1961 // Objective-C class name, we're in trouble because the parser 1962 // is in the wrong place to recover. Suggest the typo 1963 // correction, but don't make it a fix-it since we're not going 1964 // to recover well anyway. 1965 AcceptableWithoutRecovery = 1966 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1967 } else { 1968 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1969 // because we aren't able to recover. 1970 AcceptableWithoutRecovery = true; 1971 } 1972 1973 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1974 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1975 ? diag::note_implicit_param_decl 1976 : diag::note_previous_decl; 1977 if (SS.isEmpty()) 1978 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1979 PDiag(NoteID), AcceptableWithRecovery); 1980 else 1981 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1982 << Name << computeDeclContext(SS, false) 1983 << DroppedSpecifier << SS.getRange(), 1984 PDiag(NoteID), AcceptableWithRecovery); 1985 1986 // Tell the callee whether to try to recover. 1987 return !AcceptableWithRecovery; 1988 } 1989 } 1990 R.clear(); 1991 1992 // Emit a special diagnostic for failed member lookups. 1993 // FIXME: computing the declaration context might fail here (?) 1994 if (!SS.isEmpty()) { 1995 Diag(R.getNameLoc(), diag::err_no_member) 1996 << Name << computeDeclContext(SS, false) 1997 << SS.getRange(); 1998 return true; 1999 } 2000 2001 // Give up, we can't recover. 2002 Diag(R.getNameLoc(), diagnostic) << Name; 2003 return true; 2004 } 2005 2006 /// In Microsoft mode, if we are inside a template class whose parent class has 2007 /// dependent base classes, and we can't resolve an unqualified identifier, then 2008 /// assume the identifier is a member of a dependent base class. We can only 2009 /// recover successfully in static methods, instance methods, and other contexts 2010 /// where 'this' is available. This doesn't precisely match MSVC's 2011 /// instantiation model, but it's close enough. 2012 static Expr * 2013 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2014 DeclarationNameInfo &NameInfo, 2015 SourceLocation TemplateKWLoc, 2016 const TemplateArgumentListInfo *TemplateArgs) { 2017 // Only try to recover from lookup into dependent bases in static methods or 2018 // contexts where 'this' is available. 2019 QualType ThisType = S.getCurrentThisType(); 2020 const CXXRecordDecl *RD = nullptr; 2021 if (!ThisType.isNull()) 2022 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2023 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2024 RD = MD->getParent(); 2025 if (!RD || !RD->hasAnyDependentBases()) 2026 return nullptr; 2027 2028 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2029 // is available, suggest inserting 'this->' as a fixit. 2030 SourceLocation Loc = NameInfo.getLoc(); 2031 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2032 DB << NameInfo.getName() << RD; 2033 2034 if (!ThisType.isNull()) { 2035 DB << FixItHint::CreateInsertion(Loc, "this->"); 2036 return CXXDependentScopeMemberExpr::Create( 2037 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2038 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2039 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2040 } 2041 2042 // Synthesize a fake NNS that points to the derived class. This will 2043 // perform name lookup during template instantiation. 2044 CXXScopeSpec SS; 2045 auto *NNS = 2046 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2047 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2048 return DependentScopeDeclRefExpr::Create( 2049 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2050 TemplateArgs); 2051 } 2052 2053 ExprResult 2054 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2055 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2056 bool HasTrailingLParen, bool IsAddressOfOperand, 2057 std::unique_ptr<CorrectionCandidateCallback> CCC, 2058 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2059 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2060 "cannot be direct & operand and have a trailing lparen"); 2061 if (SS.isInvalid()) 2062 return ExprError(); 2063 2064 TemplateArgumentListInfo TemplateArgsBuffer; 2065 2066 // Decompose the UnqualifiedId into the following data. 2067 DeclarationNameInfo NameInfo; 2068 const TemplateArgumentListInfo *TemplateArgs; 2069 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2070 2071 DeclarationName Name = NameInfo.getName(); 2072 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2073 SourceLocation NameLoc = NameInfo.getLoc(); 2074 2075 // C++ [temp.dep.expr]p3: 2076 // An id-expression is type-dependent if it contains: 2077 // -- an identifier that was declared with a dependent type, 2078 // (note: handled after lookup) 2079 // -- a template-id that is dependent, 2080 // (note: handled in BuildTemplateIdExpr) 2081 // -- a conversion-function-id that specifies a dependent type, 2082 // -- a nested-name-specifier that contains a class-name that 2083 // names a dependent type. 2084 // Determine whether this is a member of an unknown specialization; 2085 // we need to handle these differently. 2086 bool DependentID = false; 2087 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2088 Name.getCXXNameType()->isDependentType()) { 2089 DependentID = true; 2090 } else if (SS.isSet()) { 2091 if (DeclContext *DC = computeDeclContext(SS, false)) { 2092 if (RequireCompleteDeclContext(SS, DC)) 2093 return ExprError(); 2094 } else { 2095 DependentID = true; 2096 } 2097 } 2098 2099 if (DependentID) 2100 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2101 IsAddressOfOperand, TemplateArgs); 2102 2103 // Perform the required lookup. 2104 LookupResult R(*this, NameInfo, 2105 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2106 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2107 if (TemplateArgs) { 2108 // Lookup the template name again to correctly establish the context in 2109 // which it was found. This is really unfortunate as we already did the 2110 // lookup to determine that it was a template name in the first place. If 2111 // this becomes a performance hit, we can work harder to preserve those 2112 // results until we get here but it's likely not worth it. 2113 bool MemberOfUnknownSpecialization; 2114 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2115 MemberOfUnknownSpecialization); 2116 2117 if (MemberOfUnknownSpecialization || 2118 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2119 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2120 IsAddressOfOperand, TemplateArgs); 2121 } else { 2122 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2123 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2124 2125 // If the result might be in a dependent base class, this is a dependent 2126 // id-expression. 2127 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2128 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2129 IsAddressOfOperand, TemplateArgs); 2130 2131 // If this reference is in an Objective-C method, then we need to do 2132 // some special Objective-C lookup, too. 2133 if (IvarLookupFollowUp) { 2134 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2135 if (E.isInvalid()) 2136 return ExprError(); 2137 2138 if (Expr *Ex = E.getAs<Expr>()) 2139 return Ex; 2140 } 2141 } 2142 2143 if (R.isAmbiguous()) 2144 return ExprError(); 2145 2146 // This could be an implicitly declared function reference (legal in C90, 2147 // extension in C99, forbidden in C++). 2148 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2149 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2150 if (D) R.addDecl(D); 2151 } 2152 2153 // Determine whether this name might be a candidate for 2154 // argument-dependent lookup. 2155 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2156 2157 if (R.empty() && !ADL) { 2158 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2159 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2160 TemplateKWLoc, TemplateArgs)) 2161 return E; 2162 } 2163 2164 // Don't diagnose an empty lookup for inline assembly. 2165 if (IsInlineAsmIdentifier) 2166 return ExprError(); 2167 2168 // If this name wasn't predeclared and if this is not a function 2169 // call, diagnose the problem. 2170 TypoExpr *TE = nullptr; 2171 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2172 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2173 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2174 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2175 "Typo correction callback misconfigured"); 2176 if (CCC) { 2177 // Make sure the callback knows what the typo being diagnosed is. 2178 CCC->setTypoName(II); 2179 if (SS.isValid()) 2180 CCC->setTypoNNS(SS.getScopeRep()); 2181 } 2182 if (DiagnoseEmptyLookup(S, SS, R, 2183 CCC ? std::move(CCC) : std::move(DefaultValidator), 2184 nullptr, None, &TE)) { 2185 if (TE && KeywordReplacement) { 2186 auto &State = getTypoExprState(TE); 2187 auto BestTC = State.Consumer->getNextCorrection(); 2188 if (BestTC.isKeyword()) { 2189 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2190 if (State.DiagHandler) 2191 State.DiagHandler(BestTC); 2192 KeywordReplacement->startToken(); 2193 KeywordReplacement->setKind(II->getTokenID()); 2194 KeywordReplacement->setIdentifierInfo(II); 2195 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2196 // Clean up the state associated with the TypoExpr, since it has 2197 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2198 clearDelayedTypo(TE); 2199 // Signal that a correction to a keyword was performed by returning a 2200 // valid-but-null ExprResult. 2201 return (Expr*)nullptr; 2202 } 2203 State.Consumer->resetCorrectionStream(); 2204 } 2205 return TE ? TE : ExprError(); 2206 } 2207 2208 assert(!R.empty() && 2209 "DiagnoseEmptyLookup returned false but added no results"); 2210 2211 // If we found an Objective-C instance variable, let 2212 // LookupInObjCMethod build the appropriate expression to 2213 // reference the ivar. 2214 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2215 R.clear(); 2216 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2217 // In a hopelessly buggy code, Objective-C instance variable 2218 // lookup fails and no expression will be built to reference it. 2219 if (!E.isInvalid() && !E.get()) 2220 return ExprError(); 2221 return E; 2222 } 2223 } 2224 2225 // This is guaranteed from this point on. 2226 assert(!R.empty() || ADL); 2227 2228 // Check whether this might be a C++ implicit instance member access. 2229 // C++ [class.mfct.non-static]p3: 2230 // When an id-expression that is not part of a class member access 2231 // syntax and not used to form a pointer to member is used in the 2232 // body of a non-static member function of class X, if name lookup 2233 // resolves the name in the id-expression to a non-static non-type 2234 // member of some class C, the id-expression is transformed into a 2235 // class member access expression using (*this) as the 2236 // postfix-expression to the left of the . operator. 2237 // 2238 // But we don't actually need to do this for '&' operands if R 2239 // resolved to a function or overloaded function set, because the 2240 // expression is ill-formed if it actually works out to be a 2241 // non-static member function: 2242 // 2243 // C++ [expr.ref]p4: 2244 // Otherwise, if E1.E2 refers to a non-static member function. . . 2245 // [t]he expression can be used only as the left-hand operand of a 2246 // member function call. 2247 // 2248 // There are other safeguards against such uses, but it's important 2249 // to get this right here so that we don't end up making a 2250 // spuriously dependent expression if we're inside a dependent 2251 // instance method. 2252 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2253 bool MightBeImplicitMember; 2254 if (!IsAddressOfOperand) 2255 MightBeImplicitMember = true; 2256 else if (!SS.isEmpty()) 2257 MightBeImplicitMember = false; 2258 else if (R.isOverloadedResult()) 2259 MightBeImplicitMember = false; 2260 else if (R.isUnresolvableResult()) 2261 MightBeImplicitMember = true; 2262 else 2263 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2264 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2265 isa<MSPropertyDecl>(R.getFoundDecl()); 2266 2267 if (MightBeImplicitMember) 2268 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2269 R, TemplateArgs, S); 2270 } 2271 2272 if (TemplateArgs || TemplateKWLoc.isValid()) { 2273 2274 // In C++1y, if this is a variable template id, then check it 2275 // in BuildTemplateIdExpr(). 2276 // The single lookup result must be a variable template declaration. 2277 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2278 Id.TemplateId->Kind == TNK_Var_template) { 2279 assert(R.getAsSingle<VarTemplateDecl>() && 2280 "There should only be one declaration found."); 2281 } 2282 2283 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2284 } 2285 2286 return BuildDeclarationNameExpr(SS, R, ADL); 2287 } 2288 2289 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2290 /// declaration name, generally during template instantiation. 2291 /// There's a large number of things which don't need to be done along 2292 /// this path. 2293 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2294 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2295 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2296 DeclContext *DC = computeDeclContext(SS, false); 2297 if (!DC) 2298 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2299 NameInfo, /*TemplateArgs=*/nullptr); 2300 2301 if (RequireCompleteDeclContext(SS, DC)) 2302 return ExprError(); 2303 2304 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2305 LookupQualifiedName(R, DC); 2306 2307 if (R.isAmbiguous()) 2308 return ExprError(); 2309 2310 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2311 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2312 NameInfo, /*TemplateArgs=*/nullptr); 2313 2314 if (R.empty()) { 2315 Diag(NameInfo.getLoc(), diag::err_no_member) 2316 << NameInfo.getName() << DC << SS.getRange(); 2317 return ExprError(); 2318 } 2319 2320 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2321 // Diagnose a missing typename if this resolved unambiguously to a type in 2322 // a dependent context. If we can recover with a type, downgrade this to 2323 // a warning in Microsoft compatibility mode. 2324 unsigned DiagID = diag::err_typename_missing; 2325 if (RecoveryTSI && getLangOpts().MSVCCompat) 2326 DiagID = diag::ext_typename_missing; 2327 SourceLocation Loc = SS.getBeginLoc(); 2328 auto D = Diag(Loc, DiagID); 2329 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2330 << SourceRange(Loc, NameInfo.getEndLoc()); 2331 2332 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2333 // context. 2334 if (!RecoveryTSI) 2335 return ExprError(); 2336 2337 // Only issue the fixit if we're prepared to recover. 2338 D << FixItHint::CreateInsertion(Loc, "typename "); 2339 2340 // Recover by pretending this was an elaborated type. 2341 QualType Ty = Context.getTypeDeclType(TD); 2342 TypeLocBuilder TLB; 2343 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2344 2345 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2346 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2347 QTL.setElaboratedKeywordLoc(SourceLocation()); 2348 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2349 2350 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2351 2352 return ExprEmpty(); 2353 } 2354 2355 // Defend against this resolving to an implicit member access. We usually 2356 // won't get here if this might be a legitimate a class member (we end up in 2357 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2358 // a pointer-to-member or in an unevaluated context in C++11. 2359 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2360 return BuildPossibleImplicitMemberExpr(SS, 2361 /*TemplateKWLoc=*/SourceLocation(), 2362 R, /*TemplateArgs=*/nullptr, S); 2363 2364 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2365 } 2366 2367 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2368 /// detected that we're currently inside an ObjC method. Perform some 2369 /// additional lookup. 2370 /// 2371 /// Ideally, most of this would be done by lookup, but there's 2372 /// actually quite a lot of extra work involved. 2373 /// 2374 /// Returns a null sentinel to indicate trivial success. 2375 ExprResult 2376 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2377 IdentifierInfo *II, bool AllowBuiltinCreation) { 2378 SourceLocation Loc = Lookup.getNameLoc(); 2379 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2380 2381 // Check for error condition which is already reported. 2382 if (!CurMethod) 2383 return ExprError(); 2384 2385 // There are two cases to handle here. 1) scoped lookup could have failed, 2386 // in which case we should look for an ivar. 2) scoped lookup could have 2387 // found a decl, but that decl is outside the current instance method (i.e. 2388 // a global variable). In these two cases, we do a lookup for an ivar with 2389 // this name, if the lookup sucedes, we replace it our current decl. 2390 2391 // If we're in a class method, we don't normally want to look for 2392 // ivars. But if we don't find anything else, and there's an 2393 // ivar, that's an error. 2394 bool IsClassMethod = CurMethod->isClassMethod(); 2395 2396 bool LookForIvars; 2397 if (Lookup.empty()) 2398 LookForIvars = true; 2399 else if (IsClassMethod) 2400 LookForIvars = false; 2401 else 2402 LookForIvars = (Lookup.isSingleResult() && 2403 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2404 ObjCInterfaceDecl *IFace = nullptr; 2405 if (LookForIvars) { 2406 IFace = CurMethod->getClassInterface(); 2407 ObjCInterfaceDecl *ClassDeclared; 2408 ObjCIvarDecl *IV = nullptr; 2409 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2410 // Diagnose using an ivar in a class method. 2411 if (IsClassMethod) 2412 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2413 << IV->getDeclName()); 2414 2415 // If we're referencing an invalid decl, just return this as a silent 2416 // error node. The error diagnostic was already emitted on the decl. 2417 if (IV->isInvalidDecl()) 2418 return ExprError(); 2419 2420 // Check if referencing a field with __attribute__((deprecated)). 2421 if (DiagnoseUseOfDecl(IV, Loc)) 2422 return ExprError(); 2423 2424 // Diagnose the use of an ivar outside of the declaring class. 2425 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2426 !declaresSameEntity(ClassDeclared, IFace) && 2427 !getLangOpts().DebuggerSupport) 2428 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2429 2430 // FIXME: This should use a new expr for a direct reference, don't 2431 // turn this into Self->ivar, just return a BareIVarExpr or something. 2432 IdentifierInfo &II = Context.Idents.get("self"); 2433 UnqualifiedId SelfName; 2434 SelfName.setIdentifier(&II, SourceLocation()); 2435 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2436 CXXScopeSpec SelfScopeSpec; 2437 SourceLocation TemplateKWLoc; 2438 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2439 SelfName, false, false); 2440 if (SelfExpr.isInvalid()) 2441 return ExprError(); 2442 2443 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2444 if (SelfExpr.isInvalid()) 2445 return ExprError(); 2446 2447 MarkAnyDeclReferenced(Loc, IV, true); 2448 2449 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2450 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2451 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2452 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2453 2454 ObjCIvarRefExpr *Result = new (Context) 2455 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2456 IV->getLocation(), SelfExpr.get(), true, true); 2457 2458 if (getLangOpts().ObjCAutoRefCount) { 2459 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2460 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2461 recordUseOfEvaluatedWeak(Result); 2462 } 2463 if (CurContext->isClosure()) 2464 Diag(Loc, diag::warn_implicitly_retains_self) 2465 << FixItHint::CreateInsertion(Loc, "self->"); 2466 } 2467 2468 return Result; 2469 } 2470 } else if (CurMethod->isInstanceMethod()) { 2471 // We should warn if a local variable hides an ivar. 2472 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2473 ObjCInterfaceDecl *ClassDeclared; 2474 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2475 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2476 declaresSameEntity(IFace, ClassDeclared)) 2477 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2478 } 2479 } 2480 } else if (Lookup.isSingleResult() && 2481 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2482 // If accessing a stand-alone ivar in a class method, this is an error. 2483 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2484 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2485 << IV->getDeclName()); 2486 } 2487 2488 if (Lookup.empty() && II && AllowBuiltinCreation) { 2489 // FIXME. Consolidate this with similar code in LookupName. 2490 if (unsigned BuiltinID = II->getBuiltinID()) { 2491 if (!(getLangOpts().CPlusPlus && 2492 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2493 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2494 S, Lookup.isForRedeclaration(), 2495 Lookup.getNameLoc()); 2496 if (D) Lookup.addDecl(D); 2497 } 2498 } 2499 } 2500 // Sentinel value saying that we didn't do anything special. 2501 return ExprResult((Expr *)nullptr); 2502 } 2503 2504 /// \brief Cast a base object to a member's actual type. 2505 /// 2506 /// Logically this happens in three phases: 2507 /// 2508 /// * First we cast from the base type to the naming class. 2509 /// The naming class is the class into which we were looking 2510 /// when we found the member; it's the qualifier type if a 2511 /// qualifier was provided, and otherwise it's the base type. 2512 /// 2513 /// * Next we cast from the naming class to the declaring class. 2514 /// If the member we found was brought into a class's scope by 2515 /// a using declaration, this is that class; otherwise it's 2516 /// the class declaring the member. 2517 /// 2518 /// * Finally we cast from the declaring class to the "true" 2519 /// declaring class of the member. This conversion does not 2520 /// obey access control. 2521 ExprResult 2522 Sema::PerformObjectMemberConversion(Expr *From, 2523 NestedNameSpecifier *Qualifier, 2524 NamedDecl *FoundDecl, 2525 NamedDecl *Member) { 2526 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2527 if (!RD) 2528 return From; 2529 2530 QualType DestRecordType; 2531 QualType DestType; 2532 QualType FromRecordType; 2533 QualType FromType = From->getType(); 2534 bool PointerConversions = false; 2535 if (isa<FieldDecl>(Member)) { 2536 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2537 2538 if (FromType->getAs<PointerType>()) { 2539 DestType = Context.getPointerType(DestRecordType); 2540 FromRecordType = FromType->getPointeeType(); 2541 PointerConversions = true; 2542 } else { 2543 DestType = DestRecordType; 2544 FromRecordType = FromType; 2545 } 2546 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2547 if (Method->isStatic()) 2548 return From; 2549 2550 DestType = Method->getThisType(Context); 2551 DestRecordType = DestType->getPointeeType(); 2552 2553 if (FromType->getAs<PointerType>()) { 2554 FromRecordType = FromType->getPointeeType(); 2555 PointerConversions = true; 2556 } else { 2557 FromRecordType = FromType; 2558 DestType = DestRecordType; 2559 } 2560 } else { 2561 // No conversion necessary. 2562 return From; 2563 } 2564 2565 if (DestType->isDependentType() || FromType->isDependentType()) 2566 return From; 2567 2568 // If the unqualified types are the same, no conversion is necessary. 2569 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2570 return From; 2571 2572 SourceRange FromRange = From->getSourceRange(); 2573 SourceLocation FromLoc = FromRange.getBegin(); 2574 2575 ExprValueKind VK = From->getValueKind(); 2576 2577 // C++ [class.member.lookup]p8: 2578 // [...] Ambiguities can often be resolved by qualifying a name with its 2579 // class name. 2580 // 2581 // If the member was a qualified name and the qualified referred to a 2582 // specific base subobject type, we'll cast to that intermediate type 2583 // first and then to the object in which the member is declared. That allows 2584 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2585 // 2586 // class Base { public: int x; }; 2587 // class Derived1 : public Base { }; 2588 // class Derived2 : public Base { }; 2589 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2590 // 2591 // void VeryDerived::f() { 2592 // x = 17; // error: ambiguous base subobjects 2593 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2594 // } 2595 if (Qualifier && Qualifier->getAsType()) { 2596 QualType QType = QualType(Qualifier->getAsType(), 0); 2597 assert(QType->isRecordType() && "lookup done with non-record type"); 2598 2599 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2600 2601 // In C++98, the qualifier type doesn't actually have to be a base 2602 // type of the object type, in which case we just ignore it. 2603 // Otherwise build the appropriate casts. 2604 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2605 CXXCastPath BasePath; 2606 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2607 FromLoc, FromRange, &BasePath)) 2608 return ExprError(); 2609 2610 if (PointerConversions) 2611 QType = Context.getPointerType(QType); 2612 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2613 VK, &BasePath).get(); 2614 2615 FromType = QType; 2616 FromRecordType = QRecordType; 2617 2618 // If the qualifier type was the same as the destination type, 2619 // we're done. 2620 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2621 return From; 2622 } 2623 } 2624 2625 bool IgnoreAccess = false; 2626 2627 // If we actually found the member through a using declaration, cast 2628 // down to the using declaration's type. 2629 // 2630 // Pointer equality is fine here because only one declaration of a 2631 // class ever has member declarations. 2632 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2633 assert(isa<UsingShadowDecl>(FoundDecl)); 2634 QualType URecordType = Context.getTypeDeclType( 2635 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2636 2637 // We only need to do this if the naming-class to declaring-class 2638 // conversion is non-trivial. 2639 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2640 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2641 CXXCastPath BasePath; 2642 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2643 FromLoc, FromRange, &BasePath)) 2644 return ExprError(); 2645 2646 QualType UType = URecordType; 2647 if (PointerConversions) 2648 UType = Context.getPointerType(UType); 2649 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2650 VK, &BasePath).get(); 2651 FromType = UType; 2652 FromRecordType = URecordType; 2653 } 2654 2655 // We don't do access control for the conversion from the 2656 // declaring class to the true declaring class. 2657 IgnoreAccess = true; 2658 } 2659 2660 CXXCastPath BasePath; 2661 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2662 FromLoc, FromRange, &BasePath, 2663 IgnoreAccess)) 2664 return ExprError(); 2665 2666 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2667 VK, &BasePath); 2668 } 2669 2670 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2671 const LookupResult &R, 2672 bool HasTrailingLParen) { 2673 // Only when used directly as the postfix-expression of a call. 2674 if (!HasTrailingLParen) 2675 return false; 2676 2677 // Never if a scope specifier was provided. 2678 if (SS.isSet()) 2679 return false; 2680 2681 // Only in C++ or ObjC++. 2682 if (!getLangOpts().CPlusPlus) 2683 return false; 2684 2685 // Turn off ADL when we find certain kinds of declarations during 2686 // normal lookup: 2687 for (NamedDecl *D : R) { 2688 // C++0x [basic.lookup.argdep]p3: 2689 // -- a declaration of a class member 2690 // Since using decls preserve this property, we check this on the 2691 // original decl. 2692 if (D->isCXXClassMember()) 2693 return false; 2694 2695 // C++0x [basic.lookup.argdep]p3: 2696 // -- a block-scope function declaration that is not a 2697 // using-declaration 2698 // NOTE: we also trigger this for function templates (in fact, we 2699 // don't check the decl type at all, since all other decl types 2700 // turn off ADL anyway). 2701 if (isa<UsingShadowDecl>(D)) 2702 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2703 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2704 return false; 2705 2706 // C++0x [basic.lookup.argdep]p3: 2707 // -- a declaration that is neither a function or a function 2708 // template 2709 // And also for builtin functions. 2710 if (isa<FunctionDecl>(D)) { 2711 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2712 2713 // But also builtin functions. 2714 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2715 return false; 2716 } else if (!isa<FunctionTemplateDecl>(D)) 2717 return false; 2718 } 2719 2720 return true; 2721 } 2722 2723 2724 /// Diagnoses obvious problems with the use of the given declaration 2725 /// as an expression. This is only actually called for lookups that 2726 /// were not overloaded, and it doesn't promise that the declaration 2727 /// will in fact be used. 2728 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2729 if (isa<TypedefNameDecl>(D)) { 2730 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2731 return true; 2732 } 2733 2734 if (isa<ObjCInterfaceDecl>(D)) { 2735 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2736 return true; 2737 } 2738 2739 if (isa<NamespaceDecl>(D)) { 2740 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2741 return true; 2742 } 2743 2744 return false; 2745 } 2746 2747 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2748 LookupResult &R, bool NeedsADL, 2749 bool AcceptInvalidDecl) { 2750 // If this is a single, fully-resolved result and we don't need ADL, 2751 // just build an ordinary singleton decl ref. 2752 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2753 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2754 R.getRepresentativeDecl(), nullptr, 2755 AcceptInvalidDecl); 2756 2757 // We only need to check the declaration if there's exactly one 2758 // result, because in the overloaded case the results can only be 2759 // functions and function templates. 2760 if (R.isSingleResult() && 2761 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2762 return ExprError(); 2763 2764 // Otherwise, just build an unresolved lookup expression. Suppress 2765 // any lookup-related diagnostics; we'll hash these out later, when 2766 // we've picked a target. 2767 R.suppressDiagnostics(); 2768 2769 UnresolvedLookupExpr *ULE 2770 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2771 SS.getWithLocInContext(Context), 2772 R.getLookupNameInfo(), 2773 NeedsADL, R.isOverloadedResult(), 2774 R.begin(), R.end()); 2775 2776 return ULE; 2777 } 2778 2779 /// \brief Complete semantic analysis for a reference to the given declaration. 2780 ExprResult Sema::BuildDeclarationNameExpr( 2781 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2782 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2783 bool AcceptInvalidDecl) { 2784 assert(D && "Cannot refer to a NULL declaration"); 2785 assert(!isa<FunctionTemplateDecl>(D) && 2786 "Cannot refer unambiguously to a function template"); 2787 2788 SourceLocation Loc = NameInfo.getLoc(); 2789 if (CheckDeclInExpr(*this, Loc, D)) 2790 return ExprError(); 2791 2792 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2793 // Specifically diagnose references to class templates that are missing 2794 // a template argument list. 2795 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2796 << Template << SS.getRange(); 2797 Diag(Template->getLocation(), diag::note_template_decl_here); 2798 return ExprError(); 2799 } 2800 2801 // Make sure that we're referring to a value. 2802 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2803 if (!VD) { 2804 Diag(Loc, diag::err_ref_non_value) 2805 << D << SS.getRange(); 2806 Diag(D->getLocation(), diag::note_declared_at); 2807 return ExprError(); 2808 } 2809 2810 // Check whether this declaration can be used. Note that we suppress 2811 // this check when we're going to perform argument-dependent lookup 2812 // on this function name, because this might not be the function 2813 // that overload resolution actually selects. 2814 if (DiagnoseUseOfDecl(VD, Loc)) 2815 return ExprError(); 2816 2817 // Only create DeclRefExpr's for valid Decl's. 2818 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2819 return ExprError(); 2820 2821 // Handle members of anonymous structs and unions. If we got here, 2822 // and the reference is to a class member indirect field, then this 2823 // must be the subject of a pointer-to-member expression. 2824 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2825 if (!indirectField->isCXXClassMember()) 2826 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2827 indirectField); 2828 2829 { 2830 QualType type = VD->getType(); 2831 ExprValueKind valueKind = VK_RValue; 2832 2833 switch (D->getKind()) { 2834 // Ignore all the non-ValueDecl kinds. 2835 #define ABSTRACT_DECL(kind) 2836 #define VALUE(type, base) 2837 #define DECL(type, base) \ 2838 case Decl::type: 2839 #include "clang/AST/DeclNodes.inc" 2840 llvm_unreachable("invalid value decl kind"); 2841 2842 // These shouldn't make it here. 2843 case Decl::ObjCAtDefsField: 2844 case Decl::ObjCIvar: 2845 llvm_unreachable("forming non-member reference to ivar?"); 2846 2847 // Enum constants are always r-values and never references. 2848 // Unresolved using declarations are dependent. 2849 case Decl::EnumConstant: 2850 case Decl::UnresolvedUsingValue: 2851 valueKind = VK_RValue; 2852 break; 2853 2854 // Fields and indirect fields that got here must be for 2855 // pointer-to-member expressions; we just call them l-values for 2856 // internal consistency, because this subexpression doesn't really 2857 // exist in the high-level semantics. 2858 case Decl::Field: 2859 case Decl::IndirectField: 2860 assert(getLangOpts().CPlusPlus && 2861 "building reference to field in C?"); 2862 2863 // These can't have reference type in well-formed programs, but 2864 // for internal consistency we do this anyway. 2865 type = type.getNonReferenceType(); 2866 valueKind = VK_LValue; 2867 break; 2868 2869 // Non-type template parameters are either l-values or r-values 2870 // depending on the type. 2871 case Decl::NonTypeTemplateParm: { 2872 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2873 type = reftype->getPointeeType(); 2874 valueKind = VK_LValue; // even if the parameter is an r-value reference 2875 break; 2876 } 2877 2878 // For non-references, we need to strip qualifiers just in case 2879 // the template parameter was declared as 'const int' or whatever. 2880 valueKind = VK_RValue; 2881 type = type.getUnqualifiedType(); 2882 break; 2883 } 2884 2885 case Decl::Var: 2886 case Decl::VarTemplateSpecialization: 2887 case Decl::VarTemplatePartialSpecialization: 2888 case Decl::OMPCapturedExpr: 2889 // In C, "extern void blah;" is valid and is an r-value. 2890 if (!getLangOpts().CPlusPlus && 2891 !type.hasQualifiers() && 2892 type->isVoidType()) { 2893 valueKind = VK_RValue; 2894 break; 2895 } 2896 // fallthrough 2897 2898 case Decl::ImplicitParam: 2899 case Decl::ParmVar: { 2900 // These are always l-values. 2901 valueKind = VK_LValue; 2902 type = type.getNonReferenceType(); 2903 2904 // FIXME: Does the addition of const really only apply in 2905 // potentially-evaluated contexts? Since the variable isn't actually 2906 // captured in an unevaluated context, it seems that the answer is no. 2907 if (!isUnevaluatedContext()) { 2908 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2909 if (!CapturedType.isNull()) 2910 type = CapturedType; 2911 } 2912 2913 break; 2914 } 2915 2916 case Decl::Function: { 2917 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2918 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2919 type = Context.BuiltinFnTy; 2920 valueKind = VK_RValue; 2921 break; 2922 } 2923 } 2924 2925 const FunctionType *fty = type->castAs<FunctionType>(); 2926 2927 // If we're referring to a function with an __unknown_anytype 2928 // result type, make the entire expression __unknown_anytype. 2929 if (fty->getReturnType() == Context.UnknownAnyTy) { 2930 type = Context.UnknownAnyTy; 2931 valueKind = VK_RValue; 2932 break; 2933 } 2934 2935 // Functions are l-values in C++. 2936 if (getLangOpts().CPlusPlus) { 2937 valueKind = VK_LValue; 2938 break; 2939 } 2940 2941 // C99 DR 316 says that, if a function type comes from a 2942 // function definition (without a prototype), that type is only 2943 // used for checking compatibility. Therefore, when referencing 2944 // the function, we pretend that we don't have the full function 2945 // type. 2946 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2947 isa<FunctionProtoType>(fty)) 2948 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2949 fty->getExtInfo()); 2950 2951 // Functions are r-values in C. 2952 valueKind = VK_RValue; 2953 break; 2954 } 2955 2956 case Decl::MSProperty: 2957 valueKind = VK_LValue; 2958 break; 2959 2960 case Decl::CXXMethod: 2961 // If we're referring to a method with an __unknown_anytype 2962 // result type, make the entire expression __unknown_anytype. 2963 // This should only be possible with a type written directly. 2964 if (const FunctionProtoType *proto 2965 = dyn_cast<FunctionProtoType>(VD->getType())) 2966 if (proto->getReturnType() == Context.UnknownAnyTy) { 2967 type = Context.UnknownAnyTy; 2968 valueKind = VK_RValue; 2969 break; 2970 } 2971 2972 // C++ methods are l-values if static, r-values if non-static. 2973 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2974 valueKind = VK_LValue; 2975 break; 2976 } 2977 // fallthrough 2978 2979 case Decl::CXXConversion: 2980 case Decl::CXXDestructor: 2981 case Decl::CXXConstructor: 2982 valueKind = VK_RValue; 2983 break; 2984 } 2985 2986 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2987 TemplateArgs); 2988 } 2989 } 2990 2991 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2992 SmallString<32> &Target) { 2993 Target.resize(CharByteWidth * (Source.size() + 1)); 2994 char *ResultPtr = &Target[0]; 2995 const UTF8 *ErrorPtr; 2996 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2997 (void)success; 2998 assert(success); 2999 Target.resize(ResultPtr - &Target[0]); 3000 } 3001 3002 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3003 PredefinedExpr::IdentType IT) { 3004 // Pick the current block, lambda, captured statement or function. 3005 Decl *currentDecl = nullptr; 3006 if (const BlockScopeInfo *BSI = getCurBlock()) 3007 currentDecl = BSI->TheDecl; 3008 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3009 currentDecl = LSI->CallOperator; 3010 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3011 currentDecl = CSI->TheCapturedDecl; 3012 else 3013 currentDecl = getCurFunctionOrMethodDecl(); 3014 3015 if (!currentDecl) { 3016 Diag(Loc, diag::ext_predef_outside_function); 3017 currentDecl = Context.getTranslationUnitDecl(); 3018 } 3019 3020 QualType ResTy; 3021 StringLiteral *SL = nullptr; 3022 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3023 ResTy = Context.DependentTy; 3024 else { 3025 // Pre-defined identifiers are of type char[x], where x is the length of 3026 // the string. 3027 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3028 unsigned Length = Str.length(); 3029 3030 llvm::APInt LengthI(32, Length + 1); 3031 if (IT == PredefinedExpr::LFunction) { 3032 ResTy = Context.WideCharTy.withConst(); 3033 SmallString<32> RawChars; 3034 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3035 Str, RawChars); 3036 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3037 /*IndexTypeQuals*/ 0); 3038 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3039 /*Pascal*/ false, ResTy, Loc); 3040 } else { 3041 ResTy = Context.CharTy.withConst(); 3042 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3043 /*IndexTypeQuals*/ 0); 3044 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3045 /*Pascal*/ false, ResTy, Loc); 3046 } 3047 } 3048 3049 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3050 } 3051 3052 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3053 PredefinedExpr::IdentType IT; 3054 3055 switch (Kind) { 3056 default: llvm_unreachable("Unknown simple primary expr!"); 3057 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3058 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3059 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3060 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3061 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3062 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3063 } 3064 3065 return BuildPredefinedExpr(Loc, IT); 3066 } 3067 3068 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3069 SmallString<16> CharBuffer; 3070 bool Invalid = false; 3071 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3072 if (Invalid) 3073 return ExprError(); 3074 3075 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3076 PP, Tok.getKind()); 3077 if (Literal.hadError()) 3078 return ExprError(); 3079 3080 QualType Ty; 3081 if (Literal.isWide()) 3082 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3083 else if (Literal.isUTF16()) 3084 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3085 else if (Literal.isUTF32()) 3086 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3087 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3088 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3089 else 3090 Ty = Context.CharTy; // 'x' -> char in C++ 3091 3092 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3093 if (Literal.isWide()) 3094 Kind = CharacterLiteral::Wide; 3095 else if (Literal.isUTF16()) 3096 Kind = CharacterLiteral::UTF16; 3097 else if (Literal.isUTF32()) 3098 Kind = CharacterLiteral::UTF32; 3099 else if (Literal.isUTF8()) 3100 Kind = CharacterLiteral::UTF8; 3101 3102 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3103 Tok.getLocation()); 3104 3105 if (Literal.getUDSuffix().empty()) 3106 return Lit; 3107 3108 // We're building a user-defined literal. 3109 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3110 SourceLocation UDSuffixLoc = 3111 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3112 3113 // Make sure we're allowed user-defined literals here. 3114 if (!UDLScope) 3115 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3116 3117 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3118 // operator "" X (ch) 3119 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3120 Lit, Tok.getLocation()); 3121 } 3122 3123 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3124 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3125 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3126 Context.IntTy, Loc); 3127 } 3128 3129 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3130 QualType Ty, SourceLocation Loc) { 3131 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3132 3133 using llvm::APFloat; 3134 APFloat Val(Format); 3135 3136 APFloat::opStatus result = Literal.GetFloatValue(Val); 3137 3138 // Overflow is always an error, but underflow is only an error if 3139 // we underflowed to zero (APFloat reports denormals as underflow). 3140 if ((result & APFloat::opOverflow) || 3141 ((result & APFloat::opUnderflow) && Val.isZero())) { 3142 unsigned diagnostic; 3143 SmallString<20> buffer; 3144 if (result & APFloat::opOverflow) { 3145 diagnostic = diag::warn_float_overflow; 3146 APFloat::getLargest(Format).toString(buffer); 3147 } else { 3148 diagnostic = diag::warn_float_underflow; 3149 APFloat::getSmallest(Format).toString(buffer); 3150 } 3151 3152 S.Diag(Loc, diagnostic) 3153 << Ty 3154 << StringRef(buffer.data(), buffer.size()); 3155 } 3156 3157 bool isExact = (result == APFloat::opOK); 3158 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3159 } 3160 3161 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3162 assert(E && "Invalid expression"); 3163 3164 if (E->isValueDependent()) 3165 return false; 3166 3167 QualType QT = E->getType(); 3168 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3169 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3170 return true; 3171 } 3172 3173 llvm::APSInt ValueAPS; 3174 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3175 3176 if (R.isInvalid()) 3177 return true; 3178 3179 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3180 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3181 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3182 << ValueAPS.toString(10) << ValueIsPositive; 3183 return true; 3184 } 3185 3186 return false; 3187 } 3188 3189 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3190 // Fast path for a single digit (which is quite common). A single digit 3191 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3192 if (Tok.getLength() == 1) { 3193 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3194 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3195 } 3196 3197 SmallString<128> SpellingBuffer; 3198 // NumericLiteralParser wants to overread by one character. Add padding to 3199 // the buffer in case the token is copied to the buffer. If getSpelling() 3200 // returns a StringRef to the memory buffer, it should have a null char at 3201 // the EOF, so it is also safe. 3202 SpellingBuffer.resize(Tok.getLength() + 1); 3203 3204 // Get the spelling of the token, which eliminates trigraphs, etc. 3205 bool Invalid = false; 3206 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3207 if (Invalid) 3208 return ExprError(); 3209 3210 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3211 if (Literal.hadError) 3212 return ExprError(); 3213 3214 if (Literal.hasUDSuffix()) { 3215 // We're building a user-defined literal. 3216 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3217 SourceLocation UDSuffixLoc = 3218 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3219 3220 // Make sure we're allowed user-defined literals here. 3221 if (!UDLScope) 3222 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3223 3224 QualType CookedTy; 3225 if (Literal.isFloatingLiteral()) { 3226 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3227 // long double, the literal is treated as a call of the form 3228 // operator "" X (f L) 3229 CookedTy = Context.LongDoubleTy; 3230 } else { 3231 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3232 // unsigned long long, the literal is treated as a call of the form 3233 // operator "" X (n ULL) 3234 CookedTy = Context.UnsignedLongLongTy; 3235 } 3236 3237 DeclarationName OpName = 3238 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3239 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3240 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3241 3242 SourceLocation TokLoc = Tok.getLocation(); 3243 3244 // Perform literal operator lookup to determine if we're building a raw 3245 // literal or a cooked one. 3246 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3247 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3248 /*AllowRaw*/true, /*AllowTemplate*/true, 3249 /*AllowStringTemplate*/false)) { 3250 case LOLR_Error: 3251 return ExprError(); 3252 3253 case LOLR_Cooked: { 3254 Expr *Lit; 3255 if (Literal.isFloatingLiteral()) { 3256 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3257 } else { 3258 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3259 if (Literal.GetIntegerValue(ResultVal)) 3260 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3261 << /* Unsigned */ 1; 3262 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3263 Tok.getLocation()); 3264 } 3265 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3266 } 3267 3268 case LOLR_Raw: { 3269 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3270 // literal is treated as a call of the form 3271 // operator "" X ("n") 3272 unsigned Length = Literal.getUDSuffixOffset(); 3273 QualType StrTy = Context.getConstantArrayType( 3274 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3275 ArrayType::Normal, 0); 3276 Expr *Lit = StringLiteral::Create( 3277 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3278 /*Pascal*/false, StrTy, &TokLoc, 1); 3279 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3280 } 3281 3282 case LOLR_Template: { 3283 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3284 // template), L is treated as a call fo the form 3285 // operator "" X <'c1', 'c2', ... 'ck'>() 3286 // where n is the source character sequence c1 c2 ... ck. 3287 TemplateArgumentListInfo ExplicitArgs; 3288 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3289 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3290 llvm::APSInt Value(CharBits, CharIsUnsigned); 3291 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3292 Value = TokSpelling[I]; 3293 TemplateArgument Arg(Context, Value, Context.CharTy); 3294 TemplateArgumentLocInfo ArgInfo; 3295 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3296 } 3297 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3298 &ExplicitArgs); 3299 } 3300 case LOLR_StringTemplate: 3301 llvm_unreachable("unexpected literal operator lookup result"); 3302 } 3303 } 3304 3305 Expr *Res; 3306 3307 if (Literal.isFloatingLiteral()) { 3308 QualType Ty; 3309 if (Literal.isHalf){ 3310 if (getOpenCLOptions().cl_khr_fp16) 3311 Ty = Context.HalfTy; 3312 else { 3313 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3314 return ExprError(); 3315 } 3316 } else if (Literal.isFloat) 3317 Ty = Context.FloatTy; 3318 else if (!Literal.isLong) 3319 Ty = Context.DoubleTy; 3320 else 3321 Ty = Context.LongDoubleTy; 3322 3323 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3324 3325 if (Ty == Context.DoubleTy) { 3326 if (getLangOpts().SinglePrecisionConstants) { 3327 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3328 } else if (getLangOpts().OpenCL && 3329 !((getLangOpts().OpenCLVersion >= 120) || 3330 getOpenCLOptions().cl_khr_fp64)) { 3331 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3332 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3333 } 3334 } 3335 } else if (!Literal.isIntegerLiteral()) { 3336 return ExprError(); 3337 } else { 3338 QualType Ty; 3339 3340 // 'long long' is a C99 or C++11 feature. 3341 if (!getLangOpts().C99 && Literal.isLongLong) { 3342 if (getLangOpts().CPlusPlus) 3343 Diag(Tok.getLocation(), 3344 getLangOpts().CPlusPlus11 ? 3345 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3346 else 3347 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3348 } 3349 3350 // Get the value in the widest-possible width. 3351 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3352 llvm::APInt ResultVal(MaxWidth, 0); 3353 3354 if (Literal.GetIntegerValue(ResultVal)) { 3355 // If this value didn't fit into uintmax_t, error and force to ull. 3356 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3357 << /* Unsigned */ 1; 3358 Ty = Context.UnsignedLongLongTy; 3359 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3360 "long long is not intmax_t?"); 3361 } else { 3362 // If this value fits into a ULL, try to figure out what else it fits into 3363 // according to the rules of C99 6.4.4.1p5. 3364 3365 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3366 // be an unsigned int. 3367 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3368 3369 // Check from smallest to largest, picking the smallest type we can. 3370 unsigned Width = 0; 3371 3372 // Microsoft specific integer suffixes are explicitly sized. 3373 if (Literal.MicrosoftInteger) { 3374 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3375 Width = 8; 3376 Ty = Context.CharTy; 3377 } else { 3378 Width = Literal.MicrosoftInteger; 3379 Ty = Context.getIntTypeForBitwidth(Width, 3380 /*Signed=*/!Literal.isUnsigned); 3381 } 3382 } 3383 3384 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3385 // Are int/unsigned possibilities? 3386 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3387 3388 // Does it fit in a unsigned int? 3389 if (ResultVal.isIntN(IntSize)) { 3390 // Does it fit in a signed int? 3391 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3392 Ty = Context.IntTy; 3393 else if (AllowUnsigned) 3394 Ty = Context.UnsignedIntTy; 3395 Width = IntSize; 3396 } 3397 } 3398 3399 // Are long/unsigned long possibilities? 3400 if (Ty.isNull() && !Literal.isLongLong) { 3401 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3402 3403 // Does it fit in a unsigned long? 3404 if (ResultVal.isIntN(LongSize)) { 3405 // Does it fit in a signed long? 3406 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3407 Ty = Context.LongTy; 3408 else if (AllowUnsigned) 3409 Ty = Context.UnsignedLongTy; 3410 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3411 // is compatible. 3412 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3413 const unsigned LongLongSize = 3414 Context.getTargetInfo().getLongLongWidth(); 3415 Diag(Tok.getLocation(), 3416 getLangOpts().CPlusPlus 3417 ? Literal.isLong 3418 ? diag::warn_old_implicitly_unsigned_long_cxx 3419 : /*C++98 UB*/ diag:: 3420 ext_old_implicitly_unsigned_long_cxx 3421 : diag::warn_old_implicitly_unsigned_long) 3422 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3423 : /*will be ill-formed*/ 1); 3424 Ty = Context.UnsignedLongTy; 3425 } 3426 Width = LongSize; 3427 } 3428 } 3429 3430 // Check long long if needed. 3431 if (Ty.isNull()) { 3432 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3433 3434 // Does it fit in a unsigned long long? 3435 if (ResultVal.isIntN(LongLongSize)) { 3436 // Does it fit in a signed long long? 3437 // To be compatible with MSVC, hex integer literals ending with the 3438 // LL or i64 suffix are always signed in Microsoft mode. 3439 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3440 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3441 Ty = Context.LongLongTy; 3442 else if (AllowUnsigned) 3443 Ty = Context.UnsignedLongLongTy; 3444 Width = LongLongSize; 3445 } 3446 } 3447 3448 // If we still couldn't decide a type, we probably have something that 3449 // does not fit in a signed long long, but has no U suffix. 3450 if (Ty.isNull()) { 3451 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3452 Ty = Context.UnsignedLongLongTy; 3453 Width = Context.getTargetInfo().getLongLongWidth(); 3454 } 3455 3456 if (ResultVal.getBitWidth() != Width) 3457 ResultVal = ResultVal.trunc(Width); 3458 } 3459 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3460 } 3461 3462 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3463 if (Literal.isImaginary) 3464 Res = new (Context) ImaginaryLiteral(Res, 3465 Context.getComplexType(Res->getType())); 3466 3467 return Res; 3468 } 3469 3470 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3471 assert(E && "ActOnParenExpr() missing expr"); 3472 return new (Context) ParenExpr(L, R, E); 3473 } 3474 3475 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3476 SourceLocation Loc, 3477 SourceRange ArgRange) { 3478 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3479 // scalar or vector data type argument..." 3480 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3481 // type (C99 6.2.5p18) or void. 3482 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3483 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3484 << T << ArgRange; 3485 return true; 3486 } 3487 3488 assert((T->isVoidType() || !T->isIncompleteType()) && 3489 "Scalar types should always be complete"); 3490 return false; 3491 } 3492 3493 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3494 SourceLocation Loc, 3495 SourceRange ArgRange, 3496 UnaryExprOrTypeTrait TraitKind) { 3497 // Invalid types must be hard errors for SFINAE in C++. 3498 if (S.LangOpts.CPlusPlus) 3499 return true; 3500 3501 // C99 6.5.3.4p1: 3502 if (T->isFunctionType() && 3503 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3504 // sizeof(function)/alignof(function) is allowed as an extension. 3505 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3506 << TraitKind << ArgRange; 3507 return false; 3508 } 3509 3510 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3511 // this is an error (OpenCL v1.1 s6.3.k) 3512 if (T->isVoidType()) { 3513 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3514 : diag::ext_sizeof_alignof_void_type; 3515 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3516 return false; 3517 } 3518 3519 return true; 3520 } 3521 3522 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3523 SourceLocation Loc, 3524 SourceRange ArgRange, 3525 UnaryExprOrTypeTrait TraitKind) { 3526 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3527 // runtime doesn't allow it. 3528 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3529 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3530 << T << (TraitKind == UETT_SizeOf) 3531 << ArgRange; 3532 return true; 3533 } 3534 3535 return false; 3536 } 3537 3538 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3539 /// pointer type is equal to T) and emit a warning if it is. 3540 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3541 Expr *E) { 3542 // Don't warn if the operation changed the type. 3543 if (T != E->getType()) 3544 return; 3545 3546 // Now look for array decays. 3547 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3548 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3549 return; 3550 3551 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3552 << ICE->getType() 3553 << ICE->getSubExpr()->getType(); 3554 } 3555 3556 /// \brief Check the constraints on expression operands to unary type expression 3557 /// and type traits. 3558 /// 3559 /// Completes any types necessary and validates the constraints on the operand 3560 /// expression. The logic mostly mirrors the type-based overload, but may modify 3561 /// the expression as it completes the type for that expression through template 3562 /// instantiation, etc. 3563 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3564 UnaryExprOrTypeTrait ExprKind) { 3565 QualType ExprTy = E->getType(); 3566 assert(!ExprTy->isReferenceType()); 3567 3568 if (ExprKind == UETT_VecStep) 3569 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3570 E->getSourceRange()); 3571 3572 // Whitelist some types as extensions 3573 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3574 E->getSourceRange(), ExprKind)) 3575 return false; 3576 3577 // 'alignof' applied to an expression only requires the base element type of 3578 // the expression to be complete. 'sizeof' requires the expression's type to 3579 // be complete (and will attempt to complete it if it's an array of unknown 3580 // bound). 3581 if (ExprKind == UETT_AlignOf) { 3582 if (RequireCompleteType(E->getExprLoc(), 3583 Context.getBaseElementType(E->getType()), 3584 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3585 E->getSourceRange())) 3586 return true; 3587 } else { 3588 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3589 ExprKind, E->getSourceRange())) 3590 return true; 3591 } 3592 3593 // Completing the expression's type may have changed it. 3594 ExprTy = E->getType(); 3595 assert(!ExprTy->isReferenceType()); 3596 3597 if (ExprTy->isFunctionType()) { 3598 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3599 << ExprKind << E->getSourceRange(); 3600 return true; 3601 } 3602 3603 // The operand for sizeof and alignof is in an unevaluated expression context, 3604 // so side effects could result in unintended consequences. 3605 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3606 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3607 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3608 3609 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3610 E->getSourceRange(), ExprKind)) 3611 return true; 3612 3613 if (ExprKind == UETT_SizeOf) { 3614 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3615 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3616 QualType OType = PVD->getOriginalType(); 3617 QualType Type = PVD->getType(); 3618 if (Type->isPointerType() && OType->isArrayType()) { 3619 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3620 << Type << OType; 3621 Diag(PVD->getLocation(), diag::note_declared_at); 3622 } 3623 } 3624 } 3625 3626 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3627 // decays into a pointer and returns an unintended result. This is most 3628 // likely a typo for "sizeof(array) op x". 3629 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3630 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3631 BO->getLHS()); 3632 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3633 BO->getRHS()); 3634 } 3635 } 3636 3637 return false; 3638 } 3639 3640 /// \brief Check the constraints on operands to unary expression and type 3641 /// traits. 3642 /// 3643 /// This will complete any types necessary, and validate the various constraints 3644 /// on those operands. 3645 /// 3646 /// The UsualUnaryConversions() function is *not* called by this routine. 3647 /// C99 6.3.2.1p[2-4] all state: 3648 /// Except when it is the operand of the sizeof operator ... 3649 /// 3650 /// C++ [expr.sizeof]p4 3651 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3652 /// standard conversions are not applied to the operand of sizeof. 3653 /// 3654 /// This policy is followed for all of the unary trait expressions. 3655 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3656 SourceLocation OpLoc, 3657 SourceRange ExprRange, 3658 UnaryExprOrTypeTrait ExprKind) { 3659 if (ExprType->isDependentType()) 3660 return false; 3661 3662 // C++ [expr.sizeof]p2: 3663 // When applied to a reference or a reference type, the result 3664 // is the size of the referenced type. 3665 // C++11 [expr.alignof]p3: 3666 // When alignof is applied to a reference type, the result 3667 // shall be the alignment of the referenced type. 3668 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3669 ExprType = Ref->getPointeeType(); 3670 3671 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3672 // When alignof or _Alignof is applied to an array type, the result 3673 // is the alignment of the element type. 3674 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3675 ExprType = Context.getBaseElementType(ExprType); 3676 3677 if (ExprKind == UETT_VecStep) 3678 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3679 3680 // Whitelist some types as extensions 3681 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3682 ExprKind)) 3683 return false; 3684 3685 if (RequireCompleteType(OpLoc, ExprType, 3686 diag::err_sizeof_alignof_incomplete_type, 3687 ExprKind, ExprRange)) 3688 return true; 3689 3690 if (ExprType->isFunctionType()) { 3691 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3692 << ExprKind << ExprRange; 3693 return true; 3694 } 3695 3696 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3697 ExprKind)) 3698 return true; 3699 3700 return false; 3701 } 3702 3703 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3704 E = E->IgnoreParens(); 3705 3706 // Cannot know anything else if the expression is dependent. 3707 if (E->isTypeDependent()) 3708 return false; 3709 3710 if (E->getObjectKind() == OK_BitField) { 3711 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3712 << 1 << E->getSourceRange(); 3713 return true; 3714 } 3715 3716 ValueDecl *D = nullptr; 3717 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3718 D = DRE->getDecl(); 3719 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3720 D = ME->getMemberDecl(); 3721 } 3722 3723 // If it's a field, require the containing struct to have a 3724 // complete definition so that we can compute the layout. 3725 // 3726 // This can happen in C++11 onwards, either by naming the member 3727 // in a way that is not transformed into a member access expression 3728 // (in an unevaluated operand, for instance), or by naming the member 3729 // in a trailing-return-type. 3730 // 3731 // For the record, since __alignof__ on expressions is a GCC 3732 // extension, GCC seems to permit this but always gives the 3733 // nonsensical answer 0. 3734 // 3735 // We don't really need the layout here --- we could instead just 3736 // directly check for all the appropriate alignment-lowing 3737 // attributes --- but that would require duplicating a lot of 3738 // logic that just isn't worth duplicating for such a marginal 3739 // use-case. 3740 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3741 // Fast path this check, since we at least know the record has a 3742 // definition if we can find a member of it. 3743 if (!FD->getParent()->isCompleteDefinition()) { 3744 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3745 << E->getSourceRange(); 3746 return true; 3747 } 3748 3749 // Otherwise, if it's a field, and the field doesn't have 3750 // reference type, then it must have a complete type (or be a 3751 // flexible array member, which we explicitly want to 3752 // white-list anyway), which makes the following checks trivial. 3753 if (!FD->getType()->isReferenceType()) 3754 return false; 3755 } 3756 3757 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3758 } 3759 3760 bool Sema::CheckVecStepExpr(Expr *E) { 3761 E = E->IgnoreParens(); 3762 3763 // Cannot know anything else if the expression is dependent. 3764 if (E->isTypeDependent()) 3765 return false; 3766 3767 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3768 } 3769 3770 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3771 CapturingScopeInfo *CSI) { 3772 assert(T->isVariablyModifiedType()); 3773 assert(CSI != nullptr); 3774 3775 // We're going to walk down into the type and look for VLA expressions. 3776 do { 3777 const Type *Ty = T.getTypePtr(); 3778 switch (Ty->getTypeClass()) { 3779 #define TYPE(Class, Base) 3780 #define ABSTRACT_TYPE(Class, Base) 3781 #define NON_CANONICAL_TYPE(Class, Base) 3782 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3783 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3784 #include "clang/AST/TypeNodes.def" 3785 T = QualType(); 3786 break; 3787 // These types are never variably-modified. 3788 case Type::Builtin: 3789 case Type::Complex: 3790 case Type::Vector: 3791 case Type::ExtVector: 3792 case Type::Record: 3793 case Type::Enum: 3794 case Type::Elaborated: 3795 case Type::TemplateSpecialization: 3796 case Type::ObjCObject: 3797 case Type::ObjCInterface: 3798 case Type::ObjCObjectPointer: 3799 case Type::Pipe: 3800 llvm_unreachable("type class is never variably-modified!"); 3801 case Type::Adjusted: 3802 T = cast<AdjustedType>(Ty)->getOriginalType(); 3803 break; 3804 case Type::Decayed: 3805 T = cast<DecayedType>(Ty)->getPointeeType(); 3806 break; 3807 case Type::Pointer: 3808 T = cast<PointerType>(Ty)->getPointeeType(); 3809 break; 3810 case Type::BlockPointer: 3811 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3812 break; 3813 case Type::LValueReference: 3814 case Type::RValueReference: 3815 T = cast<ReferenceType>(Ty)->getPointeeType(); 3816 break; 3817 case Type::MemberPointer: 3818 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3819 break; 3820 case Type::ConstantArray: 3821 case Type::IncompleteArray: 3822 // Losing element qualification here is fine. 3823 T = cast<ArrayType>(Ty)->getElementType(); 3824 break; 3825 case Type::VariableArray: { 3826 // Losing element qualification here is fine. 3827 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3828 3829 // Unknown size indication requires no size computation. 3830 // Otherwise, evaluate and record it. 3831 if (auto Size = VAT->getSizeExpr()) { 3832 if (!CSI->isVLATypeCaptured(VAT)) { 3833 RecordDecl *CapRecord = nullptr; 3834 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3835 CapRecord = LSI->Lambda; 3836 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3837 CapRecord = CRSI->TheRecordDecl; 3838 } 3839 if (CapRecord) { 3840 auto ExprLoc = Size->getExprLoc(); 3841 auto SizeType = Context.getSizeType(); 3842 // Build the non-static data member. 3843 auto Field = 3844 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3845 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3846 /*BW*/ nullptr, /*Mutable*/ false, 3847 /*InitStyle*/ ICIS_NoInit); 3848 Field->setImplicit(true); 3849 Field->setAccess(AS_private); 3850 Field->setCapturedVLAType(VAT); 3851 CapRecord->addDecl(Field); 3852 3853 CSI->addVLATypeCapture(ExprLoc, SizeType); 3854 } 3855 } 3856 } 3857 T = VAT->getElementType(); 3858 break; 3859 } 3860 case Type::FunctionProto: 3861 case Type::FunctionNoProto: 3862 T = cast<FunctionType>(Ty)->getReturnType(); 3863 break; 3864 case Type::Paren: 3865 case Type::TypeOf: 3866 case Type::UnaryTransform: 3867 case Type::Attributed: 3868 case Type::SubstTemplateTypeParm: 3869 case Type::PackExpansion: 3870 // Keep walking after single level desugaring. 3871 T = T.getSingleStepDesugaredType(Context); 3872 break; 3873 case Type::Typedef: 3874 T = cast<TypedefType>(Ty)->desugar(); 3875 break; 3876 case Type::Decltype: 3877 T = cast<DecltypeType>(Ty)->desugar(); 3878 break; 3879 case Type::Auto: 3880 T = cast<AutoType>(Ty)->getDeducedType(); 3881 break; 3882 case Type::TypeOfExpr: 3883 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3884 break; 3885 case Type::Atomic: 3886 T = cast<AtomicType>(Ty)->getValueType(); 3887 break; 3888 } 3889 } while (!T.isNull() && T->isVariablyModifiedType()); 3890 } 3891 3892 /// \brief Build a sizeof or alignof expression given a type operand. 3893 ExprResult 3894 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3895 SourceLocation OpLoc, 3896 UnaryExprOrTypeTrait ExprKind, 3897 SourceRange R) { 3898 if (!TInfo) 3899 return ExprError(); 3900 3901 QualType T = TInfo->getType(); 3902 3903 if (!T->isDependentType() && 3904 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3905 return ExprError(); 3906 3907 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3908 if (auto *TT = T->getAs<TypedefType>()) { 3909 for (auto I = FunctionScopes.rbegin(), 3910 E = std::prev(FunctionScopes.rend()); 3911 I != E; ++I) { 3912 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3913 if (CSI == nullptr) 3914 break; 3915 DeclContext *DC = nullptr; 3916 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3917 DC = LSI->CallOperator; 3918 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3919 DC = CRSI->TheCapturedDecl; 3920 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3921 DC = BSI->TheDecl; 3922 if (DC) { 3923 if (DC->containsDecl(TT->getDecl())) 3924 break; 3925 captureVariablyModifiedType(Context, T, CSI); 3926 } 3927 } 3928 } 3929 } 3930 3931 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3932 return new (Context) UnaryExprOrTypeTraitExpr( 3933 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3934 } 3935 3936 /// \brief Build a sizeof or alignof expression given an expression 3937 /// operand. 3938 ExprResult 3939 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3940 UnaryExprOrTypeTrait ExprKind) { 3941 ExprResult PE = CheckPlaceholderExpr(E); 3942 if (PE.isInvalid()) 3943 return ExprError(); 3944 3945 E = PE.get(); 3946 3947 // Verify that the operand is valid. 3948 bool isInvalid = false; 3949 if (E->isTypeDependent()) { 3950 // Delay type-checking for type-dependent expressions. 3951 } else if (ExprKind == UETT_AlignOf) { 3952 isInvalid = CheckAlignOfExpr(*this, E); 3953 } else if (ExprKind == UETT_VecStep) { 3954 isInvalid = CheckVecStepExpr(E); 3955 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3956 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3957 isInvalid = true; 3958 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3959 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3960 isInvalid = true; 3961 } else { 3962 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3963 } 3964 3965 if (isInvalid) 3966 return ExprError(); 3967 3968 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3969 PE = TransformToPotentiallyEvaluated(E); 3970 if (PE.isInvalid()) return ExprError(); 3971 E = PE.get(); 3972 } 3973 3974 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3975 return new (Context) UnaryExprOrTypeTraitExpr( 3976 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3977 } 3978 3979 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3980 /// expr and the same for @c alignof and @c __alignof 3981 /// Note that the ArgRange is invalid if isType is false. 3982 ExprResult 3983 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3984 UnaryExprOrTypeTrait ExprKind, bool IsType, 3985 void *TyOrEx, SourceRange ArgRange) { 3986 // If error parsing type, ignore. 3987 if (!TyOrEx) return ExprError(); 3988 3989 if (IsType) { 3990 TypeSourceInfo *TInfo; 3991 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3992 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3993 } 3994 3995 Expr *ArgEx = (Expr *)TyOrEx; 3996 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3997 return Result; 3998 } 3999 4000 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4001 bool IsReal) { 4002 if (V.get()->isTypeDependent()) 4003 return S.Context.DependentTy; 4004 4005 // _Real and _Imag are only l-values for normal l-values. 4006 if (V.get()->getObjectKind() != OK_Ordinary) { 4007 V = S.DefaultLvalueConversion(V.get()); 4008 if (V.isInvalid()) 4009 return QualType(); 4010 } 4011 4012 // These operators return the element type of a complex type. 4013 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4014 return CT->getElementType(); 4015 4016 // Otherwise they pass through real integer and floating point types here. 4017 if (V.get()->getType()->isArithmeticType()) 4018 return V.get()->getType(); 4019 4020 // Test for placeholders. 4021 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4022 if (PR.isInvalid()) return QualType(); 4023 if (PR.get() != V.get()) { 4024 V = PR; 4025 return CheckRealImagOperand(S, V, Loc, IsReal); 4026 } 4027 4028 // Reject anything else. 4029 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4030 << (IsReal ? "__real" : "__imag"); 4031 return QualType(); 4032 } 4033 4034 4035 4036 ExprResult 4037 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4038 tok::TokenKind Kind, Expr *Input) { 4039 UnaryOperatorKind Opc; 4040 switch (Kind) { 4041 default: llvm_unreachable("Unknown unary op!"); 4042 case tok::plusplus: Opc = UO_PostInc; break; 4043 case tok::minusminus: Opc = UO_PostDec; break; 4044 } 4045 4046 // Since this might is a postfix expression, get rid of ParenListExprs. 4047 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4048 if (Result.isInvalid()) return ExprError(); 4049 Input = Result.get(); 4050 4051 return BuildUnaryOp(S, OpLoc, Opc, Input); 4052 } 4053 4054 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4055 /// 4056 /// \return true on error 4057 static bool checkArithmeticOnObjCPointer(Sema &S, 4058 SourceLocation opLoc, 4059 Expr *op) { 4060 assert(op->getType()->isObjCObjectPointerType()); 4061 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4062 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4063 return false; 4064 4065 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4066 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4067 << op->getSourceRange(); 4068 return true; 4069 } 4070 4071 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4072 auto *BaseNoParens = Base->IgnoreParens(); 4073 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4074 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4075 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4076 } 4077 4078 ExprResult 4079 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4080 Expr *idx, SourceLocation rbLoc) { 4081 if (base && !base->getType().isNull() && 4082 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4083 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4084 /*Length=*/nullptr, rbLoc); 4085 4086 // Since this might be a postfix expression, get rid of ParenListExprs. 4087 if (isa<ParenListExpr>(base)) { 4088 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4089 if (result.isInvalid()) return ExprError(); 4090 base = result.get(); 4091 } 4092 4093 // Handle any non-overload placeholder types in the base and index 4094 // expressions. We can't handle overloads here because the other 4095 // operand might be an overloadable type, in which case the overload 4096 // resolution for the operator overload should get the first crack 4097 // at the overload. 4098 bool IsMSPropertySubscript = false; 4099 if (base->getType()->isNonOverloadPlaceholderType()) { 4100 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4101 if (!IsMSPropertySubscript) { 4102 ExprResult result = CheckPlaceholderExpr(base); 4103 if (result.isInvalid()) 4104 return ExprError(); 4105 base = result.get(); 4106 } 4107 } 4108 if (idx->getType()->isNonOverloadPlaceholderType()) { 4109 ExprResult result = CheckPlaceholderExpr(idx); 4110 if (result.isInvalid()) return ExprError(); 4111 idx = result.get(); 4112 } 4113 4114 // Build an unanalyzed expression if either operand is type-dependent. 4115 if (getLangOpts().CPlusPlus && 4116 (base->isTypeDependent() || idx->isTypeDependent())) { 4117 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4118 VK_LValue, OK_Ordinary, rbLoc); 4119 } 4120 4121 // MSDN, property (C++) 4122 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4123 // This attribute can also be used in the declaration of an empty array in a 4124 // class or structure definition. For example: 4125 // __declspec(property(get=GetX, put=PutX)) int x[]; 4126 // The above statement indicates that x[] can be used with one or more array 4127 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4128 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4129 if (IsMSPropertySubscript) { 4130 // Build MS property subscript expression if base is MS property reference 4131 // or MS property subscript. 4132 return new (Context) MSPropertySubscriptExpr( 4133 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4134 } 4135 4136 // Use C++ overloaded-operator rules if either operand has record 4137 // type. The spec says to do this if either type is *overloadable*, 4138 // but enum types can't declare subscript operators or conversion 4139 // operators, so there's nothing interesting for overload resolution 4140 // to do if there aren't any record types involved. 4141 // 4142 // ObjC pointers have their own subscripting logic that is not tied 4143 // to overload resolution and so should not take this path. 4144 if (getLangOpts().CPlusPlus && 4145 (base->getType()->isRecordType() || 4146 (!base->getType()->isObjCObjectPointerType() && 4147 idx->getType()->isRecordType()))) { 4148 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4149 } 4150 4151 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4152 } 4153 4154 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4155 Expr *LowerBound, 4156 SourceLocation ColonLoc, Expr *Length, 4157 SourceLocation RBLoc) { 4158 if (Base->getType()->isPlaceholderType() && 4159 !Base->getType()->isSpecificPlaceholderType( 4160 BuiltinType::OMPArraySection)) { 4161 ExprResult Result = CheckPlaceholderExpr(Base); 4162 if (Result.isInvalid()) 4163 return ExprError(); 4164 Base = Result.get(); 4165 } 4166 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4167 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4168 if (Result.isInvalid()) 4169 return ExprError(); 4170 Result = DefaultLvalueConversion(Result.get()); 4171 if (Result.isInvalid()) 4172 return ExprError(); 4173 LowerBound = Result.get(); 4174 } 4175 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4176 ExprResult Result = CheckPlaceholderExpr(Length); 4177 if (Result.isInvalid()) 4178 return ExprError(); 4179 Result = DefaultLvalueConversion(Result.get()); 4180 if (Result.isInvalid()) 4181 return ExprError(); 4182 Length = Result.get(); 4183 } 4184 4185 // Build an unanalyzed expression if either operand is type-dependent. 4186 if (Base->isTypeDependent() || 4187 (LowerBound && 4188 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4189 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4190 return new (Context) 4191 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4192 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4193 } 4194 4195 // Perform default conversions. 4196 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4197 QualType ResultTy; 4198 if (OriginalTy->isAnyPointerType()) { 4199 ResultTy = OriginalTy->getPointeeType(); 4200 } else if (OriginalTy->isArrayType()) { 4201 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4202 } else { 4203 return ExprError( 4204 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4205 << Base->getSourceRange()); 4206 } 4207 // C99 6.5.2.1p1 4208 if (LowerBound) { 4209 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4210 LowerBound); 4211 if (Res.isInvalid()) 4212 return ExprError(Diag(LowerBound->getExprLoc(), 4213 diag::err_omp_typecheck_section_not_integer) 4214 << 0 << LowerBound->getSourceRange()); 4215 LowerBound = Res.get(); 4216 4217 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4218 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4219 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4220 << 0 << LowerBound->getSourceRange(); 4221 } 4222 if (Length) { 4223 auto Res = 4224 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4225 if (Res.isInvalid()) 4226 return ExprError(Diag(Length->getExprLoc(), 4227 diag::err_omp_typecheck_section_not_integer) 4228 << 1 << Length->getSourceRange()); 4229 Length = Res.get(); 4230 4231 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4232 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4233 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4234 << 1 << Length->getSourceRange(); 4235 } 4236 4237 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4238 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4239 // type. Note that functions are not objects, and that (in C99 parlance) 4240 // incomplete types are not object types. 4241 if (ResultTy->isFunctionType()) { 4242 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4243 << ResultTy << Base->getSourceRange(); 4244 return ExprError(); 4245 } 4246 4247 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4248 diag::err_omp_section_incomplete_type, Base)) 4249 return ExprError(); 4250 4251 if (LowerBound) { 4252 llvm::APSInt LowerBoundValue; 4253 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4254 // OpenMP 4.0, [2.4 Array Sections] 4255 // The lower-bound and length must evaluate to non-negative integers. 4256 if (LowerBoundValue.isNegative()) { 4257 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4258 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4259 << LowerBound->getSourceRange(); 4260 return ExprError(); 4261 } 4262 } 4263 } 4264 4265 if (Length) { 4266 llvm::APSInt LengthValue; 4267 if (Length->EvaluateAsInt(LengthValue, Context)) { 4268 // OpenMP 4.0, [2.4 Array Sections] 4269 // The lower-bound and length must evaluate to non-negative integers. 4270 if (LengthValue.isNegative()) { 4271 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4272 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4273 << Length->getSourceRange(); 4274 return ExprError(); 4275 } 4276 } 4277 } else if (ColonLoc.isValid() && 4278 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4279 !OriginalTy->isVariableArrayType()))) { 4280 // OpenMP 4.0, [2.4 Array Sections] 4281 // When the size of the array dimension is not known, the length must be 4282 // specified explicitly. 4283 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4284 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4285 return ExprError(); 4286 } 4287 4288 if (!Base->getType()->isSpecificPlaceholderType( 4289 BuiltinType::OMPArraySection)) { 4290 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4291 if (Result.isInvalid()) 4292 return ExprError(); 4293 Base = Result.get(); 4294 } 4295 return new (Context) 4296 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4297 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4298 } 4299 4300 ExprResult 4301 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4302 Expr *Idx, SourceLocation RLoc) { 4303 Expr *LHSExp = Base; 4304 Expr *RHSExp = Idx; 4305 4306 // Perform default conversions. 4307 if (!LHSExp->getType()->getAs<VectorType>()) { 4308 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4309 if (Result.isInvalid()) 4310 return ExprError(); 4311 LHSExp = Result.get(); 4312 } 4313 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4314 if (Result.isInvalid()) 4315 return ExprError(); 4316 RHSExp = Result.get(); 4317 4318 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4319 ExprValueKind VK = VK_LValue; 4320 ExprObjectKind OK = OK_Ordinary; 4321 4322 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4323 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4324 // in the subscript position. As a result, we need to derive the array base 4325 // and index from the expression types. 4326 Expr *BaseExpr, *IndexExpr; 4327 QualType ResultType; 4328 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4329 BaseExpr = LHSExp; 4330 IndexExpr = RHSExp; 4331 ResultType = Context.DependentTy; 4332 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4333 BaseExpr = LHSExp; 4334 IndexExpr = RHSExp; 4335 ResultType = PTy->getPointeeType(); 4336 } else if (const ObjCObjectPointerType *PTy = 4337 LHSTy->getAs<ObjCObjectPointerType>()) { 4338 BaseExpr = LHSExp; 4339 IndexExpr = RHSExp; 4340 4341 // Use custom logic if this should be the pseudo-object subscript 4342 // expression. 4343 if (!LangOpts.isSubscriptPointerArithmetic()) 4344 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4345 nullptr); 4346 4347 ResultType = PTy->getPointeeType(); 4348 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4349 // Handle the uncommon case of "123[Ptr]". 4350 BaseExpr = RHSExp; 4351 IndexExpr = LHSExp; 4352 ResultType = PTy->getPointeeType(); 4353 } else if (const ObjCObjectPointerType *PTy = 4354 RHSTy->getAs<ObjCObjectPointerType>()) { 4355 // Handle the uncommon case of "123[Ptr]". 4356 BaseExpr = RHSExp; 4357 IndexExpr = LHSExp; 4358 ResultType = PTy->getPointeeType(); 4359 if (!LangOpts.isSubscriptPointerArithmetic()) { 4360 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4361 << ResultType << BaseExpr->getSourceRange(); 4362 return ExprError(); 4363 } 4364 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4365 BaseExpr = LHSExp; // vectors: V[123] 4366 IndexExpr = RHSExp; 4367 VK = LHSExp->getValueKind(); 4368 if (VK != VK_RValue) 4369 OK = OK_VectorComponent; 4370 4371 // FIXME: need to deal with const... 4372 ResultType = VTy->getElementType(); 4373 } else if (LHSTy->isArrayType()) { 4374 // If we see an array that wasn't promoted by 4375 // DefaultFunctionArrayLvalueConversion, it must be an array that 4376 // wasn't promoted because of the C90 rule that doesn't 4377 // allow promoting non-lvalue arrays. Warn, then 4378 // force the promotion here. 4379 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4380 LHSExp->getSourceRange(); 4381 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4382 CK_ArrayToPointerDecay).get(); 4383 LHSTy = LHSExp->getType(); 4384 4385 BaseExpr = LHSExp; 4386 IndexExpr = RHSExp; 4387 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4388 } else if (RHSTy->isArrayType()) { 4389 // Same as previous, except for 123[f().a] case 4390 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4391 RHSExp->getSourceRange(); 4392 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4393 CK_ArrayToPointerDecay).get(); 4394 RHSTy = RHSExp->getType(); 4395 4396 BaseExpr = RHSExp; 4397 IndexExpr = LHSExp; 4398 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4399 } else { 4400 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4401 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4402 } 4403 // C99 6.5.2.1p1 4404 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4405 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4406 << IndexExpr->getSourceRange()); 4407 4408 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4409 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4410 && !IndexExpr->isTypeDependent()) 4411 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4412 4413 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4414 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4415 // type. Note that Functions are not objects, and that (in C99 parlance) 4416 // incomplete types are not object types. 4417 if (ResultType->isFunctionType()) { 4418 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4419 << ResultType << BaseExpr->getSourceRange(); 4420 return ExprError(); 4421 } 4422 4423 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4424 // GNU extension: subscripting on pointer to void 4425 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4426 << BaseExpr->getSourceRange(); 4427 4428 // C forbids expressions of unqualified void type from being l-values. 4429 // See IsCForbiddenLValueType. 4430 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4431 } else if (!ResultType->isDependentType() && 4432 RequireCompleteType(LLoc, ResultType, 4433 diag::err_subscript_incomplete_type, BaseExpr)) 4434 return ExprError(); 4435 4436 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4437 !ResultType.isCForbiddenLValueType()); 4438 4439 return new (Context) 4440 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4441 } 4442 4443 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4444 FunctionDecl *FD, 4445 ParmVarDecl *Param) { 4446 if (Param->hasUnparsedDefaultArg()) { 4447 Diag(CallLoc, 4448 diag::err_use_of_default_argument_to_function_declared_later) << 4449 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4450 Diag(UnparsedDefaultArgLocs[Param], 4451 diag::note_default_argument_declared_here); 4452 return ExprError(); 4453 } 4454 4455 if (Param->hasUninstantiatedDefaultArg()) { 4456 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4457 4458 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4459 Param); 4460 4461 // Instantiate the expression. 4462 MultiLevelTemplateArgumentList MutiLevelArgList 4463 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4464 4465 InstantiatingTemplate Inst(*this, CallLoc, Param, 4466 MutiLevelArgList.getInnermost()); 4467 if (Inst.isInvalid()) 4468 return ExprError(); 4469 4470 ExprResult Result; 4471 { 4472 // C++ [dcl.fct.default]p5: 4473 // The names in the [default argument] expression are bound, and 4474 // the semantic constraints are checked, at the point where the 4475 // default argument expression appears. 4476 ContextRAII SavedContext(*this, FD); 4477 LocalInstantiationScope Local(*this); 4478 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4479 } 4480 if (Result.isInvalid()) 4481 return ExprError(); 4482 4483 // Check the expression as an initializer for the parameter. 4484 InitializedEntity Entity 4485 = InitializedEntity::InitializeParameter(Context, Param); 4486 InitializationKind Kind 4487 = InitializationKind::CreateCopy(Param->getLocation(), 4488 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4489 Expr *ResultE = Result.getAs<Expr>(); 4490 4491 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4492 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4493 if (Result.isInvalid()) 4494 return ExprError(); 4495 4496 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4497 Param->getOuterLocStart()); 4498 if (Result.isInvalid()) 4499 return ExprError(); 4500 4501 // Remember the instantiated default argument. 4502 Param->setDefaultArg(Result.getAs<Expr>()); 4503 if (ASTMutationListener *L = getASTMutationListener()) { 4504 L->DefaultArgumentInstantiated(Param); 4505 } 4506 } 4507 4508 // If the default expression creates temporaries, we need to 4509 // push them to the current stack of expression temporaries so they'll 4510 // be properly destroyed. 4511 // FIXME: We should really be rebuilding the default argument with new 4512 // bound temporaries; see the comment in PR5810. 4513 // We don't need to do that with block decls, though, because 4514 // blocks in default argument expression can never capture anything. 4515 if (isa<ExprWithCleanups>(Param->getInit())) { 4516 // Set the "needs cleanups" bit regardless of whether there are 4517 // any explicit objects. 4518 ExprNeedsCleanups = true; 4519 4520 // Append all the objects to the cleanup list. Right now, this 4521 // should always be a no-op, because blocks in default argument 4522 // expressions should never be able to capture anything. 4523 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4524 "default argument expression has capturing blocks?"); 4525 } 4526 4527 // We already type-checked the argument, so we know it works. 4528 // Just mark all of the declarations in this potentially-evaluated expression 4529 // as being "referenced". 4530 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4531 /*SkipLocalVariables=*/true); 4532 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4533 } 4534 4535 4536 Sema::VariadicCallType 4537 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4538 Expr *Fn) { 4539 if (Proto && Proto->isVariadic()) { 4540 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4541 return VariadicConstructor; 4542 else if (Fn && Fn->getType()->isBlockPointerType()) 4543 return VariadicBlock; 4544 else if (FDecl) { 4545 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4546 if (Method->isInstance()) 4547 return VariadicMethod; 4548 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4549 return VariadicMethod; 4550 return VariadicFunction; 4551 } 4552 return VariadicDoesNotApply; 4553 } 4554 4555 namespace { 4556 class FunctionCallCCC : public FunctionCallFilterCCC { 4557 public: 4558 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4559 unsigned NumArgs, MemberExpr *ME) 4560 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4561 FunctionName(FuncName) {} 4562 4563 bool ValidateCandidate(const TypoCorrection &candidate) override { 4564 if (!candidate.getCorrectionSpecifier() || 4565 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4566 return false; 4567 } 4568 4569 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4570 } 4571 4572 private: 4573 const IdentifierInfo *const FunctionName; 4574 }; 4575 } 4576 4577 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4578 FunctionDecl *FDecl, 4579 ArrayRef<Expr *> Args) { 4580 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4581 DeclarationName FuncName = FDecl->getDeclName(); 4582 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4583 4584 if (TypoCorrection Corrected = S.CorrectTypo( 4585 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4586 S.getScopeForContext(S.CurContext), nullptr, 4587 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4588 Args.size(), ME), 4589 Sema::CTK_ErrorRecovery)) { 4590 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4591 if (Corrected.isOverloaded()) { 4592 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4593 OverloadCandidateSet::iterator Best; 4594 for (NamedDecl *CD : Corrected) { 4595 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4596 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4597 OCS); 4598 } 4599 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4600 case OR_Success: 4601 ND = Best->FoundDecl; 4602 Corrected.setCorrectionDecl(ND); 4603 break; 4604 default: 4605 break; 4606 } 4607 } 4608 ND = ND->getUnderlyingDecl(); 4609 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4610 return Corrected; 4611 } 4612 } 4613 return TypoCorrection(); 4614 } 4615 4616 /// ConvertArgumentsForCall - Converts the arguments specified in 4617 /// Args/NumArgs to the parameter types of the function FDecl with 4618 /// function prototype Proto. Call is the call expression itself, and 4619 /// Fn is the function expression. For a C++ member function, this 4620 /// routine does not attempt to convert the object argument. Returns 4621 /// true if the call is ill-formed. 4622 bool 4623 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4624 FunctionDecl *FDecl, 4625 const FunctionProtoType *Proto, 4626 ArrayRef<Expr *> Args, 4627 SourceLocation RParenLoc, 4628 bool IsExecConfig) { 4629 // Bail out early if calling a builtin with custom typechecking. 4630 if (FDecl) 4631 if (unsigned ID = FDecl->getBuiltinID()) 4632 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4633 return false; 4634 4635 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4636 // assignment, to the types of the corresponding parameter, ... 4637 unsigned NumParams = Proto->getNumParams(); 4638 bool Invalid = false; 4639 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4640 unsigned FnKind = Fn->getType()->isBlockPointerType() 4641 ? 1 /* block */ 4642 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4643 : 0 /* function */); 4644 4645 // If too few arguments are available (and we don't have default 4646 // arguments for the remaining parameters), don't make the call. 4647 if (Args.size() < NumParams) { 4648 if (Args.size() < MinArgs) { 4649 TypoCorrection TC; 4650 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4651 unsigned diag_id = 4652 MinArgs == NumParams && !Proto->isVariadic() 4653 ? diag::err_typecheck_call_too_few_args_suggest 4654 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4655 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4656 << static_cast<unsigned>(Args.size()) 4657 << TC.getCorrectionRange()); 4658 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4659 Diag(RParenLoc, 4660 MinArgs == NumParams && !Proto->isVariadic() 4661 ? diag::err_typecheck_call_too_few_args_one 4662 : diag::err_typecheck_call_too_few_args_at_least_one) 4663 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4664 else 4665 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4666 ? diag::err_typecheck_call_too_few_args 4667 : diag::err_typecheck_call_too_few_args_at_least) 4668 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4669 << Fn->getSourceRange(); 4670 4671 // Emit the location of the prototype. 4672 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4673 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4674 << FDecl; 4675 4676 return true; 4677 } 4678 Call->setNumArgs(Context, NumParams); 4679 } 4680 4681 // If too many are passed and not variadic, error on the extras and drop 4682 // them. 4683 if (Args.size() > NumParams) { 4684 if (!Proto->isVariadic()) { 4685 TypoCorrection TC; 4686 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4687 unsigned diag_id = 4688 MinArgs == NumParams && !Proto->isVariadic() 4689 ? diag::err_typecheck_call_too_many_args_suggest 4690 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4691 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4692 << static_cast<unsigned>(Args.size()) 4693 << TC.getCorrectionRange()); 4694 } else if (NumParams == 1 && FDecl && 4695 FDecl->getParamDecl(0)->getDeclName()) 4696 Diag(Args[NumParams]->getLocStart(), 4697 MinArgs == NumParams 4698 ? diag::err_typecheck_call_too_many_args_one 4699 : diag::err_typecheck_call_too_many_args_at_most_one) 4700 << FnKind << FDecl->getParamDecl(0) 4701 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4702 << SourceRange(Args[NumParams]->getLocStart(), 4703 Args.back()->getLocEnd()); 4704 else 4705 Diag(Args[NumParams]->getLocStart(), 4706 MinArgs == NumParams 4707 ? diag::err_typecheck_call_too_many_args 4708 : diag::err_typecheck_call_too_many_args_at_most) 4709 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4710 << Fn->getSourceRange() 4711 << SourceRange(Args[NumParams]->getLocStart(), 4712 Args.back()->getLocEnd()); 4713 4714 // Emit the location of the prototype. 4715 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4716 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4717 << FDecl; 4718 4719 // This deletes the extra arguments. 4720 Call->setNumArgs(Context, NumParams); 4721 return true; 4722 } 4723 } 4724 SmallVector<Expr *, 8> AllArgs; 4725 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4726 4727 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4728 Proto, 0, Args, AllArgs, CallType); 4729 if (Invalid) 4730 return true; 4731 unsigned TotalNumArgs = AllArgs.size(); 4732 for (unsigned i = 0; i < TotalNumArgs; ++i) 4733 Call->setArg(i, AllArgs[i]); 4734 4735 return false; 4736 } 4737 4738 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4739 const FunctionProtoType *Proto, 4740 unsigned FirstParam, ArrayRef<Expr *> Args, 4741 SmallVectorImpl<Expr *> &AllArgs, 4742 VariadicCallType CallType, bool AllowExplicit, 4743 bool IsListInitialization) { 4744 unsigned NumParams = Proto->getNumParams(); 4745 bool Invalid = false; 4746 size_t ArgIx = 0; 4747 // Continue to check argument types (even if we have too few/many args). 4748 for (unsigned i = FirstParam; i < NumParams; i++) { 4749 QualType ProtoArgType = Proto->getParamType(i); 4750 4751 Expr *Arg; 4752 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4753 if (ArgIx < Args.size()) { 4754 Arg = Args[ArgIx++]; 4755 4756 if (RequireCompleteType(Arg->getLocStart(), 4757 ProtoArgType, 4758 diag::err_call_incomplete_argument, Arg)) 4759 return true; 4760 4761 // Strip the unbridged-cast placeholder expression off, if applicable. 4762 bool CFAudited = false; 4763 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4764 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4765 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4766 Arg = stripARCUnbridgedCast(Arg); 4767 else if (getLangOpts().ObjCAutoRefCount && 4768 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4769 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4770 CFAudited = true; 4771 4772 InitializedEntity Entity = 4773 Param ? InitializedEntity::InitializeParameter(Context, Param, 4774 ProtoArgType) 4775 : InitializedEntity::InitializeParameter( 4776 Context, ProtoArgType, Proto->isParamConsumed(i)); 4777 4778 // Remember that parameter belongs to a CF audited API. 4779 if (CFAudited) 4780 Entity.setParameterCFAudited(); 4781 4782 ExprResult ArgE = PerformCopyInitialization( 4783 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4784 if (ArgE.isInvalid()) 4785 return true; 4786 4787 Arg = ArgE.getAs<Expr>(); 4788 } else { 4789 assert(Param && "can't use default arguments without a known callee"); 4790 4791 ExprResult ArgExpr = 4792 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4793 if (ArgExpr.isInvalid()) 4794 return true; 4795 4796 Arg = ArgExpr.getAs<Expr>(); 4797 } 4798 4799 // Check for array bounds violations for each argument to the call. This 4800 // check only triggers warnings when the argument isn't a more complex Expr 4801 // with its own checking, such as a BinaryOperator. 4802 CheckArrayAccess(Arg); 4803 4804 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4805 CheckStaticArrayArgument(CallLoc, Param, Arg); 4806 4807 AllArgs.push_back(Arg); 4808 } 4809 4810 // If this is a variadic call, handle args passed through "...". 4811 if (CallType != VariadicDoesNotApply) { 4812 // Assume that extern "C" functions with variadic arguments that 4813 // return __unknown_anytype aren't *really* variadic. 4814 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4815 FDecl->isExternC()) { 4816 for (Expr *A : Args.slice(ArgIx)) { 4817 QualType paramType; // ignored 4818 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4819 Invalid |= arg.isInvalid(); 4820 AllArgs.push_back(arg.get()); 4821 } 4822 4823 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4824 } else { 4825 for (Expr *A : Args.slice(ArgIx)) { 4826 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4827 Invalid |= Arg.isInvalid(); 4828 AllArgs.push_back(Arg.get()); 4829 } 4830 } 4831 4832 // Check for array bounds violations. 4833 for (Expr *A : Args.slice(ArgIx)) 4834 CheckArrayAccess(A); 4835 } 4836 return Invalid; 4837 } 4838 4839 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4840 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4841 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4842 TL = DTL.getOriginalLoc(); 4843 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4844 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4845 << ATL.getLocalSourceRange(); 4846 } 4847 4848 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4849 /// array parameter, check that it is non-null, and that if it is formed by 4850 /// array-to-pointer decay, the underlying array is sufficiently large. 4851 /// 4852 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4853 /// array type derivation, then for each call to the function, the value of the 4854 /// corresponding actual argument shall provide access to the first element of 4855 /// an array with at least as many elements as specified by the size expression. 4856 void 4857 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4858 ParmVarDecl *Param, 4859 const Expr *ArgExpr) { 4860 // Static array parameters are not supported in C++. 4861 if (!Param || getLangOpts().CPlusPlus) 4862 return; 4863 4864 QualType OrigTy = Param->getOriginalType(); 4865 4866 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4867 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4868 return; 4869 4870 if (ArgExpr->isNullPointerConstant(Context, 4871 Expr::NPC_NeverValueDependent)) { 4872 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4873 DiagnoseCalleeStaticArrayParam(*this, Param); 4874 return; 4875 } 4876 4877 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4878 if (!CAT) 4879 return; 4880 4881 const ConstantArrayType *ArgCAT = 4882 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4883 if (!ArgCAT) 4884 return; 4885 4886 if (ArgCAT->getSize().ult(CAT->getSize())) { 4887 Diag(CallLoc, diag::warn_static_array_too_small) 4888 << ArgExpr->getSourceRange() 4889 << (unsigned) ArgCAT->getSize().getZExtValue() 4890 << (unsigned) CAT->getSize().getZExtValue(); 4891 DiagnoseCalleeStaticArrayParam(*this, Param); 4892 } 4893 } 4894 4895 /// Given a function expression of unknown-any type, try to rebuild it 4896 /// to have a function type. 4897 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4898 4899 /// Is the given type a placeholder that we need to lower out 4900 /// immediately during argument processing? 4901 static bool isPlaceholderToRemoveAsArg(QualType type) { 4902 // Placeholders are never sugared. 4903 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4904 if (!placeholder) return false; 4905 4906 switch (placeholder->getKind()) { 4907 // Ignore all the non-placeholder types. 4908 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4909 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4910 #include "clang/AST/BuiltinTypes.def" 4911 return false; 4912 4913 // We cannot lower out overload sets; they might validly be resolved 4914 // by the call machinery. 4915 case BuiltinType::Overload: 4916 return false; 4917 4918 // Unbridged casts in ARC can be handled in some call positions and 4919 // should be left in place. 4920 case BuiltinType::ARCUnbridgedCast: 4921 return false; 4922 4923 // Pseudo-objects should be converted as soon as possible. 4924 case BuiltinType::PseudoObject: 4925 return true; 4926 4927 // The debugger mode could theoretically but currently does not try 4928 // to resolve unknown-typed arguments based on known parameter types. 4929 case BuiltinType::UnknownAny: 4930 return true; 4931 4932 // These are always invalid as call arguments and should be reported. 4933 case BuiltinType::BoundMember: 4934 case BuiltinType::BuiltinFn: 4935 case BuiltinType::OMPArraySection: 4936 return true; 4937 4938 } 4939 llvm_unreachable("bad builtin type kind"); 4940 } 4941 4942 /// Check an argument list for placeholders that we won't try to 4943 /// handle later. 4944 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4945 // Apply this processing to all the arguments at once instead of 4946 // dying at the first failure. 4947 bool hasInvalid = false; 4948 for (size_t i = 0, e = args.size(); i != e; i++) { 4949 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4950 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4951 if (result.isInvalid()) hasInvalid = true; 4952 else args[i] = result.get(); 4953 } else if (hasInvalid) { 4954 (void)S.CorrectDelayedTyposInExpr(args[i]); 4955 } 4956 } 4957 return hasInvalid; 4958 } 4959 4960 /// If a builtin function has a pointer argument with no explicit address 4961 /// space, then it should be able to accept a pointer to any address 4962 /// space as input. In order to do this, we need to replace the 4963 /// standard builtin declaration with one that uses the same address space 4964 /// as the call. 4965 /// 4966 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4967 /// it does not contain any pointer arguments without 4968 /// an address space qualifer. Otherwise the rewritten 4969 /// FunctionDecl is returned. 4970 /// TODO: Handle pointer return types. 4971 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4972 const FunctionDecl *FDecl, 4973 MultiExprArg ArgExprs) { 4974 4975 QualType DeclType = FDecl->getType(); 4976 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4977 4978 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4979 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4980 return nullptr; 4981 4982 bool NeedsNewDecl = false; 4983 unsigned i = 0; 4984 SmallVector<QualType, 8> OverloadParams; 4985 4986 for (QualType ParamType : FT->param_types()) { 4987 4988 // Convert array arguments to pointer to simplify type lookup. 4989 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4990 QualType ArgType = Arg->getType(); 4991 if (!ParamType->isPointerType() || 4992 ParamType.getQualifiers().hasAddressSpace() || 4993 !ArgType->isPointerType() || 4994 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4995 OverloadParams.push_back(ParamType); 4996 continue; 4997 } 4998 4999 NeedsNewDecl = true; 5000 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5001 5002 QualType PointeeType = ParamType->getPointeeType(); 5003 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5004 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5005 } 5006 5007 if (!NeedsNewDecl) 5008 return nullptr; 5009 5010 FunctionProtoType::ExtProtoInfo EPI; 5011 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5012 OverloadParams, EPI); 5013 DeclContext *Parent = Context.getTranslationUnitDecl(); 5014 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5015 FDecl->getLocation(), 5016 FDecl->getLocation(), 5017 FDecl->getIdentifier(), 5018 OverloadTy, 5019 /*TInfo=*/nullptr, 5020 SC_Extern, false, 5021 /*hasPrototype=*/true); 5022 SmallVector<ParmVarDecl*, 16> Params; 5023 FT = cast<FunctionProtoType>(OverloadTy); 5024 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5025 QualType ParamType = FT->getParamType(i); 5026 ParmVarDecl *Parm = 5027 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5028 SourceLocation(), nullptr, ParamType, 5029 /*TInfo=*/nullptr, SC_None, nullptr); 5030 Parm->setScopeInfo(0, i); 5031 Params.push_back(Parm); 5032 } 5033 OverloadDecl->setParams(Params); 5034 return OverloadDecl; 5035 } 5036 5037 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5038 /// This provides the location of the left/right parens and a list of comma 5039 /// locations. 5040 ExprResult 5041 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5042 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5043 Expr *ExecConfig, bool IsExecConfig) { 5044 // Since this might be a postfix expression, get rid of ParenListExprs. 5045 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 5046 if (Result.isInvalid()) return ExprError(); 5047 Fn = Result.get(); 5048 5049 if (checkArgsForPlaceholders(*this, ArgExprs)) 5050 return ExprError(); 5051 5052 if (getLangOpts().CPlusPlus) { 5053 // If this is a pseudo-destructor expression, build the call immediately. 5054 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5055 if (!ArgExprs.empty()) { 5056 // Pseudo-destructor calls should not have any arguments. 5057 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5058 << FixItHint::CreateRemoval( 5059 SourceRange(ArgExprs.front()->getLocStart(), 5060 ArgExprs.back()->getLocEnd())); 5061 } 5062 5063 return new (Context) 5064 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5065 } 5066 if (Fn->getType() == Context.PseudoObjectTy) { 5067 ExprResult result = CheckPlaceholderExpr(Fn); 5068 if (result.isInvalid()) return ExprError(); 5069 Fn = result.get(); 5070 } 5071 5072 // Determine whether this is a dependent call inside a C++ template, 5073 // in which case we won't do any semantic analysis now. 5074 // FIXME: Will need to cache the results of name lookup (including ADL) in 5075 // Fn. 5076 bool Dependent = false; 5077 if (Fn->isTypeDependent()) 5078 Dependent = true; 5079 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5080 Dependent = true; 5081 5082 if (Dependent) { 5083 if (ExecConfig) { 5084 return new (Context) CUDAKernelCallExpr( 5085 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5086 Context.DependentTy, VK_RValue, RParenLoc); 5087 } else { 5088 return new (Context) CallExpr( 5089 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5090 } 5091 } 5092 5093 // Determine whether this is a call to an object (C++ [over.call.object]). 5094 if (Fn->getType()->isRecordType()) 5095 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 5096 RParenLoc); 5097 5098 if (Fn->getType() == Context.UnknownAnyTy) { 5099 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5100 if (result.isInvalid()) return ExprError(); 5101 Fn = result.get(); 5102 } 5103 5104 if (Fn->getType() == Context.BoundMemberTy) { 5105 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5106 } 5107 } 5108 5109 // Check for overloaded calls. This can happen even in C due to extensions. 5110 if (Fn->getType() == Context.OverloadTy) { 5111 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5112 5113 // We aren't supposed to apply this logic for if there's an '&' involved. 5114 if (!find.HasFormOfMemberPointer) { 5115 OverloadExpr *ovl = find.Expression; 5116 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5117 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 5118 RParenLoc, ExecConfig, 5119 /*AllowTypoCorrection=*/true, 5120 find.IsAddressOfOperand); 5121 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5122 } 5123 } 5124 5125 // If we're directly calling a function, get the appropriate declaration. 5126 if (Fn->getType() == Context.UnknownAnyTy) { 5127 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5128 if (result.isInvalid()) return ExprError(); 5129 Fn = result.get(); 5130 } 5131 5132 Expr *NakedFn = Fn->IgnoreParens(); 5133 5134 bool CallingNDeclIndirectly = false; 5135 NamedDecl *NDecl = nullptr; 5136 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5137 if (UnOp->getOpcode() == UO_AddrOf) { 5138 CallingNDeclIndirectly = true; 5139 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5140 } 5141 } 5142 5143 if (isa<DeclRefExpr>(NakedFn)) { 5144 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5145 5146 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5147 if (FDecl && FDecl->getBuiltinID()) { 5148 // Rewrite the function decl for this builtin by replacing parameters 5149 // with no explicit address space with the address space of the arguments 5150 // in ArgExprs. 5151 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5152 NDecl = FDecl; 5153 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 5154 SourceLocation(), FDecl, false, 5155 SourceLocation(), FDecl->getType(), 5156 Fn->getValueKind(), FDecl); 5157 } 5158 } 5159 } else if (isa<MemberExpr>(NakedFn)) 5160 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5161 5162 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5163 if (CallingNDeclIndirectly && 5164 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5165 Fn->getLocStart())) 5166 return ExprError(); 5167 5168 if (FD->hasAttr<EnableIfAttr>()) { 5169 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5170 Diag(Fn->getLocStart(), 5171 isa<CXXMethodDecl>(FD) ? 5172 diag::err_ovl_no_viable_member_function_in_call : 5173 diag::err_ovl_no_viable_function_in_call) 5174 << FD << FD->getSourceRange(); 5175 Diag(FD->getLocation(), 5176 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5177 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5178 } 5179 } 5180 } 5181 5182 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5183 ExecConfig, IsExecConfig); 5184 } 5185 5186 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5187 /// 5188 /// __builtin_astype( value, dst type ) 5189 /// 5190 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5191 SourceLocation BuiltinLoc, 5192 SourceLocation RParenLoc) { 5193 ExprValueKind VK = VK_RValue; 5194 ExprObjectKind OK = OK_Ordinary; 5195 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5196 QualType SrcTy = E->getType(); 5197 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5198 return ExprError(Diag(BuiltinLoc, 5199 diag::err_invalid_astype_of_different_size) 5200 << DstTy 5201 << SrcTy 5202 << E->getSourceRange()); 5203 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5204 } 5205 5206 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5207 /// provided arguments. 5208 /// 5209 /// __builtin_convertvector( value, dst type ) 5210 /// 5211 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5212 SourceLocation BuiltinLoc, 5213 SourceLocation RParenLoc) { 5214 TypeSourceInfo *TInfo; 5215 GetTypeFromParser(ParsedDestTy, &TInfo); 5216 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5217 } 5218 5219 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5220 /// i.e. an expression not of \p OverloadTy. The expression should 5221 /// unary-convert to an expression of function-pointer or 5222 /// block-pointer type. 5223 /// 5224 /// \param NDecl the declaration being called, if available 5225 ExprResult 5226 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5227 SourceLocation LParenLoc, 5228 ArrayRef<Expr *> Args, 5229 SourceLocation RParenLoc, 5230 Expr *Config, bool IsExecConfig) { 5231 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5232 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5233 5234 // Functions with 'interrupt' attribute cannot be called directly. 5235 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5236 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5237 return ExprError(); 5238 } 5239 5240 // Promote the function operand. 5241 // We special-case function promotion here because we only allow promoting 5242 // builtin functions to function pointers in the callee of a call. 5243 ExprResult Result; 5244 if (BuiltinID && 5245 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5246 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5247 CK_BuiltinFnToFnPtr).get(); 5248 } else { 5249 Result = CallExprUnaryConversions(Fn); 5250 } 5251 if (Result.isInvalid()) 5252 return ExprError(); 5253 Fn = Result.get(); 5254 5255 // Make the call expr early, before semantic checks. This guarantees cleanup 5256 // of arguments and function on error. 5257 CallExpr *TheCall; 5258 if (Config) 5259 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5260 cast<CallExpr>(Config), Args, 5261 Context.BoolTy, VK_RValue, 5262 RParenLoc); 5263 else 5264 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5265 VK_RValue, RParenLoc); 5266 5267 if (!getLangOpts().CPlusPlus) { 5268 // C cannot always handle TypoExpr nodes in builtin calls and direct 5269 // function calls as their argument checking don't necessarily handle 5270 // dependent types properly, so make sure any TypoExprs have been 5271 // dealt with. 5272 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5273 if (!Result.isUsable()) return ExprError(); 5274 TheCall = dyn_cast<CallExpr>(Result.get()); 5275 if (!TheCall) return Result; 5276 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5277 } 5278 5279 // Bail out early if calling a builtin with custom typechecking. 5280 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5281 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5282 5283 retry: 5284 const FunctionType *FuncT; 5285 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5286 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5287 // have type pointer to function". 5288 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5289 if (!FuncT) 5290 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5291 << Fn->getType() << Fn->getSourceRange()); 5292 } else if (const BlockPointerType *BPT = 5293 Fn->getType()->getAs<BlockPointerType>()) { 5294 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5295 } else { 5296 // Handle calls to expressions of unknown-any type. 5297 if (Fn->getType() == Context.UnknownAnyTy) { 5298 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5299 if (rewrite.isInvalid()) return ExprError(); 5300 Fn = rewrite.get(); 5301 TheCall->setCallee(Fn); 5302 goto retry; 5303 } 5304 5305 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5306 << Fn->getType() << Fn->getSourceRange()); 5307 } 5308 5309 if (getLangOpts().CUDA) { 5310 if (Config) { 5311 // CUDA: Kernel calls must be to global functions 5312 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5313 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5314 << FDecl->getName() << Fn->getSourceRange()); 5315 5316 // CUDA: Kernel function must have 'void' return type 5317 if (!FuncT->getReturnType()->isVoidType()) 5318 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5319 << Fn->getType() << Fn->getSourceRange()); 5320 } else { 5321 // CUDA: Calls to global functions must be configured 5322 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5323 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5324 << FDecl->getName() << Fn->getSourceRange()); 5325 } 5326 } 5327 5328 // Check for a valid return type 5329 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5330 FDecl)) 5331 return ExprError(); 5332 5333 // We know the result type of the call, set it. 5334 TheCall->setType(FuncT->getCallResultType(Context)); 5335 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5336 5337 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5338 if (Proto) { 5339 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5340 IsExecConfig)) 5341 return ExprError(); 5342 } else { 5343 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5344 5345 if (FDecl) { 5346 // Check if we have too few/too many template arguments, based 5347 // on our knowledge of the function definition. 5348 const FunctionDecl *Def = nullptr; 5349 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5350 Proto = Def->getType()->getAs<FunctionProtoType>(); 5351 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5352 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5353 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5354 } 5355 5356 // If the function we're calling isn't a function prototype, but we have 5357 // a function prototype from a prior declaratiom, use that prototype. 5358 if (!FDecl->hasPrototype()) 5359 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5360 } 5361 5362 // Promote the arguments (C99 6.5.2.2p6). 5363 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5364 Expr *Arg = Args[i]; 5365 5366 if (Proto && i < Proto->getNumParams()) { 5367 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5368 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5369 ExprResult ArgE = 5370 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5371 if (ArgE.isInvalid()) 5372 return true; 5373 5374 Arg = ArgE.getAs<Expr>(); 5375 5376 } else { 5377 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5378 5379 if (ArgE.isInvalid()) 5380 return true; 5381 5382 Arg = ArgE.getAs<Expr>(); 5383 } 5384 5385 if (RequireCompleteType(Arg->getLocStart(), 5386 Arg->getType(), 5387 diag::err_call_incomplete_argument, Arg)) 5388 return ExprError(); 5389 5390 TheCall->setArg(i, Arg); 5391 } 5392 } 5393 5394 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5395 if (!Method->isStatic()) 5396 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5397 << Fn->getSourceRange()); 5398 5399 // Check for sentinels 5400 if (NDecl) 5401 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5402 5403 // Do special checking on direct calls to functions. 5404 if (FDecl) { 5405 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5406 return ExprError(); 5407 5408 if (BuiltinID) 5409 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5410 } else if (NDecl) { 5411 if (CheckPointerCall(NDecl, TheCall, Proto)) 5412 return ExprError(); 5413 } else { 5414 if (CheckOtherCall(TheCall, Proto)) 5415 return ExprError(); 5416 } 5417 5418 return MaybeBindToTemporary(TheCall); 5419 } 5420 5421 ExprResult 5422 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5423 SourceLocation RParenLoc, Expr *InitExpr) { 5424 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5425 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5426 5427 TypeSourceInfo *TInfo; 5428 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5429 if (!TInfo) 5430 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5431 5432 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5433 } 5434 5435 ExprResult 5436 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5437 SourceLocation RParenLoc, Expr *LiteralExpr) { 5438 QualType literalType = TInfo->getType(); 5439 5440 if (literalType->isArrayType()) { 5441 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5442 diag::err_illegal_decl_array_incomplete_type, 5443 SourceRange(LParenLoc, 5444 LiteralExpr->getSourceRange().getEnd()))) 5445 return ExprError(); 5446 if (literalType->isVariableArrayType()) 5447 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5448 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5449 } else if (!literalType->isDependentType() && 5450 RequireCompleteType(LParenLoc, literalType, 5451 diag::err_typecheck_decl_incomplete_type, 5452 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5453 return ExprError(); 5454 5455 InitializedEntity Entity 5456 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5457 InitializationKind Kind 5458 = InitializationKind::CreateCStyleCast(LParenLoc, 5459 SourceRange(LParenLoc, RParenLoc), 5460 /*InitList=*/true); 5461 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5462 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5463 &literalType); 5464 if (Result.isInvalid()) 5465 return ExprError(); 5466 LiteralExpr = Result.get(); 5467 5468 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5469 if (isFileScope && 5470 !LiteralExpr->isTypeDependent() && 5471 !LiteralExpr->isValueDependent() && 5472 !literalType->isDependentType()) { // 6.5.2.5p3 5473 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5474 return ExprError(); 5475 } 5476 5477 // In C, compound literals are l-values for some reason. 5478 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5479 5480 return MaybeBindToTemporary( 5481 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5482 VK, LiteralExpr, isFileScope)); 5483 } 5484 5485 ExprResult 5486 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5487 SourceLocation RBraceLoc) { 5488 // Immediately handle non-overload placeholders. Overloads can be 5489 // resolved contextually, but everything else here can't. 5490 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5491 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5492 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5493 5494 // Ignore failures; dropping the entire initializer list because 5495 // of one failure would be terrible for indexing/etc. 5496 if (result.isInvalid()) continue; 5497 5498 InitArgList[I] = result.get(); 5499 } 5500 } 5501 5502 // Semantic analysis for initializers is done by ActOnDeclarator() and 5503 // CheckInitializer() - it requires knowledge of the object being intialized. 5504 5505 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5506 RBraceLoc); 5507 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5508 return E; 5509 } 5510 5511 /// Do an explicit extend of the given block pointer if we're in ARC. 5512 void Sema::maybeExtendBlockObject(ExprResult &E) { 5513 assert(E.get()->getType()->isBlockPointerType()); 5514 assert(E.get()->isRValue()); 5515 5516 // Only do this in an r-value context. 5517 if (!getLangOpts().ObjCAutoRefCount) return; 5518 5519 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5520 CK_ARCExtendBlockObject, E.get(), 5521 /*base path*/ nullptr, VK_RValue); 5522 ExprNeedsCleanups = true; 5523 } 5524 5525 /// Prepare a conversion of the given expression to an ObjC object 5526 /// pointer type. 5527 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5528 QualType type = E.get()->getType(); 5529 if (type->isObjCObjectPointerType()) { 5530 return CK_BitCast; 5531 } else if (type->isBlockPointerType()) { 5532 maybeExtendBlockObject(E); 5533 return CK_BlockPointerToObjCPointerCast; 5534 } else { 5535 assert(type->isPointerType()); 5536 return CK_CPointerToObjCPointerCast; 5537 } 5538 } 5539 5540 /// Prepares for a scalar cast, performing all the necessary stages 5541 /// except the final cast and returning the kind required. 5542 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5543 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5544 // Also, callers should have filtered out the invalid cases with 5545 // pointers. Everything else should be possible. 5546 5547 QualType SrcTy = Src.get()->getType(); 5548 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5549 return CK_NoOp; 5550 5551 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5552 case Type::STK_MemberPointer: 5553 llvm_unreachable("member pointer type in C"); 5554 5555 case Type::STK_CPointer: 5556 case Type::STK_BlockPointer: 5557 case Type::STK_ObjCObjectPointer: 5558 switch (DestTy->getScalarTypeKind()) { 5559 case Type::STK_CPointer: { 5560 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5561 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5562 if (SrcAS != DestAS) 5563 return CK_AddressSpaceConversion; 5564 return CK_BitCast; 5565 } 5566 case Type::STK_BlockPointer: 5567 return (SrcKind == Type::STK_BlockPointer 5568 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5569 case Type::STK_ObjCObjectPointer: 5570 if (SrcKind == Type::STK_ObjCObjectPointer) 5571 return CK_BitCast; 5572 if (SrcKind == Type::STK_CPointer) 5573 return CK_CPointerToObjCPointerCast; 5574 maybeExtendBlockObject(Src); 5575 return CK_BlockPointerToObjCPointerCast; 5576 case Type::STK_Bool: 5577 return CK_PointerToBoolean; 5578 case Type::STK_Integral: 5579 return CK_PointerToIntegral; 5580 case Type::STK_Floating: 5581 case Type::STK_FloatingComplex: 5582 case Type::STK_IntegralComplex: 5583 case Type::STK_MemberPointer: 5584 llvm_unreachable("illegal cast from pointer"); 5585 } 5586 llvm_unreachable("Should have returned before this"); 5587 5588 case Type::STK_Bool: // casting from bool is like casting from an integer 5589 case Type::STK_Integral: 5590 switch (DestTy->getScalarTypeKind()) { 5591 case Type::STK_CPointer: 5592 case Type::STK_ObjCObjectPointer: 5593 case Type::STK_BlockPointer: 5594 if (Src.get()->isNullPointerConstant(Context, 5595 Expr::NPC_ValueDependentIsNull)) 5596 return CK_NullToPointer; 5597 return CK_IntegralToPointer; 5598 case Type::STK_Bool: 5599 return CK_IntegralToBoolean; 5600 case Type::STK_Integral: 5601 return CK_IntegralCast; 5602 case Type::STK_Floating: 5603 return CK_IntegralToFloating; 5604 case Type::STK_IntegralComplex: 5605 Src = ImpCastExprToType(Src.get(), 5606 DestTy->castAs<ComplexType>()->getElementType(), 5607 CK_IntegralCast); 5608 return CK_IntegralRealToComplex; 5609 case Type::STK_FloatingComplex: 5610 Src = ImpCastExprToType(Src.get(), 5611 DestTy->castAs<ComplexType>()->getElementType(), 5612 CK_IntegralToFloating); 5613 return CK_FloatingRealToComplex; 5614 case Type::STK_MemberPointer: 5615 llvm_unreachable("member pointer type in C"); 5616 } 5617 llvm_unreachable("Should have returned before this"); 5618 5619 case Type::STK_Floating: 5620 switch (DestTy->getScalarTypeKind()) { 5621 case Type::STK_Floating: 5622 return CK_FloatingCast; 5623 case Type::STK_Bool: 5624 return CK_FloatingToBoolean; 5625 case Type::STK_Integral: 5626 return CK_FloatingToIntegral; 5627 case Type::STK_FloatingComplex: 5628 Src = ImpCastExprToType(Src.get(), 5629 DestTy->castAs<ComplexType>()->getElementType(), 5630 CK_FloatingCast); 5631 return CK_FloatingRealToComplex; 5632 case Type::STK_IntegralComplex: 5633 Src = ImpCastExprToType(Src.get(), 5634 DestTy->castAs<ComplexType>()->getElementType(), 5635 CK_FloatingToIntegral); 5636 return CK_IntegralRealToComplex; 5637 case Type::STK_CPointer: 5638 case Type::STK_ObjCObjectPointer: 5639 case Type::STK_BlockPointer: 5640 llvm_unreachable("valid float->pointer cast?"); 5641 case Type::STK_MemberPointer: 5642 llvm_unreachable("member pointer type in C"); 5643 } 5644 llvm_unreachable("Should have returned before this"); 5645 5646 case Type::STK_FloatingComplex: 5647 switch (DestTy->getScalarTypeKind()) { 5648 case Type::STK_FloatingComplex: 5649 return CK_FloatingComplexCast; 5650 case Type::STK_IntegralComplex: 5651 return CK_FloatingComplexToIntegralComplex; 5652 case Type::STK_Floating: { 5653 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5654 if (Context.hasSameType(ET, DestTy)) 5655 return CK_FloatingComplexToReal; 5656 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5657 return CK_FloatingCast; 5658 } 5659 case Type::STK_Bool: 5660 return CK_FloatingComplexToBoolean; 5661 case Type::STK_Integral: 5662 Src = ImpCastExprToType(Src.get(), 5663 SrcTy->castAs<ComplexType>()->getElementType(), 5664 CK_FloatingComplexToReal); 5665 return CK_FloatingToIntegral; 5666 case Type::STK_CPointer: 5667 case Type::STK_ObjCObjectPointer: 5668 case Type::STK_BlockPointer: 5669 llvm_unreachable("valid complex float->pointer cast?"); 5670 case Type::STK_MemberPointer: 5671 llvm_unreachable("member pointer type in C"); 5672 } 5673 llvm_unreachable("Should have returned before this"); 5674 5675 case Type::STK_IntegralComplex: 5676 switch (DestTy->getScalarTypeKind()) { 5677 case Type::STK_FloatingComplex: 5678 return CK_IntegralComplexToFloatingComplex; 5679 case Type::STK_IntegralComplex: 5680 return CK_IntegralComplexCast; 5681 case Type::STK_Integral: { 5682 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5683 if (Context.hasSameType(ET, DestTy)) 5684 return CK_IntegralComplexToReal; 5685 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5686 return CK_IntegralCast; 5687 } 5688 case Type::STK_Bool: 5689 return CK_IntegralComplexToBoolean; 5690 case Type::STK_Floating: 5691 Src = ImpCastExprToType(Src.get(), 5692 SrcTy->castAs<ComplexType>()->getElementType(), 5693 CK_IntegralComplexToReal); 5694 return CK_IntegralToFloating; 5695 case Type::STK_CPointer: 5696 case Type::STK_ObjCObjectPointer: 5697 case Type::STK_BlockPointer: 5698 llvm_unreachable("valid complex int->pointer cast?"); 5699 case Type::STK_MemberPointer: 5700 llvm_unreachable("member pointer type in C"); 5701 } 5702 llvm_unreachable("Should have returned before this"); 5703 } 5704 5705 llvm_unreachable("Unhandled scalar cast"); 5706 } 5707 5708 static bool breakDownVectorType(QualType type, uint64_t &len, 5709 QualType &eltType) { 5710 // Vectors are simple. 5711 if (const VectorType *vecType = type->getAs<VectorType>()) { 5712 len = vecType->getNumElements(); 5713 eltType = vecType->getElementType(); 5714 assert(eltType->isScalarType()); 5715 return true; 5716 } 5717 5718 // We allow lax conversion to and from non-vector types, but only if 5719 // they're real types (i.e. non-complex, non-pointer scalar types). 5720 if (!type->isRealType()) return false; 5721 5722 len = 1; 5723 eltType = type; 5724 return true; 5725 } 5726 5727 /// Are the two types lax-compatible vector types? That is, given 5728 /// that one of them is a vector, do they have equal storage sizes, 5729 /// where the storage size is the number of elements times the element 5730 /// size? 5731 /// 5732 /// This will also return false if either of the types is neither a 5733 /// vector nor a real type. 5734 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5735 assert(destTy->isVectorType() || srcTy->isVectorType()); 5736 5737 // Disallow lax conversions between scalars and ExtVectors (these 5738 // conversions are allowed for other vector types because common headers 5739 // depend on them). Most scalar OP ExtVector cases are handled by the 5740 // splat path anyway, which does what we want (convert, not bitcast). 5741 // What this rules out for ExtVectors is crazy things like char4*float. 5742 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5743 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5744 5745 uint64_t srcLen, destLen; 5746 QualType srcEltTy, destEltTy; 5747 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5748 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5749 5750 // ASTContext::getTypeSize will return the size rounded up to a 5751 // power of 2, so instead of using that, we need to use the raw 5752 // element size multiplied by the element count. 5753 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5754 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5755 5756 return (srcLen * srcEltSize == destLen * destEltSize); 5757 } 5758 5759 /// Is this a legal conversion between two types, one of which is 5760 /// known to be a vector type? 5761 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5762 assert(destTy->isVectorType() || srcTy->isVectorType()); 5763 5764 if (!Context.getLangOpts().LaxVectorConversions) 5765 return false; 5766 return areLaxCompatibleVectorTypes(srcTy, destTy); 5767 } 5768 5769 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5770 CastKind &Kind) { 5771 assert(VectorTy->isVectorType() && "Not a vector type!"); 5772 5773 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5774 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5775 return Diag(R.getBegin(), 5776 Ty->isVectorType() ? 5777 diag::err_invalid_conversion_between_vectors : 5778 diag::err_invalid_conversion_between_vector_and_integer) 5779 << VectorTy << Ty << R; 5780 } else 5781 return Diag(R.getBegin(), 5782 diag::err_invalid_conversion_between_vector_and_scalar) 5783 << VectorTy << Ty << R; 5784 5785 Kind = CK_BitCast; 5786 return false; 5787 } 5788 5789 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5790 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5791 5792 if (DestElemTy == SplattedExpr->getType()) 5793 return SplattedExpr; 5794 5795 assert(DestElemTy->isFloatingType() || 5796 DestElemTy->isIntegralOrEnumerationType()); 5797 5798 CastKind CK; 5799 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5800 // OpenCL requires that we convert `true` boolean expressions to -1, but 5801 // only when splatting vectors. 5802 if (DestElemTy->isFloatingType()) { 5803 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5804 // in two steps: boolean to signed integral, then to floating. 5805 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5806 CK_BooleanToSignedIntegral); 5807 SplattedExpr = CastExprRes.get(); 5808 CK = CK_IntegralToFloating; 5809 } else { 5810 CK = CK_BooleanToSignedIntegral; 5811 } 5812 } else { 5813 ExprResult CastExprRes = SplattedExpr; 5814 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5815 if (CastExprRes.isInvalid()) 5816 return ExprError(); 5817 SplattedExpr = CastExprRes.get(); 5818 } 5819 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5820 } 5821 5822 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5823 Expr *CastExpr, CastKind &Kind) { 5824 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5825 5826 QualType SrcTy = CastExpr->getType(); 5827 5828 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5829 // an ExtVectorType. 5830 // In OpenCL, casts between vectors of different types are not allowed. 5831 // (See OpenCL 6.2). 5832 if (SrcTy->isVectorType()) { 5833 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5834 || (getLangOpts().OpenCL && 5835 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5836 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5837 << DestTy << SrcTy << R; 5838 return ExprError(); 5839 } 5840 Kind = CK_BitCast; 5841 return CastExpr; 5842 } 5843 5844 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5845 // conversion will take place first from scalar to elt type, and then 5846 // splat from elt type to vector. 5847 if (SrcTy->isPointerType()) 5848 return Diag(R.getBegin(), 5849 diag::err_invalid_conversion_between_vector_and_scalar) 5850 << DestTy << SrcTy << R; 5851 5852 Kind = CK_VectorSplat; 5853 return prepareVectorSplat(DestTy, CastExpr); 5854 } 5855 5856 ExprResult 5857 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5858 Declarator &D, ParsedType &Ty, 5859 SourceLocation RParenLoc, Expr *CastExpr) { 5860 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5861 "ActOnCastExpr(): missing type or expr"); 5862 5863 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5864 if (D.isInvalidType()) 5865 return ExprError(); 5866 5867 if (getLangOpts().CPlusPlus) { 5868 // Check that there are no default arguments (C++ only). 5869 CheckExtraCXXDefaultArguments(D); 5870 } else { 5871 // Make sure any TypoExprs have been dealt with. 5872 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5873 if (!Res.isUsable()) 5874 return ExprError(); 5875 CastExpr = Res.get(); 5876 } 5877 5878 checkUnusedDeclAttributes(D); 5879 5880 QualType castType = castTInfo->getType(); 5881 Ty = CreateParsedType(castType, castTInfo); 5882 5883 bool isVectorLiteral = false; 5884 5885 // Check for an altivec or OpenCL literal, 5886 // i.e. all the elements are integer constants. 5887 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5888 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5889 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5890 && castType->isVectorType() && (PE || PLE)) { 5891 if (PLE && PLE->getNumExprs() == 0) { 5892 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5893 return ExprError(); 5894 } 5895 if (PE || PLE->getNumExprs() == 1) { 5896 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5897 if (!E->getType()->isVectorType()) 5898 isVectorLiteral = true; 5899 } 5900 else 5901 isVectorLiteral = true; 5902 } 5903 5904 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5905 // then handle it as such. 5906 if (isVectorLiteral) 5907 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5908 5909 // If the Expr being casted is a ParenListExpr, handle it specially. 5910 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5911 // sequence of BinOp comma operators. 5912 if (isa<ParenListExpr>(CastExpr)) { 5913 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5914 if (Result.isInvalid()) return ExprError(); 5915 CastExpr = Result.get(); 5916 } 5917 5918 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5919 !getSourceManager().isInSystemMacro(LParenLoc)) 5920 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5921 5922 CheckTollFreeBridgeCast(castType, CastExpr); 5923 5924 CheckObjCBridgeRelatedCast(castType, CastExpr); 5925 5926 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5927 } 5928 5929 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5930 SourceLocation RParenLoc, Expr *E, 5931 TypeSourceInfo *TInfo) { 5932 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5933 "Expected paren or paren list expression"); 5934 5935 Expr **exprs; 5936 unsigned numExprs; 5937 Expr *subExpr; 5938 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5939 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5940 LiteralLParenLoc = PE->getLParenLoc(); 5941 LiteralRParenLoc = PE->getRParenLoc(); 5942 exprs = PE->getExprs(); 5943 numExprs = PE->getNumExprs(); 5944 } else { // isa<ParenExpr> by assertion at function entrance 5945 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5946 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5947 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5948 exprs = &subExpr; 5949 numExprs = 1; 5950 } 5951 5952 QualType Ty = TInfo->getType(); 5953 assert(Ty->isVectorType() && "Expected vector type"); 5954 5955 SmallVector<Expr *, 8> initExprs; 5956 const VectorType *VTy = Ty->getAs<VectorType>(); 5957 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5958 5959 // '(...)' form of vector initialization in AltiVec: the number of 5960 // initializers must be one or must match the size of the vector. 5961 // If a single value is specified in the initializer then it will be 5962 // replicated to all the components of the vector 5963 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5964 // The number of initializers must be one or must match the size of the 5965 // vector. If a single value is specified in the initializer then it will 5966 // be replicated to all the components of the vector 5967 if (numExprs == 1) { 5968 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5969 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5970 if (Literal.isInvalid()) 5971 return ExprError(); 5972 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5973 PrepareScalarCast(Literal, ElemTy)); 5974 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5975 } 5976 else if (numExprs < numElems) { 5977 Diag(E->getExprLoc(), 5978 diag::err_incorrect_number_of_vector_initializers); 5979 return ExprError(); 5980 } 5981 else 5982 initExprs.append(exprs, exprs + numExprs); 5983 } 5984 else { 5985 // For OpenCL, when the number of initializers is a single value, 5986 // it will be replicated to all components of the vector. 5987 if (getLangOpts().OpenCL && 5988 VTy->getVectorKind() == VectorType::GenericVector && 5989 numExprs == 1) { 5990 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5991 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5992 if (Literal.isInvalid()) 5993 return ExprError(); 5994 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5995 PrepareScalarCast(Literal, ElemTy)); 5996 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5997 } 5998 5999 initExprs.append(exprs, exprs + numExprs); 6000 } 6001 // FIXME: This means that pretty-printing the final AST will produce curly 6002 // braces instead of the original commas. 6003 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6004 initExprs, LiteralRParenLoc); 6005 initE->setType(Ty); 6006 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6007 } 6008 6009 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6010 /// the ParenListExpr into a sequence of comma binary operators. 6011 ExprResult 6012 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6013 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6014 if (!E) 6015 return OrigExpr; 6016 6017 ExprResult Result(E->getExpr(0)); 6018 6019 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6020 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6021 E->getExpr(i)); 6022 6023 if (Result.isInvalid()) return ExprError(); 6024 6025 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6026 } 6027 6028 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6029 SourceLocation R, 6030 MultiExprArg Val) { 6031 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6032 return expr; 6033 } 6034 6035 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6036 /// constant and the other is not a pointer. Returns true if a diagnostic is 6037 /// emitted. 6038 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6039 SourceLocation QuestionLoc) { 6040 Expr *NullExpr = LHSExpr; 6041 Expr *NonPointerExpr = RHSExpr; 6042 Expr::NullPointerConstantKind NullKind = 6043 NullExpr->isNullPointerConstant(Context, 6044 Expr::NPC_ValueDependentIsNotNull); 6045 6046 if (NullKind == Expr::NPCK_NotNull) { 6047 NullExpr = RHSExpr; 6048 NonPointerExpr = LHSExpr; 6049 NullKind = 6050 NullExpr->isNullPointerConstant(Context, 6051 Expr::NPC_ValueDependentIsNotNull); 6052 } 6053 6054 if (NullKind == Expr::NPCK_NotNull) 6055 return false; 6056 6057 if (NullKind == Expr::NPCK_ZeroExpression) 6058 return false; 6059 6060 if (NullKind == Expr::NPCK_ZeroLiteral) { 6061 // In this case, check to make sure that we got here from a "NULL" 6062 // string in the source code. 6063 NullExpr = NullExpr->IgnoreParenImpCasts(); 6064 SourceLocation loc = NullExpr->getExprLoc(); 6065 if (!findMacroSpelling(loc, "NULL")) 6066 return false; 6067 } 6068 6069 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6070 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6071 << NonPointerExpr->getType() << DiagType 6072 << NonPointerExpr->getSourceRange(); 6073 return true; 6074 } 6075 6076 /// \brief Return false if the condition expression is valid, true otherwise. 6077 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6078 QualType CondTy = Cond->getType(); 6079 6080 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6081 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6082 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6083 << CondTy << Cond->getSourceRange(); 6084 return true; 6085 } 6086 6087 // C99 6.5.15p2 6088 if (CondTy->isScalarType()) return false; 6089 6090 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6091 << CondTy << Cond->getSourceRange(); 6092 return true; 6093 } 6094 6095 /// \brief Handle when one or both operands are void type. 6096 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6097 ExprResult &RHS) { 6098 Expr *LHSExpr = LHS.get(); 6099 Expr *RHSExpr = RHS.get(); 6100 6101 if (!LHSExpr->getType()->isVoidType()) 6102 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6103 << RHSExpr->getSourceRange(); 6104 if (!RHSExpr->getType()->isVoidType()) 6105 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6106 << LHSExpr->getSourceRange(); 6107 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6108 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6109 return S.Context.VoidTy; 6110 } 6111 6112 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6113 /// true otherwise. 6114 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6115 QualType PointerTy) { 6116 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6117 !NullExpr.get()->isNullPointerConstant(S.Context, 6118 Expr::NPC_ValueDependentIsNull)) 6119 return true; 6120 6121 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6122 return false; 6123 } 6124 6125 /// \brief Checks compatibility between two pointers and return the resulting 6126 /// type. 6127 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6128 ExprResult &RHS, 6129 SourceLocation Loc) { 6130 QualType LHSTy = LHS.get()->getType(); 6131 QualType RHSTy = RHS.get()->getType(); 6132 6133 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6134 // Two identical pointers types are always compatible. 6135 return LHSTy; 6136 } 6137 6138 QualType lhptee, rhptee; 6139 6140 // Get the pointee types. 6141 bool IsBlockPointer = false; 6142 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6143 lhptee = LHSBTy->getPointeeType(); 6144 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6145 IsBlockPointer = true; 6146 } else { 6147 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6148 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6149 } 6150 6151 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6152 // differently qualified versions of compatible types, the result type is 6153 // a pointer to an appropriately qualified version of the composite 6154 // type. 6155 6156 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6157 // clause doesn't make sense for our extensions. E.g. address space 2 should 6158 // be incompatible with address space 3: they may live on different devices or 6159 // anything. 6160 Qualifiers lhQual = lhptee.getQualifiers(); 6161 Qualifiers rhQual = rhptee.getQualifiers(); 6162 6163 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6164 lhQual.removeCVRQualifiers(); 6165 rhQual.removeCVRQualifiers(); 6166 6167 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6168 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6169 6170 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6171 6172 if (CompositeTy.isNull()) { 6173 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6174 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6175 << RHS.get()->getSourceRange(); 6176 // In this situation, we assume void* type. No especially good 6177 // reason, but this is what gcc does, and we do have to pick 6178 // to get a consistent AST. 6179 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6180 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6181 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6182 return incompatTy; 6183 } 6184 6185 // The pointer types are compatible. 6186 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6187 if (IsBlockPointer) 6188 ResultTy = S.Context.getBlockPointerType(ResultTy); 6189 else 6190 ResultTy = S.Context.getPointerType(ResultTy); 6191 6192 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 6193 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 6194 return ResultTy; 6195 } 6196 6197 /// \brief Return the resulting type when the operands are both block pointers. 6198 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6199 ExprResult &LHS, 6200 ExprResult &RHS, 6201 SourceLocation Loc) { 6202 QualType LHSTy = LHS.get()->getType(); 6203 QualType RHSTy = RHS.get()->getType(); 6204 6205 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6206 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6207 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6208 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6209 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6210 return destType; 6211 } 6212 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6213 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6214 << RHS.get()->getSourceRange(); 6215 return QualType(); 6216 } 6217 6218 // We have 2 block pointer types. 6219 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6220 } 6221 6222 /// \brief Return the resulting type when the operands are both pointers. 6223 static QualType 6224 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6225 ExprResult &RHS, 6226 SourceLocation Loc) { 6227 // get the pointer types 6228 QualType LHSTy = LHS.get()->getType(); 6229 QualType RHSTy = RHS.get()->getType(); 6230 6231 // get the "pointed to" types 6232 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6233 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6234 6235 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6236 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6237 // Figure out necessary qualifiers (C99 6.5.15p6) 6238 QualType destPointee 6239 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6240 QualType destType = S.Context.getPointerType(destPointee); 6241 // Add qualifiers if necessary. 6242 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6243 // Promote to void*. 6244 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6245 return destType; 6246 } 6247 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6248 QualType destPointee 6249 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6250 QualType destType = S.Context.getPointerType(destPointee); 6251 // Add qualifiers if necessary. 6252 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6253 // Promote to void*. 6254 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6255 return destType; 6256 } 6257 6258 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6259 } 6260 6261 /// \brief Return false if the first expression is not an integer and the second 6262 /// expression is not a pointer, true otherwise. 6263 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6264 Expr* PointerExpr, SourceLocation Loc, 6265 bool IsIntFirstExpr) { 6266 if (!PointerExpr->getType()->isPointerType() || 6267 !Int.get()->getType()->isIntegerType()) 6268 return false; 6269 6270 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6271 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6272 6273 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6274 << Expr1->getType() << Expr2->getType() 6275 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6276 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6277 CK_IntegralToPointer); 6278 return true; 6279 } 6280 6281 /// \brief Simple conversion between integer and floating point types. 6282 /// 6283 /// Used when handling the OpenCL conditional operator where the 6284 /// condition is a vector while the other operands are scalar. 6285 /// 6286 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6287 /// types are either integer or floating type. Between the two 6288 /// operands, the type with the higher rank is defined as the "result 6289 /// type". The other operand needs to be promoted to the same type. No 6290 /// other type promotion is allowed. We cannot use 6291 /// UsualArithmeticConversions() for this purpose, since it always 6292 /// promotes promotable types. 6293 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6294 ExprResult &RHS, 6295 SourceLocation QuestionLoc) { 6296 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6297 if (LHS.isInvalid()) 6298 return QualType(); 6299 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6300 if (RHS.isInvalid()) 6301 return QualType(); 6302 6303 // For conversion purposes, we ignore any qualifiers. 6304 // For example, "const float" and "float" are equivalent. 6305 QualType LHSType = 6306 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6307 QualType RHSType = 6308 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6309 6310 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6311 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6312 << LHSType << LHS.get()->getSourceRange(); 6313 return QualType(); 6314 } 6315 6316 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6317 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6318 << RHSType << RHS.get()->getSourceRange(); 6319 return QualType(); 6320 } 6321 6322 // If both types are identical, no conversion is needed. 6323 if (LHSType == RHSType) 6324 return LHSType; 6325 6326 // Now handle "real" floating types (i.e. float, double, long double). 6327 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6328 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6329 /*IsCompAssign = */ false); 6330 6331 // Finally, we have two differing integer types. 6332 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6333 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6334 } 6335 6336 /// \brief Convert scalar operands to a vector that matches the 6337 /// condition in length. 6338 /// 6339 /// Used when handling the OpenCL conditional operator where the 6340 /// condition is a vector while the other operands are scalar. 6341 /// 6342 /// We first compute the "result type" for the scalar operands 6343 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6344 /// into a vector of that type where the length matches the condition 6345 /// vector type. s6.11.6 requires that the element types of the result 6346 /// and the condition must have the same number of bits. 6347 static QualType 6348 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6349 QualType CondTy, SourceLocation QuestionLoc) { 6350 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6351 if (ResTy.isNull()) return QualType(); 6352 6353 const VectorType *CV = CondTy->getAs<VectorType>(); 6354 assert(CV); 6355 6356 // Determine the vector result type 6357 unsigned NumElements = CV->getNumElements(); 6358 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6359 6360 // Ensure that all types have the same number of bits 6361 if (S.Context.getTypeSize(CV->getElementType()) 6362 != S.Context.getTypeSize(ResTy)) { 6363 // Since VectorTy is created internally, it does not pretty print 6364 // with an OpenCL name. Instead, we just print a description. 6365 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6366 SmallString<64> Str; 6367 llvm::raw_svector_ostream OS(Str); 6368 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6369 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6370 << CondTy << OS.str(); 6371 return QualType(); 6372 } 6373 6374 // Convert operands to the vector result type 6375 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6376 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6377 6378 return VectorTy; 6379 } 6380 6381 /// \brief Return false if this is a valid OpenCL condition vector 6382 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6383 SourceLocation QuestionLoc) { 6384 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6385 // integral type. 6386 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6387 assert(CondTy); 6388 QualType EleTy = CondTy->getElementType(); 6389 if (EleTy->isIntegerType()) return false; 6390 6391 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6392 << Cond->getType() << Cond->getSourceRange(); 6393 return true; 6394 } 6395 6396 /// \brief Return false if the vector condition type and the vector 6397 /// result type are compatible. 6398 /// 6399 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6400 /// number of elements, and their element types have the same number 6401 /// of bits. 6402 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6403 SourceLocation QuestionLoc) { 6404 const VectorType *CV = CondTy->getAs<VectorType>(); 6405 const VectorType *RV = VecResTy->getAs<VectorType>(); 6406 assert(CV && RV); 6407 6408 if (CV->getNumElements() != RV->getNumElements()) { 6409 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6410 << CondTy << VecResTy; 6411 return true; 6412 } 6413 6414 QualType CVE = CV->getElementType(); 6415 QualType RVE = RV->getElementType(); 6416 6417 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6418 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6419 << CondTy << VecResTy; 6420 return true; 6421 } 6422 6423 return false; 6424 } 6425 6426 /// \brief Return the resulting type for the conditional operator in 6427 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6428 /// s6.3.i) when the condition is a vector type. 6429 static QualType 6430 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6431 ExprResult &LHS, ExprResult &RHS, 6432 SourceLocation QuestionLoc) { 6433 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6434 if (Cond.isInvalid()) 6435 return QualType(); 6436 QualType CondTy = Cond.get()->getType(); 6437 6438 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6439 return QualType(); 6440 6441 // If either operand is a vector then find the vector type of the 6442 // result as specified in OpenCL v1.1 s6.3.i. 6443 if (LHS.get()->getType()->isVectorType() || 6444 RHS.get()->getType()->isVectorType()) { 6445 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6446 /*isCompAssign*/false, 6447 /*AllowBothBool*/true, 6448 /*AllowBoolConversions*/false); 6449 if (VecResTy.isNull()) return QualType(); 6450 // The result type must match the condition type as specified in 6451 // OpenCL v1.1 s6.11.6. 6452 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6453 return QualType(); 6454 return VecResTy; 6455 } 6456 6457 // Both operands are scalar. 6458 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6459 } 6460 6461 /// \brief Return true if the Expr is block type 6462 static bool checkBlockType(Sema &S, const Expr *E) { 6463 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6464 QualType Ty = CE->getCallee()->getType(); 6465 if (Ty->isBlockPointerType()) { 6466 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6467 return true; 6468 } 6469 } 6470 return false; 6471 } 6472 6473 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6474 /// In that case, LHS = cond. 6475 /// C99 6.5.15 6476 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6477 ExprResult &RHS, ExprValueKind &VK, 6478 ExprObjectKind &OK, 6479 SourceLocation QuestionLoc) { 6480 6481 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6482 if (!LHSResult.isUsable()) return QualType(); 6483 LHS = LHSResult; 6484 6485 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6486 if (!RHSResult.isUsable()) return QualType(); 6487 RHS = RHSResult; 6488 6489 // C++ is sufficiently different to merit its own checker. 6490 if (getLangOpts().CPlusPlus) 6491 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6492 6493 VK = VK_RValue; 6494 OK = OK_Ordinary; 6495 6496 // The OpenCL operator with a vector condition is sufficiently 6497 // different to merit its own checker. 6498 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6499 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6500 6501 // First, check the condition. 6502 Cond = UsualUnaryConversions(Cond.get()); 6503 if (Cond.isInvalid()) 6504 return QualType(); 6505 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6506 return QualType(); 6507 6508 // Now check the two expressions. 6509 if (LHS.get()->getType()->isVectorType() || 6510 RHS.get()->getType()->isVectorType()) 6511 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6512 /*AllowBothBool*/true, 6513 /*AllowBoolConversions*/false); 6514 6515 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6516 if (LHS.isInvalid() || RHS.isInvalid()) 6517 return QualType(); 6518 6519 QualType LHSTy = LHS.get()->getType(); 6520 QualType RHSTy = RHS.get()->getType(); 6521 6522 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6523 // selection operator (?:). 6524 if (getLangOpts().OpenCL && 6525 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6526 return QualType(); 6527 } 6528 6529 // If both operands have arithmetic type, do the usual arithmetic conversions 6530 // to find a common type: C99 6.5.15p3,5. 6531 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6532 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6533 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6534 6535 return ResTy; 6536 } 6537 6538 // If both operands are the same structure or union type, the result is that 6539 // type. 6540 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6541 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6542 if (LHSRT->getDecl() == RHSRT->getDecl()) 6543 // "If both the operands have structure or union type, the result has 6544 // that type." This implies that CV qualifiers are dropped. 6545 return LHSTy.getUnqualifiedType(); 6546 // FIXME: Type of conditional expression must be complete in C mode. 6547 } 6548 6549 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6550 // The following || allows only one side to be void (a GCC-ism). 6551 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6552 return checkConditionalVoidType(*this, LHS, RHS); 6553 } 6554 6555 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6556 // the type of the other operand." 6557 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6558 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6559 6560 // All objective-c pointer type analysis is done here. 6561 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6562 QuestionLoc); 6563 if (LHS.isInvalid() || RHS.isInvalid()) 6564 return QualType(); 6565 if (!compositeType.isNull()) 6566 return compositeType; 6567 6568 6569 // Handle block pointer types. 6570 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6571 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6572 QuestionLoc); 6573 6574 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6575 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6576 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6577 QuestionLoc); 6578 6579 // GCC compatibility: soften pointer/integer mismatch. Note that 6580 // null pointers have been filtered out by this point. 6581 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6582 /*isIntFirstExpr=*/true)) 6583 return RHSTy; 6584 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6585 /*isIntFirstExpr=*/false)) 6586 return LHSTy; 6587 6588 // Emit a better diagnostic if one of the expressions is a null pointer 6589 // constant and the other is not a pointer type. In this case, the user most 6590 // likely forgot to take the address of the other expression. 6591 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6592 return QualType(); 6593 6594 // Otherwise, the operands are not compatible. 6595 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6596 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6597 << RHS.get()->getSourceRange(); 6598 return QualType(); 6599 } 6600 6601 /// FindCompositeObjCPointerType - Helper method to find composite type of 6602 /// two objective-c pointer types of the two input expressions. 6603 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6604 SourceLocation QuestionLoc) { 6605 QualType LHSTy = LHS.get()->getType(); 6606 QualType RHSTy = RHS.get()->getType(); 6607 6608 // Handle things like Class and struct objc_class*. Here we case the result 6609 // to the pseudo-builtin, because that will be implicitly cast back to the 6610 // redefinition type if an attempt is made to access its fields. 6611 if (LHSTy->isObjCClassType() && 6612 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6613 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6614 return LHSTy; 6615 } 6616 if (RHSTy->isObjCClassType() && 6617 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6618 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6619 return RHSTy; 6620 } 6621 // And the same for struct objc_object* / id 6622 if (LHSTy->isObjCIdType() && 6623 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6624 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6625 return LHSTy; 6626 } 6627 if (RHSTy->isObjCIdType() && 6628 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6629 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6630 return RHSTy; 6631 } 6632 // And the same for struct objc_selector* / SEL 6633 if (Context.isObjCSelType(LHSTy) && 6634 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6635 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6636 return LHSTy; 6637 } 6638 if (Context.isObjCSelType(RHSTy) && 6639 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6640 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6641 return RHSTy; 6642 } 6643 // Check constraints for Objective-C object pointers types. 6644 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6645 6646 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6647 // Two identical object pointer types are always compatible. 6648 return LHSTy; 6649 } 6650 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6651 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6652 QualType compositeType = LHSTy; 6653 6654 // If both operands are interfaces and either operand can be 6655 // assigned to the other, use that type as the composite 6656 // type. This allows 6657 // xxx ? (A*) a : (B*) b 6658 // where B is a subclass of A. 6659 // 6660 // Additionally, as for assignment, if either type is 'id' 6661 // allow silent coercion. Finally, if the types are 6662 // incompatible then make sure to use 'id' as the composite 6663 // type so the result is acceptable for sending messages to. 6664 6665 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6666 // It could return the composite type. 6667 if (!(compositeType = 6668 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6669 // Nothing more to do. 6670 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6671 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6672 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6673 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6674 } else if ((LHSTy->isObjCQualifiedIdType() || 6675 RHSTy->isObjCQualifiedIdType()) && 6676 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6677 // Need to handle "id<xx>" explicitly. 6678 // GCC allows qualified id and any Objective-C type to devolve to 6679 // id. Currently localizing to here until clear this should be 6680 // part of ObjCQualifiedIdTypesAreCompatible. 6681 compositeType = Context.getObjCIdType(); 6682 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6683 compositeType = Context.getObjCIdType(); 6684 } else { 6685 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6686 << LHSTy << RHSTy 6687 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6688 QualType incompatTy = Context.getObjCIdType(); 6689 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6690 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6691 return incompatTy; 6692 } 6693 // The object pointer types are compatible. 6694 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6695 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6696 return compositeType; 6697 } 6698 // Check Objective-C object pointer types and 'void *' 6699 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6700 if (getLangOpts().ObjCAutoRefCount) { 6701 // ARC forbids the implicit conversion of object pointers to 'void *', 6702 // so these types are not compatible. 6703 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6704 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6705 LHS = RHS = true; 6706 return QualType(); 6707 } 6708 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6709 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6710 QualType destPointee 6711 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6712 QualType destType = Context.getPointerType(destPointee); 6713 // Add qualifiers if necessary. 6714 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6715 // Promote to void*. 6716 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6717 return destType; 6718 } 6719 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6720 if (getLangOpts().ObjCAutoRefCount) { 6721 // ARC forbids the implicit conversion of object pointers to 'void *', 6722 // so these types are not compatible. 6723 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6724 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6725 LHS = RHS = true; 6726 return QualType(); 6727 } 6728 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6729 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6730 QualType destPointee 6731 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6732 QualType destType = Context.getPointerType(destPointee); 6733 // Add qualifiers if necessary. 6734 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6735 // Promote to void*. 6736 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6737 return destType; 6738 } 6739 return QualType(); 6740 } 6741 6742 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6743 /// ParenRange in parentheses. 6744 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6745 const PartialDiagnostic &Note, 6746 SourceRange ParenRange) { 6747 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6748 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6749 EndLoc.isValid()) { 6750 Self.Diag(Loc, Note) 6751 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6752 << FixItHint::CreateInsertion(EndLoc, ")"); 6753 } else { 6754 // We can't display the parentheses, so just show the bare note. 6755 Self.Diag(Loc, Note) << ParenRange; 6756 } 6757 } 6758 6759 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6760 return BinaryOperator::isAdditiveOp(Opc) || 6761 BinaryOperator::isMultiplicativeOp(Opc) || 6762 BinaryOperator::isShiftOp(Opc); 6763 } 6764 6765 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6766 /// expression, either using a built-in or overloaded operator, 6767 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6768 /// expression. 6769 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6770 Expr **RHSExprs) { 6771 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6772 E = E->IgnoreImpCasts(); 6773 E = E->IgnoreConversionOperator(); 6774 E = E->IgnoreImpCasts(); 6775 6776 // Built-in binary operator. 6777 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6778 if (IsArithmeticOp(OP->getOpcode())) { 6779 *Opcode = OP->getOpcode(); 6780 *RHSExprs = OP->getRHS(); 6781 return true; 6782 } 6783 } 6784 6785 // Overloaded operator. 6786 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6787 if (Call->getNumArgs() != 2) 6788 return false; 6789 6790 // Make sure this is really a binary operator that is safe to pass into 6791 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6792 OverloadedOperatorKind OO = Call->getOperator(); 6793 if (OO < OO_Plus || OO > OO_Arrow || 6794 OO == OO_PlusPlus || OO == OO_MinusMinus) 6795 return false; 6796 6797 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6798 if (IsArithmeticOp(OpKind)) { 6799 *Opcode = OpKind; 6800 *RHSExprs = Call->getArg(1); 6801 return true; 6802 } 6803 } 6804 6805 return false; 6806 } 6807 6808 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6809 /// or is a logical expression such as (x==y) which has int type, but is 6810 /// commonly interpreted as boolean. 6811 static bool ExprLooksBoolean(Expr *E) { 6812 E = E->IgnoreParenImpCasts(); 6813 6814 if (E->getType()->isBooleanType()) 6815 return true; 6816 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6817 return OP->isComparisonOp() || OP->isLogicalOp(); 6818 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6819 return OP->getOpcode() == UO_LNot; 6820 if (E->getType()->isPointerType()) 6821 return true; 6822 6823 return false; 6824 } 6825 6826 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6827 /// and binary operator are mixed in a way that suggests the programmer assumed 6828 /// the conditional operator has higher precedence, for example: 6829 /// "int x = a + someBinaryCondition ? 1 : 2". 6830 static void DiagnoseConditionalPrecedence(Sema &Self, 6831 SourceLocation OpLoc, 6832 Expr *Condition, 6833 Expr *LHSExpr, 6834 Expr *RHSExpr) { 6835 BinaryOperatorKind CondOpcode; 6836 Expr *CondRHS; 6837 6838 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6839 return; 6840 if (!ExprLooksBoolean(CondRHS)) 6841 return; 6842 6843 // The condition is an arithmetic binary expression, with a right- 6844 // hand side that looks boolean, so warn. 6845 6846 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6847 << Condition->getSourceRange() 6848 << BinaryOperator::getOpcodeStr(CondOpcode); 6849 6850 SuggestParentheses(Self, OpLoc, 6851 Self.PDiag(diag::note_precedence_silence) 6852 << BinaryOperator::getOpcodeStr(CondOpcode), 6853 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6854 6855 SuggestParentheses(Self, OpLoc, 6856 Self.PDiag(diag::note_precedence_conditional_first), 6857 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6858 } 6859 6860 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6861 /// in the case of a the GNU conditional expr extension. 6862 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6863 SourceLocation ColonLoc, 6864 Expr *CondExpr, Expr *LHSExpr, 6865 Expr *RHSExpr) { 6866 if (!getLangOpts().CPlusPlus) { 6867 // C cannot handle TypoExpr nodes in the condition because it 6868 // doesn't handle dependent types properly, so make sure any TypoExprs have 6869 // been dealt with before checking the operands. 6870 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6871 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 6872 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 6873 6874 if (!CondResult.isUsable()) 6875 return ExprError(); 6876 6877 if (LHSExpr) { 6878 if (!LHSResult.isUsable()) 6879 return ExprError(); 6880 } 6881 6882 if (!RHSResult.isUsable()) 6883 return ExprError(); 6884 6885 CondExpr = CondResult.get(); 6886 LHSExpr = LHSResult.get(); 6887 RHSExpr = RHSResult.get(); 6888 } 6889 6890 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6891 // was the condition. 6892 OpaqueValueExpr *opaqueValue = nullptr; 6893 Expr *commonExpr = nullptr; 6894 if (!LHSExpr) { 6895 commonExpr = CondExpr; 6896 // Lower out placeholder types first. This is important so that we don't 6897 // try to capture a placeholder. This happens in few cases in C++; such 6898 // as Objective-C++'s dictionary subscripting syntax. 6899 if (commonExpr->hasPlaceholderType()) { 6900 ExprResult result = CheckPlaceholderExpr(commonExpr); 6901 if (!result.isUsable()) return ExprError(); 6902 commonExpr = result.get(); 6903 } 6904 // We usually want to apply unary conversions *before* saving, except 6905 // in the special case of a C++ l-value conditional. 6906 if (!(getLangOpts().CPlusPlus 6907 && !commonExpr->isTypeDependent() 6908 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6909 && commonExpr->isGLValue() 6910 && commonExpr->isOrdinaryOrBitFieldObject() 6911 && RHSExpr->isOrdinaryOrBitFieldObject() 6912 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6913 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6914 if (commonRes.isInvalid()) 6915 return ExprError(); 6916 commonExpr = commonRes.get(); 6917 } 6918 6919 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6920 commonExpr->getType(), 6921 commonExpr->getValueKind(), 6922 commonExpr->getObjectKind(), 6923 commonExpr); 6924 LHSExpr = CondExpr = opaqueValue; 6925 } 6926 6927 ExprValueKind VK = VK_RValue; 6928 ExprObjectKind OK = OK_Ordinary; 6929 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6930 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6931 VK, OK, QuestionLoc); 6932 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6933 RHS.isInvalid()) 6934 return ExprError(); 6935 6936 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6937 RHS.get()); 6938 6939 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6940 6941 if (!commonExpr) 6942 return new (Context) 6943 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6944 RHS.get(), result, VK, OK); 6945 6946 return new (Context) BinaryConditionalOperator( 6947 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6948 ColonLoc, result, VK, OK); 6949 } 6950 6951 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6952 // being closely modeled after the C99 spec:-). The odd characteristic of this 6953 // routine is it effectively iqnores the qualifiers on the top level pointee. 6954 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6955 // FIXME: add a couple examples in this comment. 6956 static Sema::AssignConvertType 6957 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6958 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6959 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6960 6961 // get the "pointed to" type (ignoring qualifiers at the top level) 6962 const Type *lhptee, *rhptee; 6963 Qualifiers lhq, rhq; 6964 std::tie(lhptee, lhq) = 6965 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6966 std::tie(rhptee, rhq) = 6967 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6968 6969 Sema::AssignConvertType ConvTy = Sema::Compatible; 6970 6971 // C99 6.5.16.1p1: This following citation is common to constraints 6972 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6973 // qualifiers of the type *pointed to* by the right; 6974 6975 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6976 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6977 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6978 // Ignore lifetime for further calculation. 6979 lhq.removeObjCLifetime(); 6980 rhq.removeObjCLifetime(); 6981 } 6982 6983 if (!lhq.compatiblyIncludes(rhq)) { 6984 // Treat address-space mismatches as fatal. TODO: address subspaces 6985 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6986 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6987 6988 // It's okay to add or remove GC or lifetime qualifiers when converting to 6989 // and from void*. 6990 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6991 .compatiblyIncludes( 6992 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6993 && (lhptee->isVoidType() || rhptee->isVoidType())) 6994 ; // keep old 6995 6996 // Treat lifetime mismatches as fatal. 6997 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6998 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6999 7000 // For GCC compatibility, other qualifier mismatches are treated 7001 // as still compatible in C. 7002 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7003 } 7004 7005 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7006 // incomplete type and the other is a pointer to a qualified or unqualified 7007 // version of void... 7008 if (lhptee->isVoidType()) { 7009 if (rhptee->isIncompleteOrObjectType()) 7010 return ConvTy; 7011 7012 // As an extension, we allow cast to/from void* to function pointer. 7013 assert(rhptee->isFunctionType()); 7014 return Sema::FunctionVoidPointer; 7015 } 7016 7017 if (rhptee->isVoidType()) { 7018 if (lhptee->isIncompleteOrObjectType()) 7019 return ConvTy; 7020 7021 // As an extension, we allow cast to/from void* to function pointer. 7022 assert(lhptee->isFunctionType()); 7023 return Sema::FunctionVoidPointer; 7024 } 7025 7026 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7027 // unqualified versions of compatible types, ... 7028 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7029 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7030 // Check if the pointee types are compatible ignoring the sign. 7031 // We explicitly check for char so that we catch "char" vs 7032 // "unsigned char" on systems where "char" is unsigned. 7033 if (lhptee->isCharType()) 7034 ltrans = S.Context.UnsignedCharTy; 7035 else if (lhptee->hasSignedIntegerRepresentation()) 7036 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7037 7038 if (rhptee->isCharType()) 7039 rtrans = S.Context.UnsignedCharTy; 7040 else if (rhptee->hasSignedIntegerRepresentation()) 7041 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7042 7043 if (ltrans == rtrans) { 7044 // Types are compatible ignoring the sign. Qualifier incompatibility 7045 // takes priority over sign incompatibility because the sign 7046 // warning can be disabled. 7047 if (ConvTy != Sema::Compatible) 7048 return ConvTy; 7049 7050 return Sema::IncompatiblePointerSign; 7051 } 7052 7053 // If we are a multi-level pointer, it's possible that our issue is simply 7054 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7055 // the eventual target type is the same and the pointers have the same 7056 // level of indirection, this must be the issue. 7057 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7058 do { 7059 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7060 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7061 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7062 7063 if (lhptee == rhptee) 7064 return Sema::IncompatibleNestedPointerQualifiers; 7065 } 7066 7067 // General pointer incompatibility takes priority over qualifiers. 7068 return Sema::IncompatiblePointer; 7069 } 7070 if (!S.getLangOpts().CPlusPlus && 7071 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7072 return Sema::IncompatiblePointer; 7073 return ConvTy; 7074 } 7075 7076 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7077 /// block pointer types are compatible or whether a block and normal pointer 7078 /// are compatible. It is more restrict than comparing two function pointer 7079 // types. 7080 static Sema::AssignConvertType 7081 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7082 QualType RHSType) { 7083 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7084 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7085 7086 QualType lhptee, rhptee; 7087 7088 // get the "pointed to" type (ignoring qualifiers at the top level) 7089 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7090 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7091 7092 // In C++, the types have to match exactly. 7093 if (S.getLangOpts().CPlusPlus) 7094 return Sema::IncompatibleBlockPointer; 7095 7096 Sema::AssignConvertType ConvTy = Sema::Compatible; 7097 7098 // For blocks we enforce that qualifiers are identical. 7099 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7100 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7101 7102 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7103 return Sema::IncompatibleBlockPointer; 7104 7105 return ConvTy; 7106 } 7107 7108 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7109 /// for assignment compatibility. 7110 static Sema::AssignConvertType 7111 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7112 QualType RHSType) { 7113 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7114 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7115 7116 if (LHSType->isObjCBuiltinType()) { 7117 // Class is not compatible with ObjC object pointers. 7118 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7119 !RHSType->isObjCQualifiedClassType()) 7120 return Sema::IncompatiblePointer; 7121 return Sema::Compatible; 7122 } 7123 if (RHSType->isObjCBuiltinType()) { 7124 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7125 !LHSType->isObjCQualifiedClassType()) 7126 return Sema::IncompatiblePointer; 7127 return Sema::Compatible; 7128 } 7129 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7130 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7131 7132 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7133 // make an exception for id<P> 7134 !LHSType->isObjCQualifiedIdType()) 7135 return Sema::CompatiblePointerDiscardsQualifiers; 7136 7137 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7138 return Sema::Compatible; 7139 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7140 return Sema::IncompatibleObjCQualifiedId; 7141 return Sema::IncompatiblePointer; 7142 } 7143 7144 Sema::AssignConvertType 7145 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7146 QualType LHSType, QualType RHSType) { 7147 // Fake up an opaque expression. We don't actually care about what 7148 // cast operations are required, so if CheckAssignmentConstraints 7149 // adds casts to this they'll be wasted, but fortunately that doesn't 7150 // usually happen on valid code. 7151 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7152 ExprResult RHSPtr = &RHSExpr; 7153 CastKind K = CK_Invalid; 7154 7155 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7156 } 7157 7158 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7159 /// has code to accommodate several GCC extensions when type checking 7160 /// pointers. Here are some objectionable examples that GCC considers warnings: 7161 /// 7162 /// int a, *pint; 7163 /// short *pshort; 7164 /// struct foo *pfoo; 7165 /// 7166 /// pint = pshort; // warning: assignment from incompatible pointer type 7167 /// a = pint; // warning: assignment makes integer from pointer without a cast 7168 /// pint = a; // warning: assignment makes pointer from integer without a cast 7169 /// pint = pfoo; // warning: assignment from incompatible pointer type 7170 /// 7171 /// As a result, the code for dealing with pointers is more complex than the 7172 /// C99 spec dictates. 7173 /// 7174 /// Sets 'Kind' for any result kind except Incompatible. 7175 Sema::AssignConvertType 7176 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7177 CastKind &Kind, bool ConvertRHS) { 7178 QualType RHSType = RHS.get()->getType(); 7179 QualType OrigLHSType = LHSType; 7180 7181 // Get canonical types. We're not formatting these types, just comparing 7182 // them. 7183 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7184 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7185 7186 // Common case: no conversion required. 7187 if (LHSType == RHSType) { 7188 Kind = CK_NoOp; 7189 return Compatible; 7190 } 7191 7192 // If we have an atomic type, try a non-atomic assignment, then just add an 7193 // atomic qualification step. 7194 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7195 Sema::AssignConvertType result = 7196 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7197 if (result != Compatible) 7198 return result; 7199 if (Kind != CK_NoOp && ConvertRHS) 7200 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7201 Kind = CK_NonAtomicToAtomic; 7202 return Compatible; 7203 } 7204 7205 // If the left-hand side is a reference type, then we are in a 7206 // (rare!) case where we've allowed the use of references in C, 7207 // e.g., as a parameter type in a built-in function. In this case, 7208 // just make sure that the type referenced is compatible with the 7209 // right-hand side type. The caller is responsible for adjusting 7210 // LHSType so that the resulting expression does not have reference 7211 // type. 7212 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7213 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7214 Kind = CK_LValueBitCast; 7215 return Compatible; 7216 } 7217 return Incompatible; 7218 } 7219 7220 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7221 // to the same ExtVector type. 7222 if (LHSType->isExtVectorType()) { 7223 if (RHSType->isExtVectorType()) 7224 return Incompatible; 7225 if (RHSType->isArithmeticType()) { 7226 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7227 if (ConvertRHS) 7228 RHS = prepareVectorSplat(LHSType, RHS.get()); 7229 Kind = CK_VectorSplat; 7230 return Compatible; 7231 } 7232 } 7233 7234 // Conversions to or from vector type. 7235 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7236 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7237 // Allow assignments of an AltiVec vector type to an equivalent GCC 7238 // vector type and vice versa 7239 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7240 Kind = CK_BitCast; 7241 return Compatible; 7242 } 7243 7244 // If we are allowing lax vector conversions, and LHS and RHS are both 7245 // vectors, the total size only needs to be the same. This is a bitcast; 7246 // no bits are changed but the result type is different. 7247 if (isLaxVectorConversion(RHSType, LHSType)) { 7248 Kind = CK_BitCast; 7249 return IncompatibleVectors; 7250 } 7251 } 7252 return Incompatible; 7253 } 7254 7255 // Arithmetic conversions. 7256 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7257 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7258 if (ConvertRHS) 7259 Kind = PrepareScalarCast(RHS, LHSType); 7260 return Compatible; 7261 } 7262 7263 // Conversions to normal pointers. 7264 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7265 // U* -> T* 7266 if (isa<PointerType>(RHSType)) { 7267 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7268 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7269 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7270 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7271 } 7272 7273 // int -> T* 7274 if (RHSType->isIntegerType()) { 7275 Kind = CK_IntegralToPointer; // FIXME: null? 7276 return IntToPointer; 7277 } 7278 7279 // C pointers are not compatible with ObjC object pointers, 7280 // with two exceptions: 7281 if (isa<ObjCObjectPointerType>(RHSType)) { 7282 // - conversions to void* 7283 if (LHSPointer->getPointeeType()->isVoidType()) { 7284 Kind = CK_BitCast; 7285 return Compatible; 7286 } 7287 7288 // - conversions from 'Class' to the redefinition type 7289 if (RHSType->isObjCClassType() && 7290 Context.hasSameType(LHSType, 7291 Context.getObjCClassRedefinitionType())) { 7292 Kind = CK_BitCast; 7293 return Compatible; 7294 } 7295 7296 Kind = CK_BitCast; 7297 return IncompatiblePointer; 7298 } 7299 7300 // U^ -> void* 7301 if (RHSType->getAs<BlockPointerType>()) { 7302 if (LHSPointer->getPointeeType()->isVoidType()) { 7303 Kind = CK_BitCast; 7304 return Compatible; 7305 } 7306 } 7307 7308 return Incompatible; 7309 } 7310 7311 // Conversions to block pointers. 7312 if (isa<BlockPointerType>(LHSType)) { 7313 // U^ -> T^ 7314 if (RHSType->isBlockPointerType()) { 7315 Kind = CK_BitCast; 7316 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7317 } 7318 7319 // int or null -> T^ 7320 if (RHSType->isIntegerType()) { 7321 Kind = CK_IntegralToPointer; // FIXME: null 7322 return IntToBlockPointer; 7323 } 7324 7325 // id -> T^ 7326 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7327 Kind = CK_AnyPointerToBlockPointerCast; 7328 return Compatible; 7329 } 7330 7331 // void* -> T^ 7332 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7333 if (RHSPT->getPointeeType()->isVoidType()) { 7334 Kind = CK_AnyPointerToBlockPointerCast; 7335 return Compatible; 7336 } 7337 7338 return Incompatible; 7339 } 7340 7341 // Conversions to Objective-C pointers. 7342 if (isa<ObjCObjectPointerType>(LHSType)) { 7343 // A* -> B* 7344 if (RHSType->isObjCObjectPointerType()) { 7345 Kind = CK_BitCast; 7346 Sema::AssignConvertType result = 7347 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7348 if (getLangOpts().ObjCAutoRefCount && 7349 result == Compatible && 7350 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7351 result = IncompatibleObjCWeakRef; 7352 return result; 7353 } 7354 7355 // int or null -> A* 7356 if (RHSType->isIntegerType()) { 7357 Kind = CK_IntegralToPointer; // FIXME: null 7358 return IntToPointer; 7359 } 7360 7361 // In general, C pointers are not compatible with ObjC object pointers, 7362 // with two exceptions: 7363 if (isa<PointerType>(RHSType)) { 7364 Kind = CK_CPointerToObjCPointerCast; 7365 7366 // - conversions from 'void*' 7367 if (RHSType->isVoidPointerType()) { 7368 return Compatible; 7369 } 7370 7371 // - conversions to 'Class' from its redefinition type 7372 if (LHSType->isObjCClassType() && 7373 Context.hasSameType(RHSType, 7374 Context.getObjCClassRedefinitionType())) { 7375 return Compatible; 7376 } 7377 7378 return IncompatiblePointer; 7379 } 7380 7381 // Only under strict condition T^ is compatible with an Objective-C pointer. 7382 if (RHSType->isBlockPointerType() && 7383 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7384 if (ConvertRHS) 7385 maybeExtendBlockObject(RHS); 7386 Kind = CK_BlockPointerToObjCPointerCast; 7387 return Compatible; 7388 } 7389 7390 return Incompatible; 7391 } 7392 7393 // Conversions from pointers that are not covered by the above. 7394 if (isa<PointerType>(RHSType)) { 7395 // T* -> _Bool 7396 if (LHSType == Context.BoolTy) { 7397 Kind = CK_PointerToBoolean; 7398 return Compatible; 7399 } 7400 7401 // T* -> int 7402 if (LHSType->isIntegerType()) { 7403 Kind = CK_PointerToIntegral; 7404 return PointerToInt; 7405 } 7406 7407 return Incompatible; 7408 } 7409 7410 // Conversions from Objective-C pointers that are not covered by the above. 7411 if (isa<ObjCObjectPointerType>(RHSType)) { 7412 // T* -> _Bool 7413 if (LHSType == Context.BoolTy) { 7414 Kind = CK_PointerToBoolean; 7415 return Compatible; 7416 } 7417 7418 // T* -> int 7419 if (LHSType->isIntegerType()) { 7420 Kind = CK_PointerToIntegral; 7421 return PointerToInt; 7422 } 7423 7424 return Incompatible; 7425 } 7426 7427 // struct A -> struct B 7428 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7429 if (Context.typesAreCompatible(LHSType, RHSType)) { 7430 Kind = CK_NoOp; 7431 return Compatible; 7432 } 7433 } 7434 7435 return Incompatible; 7436 } 7437 7438 /// \brief Constructs a transparent union from an expression that is 7439 /// used to initialize the transparent union. 7440 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7441 ExprResult &EResult, QualType UnionType, 7442 FieldDecl *Field) { 7443 // Build an initializer list that designates the appropriate member 7444 // of the transparent union. 7445 Expr *E = EResult.get(); 7446 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7447 E, SourceLocation()); 7448 Initializer->setType(UnionType); 7449 Initializer->setInitializedFieldInUnion(Field); 7450 7451 // Build a compound literal constructing a value of the transparent 7452 // union type from this initializer list. 7453 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7454 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7455 VK_RValue, Initializer, false); 7456 } 7457 7458 Sema::AssignConvertType 7459 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7460 ExprResult &RHS) { 7461 QualType RHSType = RHS.get()->getType(); 7462 7463 // If the ArgType is a Union type, we want to handle a potential 7464 // transparent_union GCC extension. 7465 const RecordType *UT = ArgType->getAsUnionType(); 7466 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7467 return Incompatible; 7468 7469 // The field to initialize within the transparent union. 7470 RecordDecl *UD = UT->getDecl(); 7471 FieldDecl *InitField = nullptr; 7472 // It's compatible if the expression matches any of the fields. 7473 for (auto *it : UD->fields()) { 7474 if (it->getType()->isPointerType()) { 7475 // If the transparent union contains a pointer type, we allow: 7476 // 1) void pointer 7477 // 2) null pointer constant 7478 if (RHSType->isPointerType()) 7479 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7480 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7481 InitField = it; 7482 break; 7483 } 7484 7485 if (RHS.get()->isNullPointerConstant(Context, 7486 Expr::NPC_ValueDependentIsNull)) { 7487 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7488 CK_NullToPointer); 7489 InitField = it; 7490 break; 7491 } 7492 } 7493 7494 CastKind Kind = CK_Invalid; 7495 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7496 == Compatible) { 7497 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7498 InitField = it; 7499 break; 7500 } 7501 } 7502 7503 if (!InitField) 7504 return Incompatible; 7505 7506 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7507 return Compatible; 7508 } 7509 7510 Sema::AssignConvertType 7511 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7512 bool Diagnose, 7513 bool DiagnoseCFAudited, 7514 bool ConvertRHS) { 7515 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7516 // we can't avoid *all* modifications at the moment, so we need some somewhere 7517 // to put the updated value. 7518 ExprResult LocalRHS = CallerRHS; 7519 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7520 7521 if (getLangOpts().CPlusPlus) { 7522 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7523 // C++ 5.17p3: If the left operand is not of class type, the 7524 // expression is implicitly converted (C++ 4) to the 7525 // cv-unqualified type of the left operand. 7526 ExprResult Res; 7527 if (Diagnose) { 7528 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7529 AA_Assigning); 7530 } else { 7531 ImplicitConversionSequence ICS = 7532 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7533 /*SuppressUserConversions=*/false, 7534 /*AllowExplicit=*/false, 7535 /*InOverloadResolution=*/false, 7536 /*CStyle=*/false, 7537 /*AllowObjCWritebackConversion=*/false); 7538 if (ICS.isFailure()) 7539 return Incompatible; 7540 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7541 ICS, AA_Assigning); 7542 } 7543 if (Res.isInvalid()) 7544 return Incompatible; 7545 Sema::AssignConvertType result = Compatible; 7546 if (getLangOpts().ObjCAutoRefCount && 7547 !CheckObjCARCUnavailableWeakConversion(LHSType, 7548 RHS.get()->getType())) 7549 result = IncompatibleObjCWeakRef; 7550 RHS = Res; 7551 return result; 7552 } 7553 7554 // FIXME: Currently, we fall through and treat C++ classes like C 7555 // structures. 7556 // FIXME: We also fall through for atomics; not sure what should 7557 // happen there, though. 7558 } else if (RHS.get()->getType() == Context.OverloadTy) { 7559 // As a set of extensions to C, we support overloading on functions. These 7560 // functions need to be resolved here. 7561 DeclAccessPair DAP; 7562 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7563 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7564 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7565 else 7566 return Incompatible; 7567 } 7568 7569 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7570 // a null pointer constant. 7571 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7572 LHSType->isBlockPointerType()) && 7573 RHS.get()->isNullPointerConstant(Context, 7574 Expr::NPC_ValueDependentIsNull)) { 7575 if (Diagnose || ConvertRHS) { 7576 CastKind Kind; 7577 CXXCastPath Path; 7578 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7579 /*IgnoreBaseAccess=*/false, Diagnose); 7580 if (ConvertRHS) 7581 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7582 } 7583 return Compatible; 7584 } 7585 7586 // This check seems unnatural, however it is necessary to ensure the proper 7587 // conversion of functions/arrays. If the conversion were done for all 7588 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7589 // expressions that suppress this implicit conversion (&, sizeof). 7590 // 7591 // Suppress this for references: C++ 8.5.3p5. 7592 if (!LHSType->isReferenceType()) { 7593 // FIXME: We potentially allocate here even if ConvertRHS is false. 7594 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7595 if (RHS.isInvalid()) 7596 return Incompatible; 7597 } 7598 7599 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7600 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7601 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7602 if (PDecl && !PDecl->hasDefinition()) { 7603 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7604 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7605 } 7606 } 7607 7608 CastKind Kind = CK_Invalid; 7609 Sema::AssignConvertType result = 7610 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7611 7612 // C99 6.5.16.1p2: The value of the right operand is converted to the 7613 // type of the assignment expression. 7614 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7615 // so that we can use references in built-in functions even in C. 7616 // The getNonReferenceType() call makes sure that the resulting expression 7617 // does not have reference type. 7618 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7619 QualType Ty = LHSType.getNonLValueExprType(Context); 7620 Expr *E = RHS.get(); 7621 7622 // Check for various Objective-C errors. If we are not reporting 7623 // diagnostics and just checking for errors, e.g., during overload 7624 // resolution, return Incompatible to indicate the failure. 7625 if (getLangOpts().ObjCAutoRefCount && 7626 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7627 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7628 if (!Diagnose) 7629 return Incompatible; 7630 } 7631 if (getLangOpts().ObjC1 && 7632 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7633 E->getType(), E, Diagnose) || 7634 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7635 if (!Diagnose) 7636 return Incompatible; 7637 // Replace the expression with a corrected version and continue so we 7638 // can find further errors. 7639 RHS = E; 7640 return Compatible; 7641 } 7642 7643 if (ConvertRHS) 7644 RHS = ImpCastExprToType(E, Ty, Kind); 7645 } 7646 return result; 7647 } 7648 7649 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7650 ExprResult &RHS) { 7651 Diag(Loc, diag::err_typecheck_invalid_operands) 7652 << LHS.get()->getType() << RHS.get()->getType() 7653 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7654 return QualType(); 7655 } 7656 7657 /// Try to convert a value of non-vector type to a vector type by converting 7658 /// the type to the element type of the vector and then performing a splat. 7659 /// If the language is OpenCL, we only use conversions that promote scalar 7660 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7661 /// for float->int. 7662 /// 7663 /// \param scalar - if non-null, actually perform the conversions 7664 /// \return true if the operation fails (but without diagnosing the failure) 7665 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7666 QualType scalarTy, 7667 QualType vectorEltTy, 7668 QualType vectorTy) { 7669 // The conversion to apply to the scalar before splatting it, 7670 // if necessary. 7671 CastKind scalarCast = CK_Invalid; 7672 7673 if (vectorEltTy->isIntegralType(S.Context)) { 7674 if (!scalarTy->isIntegralType(S.Context)) 7675 return true; 7676 if (S.getLangOpts().OpenCL && 7677 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7678 return true; 7679 scalarCast = CK_IntegralCast; 7680 } else if (vectorEltTy->isRealFloatingType()) { 7681 if (scalarTy->isRealFloatingType()) { 7682 if (S.getLangOpts().OpenCL && 7683 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7684 return true; 7685 scalarCast = CK_FloatingCast; 7686 } 7687 else if (scalarTy->isIntegralType(S.Context)) 7688 scalarCast = CK_IntegralToFloating; 7689 else 7690 return true; 7691 } else { 7692 return true; 7693 } 7694 7695 // Adjust scalar if desired. 7696 if (scalar) { 7697 if (scalarCast != CK_Invalid) 7698 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7699 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7700 } 7701 return false; 7702 } 7703 7704 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7705 SourceLocation Loc, bool IsCompAssign, 7706 bool AllowBothBool, 7707 bool AllowBoolConversions) { 7708 if (!IsCompAssign) { 7709 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7710 if (LHS.isInvalid()) 7711 return QualType(); 7712 } 7713 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7714 if (RHS.isInvalid()) 7715 return QualType(); 7716 7717 // For conversion purposes, we ignore any qualifiers. 7718 // For example, "const float" and "float" are equivalent. 7719 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7720 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7721 7722 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7723 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7724 assert(LHSVecType || RHSVecType); 7725 7726 // AltiVec-style "vector bool op vector bool" combinations are allowed 7727 // for some operators but not others. 7728 if (!AllowBothBool && 7729 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7730 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7731 return InvalidOperands(Loc, LHS, RHS); 7732 7733 // If the vector types are identical, return. 7734 if (Context.hasSameType(LHSType, RHSType)) 7735 return LHSType; 7736 7737 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7738 if (LHSVecType && RHSVecType && 7739 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7740 if (isa<ExtVectorType>(LHSVecType)) { 7741 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7742 return LHSType; 7743 } 7744 7745 if (!IsCompAssign) 7746 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7747 return RHSType; 7748 } 7749 7750 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7751 // can be mixed, with the result being the non-bool type. The non-bool 7752 // operand must have integer element type. 7753 if (AllowBoolConversions && LHSVecType && RHSVecType && 7754 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7755 (Context.getTypeSize(LHSVecType->getElementType()) == 7756 Context.getTypeSize(RHSVecType->getElementType()))) { 7757 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7758 LHSVecType->getElementType()->isIntegerType() && 7759 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7760 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7761 return LHSType; 7762 } 7763 if (!IsCompAssign && 7764 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7765 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7766 RHSVecType->getElementType()->isIntegerType()) { 7767 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7768 return RHSType; 7769 } 7770 } 7771 7772 // If there's an ext-vector type and a scalar, try to convert the scalar to 7773 // the vector element type and splat. 7774 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7775 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7776 LHSVecType->getElementType(), LHSType)) 7777 return LHSType; 7778 } 7779 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7780 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7781 LHSType, RHSVecType->getElementType(), 7782 RHSType)) 7783 return RHSType; 7784 } 7785 7786 // If we're allowing lax vector conversions, only the total (data) size 7787 // needs to be the same. 7788 // FIXME: Should we really be allowing this? 7789 // FIXME: We really just pick the LHS type arbitrarily? 7790 if (isLaxVectorConversion(RHSType, LHSType)) { 7791 QualType resultType = LHSType; 7792 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7793 return resultType; 7794 } 7795 7796 // Okay, the expression is invalid. 7797 7798 // If there's a non-vector, non-real operand, diagnose that. 7799 if ((!RHSVecType && !RHSType->isRealType()) || 7800 (!LHSVecType && !LHSType->isRealType())) { 7801 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7802 << LHSType << RHSType 7803 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7804 return QualType(); 7805 } 7806 7807 // OpenCL V1.1 6.2.6.p1: 7808 // If the operands are of more than one vector type, then an error shall 7809 // occur. Implicit conversions between vector types are not permitted, per 7810 // section 6.2.1. 7811 if (getLangOpts().OpenCL && 7812 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7813 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7814 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7815 << RHSType; 7816 return QualType(); 7817 } 7818 7819 // Otherwise, use the generic diagnostic. 7820 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7821 << LHSType << RHSType 7822 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7823 return QualType(); 7824 } 7825 7826 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7827 // expression. These are mainly cases where the null pointer is used as an 7828 // integer instead of a pointer. 7829 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7830 SourceLocation Loc, bool IsCompare) { 7831 // The canonical way to check for a GNU null is with isNullPointerConstant, 7832 // but we use a bit of a hack here for speed; this is a relatively 7833 // hot path, and isNullPointerConstant is slow. 7834 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7835 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7836 7837 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7838 7839 // Avoid analyzing cases where the result will either be invalid (and 7840 // diagnosed as such) or entirely valid and not something to warn about. 7841 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7842 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7843 return; 7844 7845 // Comparison operations would not make sense with a null pointer no matter 7846 // what the other expression is. 7847 if (!IsCompare) { 7848 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7849 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7850 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7851 return; 7852 } 7853 7854 // The rest of the operations only make sense with a null pointer 7855 // if the other expression is a pointer. 7856 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7857 NonNullType->canDecayToPointerType()) 7858 return; 7859 7860 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7861 << LHSNull /* LHS is NULL */ << NonNullType 7862 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7863 } 7864 7865 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7866 ExprResult &RHS, 7867 SourceLocation Loc, bool IsDiv) { 7868 // Check for division/remainder by zero. 7869 llvm::APSInt RHSValue; 7870 if (!RHS.get()->isValueDependent() && 7871 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7872 S.DiagRuntimeBehavior(Loc, RHS.get(), 7873 S.PDiag(diag::warn_remainder_division_by_zero) 7874 << IsDiv << RHS.get()->getSourceRange()); 7875 } 7876 7877 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7878 SourceLocation Loc, 7879 bool IsCompAssign, bool IsDiv) { 7880 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7881 7882 if (LHS.get()->getType()->isVectorType() || 7883 RHS.get()->getType()->isVectorType()) 7884 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7885 /*AllowBothBool*/getLangOpts().AltiVec, 7886 /*AllowBoolConversions*/false); 7887 7888 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7889 if (LHS.isInvalid() || RHS.isInvalid()) 7890 return QualType(); 7891 7892 7893 if (compType.isNull() || !compType->isArithmeticType()) 7894 return InvalidOperands(Loc, LHS, RHS); 7895 if (IsDiv) 7896 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7897 return compType; 7898 } 7899 7900 QualType Sema::CheckRemainderOperands( 7901 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7902 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7903 7904 if (LHS.get()->getType()->isVectorType() || 7905 RHS.get()->getType()->isVectorType()) { 7906 if (LHS.get()->getType()->hasIntegerRepresentation() && 7907 RHS.get()->getType()->hasIntegerRepresentation()) 7908 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7909 /*AllowBothBool*/getLangOpts().AltiVec, 7910 /*AllowBoolConversions*/false); 7911 return InvalidOperands(Loc, LHS, RHS); 7912 } 7913 7914 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7915 if (LHS.isInvalid() || RHS.isInvalid()) 7916 return QualType(); 7917 7918 if (compType.isNull() || !compType->isIntegerType()) 7919 return InvalidOperands(Loc, LHS, RHS); 7920 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 7921 return compType; 7922 } 7923 7924 /// \brief Diagnose invalid arithmetic on two void pointers. 7925 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7926 Expr *LHSExpr, Expr *RHSExpr) { 7927 S.Diag(Loc, S.getLangOpts().CPlusPlus 7928 ? diag::err_typecheck_pointer_arith_void_type 7929 : diag::ext_gnu_void_ptr) 7930 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7931 << RHSExpr->getSourceRange(); 7932 } 7933 7934 /// \brief Diagnose invalid arithmetic on a void pointer. 7935 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7936 Expr *Pointer) { 7937 S.Diag(Loc, S.getLangOpts().CPlusPlus 7938 ? diag::err_typecheck_pointer_arith_void_type 7939 : diag::ext_gnu_void_ptr) 7940 << 0 /* one pointer */ << Pointer->getSourceRange(); 7941 } 7942 7943 /// \brief Diagnose invalid arithmetic on two function pointers. 7944 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7945 Expr *LHS, Expr *RHS) { 7946 assert(LHS->getType()->isAnyPointerType()); 7947 assert(RHS->getType()->isAnyPointerType()); 7948 S.Diag(Loc, S.getLangOpts().CPlusPlus 7949 ? diag::err_typecheck_pointer_arith_function_type 7950 : diag::ext_gnu_ptr_func_arith) 7951 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7952 // We only show the second type if it differs from the first. 7953 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7954 RHS->getType()) 7955 << RHS->getType()->getPointeeType() 7956 << LHS->getSourceRange() << RHS->getSourceRange(); 7957 } 7958 7959 /// \brief Diagnose invalid arithmetic on a function pointer. 7960 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7961 Expr *Pointer) { 7962 assert(Pointer->getType()->isAnyPointerType()); 7963 S.Diag(Loc, S.getLangOpts().CPlusPlus 7964 ? diag::err_typecheck_pointer_arith_function_type 7965 : diag::ext_gnu_ptr_func_arith) 7966 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7967 << 0 /* one pointer, so only one type */ 7968 << Pointer->getSourceRange(); 7969 } 7970 7971 /// \brief Emit error if Operand is incomplete pointer type 7972 /// 7973 /// \returns True if pointer has incomplete type 7974 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7975 Expr *Operand) { 7976 QualType ResType = Operand->getType(); 7977 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7978 ResType = ResAtomicType->getValueType(); 7979 7980 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7981 QualType PointeeTy = ResType->getPointeeType(); 7982 return S.RequireCompleteType(Loc, PointeeTy, 7983 diag::err_typecheck_arithmetic_incomplete_type, 7984 PointeeTy, Operand->getSourceRange()); 7985 } 7986 7987 /// \brief Check the validity of an arithmetic pointer operand. 7988 /// 7989 /// If the operand has pointer type, this code will check for pointer types 7990 /// which are invalid in arithmetic operations. These will be diagnosed 7991 /// appropriately, including whether or not the use is supported as an 7992 /// extension. 7993 /// 7994 /// \returns True when the operand is valid to use (even if as an extension). 7995 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7996 Expr *Operand) { 7997 QualType ResType = Operand->getType(); 7998 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7999 ResType = ResAtomicType->getValueType(); 8000 8001 if (!ResType->isAnyPointerType()) return true; 8002 8003 QualType PointeeTy = ResType->getPointeeType(); 8004 if (PointeeTy->isVoidType()) { 8005 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8006 return !S.getLangOpts().CPlusPlus; 8007 } 8008 if (PointeeTy->isFunctionType()) { 8009 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8010 return !S.getLangOpts().CPlusPlus; 8011 } 8012 8013 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8014 8015 return true; 8016 } 8017 8018 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8019 /// operands. 8020 /// 8021 /// This routine will diagnose any invalid arithmetic on pointer operands much 8022 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8023 /// for emitting a single diagnostic even for operations where both LHS and RHS 8024 /// are (potentially problematic) pointers. 8025 /// 8026 /// \returns True when the operand is valid to use (even if as an extension). 8027 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8028 Expr *LHSExpr, Expr *RHSExpr) { 8029 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8030 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8031 if (!isLHSPointer && !isRHSPointer) return true; 8032 8033 QualType LHSPointeeTy, RHSPointeeTy; 8034 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8035 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8036 8037 // if both are pointers check if operation is valid wrt address spaces 8038 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8039 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8040 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8041 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8042 S.Diag(Loc, 8043 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8044 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8045 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8046 return false; 8047 } 8048 } 8049 8050 // Check for arithmetic on pointers to incomplete types. 8051 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8052 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8053 if (isLHSVoidPtr || isRHSVoidPtr) { 8054 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8055 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8056 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8057 8058 return !S.getLangOpts().CPlusPlus; 8059 } 8060 8061 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8062 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8063 if (isLHSFuncPtr || isRHSFuncPtr) { 8064 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8065 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8066 RHSExpr); 8067 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8068 8069 return !S.getLangOpts().CPlusPlus; 8070 } 8071 8072 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8073 return false; 8074 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8075 return false; 8076 8077 return true; 8078 } 8079 8080 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8081 /// literal. 8082 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8083 Expr *LHSExpr, Expr *RHSExpr) { 8084 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8085 Expr* IndexExpr = RHSExpr; 8086 if (!StrExpr) { 8087 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8088 IndexExpr = LHSExpr; 8089 } 8090 8091 bool IsStringPlusInt = StrExpr && 8092 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8093 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8094 return; 8095 8096 llvm::APSInt index; 8097 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8098 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8099 if (index.isNonNegative() && 8100 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8101 index.isUnsigned())) 8102 return; 8103 } 8104 8105 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8106 Self.Diag(OpLoc, diag::warn_string_plus_int) 8107 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8108 8109 // Only print a fixit for "str" + int, not for int + "str". 8110 if (IndexExpr == RHSExpr) { 8111 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8112 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8113 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8114 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8115 << FixItHint::CreateInsertion(EndLoc, "]"); 8116 } else 8117 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8118 } 8119 8120 /// \brief Emit a warning when adding a char literal to a string. 8121 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8122 Expr *LHSExpr, Expr *RHSExpr) { 8123 const Expr *StringRefExpr = LHSExpr; 8124 const CharacterLiteral *CharExpr = 8125 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8126 8127 if (!CharExpr) { 8128 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8129 StringRefExpr = RHSExpr; 8130 } 8131 8132 if (!CharExpr || !StringRefExpr) 8133 return; 8134 8135 const QualType StringType = StringRefExpr->getType(); 8136 8137 // Return if not a PointerType. 8138 if (!StringType->isAnyPointerType()) 8139 return; 8140 8141 // Return if not a CharacterType. 8142 if (!StringType->getPointeeType()->isAnyCharacterType()) 8143 return; 8144 8145 ASTContext &Ctx = Self.getASTContext(); 8146 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8147 8148 const QualType CharType = CharExpr->getType(); 8149 if (!CharType->isAnyCharacterType() && 8150 CharType->isIntegerType() && 8151 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8152 Self.Diag(OpLoc, diag::warn_string_plus_char) 8153 << DiagRange << Ctx.CharTy; 8154 } else { 8155 Self.Diag(OpLoc, diag::warn_string_plus_char) 8156 << DiagRange << CharExpr->getType(); 8157 } 8158 8159 // Only print a fixit for str + char, not for char + str. 8160 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8161 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8162 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8163 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8164 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8165 << FixItHint::CreateInsertion(EndLoc, "]"); 8166 } else { 8167 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8168 } 8169 } 8170 8171 /// \brief Emit error when two pointers are incompatible. 8172 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8173 Expr *LHSExpr, Expr *RHSExpr) { 8174 assert(LHSExpr->getType()->isAnyPointerType()); 8175 assert(RHSExpr->getType()->isAnyPointerType()); 8176 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8177 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8178 << RHSExpr->getSourceRange(); 8179 } 8180 8181 // C99 6.5.6 8182 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8183 SourceLocation Loc, BinaryOperatorKind Opc, 8184 QualType* CompLHSTy) { 8185 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8186 8187 if (LHS.get()->getType()->isVectorType() || 8188 RHS.get()->getType()->isVectorType()) { 8189 QualType compType = CheckVectorOperands( 8190 LHS, RHS, Loc, CompLHSTy, 8191 /*AllowBothBool*/getLangOpts().AltiVec, 8192 /*AllowBoolConversions*/getLangOpts().ZVector); 8193 if (CompLHSTy) *CompLHSTy = compType; 8194 return compType; 8195 } 8196 8197 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8198 if (LHS.isInvalid() || RHS.isInvalid()) 8199 return QualType(); 8200 8201 // Diagnose "string literal" '+' int and string '+' "char literal". 8202 if (Opc == BO_Add) { 8203 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8204 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8205 } 8206 8207 // handle the common case first (both operands are arithmetic). 8208 if (!compType.isNull() && compType->isArithmeticType()) { 8209 if (CompLHSTy) *CompLHSTy = compType; 8210 return compType; 8211 } 8212 8213 // Type-checking. Ultimately the pointer's going to be in PExp; 8214 // note that we bias towards the LHS being the pointer. 8215 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8216 8217 bool isObjCPointer; 8218 if (PExp->getType()->isPointerType()) { 8219 isObjCPointer = false; 8220 } else if (PExp->getType()->isObjCObjectPointerType()) { 8221 isObjCPointer = true; 8222 } else { 8223 std::swap(PExp, IExp); 8224 if (PExp->getType()->isPointerType()) { 8225 isObjCPointer = false; 8226 } else if (PExp->getType()->isObjCObjectPointerType()) { 8227 isObjCPointer = true; 8228 } else { 8229 return InvalidOperands(Loc, LHS, RHS); 8230 } 8231 } 8232 assert(PExp->getType()->isAnyPointerType()); 8233 8234 if (!IExp->getType()->isIntegerType()) 8235 return InvalidOperands(Loc, LHS, RHS); 8236 8237 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8238 return QualType(); 8239 8240 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8241 return QualType(); 8242 8243 // Check array bounds for pointer arithemtic 8244 CheckArrayAccess(PExp, IExp); 8245 8246 if (CompLHSTy) { 8247 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8248 if (LHSTy.isNull()) { 8249 LHSTy = LHS.get()->getType(); 8250 if (LHSTy->isPromotableIntegerType()) 8251 LHSTy = Context.getPromotedIntegerType(LHSTy); 8252 } 8253 *CompLHSTy = LHSTy; 8254 } 8255 8256 return PExp->getType(); 8257 } 8258 8259 // C99 6.5.6 8260 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8261 SourceLocation Loc, 8262 QualType* CompLHSTy) { 8263 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8264 8265 if (LHS.get()->getType()->isVectorType() || 8266 RHS.get()->getType()->isVectorType()) { 8267 QualType compType = CheckVectorOperands( 8268 LHS, RHS, Loc, CompLHSTy, 8269 /*AllowBothBool*/getLangOpts().AltiVec, 8270 /*AllowBoolConversions*/getLangOpts().ZVector); 8271 if (CompLHSTy) *CompLHSTy = compType; 8272 return compType; 8273 } 8274 8275 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8276 if (LHS.isInvalid() || RHS.isInvalid()) 8277 return QualType(); 8278 8279 // Enforce type constraints: C99 6.5.6p3. 8280 8281 // Handle the common case first (both operands are arithmetic). 8282 if (!compType.isNull() && compType->isArithmeticType()) { 8283 if (CompLHSTy) *CompLHSTy = compType; 8284 return compType; 8285 } 8286 8287 // Either ptr - int or ptr - ptr. 8288 if (LHS.get()->getType()->isAnyPointerType()) { 8289 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8290 8291 // Diagnose bad cases where we step over interface counts. 8292 if (LHS.get()->getType()->isObjCObjectPointerType() && 8293 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8294 return QualType(); 8295 8296 // The result type of a pointer-int computation is the pointer type. 8297 if (RHS.get()->getType()->isIntegerType()) { 8298 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8299 return QualType(); 8300 8301 // Check array bounds for pointer arithemtic 8302 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8303 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8304 8305 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8306 return LHS.get()->getType(); 8307 } 8308 8309 // Handle pointer-pointer subtractions. 8310 if (const PointerType *RHSPTy 8311 = RHS.get()->getType()->getAs<PointerType>()) { 8312 QualType rpointee = RHSPTy->getPointeeType(); 8313 8314 if (getLangOpts().CPlusPlus) { 8315 // Pointee types must be the same: C++ [expr.add] 8316 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8317 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8318 } 8319 } else { 8320 // Pointee types must be compatible C99 6.5.6p3 8321 if (!Context.typesAreCompatible( 8322 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8323 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8324 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8325 return QualType(); 8326 } 8327 } 8328 8329 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8330 LHS.get(), RHS.get())) 8331 return QualType(); 8332 8333 // The pointee type may have zero size. As an extension, a structure or 8334 // union may have zero size or an array may have zero length. In this 8335 // case subtraction does not make sense. 8336 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8337 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8338 if (ElementSize.isZero()) { 8339 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8340 << rpointee.getUnqualifiedType() 8341 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8342 } 8343 } 8344 8345 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8346 return Context.getPointerDiffType(); 8347 } 8348 } 8349 8350 return InvalidOperands(Loc, LHS, RHS); 8351 } 8352 8353 static bool isScopedEnumerationType(QualType T) { 8354 if (const EnumType *ET = T->getAs<EnumType>()) 8355 return ET->getDecl()->isScoped(); 8356 return false; 8357 } 8358 8359 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8360 SourceLocation Loc, BinaryOperatorKind Opc, 8361 QualType LHSType) { 8362 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8363 // so skip remaining warnings as we don't want to modify values within Sema. 8364 if (S.getLangOpts().OpenCL) 8365 return; 8366 8367 llvm::APSInt Right; 8368 // Check right/shifter operand 8369 if (RHS.get()->isValueDependent() || 8370 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8371 return; 8372 8373 if (Right.isNegative()) { 8374 S.DiagRuntimeBehavior(Loc, RHS.get(), 8375 S.PDiag(diag::warn_shift_negative) 8376 << RHS.get()->getSourceRange()); 8377 return; 8378 } 8379 llvm::APInt LeftBits(Right.getBitWidth(), 8380 S.Context.getTypeSize(LHS.get()->getType())); 8381 if (Right.uge(LeftBits)) { 8382 S.DiagRuntimeBehavior(Loc, RHS.get(), 8383 S.PDiag(diag::warn_shift_gt_typewidth) 8384 << RHS.get()->getSourceRange()); 8385 return; 8386 } 8387 if (Opc != BO_Shl) 8388 return; 8389 8390 // When left shifting an ICE which is signed, we can check for overflow which 8391 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8392 // integers have defined behavior modulo one more than the maximum value 8393 // representable in the result type, so never warn for those. 8394 llvm::APSInt Left; 8395 if (LHS.get()->isValueDependent() || 8396 LHSType->hasUnsignedIntegerRepresentation() || 8397 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8398 return; 8399 8400 // If LHS does not have a signed type and non-negative value 8401 // then, the behavior is undefined. Warn about it. 8402 if (Left.isNegative()) { 8403 S.DiagRuntimeBehavior(Loc, LHS.get(), 8404 S.PDiag(diag::warn_shift_lhs_negative) 8405 << LHS.get()->getSourceRange()); 8406 return; 8407 } 8408 8409 llvm::APInt ResultBits = 8410 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8411 if (LeftBits.uge(ResultBits)) 8412 return; 8413 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8414 Result = Result.shl(Right); 8415 8416 // Print the bit representation of the signed integer as an unsigned 8417 // hexadecimal number. 8418 SmallString<40> HexResult; 8419 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8420 8421 // If we are only missing a sign bit, this is less likely to result in actual 8422 // bugs -- if the result is cast back to an unsigned type, it will have the 8423 // expected value. Thus we place this behind a different warning that can be 8424 // turned off separately if needed. 8425 if (LeftBits == ResultBits - 1) { 8426 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8427 << HexResult << LHSType 8428 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8429 return; 8430 } 8431 8432 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8433 << HexResult.str() << Result.getMinSignedBits() << LHSType 8434 << Left.getBitWidth() << LHS.get()->getSourceRange() 8435 << RHS.get()->getSourceRange(); 8436 } 8437 8438 /// \brief Return the resulting type when an OpenCL vector is shifted 8439 /// by a scalar or vector shift amount. 8440 static QualType checkOpenCLVectorShift(Sema &S, 8441 ExprResult &LHS, ExprResult &RHS, 8442 SourceLocation Loc, bool IsCompAssign) { 8443 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8444 if (!LHS.get()->getType()->isVectorType()) { 8445 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8446 << RHS.get()->getType() << LHS.get()->getType() 8447 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8448 return QualType(); 8449 } 8450 8451 if (!IsCompAssign) { 8452 LHS = S.UsualUnaryConversions(LHS.get()); 8453 if (LHS.isInvalid()) return QualType(); 8454 } 8455 8456 RHS = S.UsualUnaryConversions(RHS.get()); 8457 if (RHS.isInvalid()) return QualType(); 8458 8459 QualType LHSType = LHS.get()->getType(); 8460 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8461 QualType LHSEleType = LHSVecTy->getElementType(); 8462 8463 // Note that RHS might not be a vector. 8464 QualType RHSType = RHS.get()->getType(); 8465 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8466 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8467 8468 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8469 if (!LHSEleType->isIntegerType()) { 8470 S.Diag(Loc, diag::err_typecheck_expect_int) 8471 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8472 return QualType(); 8473 } 8474 8475 if (!RHSEleType->isIntegerType()) { 8476 S.Diag(Loc, diag::err_typecheck_expect_int) 8477 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8478 return QualType(); 8479 } 8480 8481 if (RHSVecTy) { 8482 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8483 // are applied component-wise. So if RHS is a vector, then ensure 8484 // that the number of elements is the same as LHS... 8485 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8486 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8487 << LHS.get()->getType() << RHS.get()->getType() 8488 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8489 return QualType(); 8490 } 8491 } else { 8492 // ...else expand RHS to match the number of elements in LHS. 8493 QualType VecTy = 8494 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8495 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8496 } 8497 8498 return LHSType; 8499 } 8500 8501 // C99 6.5.7 8502 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8503 SourceLocation Loc, BinaryOperatorKind Opc, 8504 bool IsCompAssign) { 8505 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8506 8507 // Vector shifts promote their scalar inputs to vector type. 8508 if (LHS.get()->getType()->isVectorType() || 8509 RHS.get()->getType()->isVectorType()) { 8510 if (LangOpts.OpenCL) 8511 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8512 if (LangOpts.ZVector) { 8513 // The shift operators for the z vector extensions work basically 8514 // like OpenCL shifts, except that neither the LHS nor the RHS is 8515 // allowed to be a "vector bool". 8516 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8517 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8518 return InvalidOperands(Loc, LHS, RHS); 8519 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8520 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8521 return InvalidOperands(Loc, LHS, RHS); 8522 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8523 } 8524 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8525 /*AllowBothBool*/true, 8526 /*AllowBoolConversions*/false); 8527 } 8528 8529 // Shifts don't perform usual arithmetic conversions, they just do integer 8530 // promotions on each operand. C99 6.5.7p3 8531 8532 // For the LHS, do usual unary conversions, but then reset them away 8533 // if this is a compound assignment. 8534 ExprResult OldLHS = LHS; 8535 LHS = UsualUnaryConversions(LHS.get()); 8536 if (LHS.isInvalid()) 8537 return QualType(); 8538 QualType LHSType = LHS.get()->getType(); 8539 if (IsCompAssign) LHS = OldLHS; 8540 8541 // The RHS is simpler. 8542 RHS = UsualUnaryConversions(RHS.get()); 8543 if (RHS.isInvalid()) 8544 return QualType(); 8545 QualType RHSType = RHS.get()->getType(); 8546 8547 // C99 6.5.7p2: Each of the operands shall have integer type. 8548 if (!LHSType->hasIntegerRepresentation() || 8549 !RHSType->hasIntegerRepresentation()) 8550 return InvalidOperands(Loc, LHS, RHS); 8551 8552 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8553 // hasIntegerRepresentation() above instead of this. 8554 if (isScopedEnumerationType(LHSType) || 8555 isScopedEnumerationType(RHSType)) { 8556 return InvalidOperands(Loc, LHS, RHS); 8557 } 8558 // Sanity-check shift operands 8559 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8560 8561 // "The type of the result is that of the promoted left operand." 8562 return LHSType; 8563 } 8564 8565 static bool IsWithinTemplateSpecialization(Decl *D) { 8566 if (DeclContext *DC = D->getDeclContext()) { 8567 if (isa<ClassTemplateSpecializationDecl>(DC)) 8568 return true; 8569 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8570 return FD->isFunctionTemplateSpecialization(); 8571 } 8572 return false; 8573 } 8574 8575 /// If two different enums are compared, raise a warning. 8576 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8577 Expr *RHS) { 8578 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8579 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8580 8581 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8582 if (!LHSEnumType) 8583 return; 8584 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8585 if (!RHSEnumType) 8586 return; 8587 8588 // Ignore anonymous enums. 8589 if (!LHSEnumType->getDecl()->getIdentifier()) 8590 return; 8591 if (!RHSEnumType->getDecl()->getIdentifier()) 8592 return; 8593 8594 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8595 return; 8596 8597 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8598 << LHSStrippedType << RHSStrippedType 8599 << LHS->getSourceRange() << RHS->getSourceRange(); 8600 } 8601 8602 /// \brief Diagnose bad pointer comparisons. 8603 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8604 ExprResult &LHS, ExprResult &RHS, 8605 bool IsError) { 8606 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8607 : diag::ext_typecheck_comparison_of_distinct_pointers) 8608 << LHS.get()->getType() << RHS.get()->getType() 8609 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8610 } 8611 8612 /// \brief Returns false if the pointers are converted to a composite type, 8613 /// true otherwise. 8614 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8615 ExprResult &LHS, ExprResult &RHS) { 8616 // C++ [expr.rel]p2: 8617 // [...] Pointer conversions (4.10) and qualification 8618 // conversions (4.4) are performed on pointer operands (or on 8619 // a pointer operand and a null pointer constant) to bring 8620 // them to their composite pointer type. [...] 8621 // 8622 // C++ [expr.eq]p1 uses the same notion for (in)equality 8623 // comparisons of pointers. 8624 8625 // C++ [expr.eq]p2: 8626 // In addition, pointers to members can be compared, or a pointer to 8627 // member and a null pointer constant. Pointer to member conversions 8628 // (4.11) and qualification conversions (4.4) are performed to bring 8629 // them to a common type. If one operand is a null pointer constant, 8630 // the common type is the type of the other operand. Otherwise, the 8631 // common type is a pointer to member type similar (4.4) to the type 8632 // of one of the operands, with a cv-qualification signature (4.4) 8633 // that is the union of the cv-qualification signatures of the operand 8634 // types. 8635 8636 QualType LHSType = LHS.get()->getType(); 8637 QualType RHSType = RHS.get()->getType(); 8638 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8639 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8640 8641 bool NonStandardCompositeType = false; 8642 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8643 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8644 if (T.isNull()) { 8645 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8646 return true; 8647 } 8648 8649 if (NonStandardCompositeType) 8650 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8651 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8652 << RHS.get()->getSourceRange(); 8653 8654 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8655 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8656 return false; 8657 } 8658 8659 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8660 ExprResult &LHS, 8661 ExprResult &RHS, 8662 bool IsError) { 8663 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8664 : diag::ext_typecheck_comparison_of_fptr_to_void) 8665 << LHS.get()->getType() << RHS.get()->getType() 8666 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8667 } 8668 8669 static bool isObjCObjectLiteral(ExprResult &E) { 8670 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8671 case Stmt::ObjCArrayLiteralClass: 8672 case Stmt::ObjCDictionaryLiteralClass: 8673 case Stmt::ObjCStringLiteralClass: 8674 case Stmt::ObjCBoxedExprClass: 8675 return true; 8676 default: 8677 // Note that ObjCBoolLiteral is NOT an object literal! 8678 return false; 8679 } 8680 } 8681 8682 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8683 const ObjCObjectPointerType *Type = 8684 LHS->getType()->getAs<ObjCObjectPointerType>(); 8685 8686 // If this is not actually an Objective-C object, bail out. 8687 if (!Type) 8688 return false; 8689 8690 // Get the LHS object's interface type. 8691 QualType InterfaceType = Type->getPointeeType(); 8692 8693 // If the RHS isn't an Objective-C object, bail out. 8694 if (!RHS->getType()->isObjCObjectPointerType()) 8695 return false; 8696 8697 // Try to find the -isEqual: method. 8698 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8699 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8700 InterfaceType, 8701 /*instance=*/true); 8702 if (!Method) { 8703 if (Type->isObjCIdType()) { 8704 // For 'id', just check the global pool. 8705 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8706 /*receiverId=*/true); 8707 } else { 8708 // Check protocols. 8709 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8710 /*instance=*/true); 8711 } 8712 } 8713 8714 if (!Method) 8715 return false; 8716 8717 QualType T = Method->parameters()[0]->getType(); 8718 if (!T->isObjCObjectPointerType()) 8719 return false; 8720 8721 QualType R = Method->getReturnType(); 8722 if (!R->isScalarType()) 8723 return false; 8724 8725 return true; 8726 } 8727 8728 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8729 FromE = FromE->IgnoreParenImpCasts(); 8730 switch (FromE->getStmtClass()) { 8731 default: 8732 break; 8733 case Stmt::ObjCStringLiteralClass: 8734 // "string literal" 8735 return LK_String; 8736 case Stmt::ObjCArrayLiteralClass: 8737 // "array literal" 8738 return LK_Array; 8739 case Stmt::ObjCDictionaryLiteralClass: 8740 // "dictionary literal" 8741 return LK_Dictionary; 8742 case Stmt::BlockExprClass: 8743 return LK_Block; 8744 case Stmt::ObjCBoxedExprClass: { 8745 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8746 switch (Inner->getStmtClass()) { 8747 case Stmt::IntegerLiteralClass: 8748 case Stmt::FloatingLiteralClass: 8749 case Stmt::CharacterLiteralClass: 8750 case Stmt::ObjCBoolLiteralExprClass: 8751 case Stmt::CXXBoolLiteralExprClass: 8752 // "numeric literal" 8753 return LK_Numeric; 8754 case Stmt::ImplicitCastExprClass: { 8755 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8756 // Boolean literals can be represented by implicit casts. 8757 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8758 return LK_Numeric; 8759 break; 8760 } 8761 default: 8762 break; 8763 } 8764 return LK_Boxed; 8765 } 8766 } 8767 return LK_None; 8768 } 8769 8770 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8771 ExprResult &LHS, ExprResult &RHS, 8772 BinaryOperator::Opcode Opc){ 8773 Expr *Literal; 8774 Expr *Other; 8775 if (isObjCObjectLiteral(LHS)) { 8776 Literal = LHS.get(); 8777 Other = RHS.get(); 8778 } else { 8779 Literal = RHS.get(); 8780 Other = LHS.get(); 8781 } 8782 8783 // Don't warn on comparisons against nil. 8784 Other = Other->IgnoreParenCasts(); 8785 if (Other->isNullPointerConstant(S.getASTContext(), 8786 Expr::NPC_ValueDependentIsNotNull)) 8787 return; 8788 8789 // This should be kept in sync with warn_objc_literal_comparison. 8790 // LK_String should always be after the other literals, since it has its own 8791 // warning flag. 8792 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8793 assert(LiteralKind != Sema::LK_Block); 8794 if (LiteralKind == Sema::LK_None) { 8795 llvm_unreachable("Unknown Objective-C object literal kind"); 8796 } 8797 8798 if (LiteralKind == Sema::LK_String) 8799 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8800 << Literal->getSourceRange(); 8801 else 8802 S.Diag(Loc, diag::warn_objc_literal_comparison) 8803 << LiteralKind << Literal->getSourceRange(); 8804 8805 if (BinaryOperator::isEqualityOp(Opc) && 8806 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8807 SourceLocation Start = LHS.get()->getLocStart(); 8808 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 8809 CharSourceRange OpRange = 8810 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 8811 8812 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8813 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8814 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8815 << FixItHint::CreateInsertion(End, "]"); 8816 } 8817 } 8818 8819 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8820 ExprResult &RHS, 8821 SourceLocation Loc, 8822 BinaryOperatorKind Opc) { 8823 // Check that left hand side is !something. 8824 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8825 if (!UO || UO->getOpcode() != UO_LNot) return; 8826 8827 // Only check if the right hand side is non-bool arithmetic type. 8828 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8829 8830 // Make sure that the something in !something is not bool. 8831 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8832 if (SubExpr->isKnownToHaveBooleanValue()) return; 8833 8834 // Emit warning. 8835 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8836 << Loc; 8837 8838 // First note suggest !(x < y) 8839 SourceLocation FirstOpen = SubExpr->getLocStart(); 8840 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8841 FirstClose = S.getLocForEndOfToken(FirstClose); 8842 if (FirstClose.isInvalid()) 8843 FirstOpen = SourceLocation(); 8844 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8845 << FixItHint::CreateInsertion(FirstOpen, "(") 8846 << FixItHint::CreateInsertion(FirstClose, ")"); 8847 8848 // Second note suggests (!x) < y 8849 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8850 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8851 SecondClose = S.getLocForEndOfToken(SecondClose); 8852 if (SecondClose.isInvalid()) 8853 SecondOpen = SourceLocation(); 8854 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8855 << FixItHint::CreateInsertion(SecondOpen, "(") 8856 << FixItHint::CreateInsertion(SecondClose, ")"); 8857 } 8858 8859 // Get the decl for a simple expression: a reference to a variable, 8860 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8861 static ValueDecl *getCompareDecl(Expr *E) { 8862 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8863 return DR->getDecl(); 8864 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8865 if (Ivar->isFreeIvar()) 8866 return Ivar->getDecl(); 8867 } 8868 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8869 if (Mem->isImplicitAccess()) 8870 return Mem->getMemberDecl(); 8871 } 8872 return nullptr; 8873 } 8874 8875 // C99 6.5.8, C++ [expr.rel] 8876 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8877 SourceLocation Loc, BinaryOperatorKind Opc, 8878 bool IsRelational) { 8879 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8880 8881 // Handle vector comparisons separately. 8882 if (LHS.get()->getType()->isVectorType() || 8883 RHS.get()->getType()->isVectorType()) 8884 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8885 8886 QualType LHSType = LHS.get()->getType(); 8887 QualType RHSType = RHS.get()->getType(); 8888 8889 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8890 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8891 8892 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8893 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 8894 8895 if (!LHSType->hasFloatingRepresentation() && 8896 !(LHSType->isBlockPointerType() && IsRelational) && 8897 !LHS.get()->getLocStart().isMacroID() && 8898 !RHS.get()->getLocStart().isMacroID() && 8899 ActiveTemplateInstantiations.empty()) { 8900 // For non-floating point types, check for self-comparisons of the form 8901 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8902 // often indicate logic errors in the program. 8903 // 8904 // NOTE: Don't warn about comparison expressions resulting from macro 8905 // expansion. Also don't warn about comparisons which are only self 8906 // comparisons within a template specialization. The warnings should catch 8907 // obvious cases in the definition of the template anyways. The idea is to 8908 // warn when the typed comparison operator will always evaluate to the same 8909 // result. 8910 ValueDecl *DL = getCompareDecl(LHSStripped); 8911 ValueDecl *DR = getCompareDecl(RHSStripped); 8912 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8913 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8914 << 0 // self- 8915 << (Opc == BO_EQ 8916 || Opc == BO_LE 8917 || Opc == BO_GE)); 8918 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8919 !DL->getType()->isReferenceType() && 8920 !DR->getType()->isReferenceType()) { 8921 // what is it always going to eval to? 8922 char always_evals_to; 8923 switch(Opc) { 8924 case BO_EQ: // e.g. array1 == array2 8925 always_evals_to = 0; // false 8926 break; 8927 case BO_NE: // e.g. array1 != array2 8928 always_evals_to = 1; // true 8929 break; 8930 default: 8931 // best we can say is 'a constant' 8932 always_evals_to = 2; // e.g. array1 <= array2 8933 break; 8934 } 8935 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8936 << 1 // array 8937 << always_evals_to); 8938 } 8939 8940 if (isa<CastExpr>(LHSStripped)) 8941 LHSStripped = LHSStripped->IgnoreParenCasts(); 8942 if (isa<CastExpr>(RHSStripped)) 8943 RHSStripped = RHSStripped->IgnoreParenCasts(); 8944 8945 // Warn about comparisons against a string constant (unless the other 8946 // operand is null), the user probably wants strcmp. 8947 Expr *literalString = nullptr; 8948 Expr *literalStringStripped = nullptr; 8949 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8950 !RHSStripped->isNullPointerConstant(Context, 8951 Expr::NPC_ValueDependentIsNull)) { 8952 literalString = LHS.get(); 8953 literalStringStripped = LHSStripped; 8954 } else if ((isa<StringLiteral>(RHSStripped) || 8955 isa<ObjCEncodeExpr>(RHSStripped)) && 8956 !LHSStripped->isNullPointerConstant(Context, 8957 Expr::NPC_ValueDependentIsNull)) { 8958 literalString = RHS.get(); 8959 literalStringStripped = RHSStripped; 8960 } 8961 8962 if (literalString) { 8963 DiagRuntimeBehavior(Loc, nullptr, 8964 PDiag(diag::warn_stringcompare) 8965 << isa<ObjCEncodeExpr>(literalStringStripped) 8966 << literalString->getSourceRange()); 8967 } 8968 } 8969 8970 // C99 6.5.8p3 / C99 6.5.9p4 8971 UsualArithmeticConversions(LHS, RHS); 8972 if (LHS.isInvalid() || RHS.isInvalid()) 8973 return QualType(); 8974 8975 LHSType = LHS.get()->getType(); 8976 RHSType = RHS.get()->getType(); 8977 8978 // The result of comparisons is 'bool' in C++, 'int' in C. 8979 QualType ResultTy = Context.getLogicalOperationType(); 8980 8981 if (IsRelational) { 8982 if (LHSType->isRealType() && RHSType->isRealType()) 8983 return ResultTy; 8984 } else { 8985 // Check for comparisons of floating point operands using != and ==. 8986 if (LHSType->hasFloatingRepresentation()) 8987 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8988 8989 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8990 return ResultTy; 8991 } 8992 8993 const Expr::NullPointerConstantKind LHSNullKind = 8994 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8995 const Expr::NullPointerConstantKind RHSNullKind = 8996 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8997 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8998 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8999 9000 if (!IsRelational && LHSIsNull != RHSIsNull) { 9001 bool IsEquality = Opc == BO_EQ; 9002 if (RHSIsNull) 9003 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9004 RHS.get()->getSourceRange()); 9005 else 9006 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9007 LHS.get()->getSourceRange()); 9008 } 9009 9010 // All of the following pointer-related warnings are GCC extensions, except 9011 // when handling null pointer constants. 9012 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9013 QualType LCanPointeeTy = 9014 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9015 QualType RCanPointeeTy = 9016 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9017 9018 if (getLangOpts().CPlusPlus) { 9019 if (LCanPointeeTy == RCanPointeeTy) 9020 return ResultTy; 9021 if (!IsRelational && 9022 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9023 // Valid unless comparison between non-null pointer and function pointer 9024 // This is a gcc extension compatibility comparison. 9025 // In a SFINAE context, we treat this as a hard error to maintain 9026 // conformance with the C++ standard. 9027 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9028 && !LHSIsNull && !RHSIsNull) { 9029 diagnoseFunctionPointerToVoidComparison( 9030 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9031 9032 if (isSFINAEContext()) 9033 return QualType(); 9034 9035 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9036 return ResultTy; 9037 } 9038 } 9039 9040 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9041 return QualType(); 9042 else 9043 return ResultTy; 9044 } 9045 // C99 6.5.9p2 and C99 6.5.8p2 9046 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9047 RCanPointeeTy.getUnqualifiedType())) { 9048 // Valid unless a relational comparison of function pointers 9049 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9050 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9051 << LHSType << RHSType << LHS.get()->getSourceRange() 9052 << RHS.get()->getSourceRange(); 9053 } 9054 } else if (!IsRelational && 9055 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9056 // Valid unless comparison between non-null pointer and function pointer 9057 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9058 && !LHSIsNull && !RHSIsNull) 9059 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9060 /*isError*/false); 9061 } else { 9062 // Invalid 9063 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9064 } 9065 if (LCanPointeeTy != RCanPointeeTy) { 9066 // Treat NULL constant as a special case in OpenCL. 9067 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9068 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9069 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9070 Diag(Loc, 9071 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9072 << LHSType << RHSType << 0 /* comparison */ 9073 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9074 } 9075 } 9076 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9077 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9078 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9079 : CK_BitCast; 9080 if (LHSIsNull && !RHSIsNull) 9081 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9082 else 9083 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9084 } 9085 return ResultTy; 9086 } 9087 9088 if (getLangOpts().CPlusPlus) { 9089 // Comparison of nullptr_t with itself. 9090 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9091 return ResultTy; 9092 9093 // Comparison of pointers with null pointer constants and equality 9094 // comparisons of member pointers to null pointer constants. 9095 if (RHSIsNull && 9096 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9097 (!IsRelational && 9098 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9099 RHS = ImpCastExprToType(RHS.get(), LHSType, 9100 LHSType->isMemberPointerType() 9101 ? CK_NullToMemberPointer 9102 : CK_NullToPointer); 9103 return ResultTy; 9104 } 9105 if (LHSIsNull && 9106 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9107 (!IsRelational && 9108 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9109 LHS = ImpCastExprToType(LHS.get(), RHSType, 9110 RHSType->isMemberPointerType() 9111 ? CK_NullToMemberPointer 9112 : CK_NullToPointer); 9113 return ResultTy; 9114 } 9115 9116 // Comparison of member pointers. 9117 if (!IsRelational && 9118 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9119 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9120 return QualType(); 9121 else 9122 return ResultTy; 9123 } 9124 9125 // Handle scoped enumeration types specifically, since they don't promote 9126 // to integers. 9127 if (LHS.get()->getType()->isEnumeralType() && 9128 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9129 RHS.get()->getType())) 9130 return ResultTy; 9131 } 9132 9133 // Handle block pointer types. 9134 if (!IsRelational && LHSType->isBlockPointerType() && 9135 RHSType->isBlockPointerType()) { 9136 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9137 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9138 9139 if (!LHSIsNull && !RHSIsNull && 9140 !Context.typesAreCompatible(lpointee, rpointee)) { 9141 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9142 << LHSType << RHSType << LHS.get()->getSourceRange() 9143 << RHS.get()->getSourceRange(); 9144 } 9145 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9146 return ResultTy; 9147 } 9148 9149 // Allow block pointers to be compared with null pointer constants. 9150 if (!IsRelational 9151 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9152 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9153 if (!LHSIsNull && !RHSIsNull) { 9154 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9155 ->getPointeeType()->isVoidType()) 9156 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9157 ->getPointeeType()->isVoidType()))) 9158 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9159 << LHSType << RHSType << LHS.get()->getSourceRange() 9160 << RHS.get()->getSourceRange(); 9161 } 9162 if (LHSIsNull && !RHSIsNull) 9163 LHS = ImpCastExprToType(LHS.get(), RHSType, 9164 RHSType->isPointerType() ? CK_BitCast 9165 : CK_AnyPointerToBlockPointerCast); 9166 else 9167 RHS = ImpCastExprToType(RHS.get(), LHSType, 9168 LHSType->isPointerType() ? CK_BitCast 9169 : CK_AnyPointerToBlockPointerCast); 9170 return ResultTy; 9171 } 9172 9173 if (LHSType->isObjCObjectPointerType() || 9174 RHSType->isObjCObjectPointerType()) { 9175 const PointerType *LPT = LHSType->getAs<PointerType>(); 9176 const PointerType *RPT = RHSType->getAs<PointerType>(); 9177 if (LPT || RPT) { 9178 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9179 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9180 9181 if (!LPtrToVoid && !RPtrToVoid && 9182 !Context.typesAreCompatible(LHSType, RHSType)) { 9183 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9184 /*isError*/false); 9185 } 9186 if (LHSIsNull && !RHSIsNull) { 9187 Expr *E = LHS.get(); 9188 if (getLangOpts().ObjCAutoRefCount) 9189 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9190 LHS = ImpCastExprToType(E, RHSType, 9191 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9192 } 9193 else { 9194 Expr *E = RHS.get(); 9195 if (getLangOpts().ObjCAutoRefCount) 9196 CheckObjCARCConversion(SourceRange(), LHSType, E, 9197 CCK_ImplicitConversion, /*Diagnose=*/true, 9198 /*DiagnoseCFAudited=*/false, Opc); 9199 RHS = ImpCastExprToType(E, LHSType, 9200 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9201 } 9202 return ResultTy; 9203 } 9204 if (LHSType->isObjCObjectPointerType() && 9205 RHSType->isObjCObjectPointerType()) { 9206 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9207 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9208 /*isError*/false); 9209 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9210 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9211 9212 if (LHSIsNull && !RHSIsNull) 9213 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9214 else 9215 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9216 return ResultTy; 9217 } 9218 } 9219 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9220 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9221 unsigned DiagID = 0; 9222 bool isError = false; 9223 if (LangOpts.DebuggerSupport) { 9224 // Under a debugger, allow the comparison of pointers to integers, 9225 // since users tend to want to compare addresses. 9226 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9227 (RHSIsNull && RHSType->isIntegerType())) { 9228 if (IsRelational && !getLangOpts().CPlusPlus) 9229 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9230 } else if (IsRelational && !getLangOpts().CPlusPlus) 9231 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9232 else if (getLangOpts().CPlusPlus) { 9233 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9234 isError = true; 9235 } else 9236 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9237 9238 if (DiagID) { 9239 Diag(Loc, DiagID) 9240 << LHSType << RHSType << LHS.get()->getSourceRange() 9241 << RHS.get()->getSourceRange(); 9242 if (isError) 9243 return QualType(); 9244 } 9245 9246 if (LHSType->isIntegerType()) 9247 LHS = ImpCastExprToType(LHS.get(), RHSType, 9248 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9249 else 9250 RHS = ImpCastExprToType(RHS.get(), LHSType, 9251 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9252 return ResultTy; 9253 } 9254 9255 // Handle block pointers. 9256 if (!IsRelational && RHSIsNull 9257 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9258 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9259 return ResultTy; 9260 } 9261 if (!IsRelational && LHSIsNull 9262 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9263 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9264 return ResultTy; 9265 } 9266 9267 return InvalidOperands(Loc, LHS, RHS); 9268 } 9269 9270 9271 // Return a signed type that is of identical size and number of elements. 9272 // For floating point vectors, return an integer type of identical size 9273 // and number of elements. 9274 QualType Sema::GetSignedVectorType(QualType V) { 9275 const VectorType *VTy = V->getAs<VectorType>(); 9276 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9277 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9278 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9279 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9280 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9281 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9282 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9283 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9284 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9285 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9286 "Unhandled vector element size in vector compare"); 9287 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9288 } 9289 9290 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9291 /// operates on extended vector types. Instead of producing an IntTy result, 9292 /// like a scalar comparison, a vector comparison produces a vector of integer 9293 /// types. 9294 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9295 SourceLocation Loc, 9296 bool IsRelational) { 9297 // Check to make sure we're operating on vectors of the same type and width, 9298 // Allowing one side to be a scalar of element type. 9299 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9300 /*AllowBothBool*/true, 9301 /*AllowBoolConversions*/getLangOpts().ZVector); 9302 if (vType.isNull()) 9303 return vType; 9304 9305 QualType LHSType = LHS.get()->getType(); 9306 9307 // If AltiVec, the comparison results in a numeric type, i.e. 9308 // bool for C++, int for C 9309 if (getLangOpts().AltiVec && 9310 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9311 return Context.getLogicalOperationType(); 9312 9313 // For non-floating point types, check for self-comparisons of the form 9314 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9315 // often indicate logic errors in the program. 9316 if (!LHSType->hasFloatingRepresentation() && 9317 ActiveTemplateInstantiations.empty()) { 9318 if (DeclRefExpr* DRL 9319 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9320 if (DeclRefExpr* DRR 9321 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9322 if (DRL->getDecl() == DRR->getDecl()) 9323 DiagRuntimeBehavior(Loc, nullptr, 9324 PDiag(diag::warn_comparison_always) 9325 << 0 // self- 9326 << 2 // "a constant" 9327 ); 9328 } 9329 9330 // Check for comparisons of floating point operands using != and ==. 9331 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9332 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9333 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9334 } 9335 9336 // Return a signed type for the vector. 9337 return GetSignedVectorType(LHSType); 9338 } 9339 9340 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9341 SourceLocation Loc) { 9342 // Ensure that either both operands are of the same vector type, or 9343 // one operand is of a vector type and the other is of its element type. 9344 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9345 /*AllowBothBool*/true, 9346 /*AllowBoolConversions*/false); 9347 if (vType.isNull()) 9348 return InvalidOperands(Loc, LHS, RHS); 9349 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9350 vType->hasFloatingRepresentation()) 9351 return InvalidOperands(Loc, LHS, RHS); 9352 9353 return GetSignedVectorType(LHS.get()->getType()); 9354 } 9355 9356 inline QualType Sema::CheckBitwiseOperands( 9357 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9358 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9359 9360 if (LHS.get()->getType()->isVectorType() || 9361 RHS.get()->getType()->isVectorType()) { 9362 if (LHS.get()->getType()->hasIntegerRepresentation() && 9363 RHS.get()->getType()->hasIntegerRepresentation()) 9364 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9365 /*AllowBothBool*/true, 9366 /*AllowBoolConversions*/getLangOpts().ZVector); 9367 return InvalidOperands(Loc, LHS, RHS); 9368 } 9369 9370 ExprResult LHSResult = LHS, RHSResult = RHS; 9371 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9372 IsCompAssign); 9373 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9374 return QualType(); 9375 LHS = LHSResult.get(); 9376 RHS = RHSResult.get(); 9377 9378 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9379 return compType; 9380 return InvalidOperands(Loc, LHS, RHS); 9381 } 9382 9383 // C99 6.5.[13,14] 9384 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9385 SourceLocation Loc, 9386 BinaryOperatorKind Opc) { 9387 // Check vector operands differently. 9388 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9389 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9390 9391 // Diagnose cases where the user write a logical and/or but probably meant a 9392 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9393 // is a constant. 9394 if (LHS.get()->getType()->isIntegerType() && 9395 !LHS.get()->getType()->isBooleanType() && 9396 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9397 // Don't warn in macros or template instantiations. 9398 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9399 // If the RHS can be constant folded, and if it constant folds to something 9400 // that isn't 0 or 1 (which indicate a potential logical operation that 9401 // happened to fold to true/false) then warn. 9402 // Parens on the RHS are ignored. 9403 llvm::APSInt Result; 9404 if (RHS.get()->EvaluateAsInt(Result, Context)) 9405 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9406 !RHS.get()->getExprLoc().isMacroID()) || 9407 (Result != 0 && Result != 1)) { 9408 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9409 << RHS.get()->getSourceRange() 9410 << (Opc == BO_LAnd ? "&&" : "||"); 9411 // Suggest replacing the logical operator with the bitwise version 9412 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9413 << (Opc == BO_LAnd ? "&" : "|") 9414 << FixItHint::CreateReplacement(SourceRange( 9415 Loc, getLocForEndOfToken(Loc)), 9416 Opc == BO_LAnd ? "&" : "|"); 9417 if (Opc == BO_LAnd) 9418 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9419 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9420 << FixItHint::CreateRemoval( 9421 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9422 RHS.get()->getLocEnd())); 9423 } 9424 } 9425 9426 if (!Context.getLangOpts().CPlusPlus) { 9427 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9428 // not operate on the built-in scalar and vector float types. 9429 if (Context.getLangOpts().OpenCL && 9430 Context.getLangOpts().OpenCLVersion < 120) { 9431 if (LHS.get()->getType()->isFloatingType() || 9432 RHS.get()->getType()->isFloatingType()) 9433 return InvalidOperands(Loc, LHS, RHS); 9434 } 9435 9436 LHS = UsualUnaryConversions(LHS.get()); 9437 if (LHS.isInvalid()) 9438 return QualType(); 9439 9440 RHS = UsualUnaryConversions(RHS.get()); 9441 if (RHS.isInvalid()) 9442 return QualType(); 9443 9444 if (!LHS.get()->getType()->isScalarType() || 9445 !RHS.get()->getType()->isScalarType()) 9446 return InvalidOperands(Loc, LHS, RHS); 9447 9448 return Context.IntTy; 9449 } 9450 9451 // The following is safe because we only use this method for 9452 // non-overloadable operands. 9453 9454 // C++ [expr.log.and]p1 9455 // C++ [expr.log.or]p1 9456 // The operands are both contextually converted to type bool. 9457 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9458 if (LHSRes.isInvalid()) 9459 return InvalidOperands(Loc, LHS, RHS); 9460 LHS = LHSRes; 9461 9462 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9463 if (RHSRes.isInvalid()) 9464 return InvalidOperands(Loc, LHS, RHS); 9465 RHS = RHSRes; 9466 9467 // C++ [expr.log.and]p2 9468 // C++ [expr.log.or]p2 9469 // The result is a bool. 9470 return Context.BoolTy; 9471 } 9472 9473 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9474 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9475 if (!ME) return false; 9476 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9477 ObjCMessageExpr *Base = 9478 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9479 if (!Base) return false; 9480 return Base->getMethodDecl() != nullptr; 9481 } 9482 9483 /// Is the given expression (which must be 'const') a reference to a 9484 /// variable which was originally non-const, but which has become 9485 /// 'const' due to being captured within a block? 9486 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9487 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9488 assert(E->isLValue() && E->getType().isConstQualified()); 9489 E = E->IgnoreParens(); 9490 9491 // Must be a reference to a declaration from an enclosing scope. 9492 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9493 if (!DRE) return NCCK_None; 9494 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9495 9496 // The declaration must be a variable which is not declared 'const'. 9497 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9498 if (!var) return NCCK_None; 9499 if (var->getType().isConstQualified()) return NCCK_None; 9500 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9501 9502 // Decide whether the first capture was for a block or a lambda. 9503 DeclContext *DC = S.CurContext, *Prev = nullptr; 9504 while (DC != var->getDeclContext()) { 9505 Prev = DC; 9506 DC = DC->getParent(); 9507 } 9508 // Unless we have an init-capture, we've gone one step too far. 9509 if (!var->isInitCapture()) 9510 DC = Prev; 9511 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9512 } 9513 9514 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9515 Ty = Ty.getNonReferenceType(); 9516 if (IsDereference && Ty->isPointerType()) 9517 Ty = Ty->getPointeeType(); 9518 return !Ty.isConstQualified(); 9519 } 9520 9521 /// Emit the "read-only variable not assignable" error and print notes to give 9522 /// more information about why the variable is not assignable, such as pointing 9523 /// to the declaration of a const variable, showing that a method is const, or 9524 /// that the function is returning a const reference. 9525 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9526 SourceLocation Loc) { 9527 // Update err_typecheck_assign_const and note_typecheck_assign_const 9528 // when this enum is changed. 9529 enum { 9530 ConstFunction, 9531 ConstVariable, 9532 ConstMember, 9533 ConstMethod, 9534 ConstUnknown, // Keep as last element 9535 }; 9536 9537 SourceRange ExprRange = E->getSourceRange(); 9538 9539 // Only emit one error on the first const found. All other consts will emit 9540 // a note to the error. 9541 bool DiagnosticEmitted = false; 9542 9543 // Track if the current expression is the result of a derefence, and if the 9544 // next checked expression is the result of a derefence. 9545 bool IsDereference = false; 9546 bool NextIsDereference = false; 9547 9548 // Loop to process MemberExpr chains. 9549 while (true) { 9550 IsDereference = NextIsDereference; 9551 NextIsDereference = false; 9552 9553 E = E->IgnoreParenImpCasts(); 9554 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9555 NextIsDereference = ME->isArrow(); 9556 const ValueDecl *VD = ME->getMemberDecl(); 9557 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9558 // Mutable fields can be modified even if the class is const. 9559 if (Field->isMutable()) { 9560 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9561 break; 9562 } 9563 9564 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9565 if (!DiagnosticEmitted) { 9566 S.Diag(Loc, diag::err_typecheck_assign_const) 9567 << ExprRange << ConstMember << false /*static*/ << Field 9568 << Field->getType(); 9569 DiagnosticEmitted = true; 9570 } 9571 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9572 << ConstMember << false /*static*/ << Field << Field->getType() 9573 << Field->getSourceRange(); 9574 } 9575 E = ME->getBase(); 9576 continue; 9577 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9578 if (VDecl->getType().isConstQualified()) { 9579 if (!DiagnosticEmitted) { 9580 S.Diag(Loc, diag::err_typecheck_assign_const) 9581 << ExprRange << ConstMember << true /*static*/ << VDecl 9582 << VDecl->getType(); 9583 DiagnosticEmitted = true; 9584 } 9585 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9586 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9587 << VDecl->getSourceRange(); 9588 } 9589 // Static fields do not inherit constness from parents. 9590 break; 9591 } 9592 break; 9593 } // End MemberExpr 9594 break; 9595 } 9596 9597 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9598 // Function calls 9599 const FunctionDecl *FD = CE->getDirectCallee(); 9600 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9601 if (!DiagnosticEmitted) { 9602 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9603 << ConstFunction << FD; 9604 DiagnosticEmitted = true; 9605 } 9606 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9607 diag::note_typecheck_assign_const) 9608 << ConstFunction << FD << FD->getReturnType() 9609 << FD->getReturnTypeSourceRange(); 9610 } 9611 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9612 // Point to variable declaration. 9613 if (const ValueDecl *VD = DRE->getDecl()) { 9614 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9615 if (!DiagnosticEmitted) { 9616 S.Diag(Loc, diag::err_typecheck_assign_const) 9617 << ExprRange << ConstVariable << VD << VD->getType(); 9618 DiagnosticEmitted = true; 9619 } 9620 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9621 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9622 } 9623 } 9624 } else if (isa<CXXThisExpr>(E)) { 9625 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9626 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9627 if (MD->isConst()) { 9628 if (!DiagnosticEmitted) { 9629 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9630 << ConstMethod << MD; 9631 DiagnosticEmitted = true; 9632 } 9633 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9634 << ConstMethod << MD << MD->getSourceRange(); 9635 } 9636 } 9637 } 9638 } 9639 9640 if (DiagnosticEmitted) 9641 return; 9642 9643 // Can't determine a more specific message, so display the generic error. 9644 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9645 } 9646 9647 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9648 /// emit an error and return true. If so, return false. 9649 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9650 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9651 SourceLocation OrigLoc = Loc; 9652 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9653 &Loc); 9654 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9655 IsLV = Expr::MLV_InvalidMessageExpression; 9656 if (IsLV == Expr::MLV_Valid) 9657 return false; 9658 9659 unsigned DiagID = 0; 9660 bool NeedType = false; 9661 switch (IsLV) { // C99 6.5.16p2 9662 case Expr::MLV_ConstQualified: 9663 // Use a specialized diagnostic when we're assigning to an object 9664 // from an enclosing function or block. 9665 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9666 if (NCCK == NCCK_Block) 9667 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9668 else 9669 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9670 break; 9671 } 9672 9673 // In ARC, use some specialized diagnostics for occasions where we 9674 // infer 'const'. These are always pseudo-strong variables. 9675 if (S.getLangOpts().ObjCAutoRefCount) { 9676 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9677 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9678 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9679 9680 // Use the normal diagnostic if it's pseudo-__strong but the 9681 // user actually wrote 'const'. 9682 if (var->isARCPseudoStrong() && 9683 (!var->getTypeSourceInfo() || 9684 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9685 // There are two pseudo-strong cases: 9686 // - self 9687 ObjCMethodDecl *method = S.getCurMethodDecl(); 9688 if (method && var == method->getSelfDecl()) 9689 DiagID = method->isClassMethod() 9690 ? diag::err_typecheck_arc_assign_self_class_method 9691 : diag::err_typecheck_arc_assign_self; 9692 9693 // - fast enumeration variables 9694 else 9695 DiagID = diag::err_typecheck_arr_assign_enumeration; 9696 9697 SourceRange Assign; 9698 if (Loc != OrigLoc) 9699 Assign = SourceRange(OrigLoc, OrigLoc); 9700 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9701 // We need to preserve the AST regardless, so migration tool 9702 // can do its job. 9703 return false; 9704 } 9705 } 9706 } 9707 9708 // If none of the special cases above are triggered, then this is a 9709 // simple const assignment. 9710 if (DiagID == 0) { 9711 DiagnoseConstAssignment(S, E, Loc); 9712 return true; 9713 } 9714 9715 break; 9716 case Expr::MLV_ConstAddrSpace: 9717 DiagnoseConstAssignment(S, E, Loc); 9718 return true; 9719 case Expr::MLV_ArrayType: 9720 case Expr::MLV_ArrayTemporary: 9721 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9722 NeedType = true; 9723 break; 9724 case Expr::MLV_NotObjectType: 9725 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9726 NeedType = true; 9727 break; 9728 case Expr::MLV_LValueCast: 9729 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9730 break; 9731 case Expr::MLV_Valid: 9732 llvm_unreachable("did not take early return for MLV_Valid"); 9733 case Expr::MLV_InvalidExpression: 9734 case Expr::MLV_MemberFunction: 9735 case Expr::MLV_ClassTemporary: 9736 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9737 break; 9738 case Expr::MLV_IncompleteType: 9739 case Expr::MLV_IncompleteVoidType: 9740 return S.RequireCompleteType(Loc, E->getType(), 9741 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9742 case Expr::MLV_DuplicateVectorComponents: 9743 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9744 break; 9745 case Expr::MLV_NoSetterProperty: 9746 llvm_unreachable("readonly properties should be processed differently"); 9747 case Expr::MLV_InvalidMessageExpression: 9748 DiagID = diag::error_readonly_message_assignment; 9749 break; 9750 case Expr::MLV_SubObjCPropertySetting: 9751 DiagID = diag::error_no_subobject_property_setting; 9752 break; 9753 } 9754 9755 SourceRange Assign; 9756 if (Loc != OrigLoc) 9757 Assign = SourceRange(OrigLoc, OrigLoc); 9758 if (NeedType) 9759 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9760 else 9761 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9762 return true; 9763 } 9764 9765 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9766 SourceLocation Loc, 9767 Sema &Sema) { 9768 // C / C++ fields 9769 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9770 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9771 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9772 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9773 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9774 } 9775 9776 // Objective-C instance variables 9777 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9778 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9779 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9780 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9781 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9782 if (RL && RR && RL->getDecl() == RR->getDecl()) 9783 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9784 } 9785 } 9786 9787 // C99 6.5.16.1 9788 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9789 SourceLocation Loc, 9790 QualType CompoundType) { 9791 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9792 9793 // Verify that LHS is a modifiable lvalue, and emit error if not. 9794 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9795 return QualType(); 9796 9797 QualType LHSType = LHSExpr->getType(); 9798 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9799 CompoundType; 9800 AssignConvertType ConvTy; 9801 if (CompoundType.isNull()) { 9802 Expr *RHSCheck = RHS.get(); 9803 9804 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9805 9806 QualType LHSTy(LHSType); 9807 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9808 if (RHS.isInvalid()) 9809 return QualType(); 9810 // Special case of NSObject attributes on c-style pointer types. 9811 if (ConvTy == IncompatiblePointer && 9812 ((Context.isObjCNSObjectType(LHSType) && 9813 RHSType->isObjCObjectPointerType()) || 9814 (Context.isObjCNSObjectType(RHSType) && 9815 LHSType->isObjCObjectPointerType()))) 9816 ConvTy = Compatible; 9817 9818 if (ConvTy == Compatible && 9819 LHSType->isObjCObjectType()) 9820 Diag(Loc, diag::err_objc_object_assignment) 9821 << LHSType; 9822 9823 // If the RHS is a unary plus or minus, check to see if they = and + are 9824 // right next to each other. If so, the user may have typo'd "x =+ 4" 9825 // instead of "x += 4". 9826 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9827 RHSCheck = ICE->getSubExpr(); 9828 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9829 if ((UO->getOpcode() == UO_Plus || 9830 UO->getOpcode() == UO_Minus) && 9831 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9832 // Only if the two operators are exactly adjacent. 9833 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9834 // And there is a space or other character before the subexpr of the 9835 // unary +/-. We don't want to warn on "x=-1". 9836 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9837 UO->getSubExpr()->getLocStart().isFileID()) { 9838 Diag(Loc, diag::warn_not_compound_assign) 9839 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9840 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9841 } 9842 } 9843 9844 if (ConvTy == Compatible) { 9845 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9846 // Warn about retain cycles where a block captures the LHS, but 9847 // not if the LHS is a simple variable into which the block is 9848 // being stored...unless that variable can be captured by reference! 9849 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9850 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9851 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9852 checkRetainCycles(LHSExpr, RHS.get()); 9853 9854 // It is safe to assign a weak reference into a strong variable. 9855 // Although this code can still have problems: 9856 // id x = self.weakProp; 9857 // id y = self.weakProp; 9858 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9859 // paths through the function. This should be revisited if 9860 // -Wrepeated-use-of-weak is made flow-sensitive. 9861 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9862 RHS.get()->getLocStart())) 9863 getCurFunction()->markSafeWeakUse(RHS.get()); 9864 9865 } else if (getLangOpts().ObjCAutoRefCount) { 9866 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9867 } 9868 } 9869 } else { 9870 // Compound assignment "x += y" 9871 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9872 } 9873 9874 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9875 RHS.get(), AA_Assigning)) 9876 return QualType(); 9877 9878 CheckForNullPointerDereference(*this, LHSExpr); 9879 9880 // C99 6.5.16p3: The type of an assignment expression is the type of the 9881 // left operand unless the left operand has qualified type, in which case 9882 // it is the unqualified version of the type of the left operand. 9883 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9884 // is converted to the type of the assignment expression (above). 9885 // C++ 5.17p1: the type of the assignment expression is that of its left 9886 // operand. 9887 return (getLangOpts().CPlusPlus 9888 ? LHSType : LHSType.getUnqualifiedType()); 9889 } 9890 9891 // Only ignore explicit casts to void. 9892 static bool IgnoreCommaOperand(const Expr *E) { 9893 E = E->IgnoreParens(); 9894 9895 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 9896 if (CE->getCastKind() == CK_ToVoid) { 9897 return true; 9898 } 9899 } 9900 9901 return false; 9902 } 9903 9904 // Look for instances where it is likely the comma operator is confused with 9905 // another operator. There is a whitelist of acceptable expressions for the 9906 // left hand side of the comma operator, otherwise emit a warning. 9907 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 9908 // No warnings in macros 9909 if (Loc.isMacroID()) 9910 return; 9911 9912 // Don't warn in template instantiations. 9913 if (!ActiveTemplateInstantiations.empty()) 9914 return; 9915 9916 // Scope isn't fine-grained enough to whitelist the specific cases, so 9917 // instead, skip more than needed, then call back into here with the 9918 // CommaVisitor in SemaStmt.cpp. 9919 // The whitelisted locations are the initialization and increment portions 9920 // of a for loop. The additional checks are on the condition of 9921 // if statements, do/while loops, and for loops. 9922 const unsigned ForIncrementFlags = 9923 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 9924 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 9925 const unsigned ScopeFlags = getCurScope()->getFlags(); 9926 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 9927 (ScopeFlags & ForInitFlags) == ForInitFlags) 9928 return; 9929 9930 // If there are multiple comma operators used together, get the RHS of the 9931 // of the comma operator as the LHS. 9932 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 9933 if (BO->getOpcode() != BO_Comma) 9934 break; 9935 LHS = BO->getRHS(); 9936 } 9937 9938 // Only allow some expressions on LHS to not warn. 9939 if (IgnoreCommaOperand(LHS)) 9940 return; 9941 9942 Diag(Loc, diag::warn_comma_operator); 9943 Diag(LHS->getLocStart(), diag::note_cast_to_void) 9944 << LHS->getSourceRange() 9945 << FixItHint::CreateInsertion(LHS->getLocStart(), 9946 LangOpts.CPlusPlus ? "static_cast<void>(" 9947 : "(void)(") 9948 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 9949 ")"); 9950 } 9951 9952 // C99 6.5.17 9953 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9954 SourceLocation Loc) { 9955 LHS = S.CheckPlaceholderExpr(LHS.get()); 9956 RHS = S.CheckPlaceholderExpr(RHS.get()); 9957 if (LHS.isInvalid() || RHS.isInvalid()) 9958 return QualType(); 9959 9960 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9961 // operands, but not unary promotions. 9962 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9963 9964 // So we treat the LHS as a ignored value, and in C++ we allow the 9965 // containing site to determine what should be done with the RHS. 9966 LHS = S.IgnoredValueConversions(LHS.get()); 9967 if (LHS.isInvalid()) 9968 return QualType(); 9969 9970 S.DiagnoseUnusedExprResult(LHS.get()); 9971 9972 if (!S.getLangOpts().CPlusPlus) { 9973 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9974 if (RHS.isInvalid()) 9975 return QualType(); 9976 if (!RHS.get()->getType()->isVoidType()) 9977 S.RequireCompleteType(Loc, RHS.get()->getType(), 9978 diag::err_incomplete_type); 9979 } 9980 9981 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 9982 S.DiagnoseCommaOperator(LHS.get(), Loc); 9983 9984 return RHS.get()->getType(); 9985 } 9986 9987 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9988 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9989 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9990 ExprValueKind &VK, 9991 ExprObjectKind &OK, 9992 SourceLocation OpLoc, 9993 bool IsInc, bool IsPrefix) { 9994 if (Op->isTypeDependent()) 9995 return S.Context.DependentTy; 9996 9997 QualType ResType = Op->getType(); 9998 // Atomic types can be used for increment / decrement where the non-atomic 9999 // versions can, so ignore the _Atomic() specifier for the purpose of 10000 // checking. 10001 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10002 ResType = ResAtomicType->getValueType(); 10003 10004 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10005 10006 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10007 // Decrement of bool is not allowed. 10008 if (!IsInc) { 10009 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10010 return QualType(); 10011 } 10012 // Increment of bool sets it to true, but is deprecated. 10013 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10014 : diag::warn_increment_bool) 10015 << Op->getSourceRange(); 10016 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10017 // Error on enum increments and decrements in C++ mode 10018 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10019 return QualType(); 10020 } else if (ResType->isRealType()) { 10021 // OK! 10022 } else if (ResType->isPointerType()) { 10023 // C99 6.5.2.4p2, 6.5.6p2 10024 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10025 return QualType(); 10026 } else if (ResType->isObjCObjectPointerType()) { 10027 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10028 // Otherwise, we just need a complete type. 10029 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10030 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10031 return QualType(); 10032 } else if (ResType->isAnyComplexType()) { 10033 // C99 does not support ++/-- on complex types, we allow as an extension. 10034 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10035 << ResType << Op->getSourceRange(); 10036 } else if (ResType->isPlaceholderType()) { 10037 ExprResult PR = S.CheckPlaceholderExpr(Op); 10038 if (PR.isInvalid()) return QualType(); 10039 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10040 IsInc, IsPrefix); 10041 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10042 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10043 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10044 (ResType->getAs<VectorType>()->getVectorKind() != 10045 VectorType::AltiVecBool)) { 10046 // The z vector extensions allow ++ and -- for non-bool vectors. 10047 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10048 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10049 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10050 } else { 10051 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10052 << ResType << int(IsInc) << Op->getSourceRange(); 10053 return QualType(); 10054 } 10055 // At this point, we know we have a real, complex or pointer type. 10056 // Now make sure the operand is a modifiable lvalue. 10057 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10058 return QualType(); 10059 // In C++, a prefix increment is the same type as the operand. Otherwise 10060 // (in C or with postfix), the increment is the unqualified type of the 10061 // operand. 10062 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10063 VK = VK_LValue; 10064 OK = Op->getObjectKind(); 10065 return ResType; 10066 } else { 10067 VK = VK_RValue; 10068 return ResType.getUnqualifiedType(); 10069 } 10070 } 10071 10072 10073 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10074 /// This routine allows us to typecheck complex/recursive expressions 10075 /// where the declaration is needed for type checking. We only need to 10076 /// handle cases when the expression references a function designator 10077 /// or is an lvalue. Here are some examples: 10078 /// - &(x) => x 10079 /// - &*****f => f for f a function designator. 10080 /// - &s.xx => s 10081 /// - &s.zz[1].yy -> s, if zz is an array 10082 /// - *(x + 1) -> x, if x is an array 10083 /// - &"123"[2] -> 0 10084 /// - & __real__ x -> x 10085 static ValueDecl *getPrimaryDecl(Expr *E) { 10086 switch (E->getStmtClass()) { 10087 case Stmt::DeclRefExprClass: 10088 return cast<DeclRefExpr>(E)->getDecl(); 10089 case Stmt::MemberExprClass: 10090 // If this is an arrow operator, the address is an offset from 10091 // the base's value, so the object the base refers to is 10092 // irrelevant. 10093 if (cast<MemberExpr>(E)->isArrow()) 10094 return nullptr; 10095 // Otherwise, the expression refers to a part of the base 10096 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10097 case Stmt::ArraySubscriptExprClass: { 10098 // FIXME: This code shouldn't be necessary! We should catch the implicit 10099 // promotion of register arrays earlier. 10100 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10101 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10102 if (ICE->getSubExpr()->getType()->isArrayType()) 10103 return getPrimaryDecl(ICE->getSubExpr()); 10104 } 10105 return nullptr; 10106 } 10107 case Stmt::UnaryOperatorClass: { 10108 UnaryOperator *UO = cast<UnaryOperator>(E); 10109 10110 switch(UO->getOpcode()) { 10111 case UO_Real: 10112 case UO_Imag: 10113 case UO_Extension: 10114 return getPrimaryDecl(UO->getSubExpr()); 10115 default: 10116 return nullptr; 10117 } 10118 } 10119 case Stmt::ParenExprClass: 10120 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10121 case Stmt::ImplicitCastExprClass: 10122 // If the result of an implicit cast is an l-value, we care about 10123 // the sub-expression; otherwise, the result here doesn't matter. 10124 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10125 default: 10126 return nullptr; 10127 } 10128 } 10129 10130 namespace { 10131 enum { 10132 AO_Bit_Field = 0, 10133 AO_Vector_Element = 1, 10134 AO_Property_Expansion = 2, 10135 AO_Register_Variable = 3, 10136 AO_No_Error = 4 10137 }; 10138 } 10139 /// \brief Diagnose invalid operand for address of operations. 10140 /// 10141 /// \param Type The type of operand which cannot have its address taken. 10142 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10143 Expr *E, unsigned Type) { 10144 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10145 } 10146 10147 /// CheckAddressOfOperand - The operand of & must be either a function 10148 /// designator or an lvalue designating an object. If it is an lvalue, the 10149 /// object cannot be declared with storage class register or be a bit field. 10150 /// Note: The usual conversions are *not* applied to the operand of the & 10151 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10152 /// In C++, the operand might be an overloaded function name, in which case 10153 /// we allow the '&' but retain the overloaded-function type. 10154 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10155 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10156 if (PTy->getKind() == BuiltinType::Overload) { 10157 Expr *E = OrigOp.get()->IgnoreParens(); 10158 if (!isa<OverloadExpr>(E)) { 10159 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10160 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10161 << OrigOp.get()->getSourceRange(); 10162 return QualType(); 10163 } 10164 10165 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10166 if (isa<UnresolvedMemberExpr>(Ovl)) 10167 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10168 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10169 << OrigOp.get()->getSourceRange(); 10170 return QualType(); 10171 } 10172 10173 return Context.OverloadTy; 10174 } 10175 10176 if (PTy->getKind() == BuiltinType::UnknownAny) 10177 return Context.UnknownAnyTy; 10178 10179 if (PTy->getKind() == BuiltinType::BoundMember) { 10180 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10181 << OrigOp.get()->getSourceRange(); 10182 return QualType(); 10183 } 10184 10185 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10186 if (OrigOp.isInvalid()) return QualType(); 10187 } 10188 10189 if (OrigOp.get()->isTypeDependent()) 10190 return Context.DependentTy; 10191 10192 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10193 10194 // Make sure to ignore parentheses in subsequent checks 10195 Expr *op = OrigOp.get()->IgnoreParens(); 10196 10197 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10198 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10199 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10200 return QualType(); 10201 } 10202 10203 if (getLangOpts().C99) { 10204 // Implement C99-only parts of addressof rules. 10205 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10206 if (uOp->getOpcode() == UO_Deref) 10207 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10208 // (assuming the deref expression is valid). 10209 return uOp->getSubExpr()->getType(); 10210 } 10211 // Technically, there should be a check for array subscript 10212 // expressions here, but the result of one is always an lvalue anyway. 10213 } 10214 ValueDecl *dcl = getPrimaryDecl(op); 10215 10216 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10217 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10218 op->getLocStart())) 10219 return QualType(); 10220 10221 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10222 unsigned AddressOfError = AO_No_Error; 10223 10224 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10225 bool sfinae = (bool)isSFINAEContext(); 10226 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10227 : diag::ext_typecheck_addrof_temporary) 10228 << op->getType() << op->getSourceRange(); 10229 if (sfinae) 10230 return QualType(); 10231 // Materialize the temporary as an lvalue so that we can take its address. 10232 OrigOp = op = new (Context) 10233 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10234 } else if (isa<ObjCSelectorExpr>(op)) { 10235 return Context.getPointerType(op->getType()); 10236 } else if (lval == Expr::LV_MemberFunction) { 10237 // If it's an instance method, make a member pointer. 10238 // The expression must have exactly the form &A::foo. 10239 10240 // If the underlying expression isn't a decl ref, give up. 10241 if (!isa<DeclRefExpr>(op)) { 10242 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10243 << OrigOp.get()->getSourceRange(); 10244 return QualType(); 10245 } 10246 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10247 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10248 10249 // The id-expression was parenthesized. 10250 if (OrigOp.get() != DRE) { 10251 Diag(OpLoc, diag::err_parens_pointer_member_function) 10252 << OrigOp.get()->getSourceRange(); 10253 10254 // The method was named without a qualifier. 10255 } else if (!DRE->getQualifier()) { 10256 if (MD->getParent()->getName().empty()) 10257 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10258 << op->getSourceRange(); 10259 else { 10260 SmallString<32> Str; 10261 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10262 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10263 << op->getSourceRange() 10264 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10265 } 10266 } 10267 10268 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10269 if (isa<CXXDestructorDecl>(MD)) 10270 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10271 10272 QualType MPTy = Context.getMemberPointerType( 10273 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10274 // Under the MS ABI, lock down the inheritance model now. 10275 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10276 (void)isCompleteType(OpLoc, MPTy); 10277 return MPTy; 10278 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10279 // C99 6.5.3.2p1 10280 // The operand must be either an l-value or a function designator 10281 if (!op->getType()->isFunctionType()) { 10282 // Use a special diagnostic for loads from property references. 10283 if (isa<PseudoObjectExpr>(op)) { 10284 AddressOfError = AO_Property_Expansion; 10285 } else { 10286 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10287 << op->getType() << op->getSourceRange(); 10288 return QualType(); 10289 } 10290 } 10291 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10292 // The operand cannot be a bit-field 10293 AddressOfError = AO_Bit_Field; 10294 } else if (op->getObjectKind() == OK_VectorComponent) { 10295 // The operand cannot be an element of a vector 10296 AddressOfError = AO_Vector_Element; 10297 } else if (dcl) { // C99 6.5.3.2p1 10298 // We have an lvalue with a decl. Make sure the decl is not declared 10299 // with the register storage-class specifier. 10300 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10301 // in C++ it is not error to take address of a register 10302 // variable (c++03 7.1.1P3) 10303 if (vd->getStorageClass() == SC_Register && 10304 !getLangOpts().CPlusPlus) { 10305 AddressOfError = AO_Register_Variable; 10306 } 10307 } else if (isa<MSPropertyDecl>(dcl)) { 10308 AddressOfError = AO_Property_Expansion; 10309 } else if (isa<FunctionTemplateDecl>(dcl)) { 10310 return Context.OverloadTy; 10311 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10312 // Okay: we can take the address of a field. 10313 // Could be a pointer to member, though, if there is an explicit 10314 // scope qualifier for the class. 10315 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10316 DeclContext *Ctx = dcl->getDeclContext(); 10317 if (Ctx && Ctx->isRecord()) { 10318 if (dcl->getType()->isReferenceType()) { 10319 Diag(OpLoc, 10320 diag::err_cannot_form_pointer_to_member_of_reference_type) 10321 << dcl->getDeclName() << dcl->getType(); 10322 return QualType(); 10323 } 10324 10325 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10326 Ctx = Ctx->getParent(); 10327 10328 QualType MPTy = Context.getMemberPointerType( 10329 op->getType(), 10330 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10331 // Under the MS ABI, lock down the inheritance model now. 10332 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10333 (void)isCompleteType(OpLoc, MPTy); 10334 return MPTy; 10335 } 10336 } 10337 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10338 llvm_unreachable("Unknown/unexpected decl type"); 10339 } 10340 10341 if (AddressOfError != AO_No_Error) { 10342 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10343 return QualType(); 10344 } 10345 10346 if (lval == Expr::LV_IncompleteVoidType) { 10347 // Taking the address of a void variable is technically illegal, but we 10348 // allow it in cases which are otherwise valid. 10349 // Example: "extern void x; void* y = &x;". 10350 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10351 } 10352 10353 // If the operand has type "type", the result has type "pointer to type". 10354 if (op->getType()->isObjCObjectType()) 10355 return Context.getObjCObjectPointerType(op->getType()); 10356 10357 // OpenCL v2.0 s6.12.5 - The unary operators & cannot be used with a block. 10358 if (getLangOpts().OpenCL && OrigOp.get()->getType()->isBlockPointerType()) { 10359 Diag(OpLoc, diag::err_typecheck_unary_expr) << OrigOp.get()->getType() 10360 << op->getSourceRange(); 10361 return QualType(); 10362 } 10363 10364 return Context.getPointerType(op->getType()); 10365 } 10366 10367 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10368 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10369 if (!DRE) 10370 return; 10371 const Decl *D = DRE->getDecl(); 10372 if (!D) 10373 return; 10374 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10375 if (!Param) 10376 return; 10377 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10378 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10379 return; 10380 if (FunctionScopeInfo *FD = S.getCurFunction()) 10381 if (!FD->ModifiedNonNullParams.count(Param)) 10382 FD->ModifiedNonNullParams.insert(Param); 10383 } 10384 10385 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10386 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10387 SourceLocation OpLoc) { 10388 if (Op->isTypeDependent()) 10389 return S.Context.DependentTy; 10390 10391 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10392 if (ConvResult.isInvalid()) 10393 return QualType(); 10394 Op = ConvResult.get(); 10395 QualType OpTy = Op->getType(); 10396 QualType Result; 10397 10398 if (isa<CXXReinterpretCastExpr>(Op)) { 10399 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10400 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10401 Op->getSourceRange()); 10402 } 10403 10404 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10405 { 10406 Result = PT->getPointeeType(); 10407 // OpenCL v2.0 s6.12.5 - The unary operators * cannot be used with a block. 10408 if (S.getLangOpts().OpenCLVersion >= 200 && Result->isBlockPointerType()) { 10409 S.Diag(OpLoc, diag::err_opencl_dereferencing) << OpTy 10410 << Op->getSourceRange(); 10411 return QualType(); 10412 } 10413 } 10414 else if (const ObjCObjectPointerType *OPT = 10415 OpTy->getAs<ObjCObjectPointerType>()) 10416 Result = OPT->getPointeeType(); 10417 else { 10418 ExprResult PR = S.CheckPlaceholderExpr(Op); 10419 if (PR.isInvalid()) return QualType(); 10420 if (PR.get() != Op) 10421 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10422 } 10423 10424 if (Result.isNull()) { 10425 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10426 << OpTy << Op->getSourceRange(); 10427 return QualType(); 10428 } 10429 10430 // Note that per both C89 and C99, indirection is always legal, even if Result 10431 // is an incomplete type or void. It would be possible to warn about 10432 // dereferencing a void pointer, but it's completely well-defined, and such a 10433 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10434 // for pointers to 'void' but is fine for any other pointer type: 10435 // 10436 // C++ [expr.unary.op]p1: 10437 // [...] the expression to which [the unary * operator] is applied shall 10438 // be a pointer to an object type, or a pointer to a function type 10439 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10440 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10441 << OpTy << Op->getSourceRange(); 10442 10443 // Dereferences are usually l-values... 10444 VK = VK_LValue; 10445 10446 // ...except that certain expressions are never l-values in C. 10447 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10448 VK = VK_RValue; 10449 10450 return Result; 10451 } 10452 10453 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10454 BinaryOperatorKind Opc; 10455 switch (Kind) { 10456 default: llvm_unreachable("Unknown binop!"); 10457 case tok::periodstar: Opc = BO_PtrMemD; break; 10458 case tok::arrowstar: Opc = BO_PtrMemI; break; 10459 case tok::star: Opc = BO_Mul; break; 10460 case tok::slash: Opc = BO_Div; break; 10461 case tok::percent: Opc = BO_Rem; break; 10462 case tok::plus: Opc = BO_Add; break; 10463 case tok::minus: Opc = BO_Sub; break; 10464 case tok::lessless: Opc = BO_Shl; break; 10465 case tok::greatergreater: Opc = BO_Shr; break; 10466 case tok::lessequal: Opc = BO_LE; break; 10467 case tok::less: Opc = BO_LT; break; 10468 case tok::greaterequal: Opc = BO_GE; break; 10469 case tok::greater: Opc = BO_GT; break; 10470 case tok::exclaimequal: Opc = BO_NE; break; 10471 case tok::equalequal: Opc = BO_EQ; break; 10472 case tok::amp: Opc = BO_And; break; 10473 case tok::caret: Opc = BO_Xor; break; 10474 case tok::pipe: Opc = BO_Or; break; 10475 case tok::ampamp: Opc = BO_LAnd; break; 10476 case tok::pipepipe: Opc = BO_LOr; break; 10477 case tok::equal: Opc = BO_Assign; break; 10478 case tok::starequal: Opc = BO_MulAssign; break; 10479 case tok::slashequal: Opc = BO_DivAssign; break; 10480 case tok::percentequal: Opc = BO_RemAssign; break; 10481 case tok::plusequal: Opc = BO_AddAssign; break; 10482 case tok::minusequal: Opc = BO_SubAssign; break; 10483 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10484 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10485 case tok::ampequal: Opc = BO_AndAssign; break; 10486 case tok::caretequal: Opc = BO_XorAssign; break; 10487 case tok::pipeequal: Opc = BO_OrAssign; break; 10488 case tok::comma: Opc = BO_Comma; break; 10489 } 10490 return Opc; 10491 } 10492 10493 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10494 tok::TokenKind Kind) { 10495 UnaryOperatorKind Opc; 10496 switch (Kind) { 10497 default: llvm_unreachable("Unknown unary op!"); 10498 case tok::plusplus: Opc = UO_PreInc; break; 10499 case tok::minusminus: Opc = UO_PreDec; break; 10500 case tok::amp: Opc = UO_AddrOf; break; 10501 case tok::star: Opc = UO_Deref; break; 10502 case tok::plus: Opc = UO_Plus; break; 10503 case tok::minus: Opc = UO_Minus; break; 10504 case tok::tilde: Opc = UO_Not; break; 10505 case tok::exclaim: Opc = UO_LNot; break; 10506 case tok::kw___real: Opc = UO_Real; break; 10507 case tok::kw___imag: Opc = UO_Imag; break; 10508 case tok::kw___extension__: Opc = UO_Extension; break; 10509 } 10510 return Opc; 10511 } 10512 10513 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10514 /// This warning is only emitted for builtin assignment operations. It is also 10515 /// suppressed in the event of macro expansions. 10516 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10517 SourceLocation OpLoc) { 10518 if (!S.ActiveTemplateInstantiations.empty()) 10519 return; 10520 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10521 return; 10522 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10523 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10524 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10525 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10526 if (!LHSDeclRef || !RHSDeclRef || 10527 LHSDeclRef->getLocation().isMacroID() || 10528 RHSDeclRef->getLocation().isMacroID()) 10529 return; 10530 const ValueDecl *LHSDecl = 10531 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10532 const ValueDecl *RHSDecl = 10533 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10534 if (LHSDecl != RHSDecl) 10535 return; 10536 if (LHSDecl->getType().isVolatileQualified()) 10537 return; 10538 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10539 if (RefTy->getPointeeType().isVolatileQualified()) 10540 return; 10541 10542 S.Diag(OpLoc, diag::warn_self_assignment) 10543 << LHSDeclRef->getType() 10544 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10545 } 10546 10547 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10548 /// is usually indicative of introspection within the Objective-C pointer. 10549 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10550 SourceLocation OpLoc) { 10551 if (!S.getLangOpts().ObjC1) 10552 return; 10553 10554 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10555 const Expr *LHS = L.get(); 10556 const Expr *RHS = R.get(); 10557 10558 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10559 ObjCPointerExpr = LHS; 10560 OtherExpr = RHS; 10561 } 10562 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10563 ObjCPointerExpr = RHS; 10564 OtherExpr = LHS; 10565 } 10566 10567 // This warning is deliberately made very specific to reduce false 10568 // positives with logic that uses '&' for hashing. This logic mainly 10569 // looks for code trying to introspect into tagged pointers, which 10570 // code should generally never do. 10571 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10572 unsigned Diag = diag::warn_objc_pointer_masking; 10573 // Determine if we are introspecting the result of performSelectorXXX. 10574 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10575 // Special case messages to -performSelector and friends, which 10576 // can return non-pointer values boxed in a pointer value. 10577 // Some clients may wish to silence warnings in this subcase. 10578 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10579 Selector S = ME->getSelector(); 10580 StringRef SelArg0 = S.getNameForSlot(0); 10581 if (SelArg0.startswith("performSelector")) 10582 Diag = diag::warn_objc_pointer_masking_performSelector; 10583 } 10584 10585 S.Diag(OpLoc, Diag) 10586 << ObjCPointerExpr->getSourceRange(); 10587 } 10588 } 10589 10590 static NamedDecl *getDeclFromExpr(Expr *E) { 10591 if (!E) 10592 return nullptr; 10593 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10594 return DRE->getDecl(); 10595 if (auto *ME = dyn_cast<MemberExpr>(E)) 10596 return ME->getMemberDecl(); 10597 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10598 return IRE->getDecl(); 10599 return nullptr; 10600 } 10601 10602 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10603 /// operator @p Opc at location @c TokLoc. This routine only supports 10604 /// built-in operations; ActOnBinOp handles overloaded operators. 10605 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10606 BinaryOperatorKind Opc, 10607 Expr *LHSExpr, Expr *RHSExpr) { 10608 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10609 // The syntax only allows initializer lists on the RHS of assignment, 10610 // so we don't need to worry about accepting invalid code for 10611 // non-assignment operators. 10612 // C++11 5.17p9: 10613 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10614 // of x = {} is x = T(). 10615 InitializationKind Kind = 10616 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10617 InitializedEntity Entity = 10618 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10619 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10620 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10621 if (Init.isInvalid()) 10622 return Init; 10623 RHSExpr = Init.get(); 10624 } 10625 10626 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10627 QualType ResultTy; // Result type of the binary operator. 10628 // The following two variables are used for compound assignment operators 10629 QualType CompLHSTy; // Type of LHS after promotions for computation 10630 QualType CompResultTy; // Type of computation result 10631 ExprValueKind VK = VK_RValue; 10632 ExprObjectKind OK = OK_Ordinary; 10633 10634 if (!getLangOpts().CPlusPlus) { 10635 // C cannot handle TypoExpr nodes on either side of a binop because it 10636 // doesn't handle dependent types properly, so make sure any TypoExprs have 10637 // been dealt with before checking the operands. 10638 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10639 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10640 if (Opc != BO_Assign) 10641 return ExprResult(E); 10642 // Avoid correcting the RHS to the same Expr as the LHS. 10643 Decl *D = getDeclFromExpr(E); 10644 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10645 }); 10646 if (!LHS.isUsable() || !RHS.isUsable()) 10647 return ExprError(); 10648 } 10649 10650 if (getLangOpts().OpenCL) { 10651 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10652 // the ATOMIC_VAR_INIT macro. 10653 if (LHSExpr->getType()->isAtomicType() || 10654 RHSExpr->getType()->isAtomicType()) { 10655 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10656 if (BO_Assign == Opc) 10657 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10658 else 10659 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10660 return ExprError(); 10661 } 10662 } 10663 10664 switch (Opc) { 10665 case BO_Assign: 10666 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10667 if (getLangOpts().CPlusPlus && 10668 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10669 VK = LHS.get()->getValueKind(); 10670 OK = LHS.get()->getObjectKind(); 10671 } 10672 if (!ResultTy.isNull()) { 10673 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10674 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10675 } 10676 RecordModifiableNonNullParam(*this, LHS.get()); 10677 break; 10678 case BO_PtrMemD: 10679 case BO_PtrMemI: 10680 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10681 Opc == BO_PtrMemI); 10682 break; 10683 case BO_Mul: 10684 case BO_Div: 10685 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10686 Opc == BO_Div); 10687 break; 10688 case BO_Rem: 10689 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10690 break; 10691 case BO_Add: 10692 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10693 break; 10694 case BO_Sub: 10695 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10696 break; 10697 case BO_Shl: 10698 case BO_Shr: 10699 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10700 break; 10701 case BO_LE: 10702 case BO_LT: 10703 case BO_GE: 10704 case BO_GT: 10705 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10706 break; 10707 case BO_EQ: 10708 case BO_NE: 10709 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10710 break; 10711 case BO_And: 10712 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10713 case BO_Xor: 10714 case BO_Or: 10715 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10716 break; 10717 case BO_LAnd: 10718 case BO_LOr: 10719 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10720 break; 10721 case BO_MulAssign: 10722 case BO_DivAssign: 10723 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10724 Opc == BO_DivAssign); 10725 CompLHSTy = CompResultTy; 10726 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10727 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10728 break; 10729 case BO_RemAssign: 10730 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10731 CompLHSTy = CompResultTy; 10732 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10733 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10734 break; 10735 case BO_AddAssign: 10736 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10737 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10738 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10739 break; 10740 case BO_SubAssign: 10741 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10742 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10743 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10744 break; 10745 case BO_ShlAssign: 10746 case BO_ShrAssign: 10747 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10748 CompLHSTy = CompResultTy; 10749 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10750 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10751 break; 10752 case BO_AndAssign: 10753 case BO_OrAssign: // fallthrough 10754 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10755 case BO_XorAssign: 10756 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10757 CompLHSTy = CompResultTy; 10758 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10759 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10760 break; 10761 case BO_Comma: 10762 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10763 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10764 VK = RHS.get()->getValueKind(); 10765 OK = RHS.get()->getObjectKind(); 10766 } 10767 break; 10768 } 10769 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10770 return ExprError(); 10771 10772 // Check for array bounds violations for both sides of the BinaryOperator 10773 CheckArrayAccess(LHS.get()); 10774 CheckArrayAccess(RHS.get()); 10775 10776 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10777 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10778 &Context.Idents.get("object_setClass"), 10779 SourceLocation(), LookupOrdinaryName); 10780 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10781 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 10782 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10783 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10784 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10785 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10786 } 10787 else 10788 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10789 } 10790 else if (const ObjCIvarRefExpr *OIRE = 10791 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10792 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10793 10794 if (CompResultTy.isNull()) 10795 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10796 OK, OpLoc, FPFeatures.fp_contract); 10797 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10798 OK_ObjCProperty) { 10799 VK = VK_LValue; 10800 OK = LHS.get()->getObjectKind(); 10801 } 10802 return new (Context) CompoundAssignOperator( 10803 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10804 OpLoc, FPFeatures.fp_contract); 10805 } 10806 10807 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10808 /// operators are mixed in a way that suggests that the programmer forgot that 10809 /// comparison operators have higher precedence. The most typical example of 10810 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10811 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10812 SourceLocation OpLoc, Expr *LHSExpr, 10813 Expr *RHSExpr) { 10814 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10815 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10816 10817 // Check that one of the sides is a comparison operator and the other isn't. 10818 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10819 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10820 if (isLeftComp == isRightComp) 10821 return; 10822 10823 // Bitwise operations are sometimes used as eager logical ops. 10824 // Don't diagnose this. 10825 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10826 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10827 if (isLeftBitwise || isRightBitwise) 10828 return; 10829 10830 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10831 OpLoc) 10832 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10833 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10834 SourceRange ParensRange = isLeftComp ? 10835 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10836 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10837 10838 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10839 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10840 SuggestParentheses(Self, OpLoc, 10841 Self.PDiag(diag::note_precedence_silence) << OpStr, 10842 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10843 SuggestParentheses(Self, OpLoc, 10844 Self.PDiag(diag::note_precedence_bitwise_first) 10845 << BinaryOperator::getOpcodeStr(Opc), 10846 ParensRange); 10847 } 10848 10849 /// \brief It accepts a '&&' expr that is inside a '||' one. 10850 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10851 /// in parentheses. 10852 static void 10853 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10854 BinaryOperator *Bop) { 10855 assert(Bop->getOpcode() == BO_LAnd); 10856 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10857 << Bop->getSourceRange() << OpLoc; 10858 SuggestParentheses(Self, Bop->getOperatorLoc(), 10859 Self.PDiag(diag::note_precedence_silence) 10860 << Bop->getOpcodeStr(), 10861 Bop->getSourceRange()); 10862 } 10863 10864 /// \brief Returns true if the given expression can be evaluated as a constant 10865 /// 'true'. 10866 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10867 bool Res; 10868 return !E->isValueDependent() && 10869 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10870 } 10871 10872 /// \brief Returns true if the given expression can be evaluated as a constant 10873 /// 'false'. 10874 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10875 bool Res; 10876 return !E->isValueDependent() && 10877 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10878 } 10879 10880 /// \brief Look for '&&' in the left hand of a '||' expr. 10881 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10882 Expr *LHSExpr, Expr *RHSExpr) { 10883 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10884 if (Bop->getOpcode() == BO_LAnd) { 10885 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10886 if (EvaluatesAsFalse(S, RHSExpr)) 10887 return; 10888 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10889 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10890 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10891 } else if (Bop->getOpcode() == BO_LOr) { 10892 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10893 // If it's "a || b && 1 || c" we didn't warn earlier for 10894 // "a || b && 1", but warn now. 10895 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10896 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10897 } 10898 } 10899 } 10900 } 10901 10902 /// \brief Look for '&&' in the right hand of a '||' expr. 10903 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10904 Expr *LHSExpr, Expr *RHSExpr) { 10905 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10906 if (Bop->getOpcode() == BO_LAnd) { 10907 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10908 if (EvaluatesAsFalse(S, LHSExpr)) 10909 return; 10910 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10911 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10912 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10913 } 10914 } 10915 } 10916 10917 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 10918 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 10919 /// the '&' expression in parentheses. 10920 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 10921 SourceLocation OpLoc, Expr *SubExpr) { 10922 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10923 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 10924 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 10925 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 10926 << Bop->getSourceRange() << OpLoc; 10927 SuggestParentheses(S, Bop->getOperatorLoc(), 10928 S.PDiag(diag::note_precedence_silence) 10929 << Bop->getOpcodeStr(), 10930 Bop->getSourceRange()); 10931 } 10932 } 10933 } 10934 10935 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10936 Expr *SubExpr, StringRef Shift) { 10937 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10938 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10939 StringRef Op = Bop->getOpcodeStr(); 10940 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10941 << Bop->getSourceRange() << OpLoc << Shift << Op; 10942 SuggestParentheses(S, Bop->getOperatorLoc(), 10943 S.PDiag(diag::note_precedence_silence) << Op, 10944 Bop->getSourceRange()); 10945 } 10946 } 10947 } 10948 10949 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10950 Expr *LHSExpr, Expr *RHSExpr) { 10951 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10952 if (!OCE) 10953 return; 10954 10955 FunctionDecl *FD = OCE->getDirectCallee(); 10956 if (!FD || !FD->isOverloadedOperator()) 10957 return; 10958 10959 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10960 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10961 return; 10962 10963 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10964 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10965 << (Kind == OO_LessLess); 10966 SuggestParentheses(S, OCE->getOperatorLoc(), 10967 S.PDiag(diag::note_precedence_silence) 10968 << (Kind == OO_LessLess ? "<<" : ">>"), 10969 OCE->getSourceRange()); 10970 SuggestParentheses(S, OpLoc, 10971 S.PDiag(diag::note_evaluate_comparison_first), 10972 SourceRange(OCE->getArg(1)->getLocStart(), 10973 RHSExpr->getLocEnd())); 10974 } 10975 10976 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10977 /// precedence. 10978 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10979 SourceLocation OpLoc, Expr *LHSExpr, 10980 Expr *RHSExpr){ 10981 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10982 if (BinaryOperator::isBitwiseOp(Opc)) 10983 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10984 10985 // Diagnose "arg1 & arg2 | arg3" 10986 if ((Opc == BO_Or || Opc == BO_Xor) && 10987 !OpLoc.isMacroID()/* Don't warn in macros. */) { 10988 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 10989 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 10990 } 10991 10992 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10993 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10994 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10995 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10996 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10997 } 10998 10999 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11000 || Opc == BO_Shr) { 11001 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11002 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11003 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11004 } 11005 11006 // Warn on overloaded shift operators and comparisons, such as: 11007 // cout << 5 == 4; 11008 if (BinaryOperator::isComparisonOp(Opc)) 11009 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11010 } 11011 11012 // Binary Operators. 'Tok' is the token for the operator. 11013 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11014 tok::TokenKind Kind, 11015 Expr *LHSExpr, Expr *RHSExpr) { 11016 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11017 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11018 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11019 11020 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11021 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11022 11023 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11024 } 11025 11026 /// Build an overloaded binary operator expression in the given scope. 11027 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11028 BinaryOperatorKind Opc, 11029 Expr *LHS, Expr *RHS) { 11030 // Find all of the overloaded operators visible from this 11031 // point. We perform both an operator-name lookup from the local 11032 // scope and an argument-dependent lookup based on the types of 11033 // the arguments. 11034 UnresolvedSet<16> Functions; 11035 OverloadedOperatorKind OverOp 11036 = BinaryOperator::getOverloadedOperator(Opc); 11037 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11038 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11039 RHS->getType(), Functions); 11040 11041 // Build the (potentially-overloaded, potentially-dependent) 11042 // binary operation. 11043 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11044 } 11045 11046 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11047 BinaryOperatorKind Opc, 11048 Expr *LHSExpr, Expr *RHSExpr) { 11049 // We want to end up calling one of checkPseudoObjectAssignment 11050 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11051 // both expressions are overloadable or either is type-dependent), 11052 // or CreateBuiltinBinOp (in any other case). We also want to get 11053 // any placeholder types out of the way. 11054 11055 // Handle pseudo-objects in the LHS. 11056 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11057 // Assignments with a pseudo-object l-value need special analysis. 11058 if (pty->getKind() == BuiltinType::PseudoObject && 11059 BinaryOperator::isAssignmentOp(Opc)) 11060 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11061 11062 // Don't resolve overloads if the other type is overloadable. 11063 if (pty->getKind() == BuiltinType::Overload) { 11064 // We can't actually test that if we still have a placeholder, 11065 // though. Fortunately, none of the exceptions we see in that 11066 // code below are valid when the LHS is an overload set. Note 11067 // that an overload set can be dependently-typed, but it never 11068 // instantiates to having an overloadable type. 11069 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11070 if (resolvedRHS.isInvalid()) return ExprError(); 11071 RHSExpr = resolvedRHS.get(); 11072 11073 if (RHSExpr->isTypeDependent() || 11074 RHSExpr->getType()->isOverloadableType()) 11075 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11076 } 11077 11078 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11079 if (LHS.isInvalid()) return ExprError(); 11080 LHSExpr = LHS.get(); 11081 } 11082 11083 // Handle pseudo-objects in the RHS. 11084 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11085 // An overload in the RHS can potentially be resolved by the type 11086 // being assigned to. 11087 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11088 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11089 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11090 11091 if (LHSExpr->getType()->isOverloadableType()) 11092 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11093 11094 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11095 } 11096 11097 // Don't resolve overloads if the other type is overloadable. 11098 if (pty->getKind() == BuiltinType::Overload && 11099 LHSExpr->getType()->isOverloadableType()) 11100 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11101 11102 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11103 if (!resolvedRHS.isUsable()) return ExprError(); 11104 RHSExpr = resolvedRHS.get(); 11105 } 11106 11107 if (getLangOpts().CPlusPlus) { 11108 // If either expression is type-dependent, always build an 11109 // overloaded op. 11110 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11111 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11112 11113 // Otherwise, build an overloaded op if either expression has an 11114 // overloadable type. 11115 if (LHSExpr->getType()->isOverloadableType() || 11116 RHSExpr->getType()->isOverloadableType()) 11117 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11118 } 11119 11120 // Build a built-in binary operation. 11121 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11122 } 11123 11124 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11125 UnaryOperatorKind Opc, 11126 Expr *InputExpr) { 11127 ExprResult Input = InputExpr; 11128 ExprValueKind VK = VK_RValue; 11129 ExprObjectKind OK = OK_Ordinary; 11130 QualType resultType; 11131 if (getLangOpts().OpenCL) { 11132 // The only legal unary operation for atomics is '&'. 11133 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 11134 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11135 << InputExpr->getType() 11136 << Input.get()->getSourceRange()); 11137 } 11138 } 11139 switch (Opc) { 11140 case UO_PreInc: 11141 case UO_PreDec: 11142 case UO_PostInc: 11143 case UO_PostDec: 11144 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11145 OpLoc, 11146 Opc == UO_PreInc || 11147 Opc == UO_PostInc, 11148 Opc == UO_PreInc || 11149 Opc == UO_PreDec); 11150 break; 11151 case UO_AddrOf: 11152 resultType = CheckAddressOfOperand(Input, OpLoc); 11153 RecordModifiableNonNullParam(*this, InputExpr); 11154 break; 11155 case UO_Deref: { 11156 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11157 if (Input.isInvalid()) return ExprError(); 11158 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11159 break; 11160 } 11161 case UO_Plus: 11162 case UO_Minus: 11163 Input = UsualUnaryConversions(Input.get()); 11164 if (Input.isInvalid()) return ExprError(); 11165 resultType = Input.get()->getType(); 11166 if (resultType->isDependentType()) 11167 break; 11168 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11169 break; 11170 else if (resultType->isVectorType() && 11171 // The z vector extensions don't allow + or - with bool vectors. 11172 (!Context.getLangOpts().ZVector || 11173 resultType->getAs<VectorType>()->getVectorKind() != 11174 VectorType::AltiVecBool)) 11175 break; 11176 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11177 Opc == UO_Plus && 11178 resultType->isPointerType()) 11179 break; 11180 11181 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11182 << resultType << Input.get()->getSourceRange()); 11183 11184 case UO_Not: // bitwise complement 11185 Input = UsualUnaryConversions(Input.get()); 11186 if (Input.isInvalid()) 11187 return ExprError(); 11188 resultType = Input.get()->getType(); 11189 if (resultType->isDependentType()) 11190 break; 11191 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11192 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11193 // C99 does not support '~' for complex conjugation. 11194 Diag(OpLoc, diag::ext_integer_complement_complex) 11195 << resultType << Input.get()->getSourceRange(); 11196 else if (resultType->hasIntegerRepresentation()) 11197 break; 11198 else if (resultType->isExtVectorType()) { 11199 if (Context.getLangOpts().OpenCL) { 11200 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11201 // on vector float types. 11202 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11203 if (!T->isIntegerType()) 11204 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11205 << resultType << Input.get()->getSourceRange()); 11206 } 11207 break; 11208 } else { 11209 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11210 << resultType << Input.get()->getSourceRange()); 11211 } 11212 break; 11213 11214 case UO_LNot: // logical negation 11215 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11216 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11217 if (Input.isInvalid()) return ExprError(); 11218 resultType = Input.get()->getType(); 11219 11220 // Though we still have to promote half FP to float... 11221 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11222 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11223 resultType = Context.FloatTy; 11224 } 11225 11226 if (resultType->isDependentType()) 11227 break; 11228 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11229 // C99 6.5.3.3p1: ok, fallthrough; 11230 if (Context.getLangOpts().CPlusPlus) { 11231 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11232 // operand contextually converted to bool. 11233 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11234 ScalarTypeToBooleanCastKind(resultType)); 11235 } else if (Context.getLangOpts().OpenCL && 11236 Context.getLangOpts().OpenCLVersion < 120) { 11237 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11238 // operate on scalar float types. 11239 if (!resultType->isIntegerType()) 11240 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11241 << resultType << Input.get()->getSourceRange()); 11242 } 11243 } else if (resultType->isExtVectorType()) { 11244 if (Context.getLangOpts().OpenCL && 11245 Context.getLangOpts().OpenCLVersion < 120) { 11246 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11247 // operate on vector float types. 11248 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11249 if (!T->isIntegerType()) 11250 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11251 << resultType << Input.get()->getSourceRange()); 11252 } 11253 // Vector logical not returns the signed variant of the operand type. 11254 resultType = GetSignedVectorType(resultType); 11255 break; 11256 } else { 11257 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11258 << resultType << Input.get()->getSourceRange()); 11259 } 11260 11261 // LNot always has type int. C99 6.5.3.3p5. 11262 // In C++, it's bool. C++ 5.3.1p8 11263 resultType = Context.getLogicalOperationType(); 11264 break; 11265 case UO_Real: 11266 case UO_Imag: 11267 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11268 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11269 // complex l-values to ordinary l-values and all other values to r-values. 11270 if (Input.isInvalid()) return ExprError(); 11271 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11272 if (Input.get()->getValueKind() != VK_RValue && 11273 Input.get()->getObjectKind() == OK_Ordinary) 11274 VK = Input.get()->getValueKind(); 11275 } else if (!getLangOpts().CPlusPlus) { 11276 // In C, a volatile scalar is read by __imag. In C++, it is not. 11277 Input = DefaultLvalueConversion(Input.get()); 11278 } 11279 break; 11280 case UO_Extension: 11281 case UO_Coawait: 11282 resultType = Input.get()->getType(); 11283 VK = Input.get()->getValueKind(); 11284 OK = Input.get()->getObjectKind(); 11285 break; 11286 } 11287 if (resultType.isNull() || Input.isInvalid()) 11288 return ExprError(); 11289 11290 // Check for array bounds violations in the operand of the UnaryOperator, 11291 // except for the '*' and '&' operators that have to be handled specially 11292 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11293 // that are explicitly defined as valid by the standard). 11294 if (Opc != UO_AddrOf && Opc != UO_Deref) 11295 CheckArrayAccess(Input.get()); 11296 11297 return new (Context) 11298 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11299 } 11300 11301 /// \brief Determine whether the given expression is a qualified member 11302 /// access expression, of a form that could be turned into a pointer to member 11303 /// with the address-of operator. 11304 static bool isQualifiedMemberAccess(Expr *E) { 11305 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11306 if (!DRE->getQualifier()) 11307 return false; 11308 11309 ValueDecl *VD = DRE->getDecl(); 11310 if (!VD->isCXXClassMember()) 11311 return false; 11312 11313 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11314 return true; 11315 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11316 return Method->isInstance(); 11317 11318 return false; 11319 } 11320 11321 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11322 if (!ULE->getQualifier()) 11323 return false; 11324 11325 for (NamedDecl *D : ULE->decls()) { 11326 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11327 if (Method->isInstance()) 11328 return true; 11329 } else { 11330 // Overload set does not contain methods. 11331 break; 11332 } 11333 } 11334 11335 return false; 11336 } 11337 11338 return false; 11339 } 11340 11341 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11342 UnaryOperatorKind Opc, Expr *Input) { 11343 // First things first: handle placeholders so that the 11344 // overloaded-operator check considers the right type. 11345 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11346 // Increment and decrement of pseudo-object references. 11347 if (pty->getKind() == BuiltinType::PseudoObject && 11348 UnaryOperator::isIncrementDecrementOp(Opc)) 11349 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11350 11351 // extension is always a builtin operator. 11352 if (Opc == UO_Extension) 11353 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11354 11355 // & gets special logic for several kinds of placeholder. 11356 // The builtin code knows what to do. 11357 if (Opc == UO_AddrOf && 11358 (pty->getKind() == BuiltinType::Overload || 11359 pty->getKind() == BuiltinType::UnknownAny || 11360 pty->getKind() == BuiltinType::BoundMember)) 11361 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11362 11363 // Anything else needs to be handled now. 11364 ExprResult Result = CheckPlaceholderExpr(Input); 11365 if (Result.isInvalid()) return ExprError(); 11366 Input = Result.get(); 11367 } 11368 11369 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11370 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11371 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11372 // Find all of the overloaded operators visible from this 11373 // point. We perform both an operator-name lookup from the local 11374 // scope and an argument-dependent lookup based on the types of 11375 // the arguments. 11376 UnresolvedSet<16> Functions; 11377 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11378 if (S && OverOp != OO_None) 11379 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11380 Functions); 11381 11382 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11383 } 11384 11385 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11386 } 11387 11388 // Unary Operators. 'Tok' is the token for the operator. 11389 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11390 tok::TokenKind Op, Expr *Input) { 11391 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11392 } 11393 11394 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11395 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11396 LabelDecl *TheDecl) { 11397 TheDecl->markUsed(Context); 11398 // Create the AST node. The address of a label always has type 'void*'. 11399 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11400 Context.getPointerType(Context.VoidTy)); 11401 } 11402 11403 /// Given the last statement in a statement-expression, check whether 11404 /// the result is a producing expression (like a call to an 11405 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11406 /// release out of the full-expression. Otherwise, return null. 11407 /// Cannot fail. 11408 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11409 // Should always be wrapped with one of these. 11410 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11411 if (!cleanups) return nullptr; 11412 11413 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11414 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11415 return nullptr; 11416 11417 // Splice out the cast. This shouldn't modify any interesting 11418 // features of the statement. 11419 Expr *producer = cast->getSubExpr(); 11420 assert(producer->getType() == cast->getType()); 11421 assert(producer->getValueKind() == cast->getValueKind()); 11422 cleanups->setSubExpr(producer); 11423 return cleanups; 11424 } 11425 11426 void Sema::ActOnStartStmtExpr() { 11427 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11428 } 11429 11430 void Sema::ActOnStmtExprError() { 11431 // Note that function is also called by TreeTransform when leaving a 11432 // StmtExpr scope without rebuilding anything. 11433 11434 DiscardCleanupsInEvaluationContext(); 11435 PopExpressionEvaluationContext(); 11436 } 11437 11438 ExprResult 11439 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11440 SourceLocation RPLoc) { // "({..})" 11441 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11442 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11443 11444 if (hasAnyUnrecoverableErrorsInThisFunction()) 11445 DiscardCleanupsInEvaluationContext(); 11446 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11447 PopExpressionEvaluationContext(); 11448 11449 // FIXME: there are a variety of strange constraints to enforce here, for 11450 // example, it is not possible to goto into a stmt expression apparently. 11451 // More semantic analysis is needed. 11452 11453 // If there are sub-stmts in the compound stmt, take the type of the last one 11454 // as the type of the stmtexpr. 11455 QualType Ty = Context.VoidTy; 11456 bool StmtExprMayBindToTemp = false; 11457 if (!Compound->body_empty()) { 11458 Stmt *LastStmt = Compound->body_back(); 11459 LabelStmt *LastLabelStmt = nullptr; 11460 // If LastStmt is a label, skip down through into the body. 11461 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11462 LastLabelStmt = Label; 11463 LastStmt = Label->getSubStmt(); 11464 } 11465 11466 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11467 // Do function/array conversion on the last expression, but not 11468 // lvalue-to-rvalue. However, initialize an unqualified type. 11469 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11470 if (LastExpr.isInvalid()) 11471 return ExprError(); 11472 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11473 11474 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11475 // In ARC, if the final expression ends in a consume, splice 11476 // the consume out and bind it later. In the alternate case 11477 // (when dealing with a retainable type), the result 11478 // initialization will create a produce. In both cases the 11479 // result will be +1, and we'll need to balance that out with 11480 // a bind. 11481 if (Expr *rebuiltLastStmt 11482 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11483 LastExpr = rebuiltLastStmt; 11484 } else { 11485 LastExpr = PerformCopyInitialization( 11486 InitializedEntity::InitializeResult(LPLoc, 11487 Ty, 11488 false), 11489 SourceLocation(), 11490 LastExpr); 11491 } 11492 11493 if (LastExpr.isInvalid()) 11494 return ExprError(); 11495 if (LastExpr.get() != nullptr) { 11496 if (!LastLabelStmt) 11497 Compound->setLastStmt(LastExpr.get()); 11498 else 11499 LastLabelStmt->setSubStmt(LastExpr.get()); 11500 StmtExprMayBindToTemp = true; 11501 } 11502 } 11503 } 11504 } 11505 11506 // FIXME: Check that expression type is complete/non-abstract; statement 11507 // expressions are not lvalues. 11508 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11509 if (StmtExprMayBindToTemp) 11510 return MaybeBindToTemporary(ResStmtExpr); 11511 return ResStmtExpr; 11512 } 11513 11514 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11515 TypeSourceInfo *TInfo, 11516 ArrayRef<OffsetOfComponent> Components, 11517 SourceLocation RParenLoc) { 11518 QualType ArgTy = TInfo->getType(); 11519 bool Dependent = ArgTy->isDependentType(); 11520 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11521 11522 // We must have at least one component that refers to the type, and the first 11523 // one is known to be a field designator. Verify that the ArgTy represents 11524 // a struct/union/class. 11525 if (!Dependent && !ArgTy->isRecordType()) 11526 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11527 << ArgTy << TypeRange); 11528 11529 // Type must be complete per C99 7.17p3 because a declaring a variable 11530 // with an incomplete type would be ill-formed. 11531 if (!Dependent 11532 && RequireCompleteType(BuiltinLoc, ArgTy, 11533 diag::err_offsetof_incomplete_type, TypeRange)) 11534 return ExprError(); 11535 11536 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11537 // GCC extension, diagnose them. 11538 // FIXME: This diagnostic isn't actually visible because the location is in 11539 // a system header! 11540 if (Components.size() != 1) 11541 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11542 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11543 11544 bool DidWarnAboutNonPOD = false; 11545 QualType CurrentType = ArgTy; 11546 SmallVector<OffsetOfNode, 4> Comps; 11547 SmallVector<Expr*, 4> Exprs; 11548 for (const OffsetOfComponent &OC : Components) { 11549 if (OC.isBrackets) { 11550 // Offset of an array sub-field. TODO: Should we allow vector elements? 11551 if (!CurrentType->isDependentType()) { 11552 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11553 if(!AT) 11554 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11555 << CurrentType); 11556 CurrentType = AT->getElementType(); 11557 } else 11558 CurrentType = Context.DependentTy; 11559 11560 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11561 if (IdxRval.isInvalid()) 11562 return ExprError(); 11563 Expr *Idx = IdxRval.get(); 11564 11565 // The expression must be an integral expression. 11566 // FIXME: An integral constant expression? 11567 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11568 !Idx->getType()->isIntegerType()) 11569 return ExprError(Diag(Idx->getLocStart(), 11570 diag::err_typecheck_subscript_not_integer) 11571 << Idx->getSourceRange()); 11572 11573 // Record this array index. 11574 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11575 Exprs.push_back(Idx); 11576 continue; 11577 } 11578 11579 // Offset of a field. 11580 if (CurrentType->isDependentType()) { 11581 // We have the offset of a field, but we can't look into the dependent 11582 // type. Just record the identifier of the field. 11583 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11584 CurrentType = Context.DependentTy; 11585 continue; 11586 } 11587 11588 // We need to have a complete type to look into. 11589 if (RequireCompleteType(OC.LocStart, CurrentType, 11590 diag::err_offsetof_incomplete_type)) 11591 return ExprError(); 11592 11593 // Look for the designated field. 11594 const RecordType *RC = CurrentType->getAs<RecordType>(); 11595 if (!RC) 11596 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11597 << CurrentType); 11598 RecordDecl *RD = RC->getDecl(); 11599 11600 // C++ [lib.support.types]p5: 11601 // The macro offsetof accepts a restricted set of type arguments in this 11602 // International Standard. type shall be a POD structure or a POD union 11603 // (clause 9). 11604 // C++11 [support.types]p4: 11605 // If type is not a standard-layout class (Clause 9), the results are 11606 // undefined. 11607 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11608 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11609 unsigned DiagID = 11610 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11611 : diag::ext_offsetof_non_pod_type; 11612 11613 if (!IsSafe && !DidWarnAboutNonPOD && 11614 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11615 PDiag(DiagID) 11616 << SourceRange(Components[0].LocStart, OC.LocEnd) 11617 << CurrentType)) 11618 DidWarnAboutNonPOD = true; 11619 } 11620 11621 // Look for the field. 11622 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11623 LookupQualifiedName(R, RD); 11624 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11625 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11626 if (!MemberDecl) { 11627 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11628 MemberDecl = IndirectMemberDecl->getAnonField(); 11629 } 11630 11631 if (!MemberDecl) 11632 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11633 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11634 OC.LocEnd)); 11635 11636 // C99 7.17p3: 11637 // (If the specified member is a bit-field, the behavior is undefined.) 11638 // 11639 // We diagnose this as an error. 11640 if (MemberDecl->isBitField()) { 11641 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11642 << MemberDecl->getDeclName() 11643 << SourceRange(BuiltinLoc, RParenLoc); 11644 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11645 return ExprError(); 11646 } 11647 11648 RecordDecl *Parent = MemberDecl->getParent(); 11649 if (IndirectMemberDecl) 11650 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11651 11652 // If the member was found in a base class, introduce OffsetOfNodes for 11653 // the base class indirections. 11654 CXXBasePaths Paths; 11655 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11656 Paths)) { 11657 if (Paths.getDetectedVirtual()) { 11658 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11659 << MemberDecl->getDeclName() 11660 << SourceRange(BuiltinLoc, RParenLoc); 11661 return ExprError(); 11662 } 11663 11664 CXXBasePath &Path = Paths.front(); 11665 for (const CXXBasePathElement &B : Path) 11666 Comps.push_back(OffsetOfNode(B.Base)); 11667 } 11668 11669 if (IndirectMemberDecl) { 11670 for (auto *FI : IndirectMemberDecl->chain()) { 11671 assert(isa<FieldDecl>(FI)); 11672 Comps.push_back(OffsetOfNode(OC.LocStart, 11673 cast<FieldDecl>(FI), OC.LocEnd)); 11674 } 11675 } else 11676 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11677 11678 CurrentType = MemberDecl->getType().getNonReferenceType(); 11679 } 11680 11681 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11682 Comps, Exprs, RParenLoc); 11683 } 11684 11685 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11686 SourceLocation BuiltinLoc, 11687 SourceLocation TypeLoc, 11688 ParsedType ParsedArgTy, 11689 ArrayRef<OffsetOfComponent> Components, 11690 SourceLocation RParenLoc) { 11691 11692 TypeSourceInfo *ArgTInfo; 11693 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11694 if (ArgTy.isNull()) 11695 return ExprError(); 11696 11697 if (!ArgTInfo) 11698 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11699 11700 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11701 } 11702 11703 11704 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11705 Expr *CondExpr, 11706 Expr *LHSExpr, Expr *RHSExpr, 11707 SourceLocation RPLoc) { 11708 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11709 11710 ExprValueKind VK = VK_RValue; 11711 ExprObjectKind OK = OK_Ordinary; 11712 QualType resType; 11713 bool ValueDependent = false; 11714 bool CondIsTrue = false; 11715 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11716 resType = Context.DependentTy; 11717 ValueDependent = true; 11718 } else { 11719 // The conditional expression is required to be a constant expression. 11720 llvm::APSInt condEval(32); 11721 ExprResult CondICE 11722 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11723 diag::err_typecheck_choose_expr_requires_constant, false); 11724 if (CondICE.isInvalid()) 11725 return ExprError(); 11726 CondExpr = CondICE.get(); 11727 CondIsTrue = condEval.getZExtValue(); 11728 11729 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11730 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11731 11732 resType = ActiveExpr->getType(); 11733 ValueDependent = ActiveExpr->isValueDependent(); 11734 VK = ActiveExpr->getValueKind(); 11735 OK = ActiveExpr->getObjectKind(); 11736 } 11737 11738 return new (Context) 11739 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11740 CondIsTrue, resType->isDependentType(), ValueDependent); 11741 } 11742 11743 //===----------------------------------------------------------------------===// 11744 // Clang Extensions. 11745 //===----------------------------------------------------------------------===// 11746 11747 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11748 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11749 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11750 11751 if (LangOpts.CPlusPlus) { 11752 Decl *ManglingContextDecl; 11753 if (MangleNumberingContext *MCtx = 11754 getCurrentMangleNumberContext(Block->getDeclContext(), 11755 ManglingContextDecl)) { 11756 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11757 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11758 } 11759 } 11760 11761 PushBlockScope(CurScope, Block); 11762 CurContext->addDecl(Block); 11763 if (CurScope) 11764 PushDeclContext(CurScope, Block); 11765 else 11766 CurContext = Block; 11767 11768 getCurBlock()->HasImplicitReturnType = true; 11769 11770 // Enter a new evaluation context to insulate the block from any 11771 // cleanups from the enclosing full-expression. 11772 PushExpressionEvaluationContext(PotentiallyEvaluated); 11773 } 11774 11775 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11776 Scope *CurScope) { 11777 assert(ParamInfo.getIdentifier() == nullptr && 11778 "block-id should have no identifier!"); 11779 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11780 BlockScopeInfo *CurBlock = getCurBlock(); 11781 11782 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11783 QualType T = Sig->getType(); 11784 11785 // FIXME: We should allow unexpanded parameter packs here, but that would, 11786 // in turn, make the block expression contain unexpanded parameter packs. 11787 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11788 // Drop the parameters. 11789 FunctionProtoType::ExtProtoInfo EPI; 11790 EPI.HasTrailingReturn = false; 11791 EPI.TypeQuals |= DeclSpec::TQ_const; 11792 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11793 Sig = Context.getTrivialTypeSourceInfo(T); 11794 } 11795 11796 // GetTypeForDeclarator always produces a function type for a block 11797 // literal signature. Furthermore, it is always a FunctionProtoType 11798 // unless the function was written with a typedef. 11799 assert(T->isFunctionType() && 11800 "GetTypeForDeclarator made a non-function block signature"); 11801 11802 // Look for an explicit signature in that function type. 11803 FunctionProtoTypeLoc ExplicitSignature; 11804 11805 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11806 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11807 11808 // Check whether that explicit signature was synthesized by 11809 // GetTypeForDeclarator. If so, don't save that as part of the 11810 // written signature. 11811 if (ExplicitSignature.getLocalRangeBegin() == 11812 ExplicitSignature.getLocalRangeEnd()) { 11813 // This would be much cheaper if we stored TypeLocs instead of 11814 // TypeSourceInfos. 11815 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11816 unsigned Size = Result.getFullDataSize(); 11817 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11818 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11819 11820 ExplicitSignature = FunctionProtoTypeLoc(); 11821 } 11822 } 11823 11824 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11825 CurBlock->FunctionType = T; 11826 11827 const FunctionType *Fn = T->getAs<FunctionType>(); 11828 QualType RetTy = Fn->getReturnType(); 11829 bool isVariadic = 11830 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11831 11832 CurBlock->TheDecl->setIsVariadic(isVariadic); 11833 11834 // Context.DependentTy is used as a placeholder for a missing block 11835 // return type. TODO: what should we do with declarators like: 11836 // ^ * { ... } 11837 // If the answer is "apply template argument deduction".... 11838 if (RetTy != Context.DependentTy) { 11839 CurBlock->ReturnType = RetTy; 11840 CurBlock->TheDecl->setBlockMissingReturnType(false); 11841 CurBlock->HasImplicitReturnType = false; 11842 } 11843 11844 // Push block parameters from the declarator if we had them. 11845 SmallVector<ParmVarDecl*, 8> Params; 11846 if (ExplicitSignature) { 11847 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11848 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11849 if (Param->getIdentifier() == nullptr && 11850 !Param->isImplicit() && 11851 !Param->isInvalidDecl() && 11852 !getLangOpts().CPlusPlus) 11853 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11854 Params.push_back(Param); 11855 } 11856 11857 // Fake up parameter variables if we have a typedef, like 11858 // ^ fntype { ... } 11859 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11860 for (const auto &I : Fn->param_types()) { 11861 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11862 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11863 Params.push_back(Param); 11864 } 11865 } 11866 11867 // Set the parameters on the block decl. 11868 if (!Params.empty()) { 11869 CurBlock->TheDecl->setParams(Params); 11870 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11871 CurBlock->TheDecl->param_end(), 11872 /*CheckParameterNames=*/false); 11873 } 11874 11875 // Finally we can process decl attributes. 11876 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11877 11878 // Put the parameter variables in scope. 11879 for (auto AI : CurBlock->TheDecl->params()) { 11880 AI->setOwningFunction(CurBlock->TheDecl); 11881 11882 // If this has an identifier, add it to the scope stack. 11883 if (AI->getIdentifier()) { 11884 CheckShadow(CurBlock->TheScope, AI); 11885 11886 PushOnScopeChains(AI, CurBlock->TheScope); 11887 } 11888 } 11889 } 11890 11891 /// ActOnBlockError - If there is an error parsing a block, this callback 11892 /// is invoked to pop the information about the block from the action impl. 11893 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11894 // Leave the expression-evaluation context. 11895 DiscardCleanupsInEvaluationContext(); 11896 PopExpressionEvaluationContext(); 11897 11898 // Pop off CurBlock, handle nested blocks. 11899 PopDeclContext(); 11900 PopFunctionScopeInfo(); 11901 } 11902 11903 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11904 /// literal was successfully completed. ^(int x){...} 11905 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11906 Stmt *Body, Scope *CurScope) { 11907 // If blocks are disabled, emit an error. 11908 if (!LangOpts.Blocks) 11909 Diag(CaretLoc, diag::err_blocks_disable); 11910 11911 // Leave the expression-evaluation context. 11912 if (hasAnyUnrecoverableErrorsInThisFunction()) 11913 DiscardCleanupsInEvaluationContext(); 11914 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11915 PopExpressionEvaluationContext(); 11916 11917 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11918 11919 if (BSI->HasImplicitReturnType) 11920 deduceClosureReturnType(*BSI); 11921 11922 PopDeclContext(); 11923 11924 QualType RetTy = Context.VoidTy; 11925 if (!BSI->ReturnType.isNull()) 11926 RetTy = BSI->ReturnType; 11927 11928 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11929 QualType BlockTy; 11930 11931 // Set the captured variables on the block. 11932 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11933 SmallVector<BlockDecl::Capture, 4> Captures; 11934 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 11935 if (Cap.isThisCapture()) 11936 continue; 11937 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11938 Cap.isNested(), Cap.getInitExpr()); 11939 Captures.push_back(NewCap); 11940 } 11941 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 11942 11943 // If the user wrote a function type in some form, try to use that. 11944 if (!BSI->FunctionType.isNull()) { 11945 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11946 11947 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11948 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11949 11950 // Turn protoless block types into nullary block types. 11951 if (isa<FunctionNoProtoType>(FTy)) { 11952 FunctionProtoType::ExtProtoInfo EPI; 11953 EPI.ExtInfo = Ext; 11954 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11955 11956 // Otherwise, if we don't need to change anything about the function type, 11957 // preserve its sugar structure. 11958 } else if (FTy->getReturnType() == RetTy && 11959 (!NoReturn || FTy->getNoReturnAttr())) { 11960 BlockTy = BSI->FunctionType; 11961 11962 // Otherwise, make the minimal modifications to the function type. 11963 } else { 11964 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11965 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11966 EPI.TypeQuals = 0; // FIXME: silently? 11967 EPI.ExtInfo = Ext; 11968 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11969 } 11970 11971 // If we don't have a function type, just build one from nothing. 11972 } else { 11973 FunctionProtoType::ExtProtoInfo EPI; 11974 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11975 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11976 } 11977 11978 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11979 BSI->TheDecl->param_end()); 11980 BlockTy = Context.getBlockPointerType(BlockTy); 11981 11982 // If needed, diagnose invalid gotos and switches in the block. 11983 if (getCurFunction()->NeedsScopeChecking() && 11984 !PP.isCodeCompletionEnabled()) 11985 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11986 11987 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11988 11989 // Try to apply the named return value optimization. We have to check again 11990 // if we can do this, though, because blocks keep return statements around 11991 // to deduce an implicit return type. 11992 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11993 !BSI->TheDecl->isDependentContext()) 11994 computeNRVO(Body, BSI); 11995 11996 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11997 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11998 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11999 12000 // If the block isn't obviously global, i.e. it captures anything at 12001 // all, then we need to do a few things in the surrounding context: 12002 if (Result->getBlockDecl()->hasCaptures()) { 12003 // First, this expression has a new cleanup object. 12004 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12005 ExprNeedsCleanups = true; 12006 12007 // It also gets a branch-protected scope if any of the captured 12008 // variables needs destruction. 12009 for (const auto &CI : Result->getBlockDecl()->captures()) { 12010 const VarDecl *var = CI.getVariable(); 12011 if (var->getType().isDestructedType() != QualType::DK_none) { 12012 getCurFunction()->setHasBranchProtectedScope(); 12013 break; 12014 } 12015 } 12016 } 12017 12018 return Result; 12019 } 12020 12021 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12022 SourceLocation RPLoc) { 12023 TypeSourceInfo *TInfo; 12024 GetTypeFromParser(Ty, &TInfo); 12025 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12026 } 12027 12028 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12029 Expr *E, TypeSourceInfo *TInfo, 12030 SourceLocation RPLoc) { 12031 Expr *OrigExpr = E; 12032 bool IsMS = false; 12033 12034 // CUDA device code does not support varargs. 12035 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12036 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12037 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12038 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12039 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12040 } 12041 } 12042 12043 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12044 // as Microsoft ABI on an actual Microsoft platform, where 12045 // __builtin_ms_va_list and __builtin_va_list are the same.) 12046 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12047 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12048 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12049 if (Context.hasSameType(MSVaListType, E->getType())) { 12050 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12051 return ExprError(); 12052 IsMS = true; 12053 } 12054 } 12055 12056 // Get the va_list type 12057 QualType VaListType = Context.getBuiltinVaListType(); 12058 if (!IsMS) { 12059 if (VaListType->isArrayType()) { 12060 // Deal with implicit array decay; for example, on x86-64, 12061 // va_list is an array, but it's supposed to decay to 12062 // a pointer for va_arg. 12063 VaListType = Context.getArrayDecayedType(VaListType); 12064 // Make sure the input expression also decays appropriately. 12065 ExprResult Result = UsualUnaryConversions(E); 12066 if (Result.isInvalid()) 12067 return ExprError(); 12068 E = Result.get(); 12069 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12070 // If va_list is a record type and we are compiling in C++ mode, 12071 // check the argument using reference binding. 12072 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12073 Context, Context.getLValueReferenceType(VaListType), false); 12074 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12075 if (Init.isInvalid()) 12076 return ExprError(); 12077 E = Init.getAs<Expr>(); 12078 } else { 12079 // Otherwise, the va_list argument must be an l-value because 12080 // it is modified by va_arg. 12081 if (!E->isTypeDependent() && 12082 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12083 return ExprError(); 12084 } 12085 } 12086 12087 if (!IsMS && !E->isTypeDependent() && 12088 !Context.hasSameType(VaListType, E->getType())) 12089 return ExprError(Diag(E->getLocStart(), 12090 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12091 << OrigExpr->getType() << E->getSourceRange()); 12092 12093 if (!TInfo->getType()->isDependentType()) { 12094 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12095 diag::err_second_parameter_to_va_arg_incomplete, 12096 TInfo->getTypeLoc())) 12097 return ExprError(); 12098 12099 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12100 TInfo->getType(), 12101 diag::err_second_parameter_to_va_arg_abstract, 12102 TInfo->getTypeLoc())) 12103 return ExprError(); 12104 12105 if (!TInfo->getType().isPODType(Context)) { 12106 Diag(TInfo->getTypeLoc().getBeginLoc(), 12107 TInfo->getType()->isObjCLifetimeType() 12108 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12109 : diag::warn_second_parameter_to_va_arg_not_pod) 12110 << TInfo->getType() 12111 << TInfo->getTypeLoc().getSourceRange(); 12112 } 12113 12114 // Check for va_arg where arguments of the given type will be promoted 12115 // (i.e. this va_arg is guaranteed to have undefined behavior). 12116 QualType PromoteType; 12117 if (TInfo->getType()->isPromotableIntegerType()) { 12118 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12119 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12120 PromoteType = QualType(); 12121 } 12122 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12123 PromoteType = Context.DoubleTy; 12124 if (!PromoteType.isNull()) 12125 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12126 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12127 << TInfo->getType() 12128 << PromoteType 12129 << TInfo->getTypeLoc().getSourceRange()); 12130 } 12131 12132 QualType T = TInfo->getType().getNonLValueExprType(Context); 12133 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12134 } 12135 12136 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12137 // The type of __null will be int or long, depending on the size of 12138 // pointers on the target. 12139 QualType Ty; 12140 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12141 if (pw == Context.getTargetInfo().getIntWidth()) 12142 Ty = Context.IntTy; 12143 else if (pw == Context.getTargetInfo().getLongWidth()) 12144 Ty = Context.LongTy; 12145 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12146 Ty = Context.LongLongTy; 12147 else { 12148 llvm_unreachable("I don't know size of pointer!"); 12149 } 12150 12151 return new (Context) GNUNullExpr(Ty, TokenLoc); 12152 } 12153 12154 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12155 bool Diagnose) { 12156 if (!getLangOpts().ObjC1) 12157 return false; 12158 12159 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12160 if (!PT) 12161 return false; 12162 12163 if (!PT->isObjCIdType()) { 12164 // Check if the destination is the 'NSString' interface. 12165 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12166 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12167 return false; 12168 } 12169 12170 // Ignore any parens, implicit casts (should only be 12171 // array-to-pointer decays), and not-so-opaque values. The last is 12172 // important for making this trigger for property assignments. 12173 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12174 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12175 if (OV->getSourceExpr()) 12176 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12177 12178 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12179 if (!SL || !SL->isAscii()) 12180 return false; 12181 if (Diagnose) { 12182 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12183 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12184 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12185 } 12186 return true; 12187 } 12188 12189 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12190 const Expr *SrcExpr) { 12191 if (!DstType->isFunctionPointerType() || 12192 !SrcExpr->getType()->isFunctionType()) 12193 return false; 12194 12195 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12196 if (!DRE) 12197 return false; 12198 12199 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12200 if (!FD) 12201 return false; 12202 12203 return !S.checkAddressOfFunctionIsAvailable(FD, 12204 /*Complain=*/true, 12205 SrcExpr->getLocStart()); 12206 } 12207 12208 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12209 SourceLocation Loc, 12210 QualType DstType, QualType SrcType, 12211 Expr *SrcExpr, AssignmentAction Action, 12212 bool *Complained) { 12213 if (Complained) 12214 *Complained = false; 12215 12216 // Decode the result (notice that AST's are still created for extensions). 12217 bool CheckInferredResultType = false; 12218 bool isInvalid = false; 12219 unsigned DiagKind = 0; 12220 FixItHint Hint; 12221 ConversionFixItGenerator ConvHints; 12222 bool MayHaveConvFixit = false; 12223 bool MayHaveFunctionDiff = false; 12224 const ObjCInterfaceDecl *IFace = nullptr; 12225 const ObjCProtocolDecl *PDecl = nullptr; 12226 12227 switch (ConvTy) { 12228 case Compatible: 12229 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12230 return false; 12231 12232 case PointerToInt: 12233 DiagKind = diag::ext_typecheck_convert_pointer_int; 12234 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12235 MayHaveConvFixit = true; 12236 break; 12237 case IntToPointer: 12238 DiagKind = diag::ext_typecheck_convert_int_pointer; 12239 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12240 MayHaveConvFixit = true; 12241 break; 12242 case IncompatiblePointer: 12243 DiagKind = 12244 (Action == AA_Passing_CFAudited ? 12245 diag::err_arc_typecheck_convert_incompatible_pointer : 12246 diag::ext_typecheck_convert_incompatible_pointer); 12247 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12248 SrcType->isObjCObjectPointerType(); 12249 if (Hint.isNull() && !CheckInferredResultType) { 12250 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12251 } 12252 else if (CheckInferredResultType) { 12253 SrcType = SrcType.getUnqualifiedType(); 12254 DstType = DstType.getUnqualifiedType(); 12255 } 12256 MayHaveConvFixit = true; 12257 break; 12258 case IncompatiblePointerSign: 12259 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12260 break; 12261 case FunctionVoidPointer: 12262 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12263 break; 12264 case IncompatiblePointerDiscardsQualifiers: { 12265 // Perform array-to-pointer decay if necessary. 12266 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12267 12268 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12269 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12270 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12271 DiagKind = diag::err_typecheck_incompatible_address_space; 12272 break; 12273 12274 12275 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12276 DiagKind = diag::err_typecheck_incompatible_ownership; 12277 break; 12278 } 12279 12280 llvm_unreachable("unknown error case for discarding qualifiers!"); 12281 // fallthrough 12282 } 12283 case CompatiblePointerDiscardsQualifiers: 12284 // If the qualifiers lost were because we were applying the 12285 // (deprecated) C++ conversion from a string literal to a char* 12286 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12287 // Ideally, this check would be performed in 12288 // checkPointerTypesForAssignment. However, that would require a 12289 // bit of refactoring (so that the second argument is an 12290 // expression, rather than a type), which should be done as part 12291 // of a larger effort to fix checkPointerTypesForAssignment for 12292 // C++ semantics. 12293 if (getLangOpts().CPlusPlus && 12294 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12295 return false; 12296 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12297 break; 12298 case IncompatibleNestedPointerQualifiers: 12299 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12300 break; 12301 case IntToBlockPointer: 12302 DiagKind = diag::err_int_to_block_pointer; 12303 break; 12304 case IncompatibleBlockPointer: 12305 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12306 break; 12307 case IncompatibleObjCQualifiedId: { 12308 if (SrcType->isObjCQualifiedIdType()) { 12309 const ObjCObjectPointerType *srcOPT = 12310 SrcType->getAs<ObjCObjectPointerType>(); 12311 for (auto *srcProto : srcOPT->quals()) { 12312 PDecl = srcProto; 12313 break; 12314 } 12315 if (const ObjCInterfaceType *IFaceT = 12316 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12317 IFace = IFaceT->getDecl(); 12318 } 12319 else if (DstType->isObjCQualifiedIdType()) { 12320 const ObjCObjectPointerType *dstOPT = 12321 DstType->getAs<ObjCObjectPointerType>(); 12322 for (auto *dstProto : dstOPT->quals()) { 12323 PDecl = dstProto; 12324 break; 12325 } 12326 if (const ObjCInterfaceType *IFaceT = 12327 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12328 IFace = IFaceT->getDecl(); 12329 } 12330 DiagKind = diag::warn_incompatible_qualified_id; 12331 break; 12332 } 12333 case IncompatibleVectors: 12334 DiagKind = diag::warn_incompatible_vectors; 12335 break; 12336 case IncompatibleObjCWeakRef: 12337 DiagKind = diag::err_arc_weak_unavailable_assign; 12338 break; 12339 case Incompatible: 12340 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12341 if (Complained) 12342 *Complained = true; 12343 return true; 12344 } 12345 12346 DiagKind = diag::err_typecheck_convert_incompatible; 12347 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12348 MayHaveConvFixit = true; 12349 isInvalid = true; 12350 MayHaveFunctionDiff = true; 12351 break; 12352 } 12353 12354 QualType FirstType, SecondType; 12355 switch (Action) { 12356 case AA_Assigning: 12357 case AA_Initializing: 12358 // The destination type comes first. 12359 FirstType = DstType; 12360 SecondType = SrcType; 12361 break; 12362 12363 case AA_Returning: 12364 case AA_Passing: 12365 case AA_Passing_CFAudited: 12366 case AA_Converting: 12367 case AA_Sending: 12368 case AA_Casting: 12369 // The source type comes first. 12370 FirstType = SrcType; 12371 SecondType = DstType; 12372 break; 12373 } 12374 12375 PartialDiagnostic FDiag = PDiag(DiagKind); 12376 if (Action == AA_Passing_CFAudited) 12377 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12378 else 12379 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12380 12381 // If we can fix the conversion, suggest the FixIts. 12382 assert(ConvHints.isNull() || Hint.isNull()); 12383 if (!ConvHints.isNull()) { 12384 for (FixItHint &H : ConvHints.Hints) 12385 FDiag << H; 12386 } else { 12387 FDiag << Hint; 12388 } 12389 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12390 12391 if (MayHaveFunctionDiff) 12392 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12393 12394 Diag(Loc, FDiag); 12395 if (DiagKind == diag::warn_incompatible_qualified_id && 12396 PDecl && IFace && !IFace->hasDefinition()) 12397 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12398 << IFace->getName() << PDecl->getName(); 12399 12400 if (SecondType == Context.OverloadTy) 12401 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12402 FirstType, /*TakingAddress=*/true); 12403 12404 if (CheckInferredResultType) 12405 EmitRelatedResultTypeNote(SrcExpr); 12406 12407 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12408 EmitRelatedResultTypeNoteForReturn(DstType); 12409 12410 if (Complained) 12411 *Complained = true; 12412 return isInvalid; 12413 } 12414 12415 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12416 llvm::APSInt *Result) { 12417 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12418 public: 12419 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12420 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12421 } 12422 } Diagnoser; 12423 12424 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12425 } 12426 12427 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12428 llvm::APSInt *Result, 12429 unsigned DiagID, 12430 bool AllowFold) { 12431 class IDDiagnoser : public VerifyICEDiagnoser { 12432 unsigned DiagID; 12433 12434 public: 12435 IDDiagnoser(unsigned DiagID) 12436 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12437 12438 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12439 S.Diag(Loc, DiagID) << SR; 12440 } 12441 } Diagnoser(DiagID); 12442 12443 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12444 } 12445 12446 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12447 SourceRange SR) { 12448 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12449 } 12450 12451 ExprResult 12452 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12453 VerifyICEDiagnoser &Diagnoser, 12454 bool AllowFold) { 12455 SourceLocation DiagLoc = E->getLocStart(); 12456 12457 if (getLangOpts().CPlusPlus11) { 12458 // C++11 [expr.const]p5: 12459 // If an expression of literal class type is used in a context where an 12460 // integral constant expression is required, then that class type shall 12461 // have a single non-explicit conversion function to an integral or 12462 // unscoped enumeration type 12463 ExprResult Converted; 12464 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12465 public: 12466 CXX11ConvertDiagnoser(bool Silent) 12467 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12468 Silent, true) {} 12469 12470 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12471 QualType T) override { 12472 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12473 } 12474 12475 SemaDiagnosticBuilder diagnoseIncomplete( 12476 Sema &S, SourceLocation Loc, QualType T) override { 12477 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12478 } 12479 12480 SemaDiagnosticBuilder diagnoseExplicitConv( 12481 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12482 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12483 } 12484 12485 SemaDiagnosticBuilder noteExplicitConv( 12486 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12487 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12488 << ConvTy->isEnumeralType() << ConvTy; 12489 } 12490 12491 SemaDiagnosticBuilder diagnoseAmbiguous( 12492 Sema &S, SourceLocation Loc, QualType T) override { 12493 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12494 } 12495 12496 SemaDiagnosticBuilder noteAmbiguous( 12497 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12498 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12499 << ConvTy->isEnumeralType() << ConvTy; 12500 } 12501 12502 SemaDiagnosticBuilder diagnoseConversion( 12503 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12504 llvm_unreachable("conversion functions are permitted"); 12505 } 12506 } ConvertDiagnoser(Diagnoser.Suppress); 12507 12508 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12509 ConvertDiagnoser); 12510 if (Converted.isInvalid()) 12511 return Converted; 12512 E = Converted.get(); 12513 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12514 return ExprError(); 12515 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12516 // An ICE must be of integral or unscoped enumeration type. 12517 if (!Diagnoser.Suppress) 12518 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12519 return ExprError(); 12520 } 12521 12522 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12523 // in the non-ICE case. 12524 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12525 if (Result) 12526 *Result = E->EvaluateKnownConstInt(Context); 12527 return E; 12528 } 12529 12530 Expr::EvalResult EvalResult; 12531 SmallVector<PartialDiagnosticAt, 8> Notes; 12532 EvalResult.Diag = &Notes; 12533 12534 // Try to evaluate the expression, and produce diagnostics explaining why it's 12535 // not a constant expression as a side-effect. 12536 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12537 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12538 12539 // In C++11, we can rely on diagnostics being produced for any expression 12540 // which is not a constant expression. If no diagnostics were produced, then 12541 // this is a constant expression. 12542 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12543 if (Result) 12544 *Result = EvalResult.Val.getInt(); 12545 return E; 12546 } 12547 12548 // If our only note is the usual "invalid subexpression" note, just point 12549 // the caret at its location rather than producing an essentially 12550 // redundant note. 12551 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12552 diag::note_invalid_subexpr_in_const_expr) { 12553 DiagLoc = Notes[0].first; 12554 Notes.clear(); 12555 } 12556 12557 if (!Folded || !AllowFold) { 12558 if (!Diagnoser.Suppress) { 12559 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12560 for (const PartialDiagnosticAt &Note : Notes) 12561 Diag(Note.first, Note.second); 12562 } 12563 12564 return ExprError(); 12565 } 12566 12567 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12568 for (const PartialDiagnosticAt &Note : Notes) 12569 Diag(Note.first, Note.second); 12570 12571 if (Result) 12572 *Result = EvalResult.Val.getInt(); 12573 return E; 12574 } 12575 12576 namespace { 12577 // Handle the case where we conclude a expression which we speculatively 12578 // considered to be unevaluated is actually evaluated. 12579 class TransformToPE : public TreeTransform<TransformToPE> { 12580 typedef TreeTransform<TransformToPE> BaseTransform; 12581 12582 public: 12583 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12584 12585 // Make sure we redo semantic analysis 12586 bool AlwaysRebuild() { return true; } 12587 12588 // Make sure we handle LabelStmts correctly. 12589 // FIXME: This does the right thing, but maybe we need a more general 12590 // fix to TreeTransform? 12591 StmtResult TransformLabelStmt(LabelStmt *S) { 12592 S->getDecl()->setStmt(nullptr); 12593 return BaseTransform::TransformLabelStmt(S); 12594 } 12595 12596 // We need to special-case DeclRefExprs referring to FieldDecls which 12597 // are not part of a member pointer formation; normal TreeTransforming 12598 // doesn't catch this case because of the way we represent them in the AST. 12599 // FIXME: This is a bit ugly; is it really the best way to handle this 12600 // case? 12601 // 12602 // Error on DeclRefExprs referring to FieldDecls. 12603 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12604 if (isa<FieldDecl>(E->getDecl()) && 12605 !SemaRef.isUnevaluatedContext()) 12606 return SemaRef.Diag(E->getLocation(), 12607 diag::err_invalid_non_static_member_use) 12608 << E->getDecl() << E->getSourceRange(); 12609 12610 return BaseTransform::TransformDeclRefExpr(E); 12611 } 12612 12613 // Exception: filter out member pointer formation 12614 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12615 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12616 return E; 12617 12618 return BaseTransform::TransformUnaryOperator(E); 12619 } 12620 12621 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12622 // Lambdas never need to be transformed. 12623 return E; 12624 } 12625 }; 12626 } 12627 12628 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12629 assert(isUnevaluatedContext() && 12630 "Should only transform unevaluated expressions"); 12631 ExprEvalContexts.back().Context = 12632 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12633 if (isUnevaluatedContext()) 12634 return E; 12635 return TransformToPE(*this).TransformExpr(E); 12636 } 12637 12638 void 12639 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12640 Decl *LambdaContextDecl, 12641 bool IsDecltype) { 12642 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12643 ExprNeedsCleanups, LambdaContextDecl, 12644 IsDecltype); 12645 ExprNeedsCleanups = false; 12646 if (!MaybeODRUseExprs.empty()) 12647 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12648 } 12649 12650 void 12651 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12652 ReuseLambdaContextDecl_t, 12653 bool IsDecltype) { 12654 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12655 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12656 } 12657 12658 void Sema::PopExpressionEvaluationContext() { 12659 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12660 unsigned NumTypos = Rec.NumTypos; 12661 12662 if (!Rec.Lambdas.empty()) { 12663 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12664 unsigned D; 12665 if (Rec.isUnevaluated()) { 12666 // C++11 [expr.prim.lambda]p2: 12667 // A lambda-expression shall not appear in an unevaluated operand 12668 // (Clause 5). 12669 D = diag::err_lambda_unevaluated_operand; 12670 } else { 12671 // C++1y [expr.const]p2: 12672 // A conditional-expression e is a core constant expression unless the 12673 // evaluation of e, following the rules of the abstract machine, would 12674 // evaluate [...] a lambda-expression. 12675 D = diag::err_lambda_in_constant_expression; 12676 } 12677 for (const auto *L : Rec.Lambdas) 12678 Diag(L->getLocStart(), D); 12679 } else { 12680 // Mark the capture expressions odr-used. This was deferred 12681 // during lambda expression creation. 12682 for (auto *Lambda : Rec.Lambdas) { 12683 for (auto *C : Lambda->capture_inits()) 12684 MarkDeclarationsReferencedInExpr(C); 12685 } 12686 } 12687 } 12688 12689 // When are coming out of an unevaluated context, clear out any 12690 // temporaries that we may have created as part of the evaluation of 12691 // the expression in that context: they aren't relevant because they 12692 // will never be constructed. 12693 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12694 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12695 ExprCleanupObjects.end()); 12696 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12697 CleanupVarDeclMarking(); 12698 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12699 // Otherwise, merge the contexts together. 12700 } else { 12701 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12702 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12703 Rec.SavedMaybeODRUseExprs.end()); 12704 } 12705 12706 // Pop the current expression evaluation context off the stack. 12707 ExprEvalContexts.pop_back(); 12708 12709 if (!ExprEvalContexts.empty()) 12710 ExprEvalContexts.back().NumTypos += NumTypos; 12711 else 12712 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12713 "last ExpressionEvaluationContextRecord"); 12714 } 12715 12716 void Sema::DiscardCleanupsInEvaluationContext() { 12717 ExprCleanupObjects.erase( 12718 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12719 ExprCleanupObjects.end()); 12720 ExprNeedsCleanups = false; 12721 MaybeODRUseExprs.clear(); 12722 } 12723 12724 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12725 if (!E->getType()->isVariablyModifiedType()) 12726 return E; 12727 return TransformToPotentiallyEvaluated(E); 12728 } 12729 12730 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12731 // Do not mark anything as "used" within a dependent context; wait for 12732 // an instantiation. 12733 if (SemaRef.CurContext->isDependentContext()) 12734 return false; 12735 12736 switch (SemaRef.ExprEvalContexts.back().Context) { 12737 case Sema::Unevaluated: 12738 case Sema::UnevaluatedAbstract: 12739 // We are in an expression that is not potentially evaluated; do nothing. 12740 // (Depending on how you read the standard, we actually do need to do 12741 // something here for null pointer constants, but the standard's 12742 // definition of a null pointer constant is completely crazy.) 12743 return false; 12744 12745 case Sema::ConstantEvaluated: 12746 case Sema::PotentiallyEvaluated: 12747 // We are in a potentially evaluated expression (or a constant-expression 12748 // in C++03); we need to do implicit template instantiation, implicitly 12749 // define class members, and mark most declarations as used. 12750 return true; 12751 12752 case Sema::PotentiallyEvaluatedIfUsed: 12753 // Referenced declarations will only be used if the construct in the 12754 // containing expression is used. 12755 return false; 12756 } 12757 llvm_unreachable("Invalid context"); 12758 } 12759 12760 /// \brief Mark a function referenced, and check whether it is odr-used 12761 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12762 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12763 bool OdrUse) { 12764 assert(Func && "No function?"); 12765 12766 Func->setReferenced(); 12767 12768 // C++11 [basic.def.odr]p3: 12769 // A function whose name appears as a potentially-evaluated expression is 12770 // odr-used if it is the unique lookup result or the selected member of a 12771 // set of overloaded functions [...]. 12772 // 12773 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12774 // can just check that here. Skip the rest of this function if we've already 12775 // marked the function as used. 12776 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12777 !IsPotentiallyEvaluatedContext(*this)) { 12778 // C++11 [temp.inst]p3: 12779 // Unless a function template specialization has been explicitly 12780 // instantiated or explicitly specialized, the function template 12781 // specialization is implicitly instantiated when the specialization is 12782 // referenced in a context that requires a function definition to exist. 12783 // 12784 // We consider constexpr function templates to be referenced in a context 12785 // that requires a definition to exist whenever they are referenced. 12786 // 12787 // FIXME: This instantiates constexpr functions too frequently. If this is 12788 // really an unevaluated context (and we're not just in the definition of a 12789 // function template or overload resolution or other cases which we 12790 // incorrectly consider to be unevaluated contexts), and we're not in a 12791 // subexpression which we actually need to evaluate (for instance, a 12792 // template argument, array bound or an expression in a braced-init-list), 12793 // we are not permitted to instantiate this constexpr function definition. 12794 // 12795 // FIXME: This also implicitly defines special members too frequently. They 12796 // are only supposed to be implicitly defined if they are odr-used, but they 12797 // are not odr-used from constant expressions in unevaluated contexts. 12798 // However, they cannot be referenced if they are deleted, and they are 12799 // deleted whenever the implicit definition of the special member would 12800 // fail. 12801 if (!Func->isConstexpr() || Func->getBody()) 12802 return; 12803 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12804 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12805 return; 12806 } 12807 12808 // Note that this declaration has been used. 12809 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12810 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12811 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12812 if (Constructor->isDefaultConstructor()) { 12813 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12814 return; 12815 DefineImplicitDefaultConstructor(Loc, Constructor); 12816 } else if (Constructor->isCopyConstructor()) { 12817 DefineImplicitCopyConstructor(Loc, Constructor); 12818 } else if (Constructor->isMoveConstructor()) { 12819 DefineImplicitMoveConstructor(Loc, Constructor); 12820 } 12821 } else if (Constructor->getInheritedConstructor()) { 12822 DefineInheritingConstructor(Loc, Constructor); 12823 } 12824 } else if (CXXDestructorDecl *Destructor = 12825 dyn_cast<CXXDestructorDecl>(Func)) { 12826 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12827 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12828 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12829 return; 12830 DefineImplicitDestructor(Loc, Destructor); 12831 } 12832 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12833 MarkVTableUsed(Loc, Destructor->getParent()); 12834 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12835 if (MethodDecl->isOverloadedOperator() && 12836 MethodDecl->getOverloadedOperator() == OO_Equal) { 12837 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12838 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12839 if (MethodDecl->isCopyAssignmentOperator()) 12840 DefineImplicitCopyAssignment(Loc, MethodDecl); 12841 else 12842 DefineImplicitMoveAssignment(Loc, MethodDecl); 12843 } 12844 } else if (isa<CXXConversionDecl>(MethodDecl) && 12845 MethodDecl->getParent()->isLambda()) { 12846 CXXConversionDecl *Conversion = 12847 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12848 if (Conversion->isLambdaToBlockPointerConversion()) 12849 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12850 else 12851 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12852 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12853 MarkVTableUsed(Loc, MethodDecl->getParent()); 12854 } 12855 12856 // Recursive functions should be marked when used from another function. 12857 // FIXME: Is this really right? 12858 if (CurContext == Func) return; 12859 12860 // Resolve the exception specification for any function which is 12861 // used: CodeGen will need it. 12862 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12863 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12864 ResolveExceptionSpec(Loc, FPT); 12865 12866 if (!OdrUse) return; 12867 12868 // Implicit instantiation of function templates and member functions of 12869 // class templates. 12870 if (Func->isImplicitlyInstantiable()) { 12871 bool AlreadyInstantiated = false; 12872 SourceLocation PointOfInstantiation = Loc; 12873 if (FunctionTemplateSpecializationInfo *SpecInfo 12874 = Func->getTemplateSpecializationInfo()) { 12875 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12876 SpecInfo->setPointOfInstantiation(Loc); 12877 else if (SpecInfo->getTemplateSpecializationKind() 12878 == TSK_ImplicitInstantiation) { 12879 AlreadyInstantiated = true; 12880 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12881 } 12882 } else if (MemberSpecializationInfo *MSInfo 12883 = Func->getMemberSpecializationInfo()) { 12884 if (MSInfo->getPointOfInstantiation().isInvalid()) 12885 MSInfo->setPointOfInstantiation(Loc); 12886 else if (MSInfo->getTemplateSpecializationKind() 12887 == TSK_ImplicitInstantiation) { 12888 AlreadyInstantiated = true; 12889 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12890 } 12891 } 12892 12893 if (!AlreadyInstantiated || Func->isConstexpr()) { 12894 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12895 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12896 ActiveTemplateInstantiations.size()) 12897 PendingLocalImplicitInstantiations.push_back( 12898 std::make_pair(Func, PointOfInstantiation)); 12899 else if (Func->isConstexpr()) 12900 // Do not defer instantiations of constexpr functions, to avoid the 12901 // expression evaluator needing to call back into Sema if it sees a 12902 // call to such a function. 12903 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12904 else { 12905 PendingInstantiations.push_back(std::make_pair(Func, 12906 PointOfInstantiation)); 12907 // Notify the consumer that a function was implicitly instantiated. 12908 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12909 } 12910 } 12911 } else { 12912 // Walk redefinitions, as some of them may be instantiable. 12913 for (auto i : Func->redecls()) { 12914 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12915 MarkFunctionReferenced(Loc, i); 12916 } 12917 } 12918 12919 // Keep track of used but undefined functions. 12920 if (!Func->isDefined()) { 12921 if (mightHaveNonExternalLinkage(Func)) 12922 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12923 else if (Func->getMostRecentDecl()->isInlined() && 12924 !LangOpts.GNUInline && 12925 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12926 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12927 } 12928 12929 // Normally the most current decl is marked used while processing the use and 12930 // any subsequent decls are marked used by decl merging. This fails with 12931 // template instantiation since marking can happen at the end of the file 12932 // and, because of the two phase lookup, this function is called with at 12933 // decl in the middle of a decl chain. We loop to maintain the invariant 12934 // that once a decl is used, all decls after it are also used. 12935 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12936 F->markUsed(Context); 12937 if (F == Func) 12938 break; 12939 } 12940 } 12941 12942 static void 12943 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12944 VarDecl *var, DeclContext *DC) { 12945 DeclContext *VarDC = var->getDeclContext(); 12946 12947 // If the parameter still belongs to the translation unit, then 12948 // we're actually just using one parameter in the declaration of 12949 // the next. 12950 if (isa<ParmVarDecl>(var) && 12951 isa<TranslationUnitDecl>(VarDC)) 12952 return; 12953 12954 // For C code, don't diagnose about capture if we're not actually in code 12955 // right now; it's impossible to write a non-constant expression outside of 12956 // function context, so we'll get other (more useful) diagnostics later. 12957 // 12958 // For C++, things get a bit more nasty... it would be nice to suppress this 12959 // diagnostic for certain cases like using a local variable in an array bound 12960 // for a member of a local class, but the correct predicate is not obvious. 12961 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12962 return; 12963 12964 if (isa<CXXMethodDecl>(VarDC) && 12965 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12966 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12967 << var->getIdentifier(); 12968 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12969 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12970 << var->getIdentifier() << fn->getDeclName(); 12971 } else if (isa<BlockDecl>(VarDC)) { 12972 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12973 << var->getIdentifier(); 12974 } else { 12975 // FIXME: Is there any other context where a local variable can be 12976 // declared? 12977 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12978 << var->getIdentifier(); 12979 } 12980 12981 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12982 << var->getIdentifier(); 12983 12984 // FIXME: Add additional diagnostic info about class etc. which prevents 12985 // capture. 12986 } 12987 12988 12989 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12990 bool &SubCapturesAreNested, 12991 QualType &CaptureType, 12992 QualType &DeclRefType) { 12993 // Check whether we've already captured it. 12994 if (CSI->CaptureMap.count(Var)) { 12995 // If we found a capture, any subcaptures are nested. 12996 SubCapturesAreNested = true; 12997 12998 // Retrieve the capture type for this variable. 12999 CaptureType = CSI->getCapture(Var).getCaptureType(); 13000 13001 // Compute the type of an expression that refers to this variable. 13002 DeclRefType = CaptureType.getNonReferenceType(); 13003 13004 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13005 // are mutable in the sense that user can change their value - they are 13006 // private instances of the captured declarations. 13007 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13008 if (Cap.isCopyCapture() && 13009 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13010 !(isa<CapturedRegionScopeInfo>(CSI) && 13011 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13012 DeclRefType.addConst(); 13013 return true; 13014 } 13015 return false; 13016 } 13017 13018 // Only block literals, captured statements, and lambda expressions can 13019 // capture; other scopes don't work. 13020 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13021 SourceLocation Loc, 13022 const bool Diagnose, Sema &S) { 13023 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13024 return getLambdaAwareParentOfDeclContext(DC); 13025 else if (Var->hasLocalStorage()) { 13026 if (Diagnose) 13027 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13028 } 13029 return nullptr; 13030 } 13031 13032 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13033 // certain types of variables (unnamed, variably modified types etc.) 13034 // so check for eligibility. 13035 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13036 SourceLocation Loc, 13037 const bool Diagnose, Sema &S) { 13038 13039 bool IsBlock = isa<BlockScopeInfo>(CSI); 13040 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13041 13042 // Lambdas are not allowed to capture unnamed variables 13043 // (e.g. anonymous unions). 13044 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13045 // assuming that's the intent. 13046 if (IsLambda && !Var->getDeclName()) { 13047 if (Diagnose) { 13048 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13049 S.Diag(Var->getLocation(), diag::note_declared_at); 13050 } 13051 return false; 13052 } 13053 13054 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13055 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13056 if (Diagnose) { 13057 S.Diag(Loc, diag::err_ref_vm_type); 13058 S.Diag(Var->getLocation(), diag::note_previous_decl) 13059 << Var->getDeclName(); 13060 } 13061 return false; 13062 } 13063 // Prohibit structs with flexible array members too. 13064 // We cannot capture what is in the tail end of the struct. 13065 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13066 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13067 if (Diagnose) { 13068 if (IsBlock) 13069 S.Diag(Loc, diag::err_ref_flexarray_type); 13070 else 13071 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13072 << Var->getDeclName(); 13073 S.Diag(Var->getLocation(), diag::note_previous_decl) 13074 << Var->getDeclName(); 13075 } 13076 return false; 13077 } 13078 } 13079 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13080 // Lambdas and captured statements are not allowed to capture __block 13081 // variables; they don't support the expected semantics. 13082 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13083 if (Diagnose) { 13084 S.Diag(Loc, diag::err_capture_block_variable) 13085 << Var->getDeclName() << !IsLambda; 13086 S.Diag(Var->getLocation(), diag::note_previous_decl) 13087 << Var->getDeclName(); 13088 } 13089 return false; 13090 } 13091 13092 return true; 13093 } 13094 13095 // Returns true if the capture by block was successful. 13096 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13097 SourceLocation Loc, 13098 const bool BuildAndDiagnose, 13099 QualType &CaptureType, 13100 QualType &DeclRefType, 13101 const bool Nested, 13102 Sema &S) { 13103 Expr *CopyExpr = nullptr; 13104 bool ByRef = false; 13105 13106 // Blocks are not allowed to capture arrays. 13107 if (CaptureType->isArrayType()) { 13108 if (BuildAndDiagnose) { 13109 S.Diag(Loc, diag::err_ref_array_type); 13110 S.Diag(Var->getLocation(), diag::note_previous_decl) 13111 << Var->getDeclName(); 13112 } 13113 return false; 13114 } 13115 13116 // Forbid the block-capture of autoreleasing variables. 13117 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13118 if (BuildAndDiagnose) { 13119 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13120 << /*block*/ 0; 13121 S.Diag(Var->getLocation(), diag::note_previous_decl) 13122 << Var->getDeclName(); 13123 } 13124 return false; 13125 } 13126 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13127 if (HasBlocksAttr || CaptureType->isReferenceType()) { 13128 // Block capture by reference does not change the capture or 13129 // declaration reference types. 13130 ByRef = true; 13131 } else { 13132 // Block capture by copy introduces 'const'. 13133 CaptureType = CaptureType.getNonReferenceType().withConst(); 13134 DeclRefType = CaptureType; 13135 13136 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13137 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13138 // The capture logic needs the destructor, so make sure we mark it. 13139 // Usually this is unnecessary because most local variables have 13140 // their destructors marked at declaration time, but parameters are 13141 // an exception because it's technically only the call site that 13142 // actually requires the destructor. 13143 if (isa<ParmVarDecl>(Var)) 13144 S.FinalizeVarWithDestructor(Var, Record); 13145 13146 // Enter a new evaluation context to insulate the copy 13147 // full-expression. 13148 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13149 13150 // According to the blocks spec, the capture of a variable from 13151 // the stack requires a const copy constructor. This is not true 13152 // of the copy/move done to move a __block variable to the heap. 13153 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13154 DeclRefType.withConst(), 13155 VK_LValue, Loc); 13156 13157 ExprResult Result 13158 = S.PerformCopyInitialization( 13159 InitializedEntity::InitializeBlock(Var->getLocation(), 13160 CaptureType, false), 13161 Loc, DeclRef); 13162 13163 // Build a full-expression copy expression if initialization 13164 // succeeded and used a non-trivial constructor. Recover from 13165 // errors by pretending that the copy isn't necessary. 13166 if (!Result.isInvalid() && 13167 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13168 ->isTrivial()) { 13169 Result = S.MaybeCreateExprWithCleanups(Result); 13170 CopyExpr = Result.get(); 13171 } 13172 } 13173 } 13174 } 13175 13176 // Actually capture the variable. 13177 if (BuildAndDiagnose) 13178 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13179 SourceLocation(), CaptureType, CopyExpr); 13180 13181 return true; 13182 13183 } 13184 13185 13186 /// \brief Capture the given variable in the captured region. 13187 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13188 VarDecl *Var, 13189 SourceLocation Loc, 13190 const bool BuildAndDiagnose, 13191 QualType &CaptureType, 13192 QualType &DeclRefType, 13193 const bool RefersToCapturedVariable, 13194 Sema &S) { 13195 13196 // By default, capture variables by reference. 13197 bool ByRef = true; 13198 // Using an LValue reference type is consistent with Lambdas (see below). 13199 if (S.getLangOpts().OpenMP) { 13200 ByRef = S.IsOpenMPCapturedByRef(Var, RSI); 13201 if (S.IsOpenMPCapturedDecl(Var)) 13202 DeclRefType = DeclRefType.getUnqualifiedType(); 13203 } 13204 13205 if (ByRef) 13206 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13207 else 13208 CaptureType = DeclRefType; 13209 13210 Expr *CopyExpr = nullptr; 13211 if (BuildAndDiagnose) { 13212 // The current implementation assumes that all variables are captured 13213 // by references. Since there is no capture by copy, no expression 13214 // evaluation will be needed. 13215 RecordDecl *RD = RSI->TheRecordDecl; 13216 13217 FieldDecl *Field 13218 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13219 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13220 nullptr, false, ICIS_NoInit); 13221 Field->setImplicit(true); 13222 Field->setAccess(AS_private); 13223 RD->addDecl(Field); 13224 13225 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13226 DeclRefType, VK_LValue, Loc); 13227 Var->setReferenced(true); 13228 Var->markUsed(S.Context); 13229 } 13230 13231 // Actually capture the variable. 13232 if (BuildAndDiagnose) 13233 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13234 SourceLocation(), CaptureType, CopyExpr); 13235 13236 13237 return true; 13238 } 13239 13240 /// \brief Create a field within the lambda class for the variable 13241 /// being captured. 13242 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 13243 QualType FieldType, QualType DeclRefType, 13244 SourceLocation Loc, 13245 bool RefersToCapturedVariable) { 13246 CXXRecordDecl *Lambda = LSI->Lambda; 13247 13248 // Build the non-static data member. 13249 FieldDecl *Field 13250 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13251 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13252 nullptr, false, ICIS_NoInit); 13253 Field->setImplicit(true); 13254 Field->setAccess(AS_private); 13255 Lambda->addDecl(Field); 13256 } 13257 13258 /// \brief Capture the given variable in the lambda. 13259 static bool captureInLambda(LambdaScopeInfo *LSI, 13260 VarDecl *Var, 13261 SourceLocation Loc, 13262 const bool BuildAndDiagnose, 13263 QualType &CaptureType, 13264 QualType &DeclRefType, 13265 const bool RefersToCapturedVariable, 13266 const Sema::TryCaptureKind Kind, 13267 SourceLocation EllipsisLoc, 13268 const bool IsTopScope, 13269 Sema &S) { 13270 13271 // Determine whether we are capturing by reference or by value. 13272 bool ByRef = false; 13273 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13274 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13275 } else { 13276 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13277 } 13278 13279 // Compute the type of the field that will capture this variable. 13280 if (ByRef) { 13281 // C++11 [expr.prim.lambda]p15: 13282 // An entity is captured by reference if it is implicitly or 13283 // explicitly captured but not captured by copy. It is 13284 // unspecified whether additional unnamed non-static data 13285 // members are declared in the closure type for entities 13286 // captured by reference. 13287 // 13288 // FIXME: It is not clear whether we want to build an lvalue reference 13289 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13290 // to do the former, while EDG does the latter. Core issue 1249 will 13291 // clarify, but for now we follow GCC because it's a more permissive and 13292 // easily defensible position. 13293 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13294 } else { 13295 // C++11 [expr.prim.lambda]p14: 13296 // For each entity captured by copy, an unnamed non-static 13297 // data member is declared in the closure type. The 13298 // declaration order of these members is unspecified. The type 13299 // of such a data member is the type of the corresponding 13300 // captured entity if the entity is not a reference to an 13301 // object, or the referenced type otherwise. [Note: If the 13302 // captured entity is a reference to a function, the 13303 // corresponding data member is also a reference to a 13304 // function. - end note ] 13305 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13306 if (!RefType->getPointeeType()->isFunctionType()) 13307 CaptureType = RefType->getPointeeType(); 13308 } 13309 13310 // Forbid the lambda copy-capture of autoreleasing variables. 13311 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13312 if (BuildAndDiagnose) { 13313 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13314 S.Diag(Var->getLocation(), diag::note_previous_decl) 13315 << Var->getDeclName(); 13316 } 13317 return false; 13318 } 13319 13320 // Make sure that by-copy captures are of a complete and non-abstract type. 13321 if (BuildAndDiagnose) { 13322 if (!CaptureType->isDependentType() && 13323 S.RequireCompleteType(Loc, CaptureType, 13324 diag::err_capture_of_incomplete_type, 13325 Var->getDeclName())) 13326 return false; 13327 13328 if (S.RequireNonAbstractType(Loc, CaptureType, 13329 diag::err_capture_of_abstract_type)) 13330 return false; 13331 } 13332 } 13333 13334 // Capture this variable in the lambda. 13335 if (BuildAndDiagnose) 13336 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 13337 RefersToCapturedVariable); 13338 13339 // Compute the type of a reference to this captured variable. 13340 if (ByRef) 13341 DeclRefType = CaptureType.getNonReferenceType(); 13342 else { 13343 // C++ [expr.prim.lambda]p5: 13344 // The closure type for a lambda-expression has a public inline 13345 // function call operator [...]. This function call operator is 13346 // declared const (9.3.1) if and only if the lambda-expression’s 13347 // parameter-declaration-clause is not followed by mutable. 13348 DeclRefType = CaptureType.getNonReferenceType(); 13349 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13350 DeclRefType.addConst(); 13351 } 13352 13353 // Add the capture. 13354 if (BuildAndDiagnose) 13355 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13356 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13357 13358 return true; 13359 } 13360 13361 bool Sema::tryCaptureVariable( 13362 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13363 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13364 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13365 // An init-capture is notionally from the context surrounding its 13366 // declaration, but its parent DC is the lambda class. 13367 DeclContext *VarDC = Var->getDeclContext(); 13368 if (Var->isInitCapture()) 13369 VarDC = VarDC->getParent(); 13370 13371 DeclContext *DC = CurContext; 13372 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13373 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13374 // We need to sync up the Declaration Context with the 13375 // FunctionScopeIndexToStopAt 13376 if (FunctionScopeIndexToStopAt) { 13377 unsigned FSIndex = FunctionScopes.size() - 1; 13378 while (FSIndex != MaxFunctionScopesIndex) { 13379 DC = getLambdaAwareParentOfDeclContext(DC); 13380 --FSIndex; 13381 } 13382 } 13383 13384 13385 // If the variable is declared in the current context, there is no need to 13386 // capture it. 13387 if (VarDC == DC) return true; 13388 13389 // Capture global variables if it is required to use private copy of this 13390 // variable. 13391 bool IsGlobal = !Var->hasLocalStorage(); 13392 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13393 return true; 13394 13395 // Walk up the stack to determine whether we can capture the variable, 13396 // performing the "simple" checks that don't depend on type. We stop when 13397 // we've either hit the declared scope of the variable or find an existing 13398 // capture of that variable. We start from the innermost capturing-entity 13399 // (the DC) and ensure that all intervening capturing-entities 13400 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13401 // declcontext can either capture the variable or have already captured 13402 // the variable. 13403 CaptureType = Var->getType(); 13404 DeclRefType = CaptureType.getNonReferenceType(); 13405 bool Nested = false; 13406 bool Explicit = (Kind != TryCapture_Implicit); 13407 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13408 unsigned OpenMPLevel = 0; 13409 do { 13410 // Only block literals, captured statements, and lambda expressions can 13411 // capture; other scopes don't work. 13412 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13413 ExprLoc, 13414 BuildAndDiagnose, 13415 *this); 13416 // We need to check for the parent *first* because, if we *have* 13417 // private-captured a global variable, we need to recursively capture it in 13418 // intermediate blocks, lambdas, etc. 13419 if (!ParentDC) { 13420 if (IsGlobal) { 13421 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13422 break; 13423 } 13424 return true; 13425 } 13426 13427 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13428 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13429 13430 13431 // Check whether we've already captured it. 13432 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13433 DeclRefType)) 13434 break; 13435 // If we are instantiating a generic lambda call operator body, 13436 // we do not want to capture new variables. What was captured 13437 // during either a lambdas transformation or initial parsing 13438 // should be used. 13439 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13440 if (BuildAndDiagnose) { 13441 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13442 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13443 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13444 Diag(Var->getLocation(), diag::note_previous_decl) 13445 << Var->getDeclName(); 13446 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13447 } else 13448 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13449 } 13450 return true; 13451 } 13452 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13453 // certain types of variables (unnamed, variably modified types etc.) 13454 // so check for eligibility. 13455 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13456 return true; 13457 13458 // Try to capture variable-length arrays types. 13459 if (Var->getType()->isVariablyModifiedType()) { 13460 // We're going to walk down into the type and look for VLA 13461 // expressions. 13462 QualType QTy = Var->getType(); 13463 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13464 QTy = PVD->getOriginalType(); 13465 captureVariablyModifiedType(Context, QTy, CSI); 13466 } 13467 13468 if (getLangOpts().OpenMP) { 13469 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13470 // OpenMP private variables should not be captured in outer scope, so 13471 // just break here. Similarly, global variables that are captured in a 13472 // target region should not be captured outside the scope of the region. 13473 if (RSI->CapRegionKind == CR_OpenMP) { 13474 auto isTargetCap = isOpenMPTargetCapturedDecl(Var, OpenMPLevel); 13475 // When we detect target captures we are looking from inside the 13476 // target region, therefore we need to propagate the capture from the 13477 // enclosing region. Therefore, the capture is not initially nested. 13478 if (isTargetCap) 13479 FunctionScopesIndex--; 13480 13481 if (isTargetCap || isOpenMPPrivateDecl(Var, OpenMPLevel)) { 13482 Nested = !isTargetCap; 13483 DeclRefType = DeclRefType.getUnqualifiedType(); 13484 CaptureType = Context.getLValueReferenceType(DeclRefType); 13485 break; 13486 } 13487 ++OpenMPLevel; 13488 } 13489 } 13490 } 13491 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13492 // No capture-default, and this is not an explicit capture 13493 // so cannot capture this variable. 13494 if (BuildAndDiagnose) { 13495 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13496 Diag(Var->getLocation(), diag::note_previous_decl) 13497 << Var->getDeclName(); 13498 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13499 diag::note_lambda_decl); 13500 // FIXME: If we error out because an outer lambda can not implicitly 13501 // capture a variable that an inner lambda explicitly captures, we 13502 // should have the inner lambda do the explicit capture - because 13503 // it makes for cleaner diagnostics later. This would purely be done 13504 // so that the diagnostic does not misleadingly claim that a variable 13505 // can not be captured by a lambda implicitly even though it is captured 13506 // explicitly. Suggestion: 13507 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13508 // at the function head 13509 // - cache the StartingDeclContext - this must be a lambda 13510 // - captureInLambda in the innermost lambda the variable. 13511 } 13512 return true; 13513 } 13514 13515 FunctionScopesIndex--; 13516 DC = ParentDC; 13517 Explicit = false; 13518 } while (!VarDC->Equals(DC)); 13519 13520 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13521 // computing the type of the capture at each step, checking type-specific 13522 // requirements, and adding captures if requested. 13523 // If the variable had already been captured previously, we start capturing 13524 // at the lambda nested within that one. 13525 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13526 ++I) { 13527 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13528 13529 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13530 if (!captureInBlock(BSI, Var, ExprLoc, 13531 BuildAndDiagnose, CaptureType, 13532 DeclRefType, Nested, *this)) 13533 return true; 13534 Nested = true; 13535 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13536 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13537 BuildAndDiagnose, CaptureType, 13538 DeclRefType, Nested, *this)) 13539 return true; 13540 Nested = true; 13541 } else { 13542 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13543 if (!captureInLambda(LSI, Var, ExprLoc, 13544 BuildAndDiagnose, CaptureType, 13545 DeclRefType, Nested, Kind, EllipsisLoc, 13546 /*IsTopScope*/I == N - 1, *this)) 13547 return true; 13548 Nested = true; 13549 } 13550 } 13551 return false; 13552 } 13553 13554 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13555 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13556 QualType CaptureType; 13557 QualType DeclRefType; 13558 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13559 /*BuildAndDiagnose=*/true, CaptureType, 13560 DeclRefType, nullptr); 13561 } 13562 13563 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13564 QualType CaptureType; 13565 QualType DeclRefType; 13566 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13567 /*BuildAndDiagnose=*/false, CaptureType, 13568 DeclRefType, nullptr); 13569 } 13570 13571 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13572 QualType CaptureType; 13573 QualType DeclRefType; 13574 13575 // Determine whether we can capture this variable. 13576 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13577 /*BuildAndDiagnose=*/false, CaptureType, 13578 DeclRefType, nullptr)) 13579 return QualType(); 13580 13581 return DeclRefType; 13582 } 13583 13584 13585 13586 // If either the type of the variable or the initializer is dependent, 13587 // return false. Otherwise, determine whether the variable is a constant 13588 // expression. Use this if you need to know if a variable that might or 13589 // might not be dependent is truly a constant expression. 13590 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13591 ASTContext &Context) { 13592 13593 if (Var->getType()->isDependentType()) 13594 return false; 13595 const VarDecl *DefVD = nullptr; 13596 Var->getAnyInitializer(DefVD); 13597 if (!DefVD) 13598 return false; 13599 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13600 Expr *Init = cast<Expr>(Eval->Value); 13601 if (Init->isValueDependent()) 13602 return false; 13603 return IsVariableAConstantExpression(Var, Context); 13604 } 13605 13606 13607 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13608 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13609 // an object that satisfies the requirements for appearing in a 13610 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13611 // is immediately applied." This function handles the lvalue-to-rvalue 13612 // conversion part. 13613 MaybeODRUseExprs.erase(E->IgnoreParens()); 13614 13615 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13616 // to a variable that is a constant expression, and if so, identify it as 13617 // a reference to a variable that does not involve an odr-use of that 13618 // variable. 13619 if (LambdaScopeInfo *LSI = getCurLambda()) { 13620 Expr *SansParensExpr = E->IgnoreParens(); 13621 VarDecl *Var = nullptr; 13622 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13623 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13624 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13625 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13626 13627 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13628 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13629 } 13630 } 13631 13632 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13633 Res = CorrectDelayedTyposInExpr(Res); 13634 13635 if (!Res.isUsable()) 13636 return Res; 13637 13638 // If a constant-expression is a reference to a variable where we delay 13639 // deciding whether it is an odr-use, just assume we will apply the 13640 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13641 // (a non-type template argument), we have special handling anyway. 13642 UpdateMarkingForLValueToRValue(Res.get()); 13643 return Res; 13644 } 13645 13646 void Sema::CleanupVarDeclMarking() { 13647 for (Expr *E : MaybeODRUseExprs) { 13648 VarDecl *Var; 13649 SourceLocation Loc; 13650 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13651 Var = cast<VarDecl>(DRE->getDecl()); 13652 Loc = DRE->getLocation(); 13653 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13654 Var = cast<VarDecl>(ME->getMemberDecl()); 13655 Loc = ME->getMemberLoc(); 13656 } else { 13657 llvm_unreachable("Unexpected expression"); 13658 } 13659 13660 MarkVarDeclODRUsed(Var, Loc, *this, 13661 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13662 } 13663 13664 MaybeODRUseExprs.clear(); 13665 } 13666 13667 13668 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13669 VarDecl *Var, Expr *E) { 13670 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13671 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13672 Var->setReferenced(); 13673 13674 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13675 bool MarkODRUsed = true; 13676 13677 // If the context is not potentially evaluated, this is not an odr-use and 13678 // does not trigger instantiation. 13679 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13680 if (SemaRef.isUnevaluatedContext()) 13681 return; 13682 13683 // If we don't yet know whether this context is going to end up being an 13684 // evaluated context, and we're referencing a variable from an enclosing 13685 // scope, add a potential capture. 13686 // 13687 // FIXME: Is this necessary? These contexts are only used for default 13688 // arguments, where local variables can't be used. 13689 const bool RefersToEnclosingScope = 13690 (SemaRef.CurContext != Var->getDeclContext() && 13691 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13692 if (RefersToEnclosingScope) { 13693 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13694 // If a variable could potentially be odr-used, defer marking it so 13695 // until we finish analyzing the full expression for any 13696 // lvalue-to-rvalue 13697 // or discarded value conversions that would obviate odr-use. 13698 // Add it to the list of potential captures that will be analyzed 13699 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13700 // unless the variable is a reference that was initialized by a constant 13701 // expression (this will never need to be captured or odr-used). 13702 assert(E && "Capture variable should be used in an expression."); 13703 if (!Var->getType()->isReferenceType() || 13704 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13705 LSI->addPotentialCapture(E->IgnoreParens()); 13706 } 13707 } 13708 13709 if (!isTemplateInstantiation(TSK)) 13710 return; 13711 13712 // Instantiate, but do not mark as odr-used, variable templates. 13713 MarkODRUsed = false; 13714 } 13715 13716 VarTemplateSpecializationDecl *VarSpec = 13717 dyn_cast<VarTemplateSpecializationDecl>(Var); 13718 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13719 "Can't instantiate a partial template specialization."); 13720 13721 // Perform implicit instantiation of static data members, static data member 13722 // templates of class templates, and variable template specializations. Delay 13723 // instantiations of variable templates, except for those that could be used 13724 // in a constant expression. 13725 if (isTemplateInstantiation(TSK)) { 13726 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13727 13728 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13729 if (Var->getPointOfInstantiation().isInvalid()) { 13730 // This is a modification of an existing AST node. Notify listeners. 13731 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13732 L->StaticDataMemberInstantiated(Var); 13733 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13734 // Don't bother trying to instantiate it again, unless we might need 13735 // its initializer before we get to the end of the TU. 13736 TryInstantiating = false; 13737 } 13738 13739 if (Var->getPointOfInstantiation().isInvalid()) 13740 Var->setTemplateSpecializationKind(TSK, Loc); 13741 13742 if (TryInstantiating) { 13743 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13744 bool InstantiationDependent = false; 13745 bool IsNonDependent = 13746 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13747 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13748 : true; 13749 13750 // Do not instantiate specializations that are still type-dependent. 13751 if (IsNonDependent) { 13752 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13753 // Do not defer instantiations of variables which could be used in a 13754 // constant expression. 13755 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13756 } else { 13757 SemaRef.PendingInstantiations 13758 .push_back(std::make_pair(Var, PointOfInstantiation)); 13759 } 13760 } 13761 } 13762 } 13763 13764 if(!MarkODRUsed) return; 13765 13766 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13767 // the requirements for appearing in a constant expression (5.19) and, if 13768 // it is an object, the lvalue-to-rvalue conversion (4.1) 13769 // is immediately applied." We check the first part here, and 13770 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13771 // Note that we use the C++11 definition everywhere because nothing in 13772 // C++03 depends on whether we get the C++03 version correct. The second 13773 // part does not apply to references, since they are not objects. 13774 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13775 // A reference initialized by a constant expression can never be 13776 // odr-used, so simply ignore it. 13777 if (!Var->getType()->isReferenceType()) 13778 SemaRef.MaybeODRUseExprs.insert(E); 13779 } else 13780 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13781 /*MaxFunctionScopeIndex ptr*/ nullptr); 13782 } 13783 13784 /// \brief Mark a variable referenced, and check whether it is odr-used 13785 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13786 /// used directly for normal expressions referring to VarDecl. 13787 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13788 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13789 } 13790 13791 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13792 Decl *D, Expr *E, bool OdrUse) { 13793 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13794 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13795 return; 13796 } 13797 13798 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13799 13800 // If this is a call to a method via a cast, also mark the method in the 13801 // derived class used in case codegen can devirtualize the call. 13802 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13803 if (!ME) 13804 return; 13805 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13806 if (!MD) 13807 return; 13808 // Only attempt to devirtualize if this is truly a virtual call. 13809 bool IsVirtualCall = MD->isVirtual() && 13810 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13811 if (!IsVirtualCall) 13812 return; 13813 const Expr *Base = ME->getBase(); 13814 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13815 if (!MostDerivedClassDecl) 13816 return; 13817 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13818 if (!DM || DM->isPure()) 13819 return; 13820 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13821 } 13822 13823 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13824 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13825 // TODO: update this with DR# once a defect report is filed. 13826 // C++11 defect. The address of a pure member should not be an ODR use, even 13827 // if it's a qualified reference. 13828 bool OdrUse = true; 13829 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13830 if (Method->isVirtual()) 13831 OdrUse = false; 13832 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13833 } 13834 13835 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13836 void Sema::MarkMemberReferenced(MemberExpr *E) { 13837 // C++11 [basic.def.odr]p2: 13838 // A non-overloaded function whose name appears as a potentially-evaluated 13839 // expression or a member of a set of candidate functions, if selected by 13840 // overload resolution when referred to from a potentially-evaluated 13841 // expression, is odr-used, unless it is a pure virtual function and its 13842 // name is not explicitly qualified. 13843 bool OdrUse = true; 13844 if (E->performsVirtualDispatch(getLangOpts())) { 13845 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13846 if (Method->isPure()) 13847 OdrUse = false; 13848 } 13849 SourceLocation Loc = E->getMemberLoc().isValid() ? 13850 E->getMemberLoc() : E->getLocStart(); 13851 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13852 } 13853 13854 /// \brief Perform marking for a reference to an arbitrary declaration. It 13855 /// marks the declaration referenced, and performs odr-use checking for 13856 /// functions and variables. This method should not be used when building a 13857 /// normal expression which refers to a variable. 13858 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13859 if (OdrUse) { 13860 if (auto *VD = dyn_cast<VarDecl>(D)) { 13861 MarkVariableReferenced(Loc, VD); 13862 return; 13863 } 13864 } 13865 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13866 MarkFunctionReferenced(Loc, FD, OdrUse); 13867 return; 13868 } 13869 D->setReferenced(); 13870 } 13871 13872 namespace { 13873 // Mark all of the declarations referenced 13874 // FIXME: Not fully implemented yet! We need to have a better understanding 13875 // of when we're entering 13876 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13877 Sema &S; 13878 SourceLocation Loc; 13879 13880 public: 13881 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13882 13883 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13884 13885 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13886 bool TraverseRecordType(RecordType *T); 13887 }; 13888 } 13889 13890 bool MarkReferencedDecls::TraverseTemplateArgument( 13891 const TemplateArgument &Arg) { 13892 if (Arg.getKind() == TemplateArgument::Declaration) { 13893 if (Decl *D = Arg.getAsDecl()) 13894 S.MarkAnyDeclReferenced(Loc, D, true); 13895 } 13896 13897 return Inherited::TraverseTemplateArgument(Arg); 13898 } 13899 13900 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13901 if (ClassTemplateSpecializationDecl *Spec 13902 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13903 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13904 return TraverseTemplateArguments(Args.data(), Args.size()); 13905 } 13906 13907 return true; 13908 } 13909 13910 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13911 MarkReferencedDecls Marker(*this, Loc); 13912 Marker.TraverseType(Context.getCanonicalType(T)); 13913 } 13914 13915 namespace { 13916 /// \brief Helper class that marks all of the declarations referenced by 13917 /// potentially-evaluated subexpressions as "referenced". 13918 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13919 Sema &S; 13920 bool SkipLocalVariables; 13921 13922 public: 13923 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13924 13925 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13926 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13927 13928 void VisitDeclRefExpr(DeclRefExpr *E) { 13929 // If we were asked not to visit local variables, don't. 13930 if (SkipLocalVariables) { 13931 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13932 if (VD->hasLocalStorage()) 13933 return; 13934 } 13935 13936 S.MarkDeclRefReferenced(E); 13937 } 13938 13939 void VisitMemberExpr(MemberExpr *E) { 13940 S.MarkMemberReferenced(E); 13941 Inherited::VisitMemberExpr(E); 13942 } 13943 13944 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13945 S.MarkFunctionReferenced(E->getLocStart(), 13946 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13947 Visit(E->getSubExpr()); 13948 } 13949 13950 void VisitCXXNewExpr(CXXNewExpr *E) { 13951 if (E->getOperatorNew()) 13952 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13953 if (E->getOperatorDelete()) 13954 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13955 Inherited::VisitCXXNewExpr(E); 13956 } 13957 13958 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13959 if (E->getOperatorDelete()) 13960 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13961 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13962 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13963 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13964 S.MarkFunctionReferenced(E->getLocStart(), 13965 S.LookupDestructor(Record)); 13966 } 13967 13968 Inherited::VisitCXXDeleteExpr(E); 13969 } 13970 13971 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13972 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13973 Inherited::VisitCXXConstructExpr(E); 13974 } 13975 13976 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13977 Visit(E->getExpr()); 13978 } 13979 13980 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13981 Inherited::VisitImplicitCastExpr(E); 13982 13983 if (E->getCastKind() == CK_LValueToRValue) 13984 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13985 } 13986 }; 13987 } 13988 13989 /// \brief Mark any declarations that appear within this expression or any 13990 /// potentially-evaluated subexpressions as "referenced". 13991 /// 13992 /// \param SkipLocalVariables If true, don't mark local variables as 13993 /// 'referenced'. 13994 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13995 bool SkipLocalVariables) { 13996 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13997 } 13998 13999 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14000 /// of the program being compiled. 14001 /// 14002 /// This routine emits the given diagnostic when the code currently being 14003 /// type-checked is "potentially evaluated", meaning that there is a 14004 /// possibility that the code will actually be executable. Code in sizeof() 14005 /// expressions, code used only during overload resolution, etc., are not 14006 /// potentially evaluated. This routine will suppress such diagnostics or, 14007 /// in the absolutely nutty case of potentially potentially evaluated 14008 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14009 /// later. 14010 /// 14011 /// This routine should be used for all diagnostics that describe the run-time 14012 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14013 /// Failure to do so will likely result in spurious diagnostics or failures 14014 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14015 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14016 const PartialDiagnostic &PD) { 14017 switch (ExprEvalContexts.back().Context) { 14018 case Unevaluated: 14019 case UnevaluatedAbstract: 14020 // The argument will never be evaluated, so don't complain. 14021 break; 14022 14023 case ConstantEvaluated: 14024 // Relevant diagnostics should be produced by constant evaluation. 14025 break; 14026 14027 case PotentiallyEvaluated: 14028 case PotentiallyEvaluatedIfUsed: 14029 if (Statement && getCurFunctionOrMethodDecl()) { 14030 FunctionScopes.back()->PossiblyUnreachableDiags. 14031 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14032 } 14033 else 14034 Diag(Loc, PD); 14035 14036 return true; 14037 } 14038 14039 return false; 14040 } 14041 14042 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14043 CallExpr *CE, FunctionDecl *FD) { 14044 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14045 return false; 14046 14047 // If we're inside a decltype's expression, don't check for a valid return 14048 // type or construct temporaries until we know whether this is the last call. 14049 if (ExprEvalContexts.back().IsDecltype) { 14050 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14051 return false; 14052 } 14053 14054 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14055 FunctionDecl *FD; 14056 CallExpr *CE; 14057 14058 public: 14059 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14060 : FD(FD), CE(CE) { } 14061 14062 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14063 if (!FD) { 14064 S.Diag(Loc, diag::err_call_incomplete_return) 14065 << T << CE->getSourceRange(); 14066 return; 14067 } 14068 14069 S.Diag(Loc, diag::err_call_function_incomplete_return) 14070 << CE->getSourceRange() << FD->getDeclName() << T; 14071 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14072 << FD->getDeclName(); 14073 } 14074 } Diagnoser(FD, CE); 14075 14076 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14077 return true; 14078 14079 return false; 14080 } 14081 14082 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14083 // will prevent this condition from triggering, which is what we want. 14084 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14085 SourceLocation Loc; 14086 14087 unsigned diagnostic = diag::warn_condition_is_assignment; 14088 bool IsOrAssign = false; 14089 14090 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14091 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14092 return; 14093 14094 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14095 14096 // Greylist some idioms by putting them into a warning subcategory. 14097 if (ObjCMessageExpr *ME 14098 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14099 Selector Sel = ME->getSelector(); 14100 14101 // self = [<foo> init...] 14102 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14103 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14104 14105 // <foo> = [<bar> nextObject] 14106 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14107 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14108 } 14109 14110 Loc = Op->getOperatorLoc(); 14111 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14112 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14113 return; 14114 14115 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14116 Loc = Op->getOperatorLoc(); 14117 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14118 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14119 else { 14120 // Not an assignment. 14121 return; 14122 } 14123 14124 Diag(Loc, diagnostic) << E->getSourceRange(); 14125 14126 SourceLocation Open = E->getLocStart(); 14127 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14128 Diag(Loc, diag::note_condition_assign_silence) 14129 << FixItHint::CreateInsertion(Open, "(") 14130 << FixItHint::CreateInsertion(Close, ")"); 14131 14132 if (IsOrAssign) 14133 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14134 << FixItHint::CreateReplacement(Loc, "!="); 14135 else 14136 Diag(Loc, diag::note_condition_assign_to_comparison) 14137 << FixItHint::CreateReplacement(Loc, "=="); 14138 } 14139 14140 /// \brief Redundant parentheses over an equality comparison can indicate 14141 /// that the user intended an assignment used as condition. 14142 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14143 // Don't warn if the parens came from a macro. 14144 SourceLocation parenLoc = ParenE->getLocStart(); 14145 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14146 return; 14147 // Don't warn for dependent expressions. 14148 if (ParenE->isTypeDependent()) 14149 return; 14150 14151 Expr *E = ParenE->IgnoreParens(); 14152 14153 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14154 if (opE->getOpcode() == BO_EQ && 14155 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14156 == Expr::MLV_Valid) { 14157 SourceLocation Loc = opE->getOperatorLoc(); 14158 14159 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14160 SourceRange ParenERange = ParenE->getSourceRange(); 14161 Diag(Loc, diag::note_equality_comparison_silence) 14162 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14163 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14164 Diag(Loc, diag::note_equality_comparison_to_assign) 14165 << FixItHint::CreateReplacement(Loc, "="); 14166 } 14167 } 14168 14169 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 14170 DiagnoseAssignmentAsCondition(E); 14171 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14172 DiagnoseEqualityWithExtraParens(parenE); 14173 14174 ExprResult result = CheckPlaceholderExpr(E); 14175 if (result.isInvalid()) return ExprError(); 14176 E = result.get(); 14177 14178 if (!E->isTypeDependent()) { 14179 if (getLangOpts().CPlusPlus) 14180 return CheckCXXBooleanCondition(E); // C++ 6.4p4 14181 14182 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14183 if (ERes.isInvalid()) 14184 return ExprError(); 14185 E = ERes.get(); 14186 14187 QualType T = E->getType(); 14188 if (!T->isScalarType()) { // C99 6.8.4.1p1 14189 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14190 << T << E->getSourceRange(); 14191 return ExprError(); 14192 } 14193 CheckBoolLikeConversion(E, Loc); 14194 } 14195 14196 return E; 14197 } 14198 14199 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 14200 Expr *SubExpr) { 14201 if (!SubExpr) 14202 return ExprError(); 14203 14204 return CheckBooleanCondition(SubExpr, Loc); 14205 } 14206 14207 namespace { 14208 /// A visitor for rebuilding a call to an __unknown_any expression 14209 /// to have an appropriate type. 14210 struct RebuildUnknownAnyFunction 14211 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14212 14213 Sema &S; 14214 14215 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14216 14217 ExprResult VisitStmt(Stmt *S) { 14218 llvm_unreachable("unexpected statement!"); 14219 } 14220 14221 ExprResult VisitExpr(Expr *E) { 14222 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14223 << E->getSourceRange(); 14224 return ExprError(); 14225 } 14226 14227 /// Rebuild an expression which simply semantically wraps another 14228 /// expression which it shares the type and value kind of. 14229 template <class T> ExprResult rebuildSugarExpr(T *E) { 14230 ExprResult SubResult = Visit(E->getSubExpr()); 14231 if (SubResult.isInvalid()) return ExprError(); 14232 14233 Expr *SubExpr = SubResult.get(); 14234 E->setSubExpr(SubExpr); 14235 E->setType(SubExpr->getType()); 14236 E->setValueKind(SubExpr->getValueKind()); 14237 assert(E->getObjectKind() == OK_Ordinary); 14238 return E; 14239 } 14240 14241 ExprResult VisitParenExpr(ParenExpr *E) { 14242 return rebuildSugarExpr(E); 14243 } 14244 14245 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14246 return rebuildSugarExpr(E); 14247 } 14248 14249 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14250 ExprResult SubResult = Visit(E->getSubExpr()); 14251 if (SubResult.isInvalid()) return ExprError(); 14252 14253 Expr *SubExpr = SubResult.get(); 14254 E->setSubExpr(SubExpr); 14255 E->setType(S.Context.getPointerType(SubExpr->getType())); 14256 assert(E->getValueKind() == VK_RValue); 14257 assert(E->getObjectKind() == OK_Ordinary); 14258 return E; 14259 } 14260 14261 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14262 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14263 14264 E->setType(VD->getType()); 14265 14266 assert(E->getValueKind() == VK_RValue); 14267 if (S.getLangOpts().CPlusPlus && 14268 !(isa<CXXMethodDecl>(VD) && 14269 cast<CXXMethodDecl>(VD)->isInstance())) 14270 E->setValueKind(VK_LValue); 14271 14272 return E; 14273 } 14274 14275 ExprResult VisitMemberExpr(MemberExpr *E) { 14276 return resolveDecl(E, E->getMemberDecl()); 14277 } 14278 14279 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14280 return resolveDecl(E, E->getDecl()); 14281 } 14282 }; 14283 } 14284 14285 /// Given a function expression of unknown-any type, try to rebuild it 14286 /// to have a function type. 14287 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14288 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14289 if (Result.isInvalid()) return ExprError(); 14290 return S.DefaultFunctionArrayConversion(Result.get()); 14291 } 14292 14293 namespace { 14294 /// A visitor for rebuilding an expression of type __unknown_anytype 14295 /// into one which resolves the type directly on the referring 14296 /// expression. Strict preservation of the original source 14297 /// structure is not a goal. 14298 struct RebuildUnknownAnyExpr 14299 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14300 14301 Sema &S; 14302 14303 /// The current destination type. 14304 QualType DestType; 14305 14306 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14307 : S(S), DestType(CastType) {} 14308 14309 ExprResult VisitStmt(Stmt *S) { 14310 llvm_unreachable("unexpected statement!"); 14311 } 14312 14313 ExprResult VisitExpr(Expr *E) { 14314 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14315 << E->getSourceRange(); 14316 return ExprError(); 14317 } 14318 14319 ExprResult VisitCallExpr(CallExpr *E); 14320 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14321 14322 /// Rebuild an expression which simply semantically wraps another 14323 /// expression which it shares the type and value kind of. 14324 template <class T> ExprResult rebuildSugarExpr(T *E) { 14325 ExprResult SubResult = Visit(E->getSubExpr()); 14326 if (SubResult.isInvalid()) return ExprError(); 14327 Expr *SubExpr = SubResult.get(); 14328 E->setSubExpr(SubExpr); 14329 E->setType(SubExpr->getType()); 14330 E->setValueKind(SubExpr->getValueKind()); 14331 assert(E->getObjectKind() == OK_Ordinary); 14332 return E; 14333 } 14334 14335 ExprResult VisitParenExpr(ParenExpr *E) { 14336 return rebuildSugarExpr(E); 14337 } 14338 14339 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14340 return rebuildSugarExpr(E); 14341 } 14342 14343 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14344 const PointerType *Ptr = DestType->getAs<PointerType>(); 14345 if (!Ptr) { 14346 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14347 << E->getSourceRange(); 14348 return ExprError(); 14349 } 14350 assert(E->getValueKind() == VK_RValue); 14351 assert(E->getObjectKind() == OK_Ordinary); 14352 E->setType(DestType); 14353 14354 // Build the sub-expression as if it were an object of the pointee type. 14355 DestType = Ptr->getPointeeType(); 14356 ExprResult SubResult = Visit(E->getSubExpr()); 14357 if (SubResult.isInvalid()) return ExprError(); 14358 E->setSubExpr(SubResult.get()); 14359 return E; 14360 } 14361 14362 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14363 14364 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14365 14366 ExprResult VisitMemberExpr(MemberExpr *E) { 14367 return resolveDecl(E, E->getMemberDecl()); 14368 } 14369 14370 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14371 return resolveDecl(E, E->getDecl()); 14372 } 14373 }; 14374 } 14375 14376 /// Rebuilds a call expression which yielded __unknown_anytype. 14377 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14378 Expr *CalleeExpr = E->getCallee(); 14379 14380 enum FnKind { 14381 FK_MemberFunction, 14382 FK_FunctionPointer, 14383 FK_BlockPointer 14384 }; 14385 14386 FnKind Kind; 14387 QualType CalleeType = CalleeExpr->getType(); 14388 if (CalleeType == S.Context.BoundMemberTy) { 14389 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14390 Kind = FK_MemberFunction; 14391 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14392 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14393 CalleeType = Ptr->getPointeeType(); 14394 Kind = FK_FunctionPointer; 14395 } else { 14396 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14397 Kind = FK_BlockPointer; 14398 } 14399 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14400 14401 // Verify that this is a legal result type of a function. 14402 if (DestType->isArrayType() || DestType->isFunctionType()) { 14403 unsigned diagID = diag::err_func_returning_array_function; 14404 if (Kind == FK_BlockPointer) 14405 diagID = diag::err_block_returning_array_function; 14406 14407 S.Diag(E->getExprLoc(), diagID) 14408 << DestType->isFunctionType() << DestType; 14409 return ExprError(); 14410 } 14411 14412 // Otherwise, go ahead and set DestType as the call's result. 14413 E->setType(DestType.getNonLValueExprType(S.Context)); 14414 E->setValueKind(Expr::getValueKindForType(DestType)); 14415 assert(E->getObjectKind() == OK_Ordinary); 14416 14417 // Rebuild the function type, replacing the result type with DestType. 14418 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14419 if (Proto) { 14420 // __unknown_anytype(...) is a special case used by the debugger when 14421 // it has no idea what a function's signature is. 14422 // 14423 // We want to build this call essentially under the K&R 14424 // unprototyped rules, but making a FunctionNoProtoType in C++ 14425 // would foul up all sorts of assumptions. However, we cannot 14426 // simply pass all arguments as variadic arguments, nor can we 14427 // portably just call the function under a non-variadic type; see 14428 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14429 // However, it turns out that in practice it is generally safe to 14430 // call a function declared as "A foo(B,C,D);" under the prototype 14431 // "A foo(B,C,D,...);". The only known exception is with the 14432 // Windows ABI, where any variadic function is implicitly cdecl 14433 // regardless of its normal CC. Therefore we change the parameter 14434 // types to match the types of the arguments. 14435 // 14436 // This is a hack, but it is far superior to moving the 14437 // corresponding target-specific code from IR-gen to Sema/AST. 14438 14439 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14440 SmallVector<QualType, 8> ArgTypes; 14441 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14442 ArgTypes.reserve(E->getNumArgs()); 14443 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14444 Expr *Arg = E->getArg(i); 14445 QualType ArgType = Arg->getType(); 14446 if (E->isLValue()) { 14447 ArgType = S.Context.getLValueReferenceType(ArgType); 14448 } else if (E->isXValue()) { 14449 ArgType = S.Context.getRValueReferenceType(ArgType); 14450 } 14451 ArgTypes.push_back(ArgType); 14452 } 14453 ParamTypes = ArgTypes; 14454 } 14455 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14456 Proto->getExtProtoInfo()); 14457 } else { 14458 DestType = S.Context.getFunctionNoProtoType(DestType, 14459 FnType->getExtInfo()); 14460 } 14461 14462 // Rebuild the appropriate pointer-to-function type. 14463 switch (Kind) { 14464 case FK_MemberFunction: 14465 // Nothing to do. 14466 break; 14467 14468 case FK_FunctionPointer: 14469 DestType = S.Context.getPointerType(DestType); 14470 break; 14471 14472 case FK_BlockPointer: 14473 DestType = S.Context.getBlockPointerType(DestType); 14474 break; 14475 } 14476 14477 // Finally, we can recurse. 14478 ExprResult CalleeResult = Visit(CalleeExpr); 14479 if (!CalleeResult.isUsable()) return ExprError(); 14480 E->setCallee(CalleeResult.get()); 14481 14482 // Bind a temporary if necessary. 14483 return S.MaybeBindToTemporary(E); 14484 } 14485 14486 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14487 // Verify that this is a legal result type of a call. 14488 if (DestType->isArrayType() || DestType->isFunctionType()) { 14489 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14490 << DestType->isFunctionType() << DestType; 14491 return ExprError(); 14492 } 14493 14494 // Rewrite the method result type if available. 14495 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14496 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14497 Method->setReturnType(DestType); 14498 } 14499 14500 // Change the type of the message. 14501 E->setType(DestType.getNonReferenceType()); 14502 E->setValueKind(Expr::getValueKindForType(DestType)); 14503 14504 return S.MaybeBindToTemporary(E); 14505 } 14506 14507 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14508 // The only case we should ever see here is a function-to-pointer decay. 14509 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14510 assert(E->getValueKind() == VK_RValue); 14511 assert(E->getObjectKind() == OK_Ordinary); 14512 14513 E->setType(DestType); 14514 14515 // Rebuild the sub-expression as the pointee (function) type. 14516 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14517 14518 ExprResult Result = Visit(E->getSubExpr()); 14519 if (!Result.isUsable()) return ExprError(); 14520 14521 E->setSubExpr(Result.get()); 14522 return E; 14523 } else if (E->getCastKind() == CK_LValueToRValue) { 14524 assert(E->getValueKind() == VK_RValue); 14525 assert(E->getObjectKind() == OK_Ordinary); 14526 14527 assert(isa<BlockPointerType>(E->getType())); 14528 14529 E->setType(DestType); 14530 14531 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14532 DestType = S.Context.getLValueReferenceType(DestType); 14533 14534 ExprResult Result = Visit(E->getSubExpr()); 14535 if (!Result.isUsable()) return ExprError(); 14536 14537 E->setSubExpr(Result.get()); 14538 return E; 14539 } else { 14540 llvm_unreachable("Unhandled cast type!"); 14541 } 14542 } 14543 14544 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14545 ExprValueKind ValueKind = VK_LValue; 14546 QualType Type = DestType; 14547 14548 // We know how to make this work for certain kinds of decls: 14549 14550 // - functions 14551 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14552 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14553 DestType = Ptr->getPointeeType(); 14554 ExprResult Result = resolveDecl(E, VD); 14555 if (Result.isInvalid()) return ExprError(); 14556 return S.ImpCastExprToType(Result.get(), Type, 14557 CK_FunctionToPointerDecay, VK_RValue); 14558 } 14559 14560 if (!Type->isFunctionType()) { 14561 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14562 << VD << E->getSourceRange(); 14563 return ExprError(); 14564 } 14565 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14566 // We must match the FunctionDecl's type to the hack introduced in 14567 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14568 // type. See the lengthy commentary in that routine. 14569 QualType FDT = FD->getType(); 14570 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14571 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14572 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14573 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14574 SourceLocation Loc = FD->getLocation(); 14575 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14576 FD->getDeclContext(), 14577 Loc, Loc, FD->getNameInfo().getName(), 14578 DestType, FD->getTypeSourceInfo(), 14579 SC_None, false/*isInlineSpecified*/, 14580 FD->hasPrototype(), 14581 false/*isConstexprSpecified*/); 14582 14583 if (FD->getQualifier()) 14584 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14585 14586 SmallVector<ParmVarDecl*, 16> Params; 14587 for (const auto &AI : FT->param_types()) { 14588 ParmVarDecl *Param = 14589 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14590 Param->setScopeInfo(0, Params.size()); 14591 Params.push_back(Param); 14592 } 14593 NewFD->setParams(Params); 14594 DRE->setDecl(NewFD); 14595 VD = DRE->getDecl(); 14596 } 14597 } 14598 14599 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14600 if (MD->isInstance()) { 14601 ValueKind = VK_RValue; 14602 Type = S.Context.BoundMemberTy; 14603 } 14604 14605 // Function references aren't l-values in C. 14606 if (!S.getLangOpts().CPlusPlus) 14607 ValueKind = VK_RValue; 14608 14609 // - variables 14610 } else if (isa<VarDecl>(VD)) { 14611 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14612 Type = RefTy->getPointeeType(); 14613 } else if (Type->isFunctionType()) { 14614 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14615 << VD << E->getSourceRange(); 14616 return ExprError(); 14617 } 14618 14619 // - nothing else 14620 } else { 14621 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14622 << VD << E->getSourceRange(); 14623 return ExprError(); 14624 } 14625 14626 // Modifying the declaration like this is friendly to IR-gen but 14627 // also really dangerous. 14628 VD->setType(DestType); 14629 E->setType(Type); 14630 E->setValueKind(ValueKind); 14631 return E; 14632 } 14633 14634 /// Check a cast of an unknown-any type. We intentionally only 14635 /// trigger this for C-style casts. 14636 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14637 Expr *CastExpr, CastKind &CastKind, 14638 ExprValueKind &VK, CXXCastPath &Path) { 14639 // The type we're casting to must be either void or complete. 14640 if (!CastType->isVoidType() && 14641 RequireCompleteType(TypeRange.getBegin(), CastType, 14642 diag::err_typecheck_cast_to_incomplete)) 14643 return ExprError(); 14644 14645 // Rewrite the casted expression from scratch. 14646 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14647 if (!result.isUsable()) return ExprError(); 14648 14649 CastExpr = result.get(); 14650 VK = CastExpr->getValueKind(); 14651 CastKind = CK_NoOp; 14652 14653 return CastExpr; 14654 } 14655 14656 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14657 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14658 } 14659 14660 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14661 Expr *arg, QualType ¶mType) { 14662 // If the syntactic form of the argument is not an explicit cast of 14663 // any sort, just do default argument promotion. 14664 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14665 if (!castArg) { 14666 ExprResult result = DefaultArgumentPromotion(arg); 14667 if (result.isInvalid()) return ExprError(); 14668 paramType = result.get()->getType(); 14669 return result; 14670 } 14671 14672 // Otherwise, use the type that was written in the explicit cast. 14673 assert(!arg->hasPlaceholderType()); 14674 paramType = castArg->getTypeAsWritten(); 14675 14676 // Copy-initialize a parameter of that type. 14677 InitializedEntity entity = 14678 InitializedEntity::InitializeParameter(Context, paramType, 14679 /*consumed*/ false); 14680 return PerformCopyInitialization(entity, callLoc, arg); 14681 } 14682 14683 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14684 Expr *orig = E; 14685 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14686 while (true) { 14687 E = E->IgnoreParenImpCasts(); 14688 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14689 E = call->getCallee(); 14690 diagID = diag::err_uncasted_call_of_unknown_any; 14691 } else { 14692 break; 14693 } 14694 } 14695 14696 SourceLocation loc; 14697 NamedDecl *d; 14698 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14699 loc = ref->getLocation(); 14700 d = ref->getDecl(); 14701 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14702 loc = mem->getMemberLoc(); 14703 d = mem->getMemberDecl(); 14704 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14705 diagID = diag::err_uncasted_call_of_unknown_any; 14706 loc = msg->getSelectorStartLoc(); 14707 d = msg->getMethodDecl(); 14708 if (!d) { 14709 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14710 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14711 << orig->getSourceRange(); 14712 return ExprError(); 14713 } 14714 } else { 14715 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14716 << E->getSourceRange(); 14717 return ExprError(); 14718 } 14719 14720 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14721 14722 // Never recoverable. 14723 return ExprError(); 14724 } 14725 14726 /// Check for operands with placeholder types and complain if found. 14727 /// Returns true if there was an error and no recovery was possible. 14728 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14729 if (!getLangOpts().CPlusPlus) { 14730 // C cannot handle TypoExpr nodes on either side of a binop because it 14731 // doesn't handle dependent types properly, so make sure any TypoExprs have 14732 // been dealt with before checking the operands. 14733 ExprResult Result = CorrectDelayedTyposInExpr(E); 14734 if (!Result.isUsable()) return ExprError(); 14735 E = Result.get(); 14736 } 14737 14738 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14739 if (!placeholderType) return E; 14740 14741 switch (placeholderType->getKind()) { 14742 14743 // Overloaded expressions. 14744 case BuiltinType::Overload: { 14745 // Try to resolve a single function template specialization. 14746 // This is obligatory. 14747 ExprResult result = E; 14748 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14749 return result; 14750 14751 // If that failed, try to recover with a call. 14752 } else { 14753 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14754 /*complain*/ true); 14755 return result; 14756 } 14757 } 14758 14759 // Bound member functions. 14760 case BuiltinType::BoundMember: { 14761 ExprResult result = E; 14762 const Expr *BME = E->IgnoreParens(); 14763 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14764 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14765 if (isa<CXXPseudoDestructorExpr>(BME)) { 14766 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14767 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14768 if (ME->getMemberNameInfo().getName().getNameKind() == 14769 DeclarationName::CXXDestructorName) 14770 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14771 } 14772 tryToRecoverWithCall(result, PD, 14773 /*complain*/ true); 14774 return result; 14775 } 14776 14777 // ARC unbridged casts. 14778 case BuiltinType::ARCUnbridgedCast: { 14779 Expr *realCast = stripARCUnbridgedCast(E); 14780 diagnoseARCUnbridgedCast(realCast); 14781 return realCast; 14782 } 14783 14784 // Expressions of unknown type. 14785 case BuiltinType::UnknownAny: 14786 return diagnoseUnknownAnyExpr(*this, E); 14787 14788 // Pseudo-objects. 14789 case BuiltinType::PseudoObject: 14790 return checkPseudoObjectRValue(E); 14791 14792 case BuiltinType::BuiltinFn: { 14793 // Accept __noop without parens by implicitly converting it to a call expr. 14794 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14795 if (DRE) { 14796 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14797 if (FD->getBuiltinID() == Builtin::BI__noop) { 14798 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14799 CK_BuiltinFnToFnPtr).get(); 14800 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14801 VK_RValue, SourceLocation()); 14802 } 14803 } 14804 14805 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14806 return ExprError(); 14807 } 14808 14809 // Expressions of unknown type. 14810 case BuiltinType::OMPArraySection: 14811 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14812 return ExprError(); 14813 14814 // Everything else should be impossible. 14815 #define BUILTIN_TYPE(Id, SingletonId) \ 14816 case BuiltinType::Id: 14817 #define PLACEHOLDER_TYPE(Id, SingletonId) 14818 #include "clang/AST/BuiltinTypes.def" 14819 break; 14820 } 14821 14822 llvm_unreachable("invalid placeholder type!"); 14823 } 14824 14825 bool Sema::CheckCaseExpression(Expr *E) { 14826 if (E->isTypeDependent()) 14827 return true; 14828 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14829 return E->getType()->isIntegralOrEnumerationType(); 14830 return false; 14831 } 14832 14833 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14834 ExprResult 14835 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14836 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14837 "Unknown Objective-C Boolean value!"); 14838 QualType BoolT = Context.ObjCBuiltinBoolTy; 14839 if (!Context.getBOOLDecl()) { 14840 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14841 Sema::LookupOrdinaryName); 14842 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14843 NamedDecl *ND = Result.getFoundDecl(); 14844 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14845 Context.setBOOLDecl(TD); 14846 } 14847 } 14848 if (Context.getBOOLDecl()) 14849 BoolT = Context.getBOOLType(); 14850 return new (Context) 14851 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14852 } 14853