1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) { 83 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 84 if (DC && !DC->hasAttr<UnusedAttr>()) 85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 86 } 87 } 88 } 89 90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 92 if (!OMD) 93 return false; 94 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 95 if (!OID) 96 return false; 97 98 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 99 if (ObjCMethodDecl *CatMeth = 100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 101 if (!CatMeth->hasAttr<AvailabilityAttr>()) 102 return true; 103 return false; 104 } 105 106 static AvailabilityResult 107 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 108 const ObjCInterfaceDecl *UnknownObjCClass, 109 bool ObjCPropertyAccess) { 110 // See if this declaration is unavailable or deprecated. 111 std::string Message; 112 AvailabilityResult Result = D->getAvailability(&Message); 113 114 // For typedefs, if the typedef declaration appears available look 115 // to the underlying type to see if it is more restrictive. 116 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 117 if (Result == AR_Available) { 118 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 119 D = TT->getDecl(); 120 Result = D->getAvailability(&Message); 121 continue; 122 } 123 } 124 break; 125 } 126 127 // Forward class declarations get their attributes from their definition. 128 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 129 if (IDecl->getDefinition()) { 130 D = IDecl->getDefinition(); 131 Result = D->getAvailability(&Message); 132 } 133 } 134 135 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 136 if (Result == AR_Available) { 137 const DeclContext *DC = ECD->getDeclContext(); 138 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 139 Result = TheEnumDecl->getAvailability(&Message); 140 } 141 142 const ObjCPropertyDecl *ObjCPDecl = nullptr; 143 if (Result == AR_Deprecated || Result == AR_Unavailable || 144 Result == AR_NotYetIntroduced) { 145 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 146 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 147 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 148 if (PDeclResult == Result) 149 ObjCPDecl = PD; 150 } 151 } 152 } 153 154 switch (Result) { 155 case AR_Available: 156 break; 157 158 case AR_Deprecated: 159 if (S.getCurContextAvailability() != AR_Deprecated) 160 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 161 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 162 ObjCPropertyAccess); 163 break; 164 165 case AR_NotYetIntroduced: { 166 // Don't do this for enums, they can't be redeclared. 167 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 168 break; 169 170 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 171 // Objective-C method declarations in categories are not modelled as 172 // redeclarations, so manually look for a redeclaration in a category 173 // if necessary. 174 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 175 Warn = false; 176 // In general, D will point to the most recent redeclaration. However, 177 // for `@class A;` decls, this isn't true -- manually go through the 178 // redecl chain in that case. 179 if (Warn && isa<ObjCInterfaceDecl>(D)) 180 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 181 Redecl = Redecl->getPreviousDecl()) 182 if (!Redecl->hasAttr<AvailabilityAttr>() || 183 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 184 Warn = false; 185 186 if (Warn) 187 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 188 UnknownObjCClass, ObjCPDecl, 189 ObjCPropertyAccess); 190 break; 191 } 192 193 case AR_Unavailable: 194 if (S.getCurContextAvailability() != AR_Unavailable) 195 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 196 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 197 ObjCPropertyAccess); 198 break; 199 200 } 201 return Result; 202 } 203 204 /// \brief Emit a note explaining that this function is deleted. 205 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 206 assert(Decl->isDeleted()); 207 208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 209 210 if (Method && Method->isDeleted() && Method->isDefaulted()) { 211 // If the method was explicitly defaulted, point at that declaration. 212 if (!Method->isImplicit()) 213 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 214 215 // Try to diagnose why this special member function was implicitly 216 // deleted. This might fail, if that reason no longer applies. 217 CXXSpecialMember CSM = getSpecialMember(Method); 218 if (CSM != CXXInvalid) 219 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 220 221 return; 222 } 223 224 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 225 if (Ctor && Ctor->isInheritingConstructor()) 226 return NoteDeletedInheritingConstructor(Ctor); 227 228 Diag(Decl->getLocation(), diag::note_availability_specified_here) 229 << Decl << true; 230 } 231 232 /// \brief Determine whether a FunctionDecl was ever declared with an 233 /// explicit storage class. 234 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 235 for (auto I : D->redecls()) { 236 if (I->getStorageClass() != SC_None) 237 return true; 238 } 239 return false; 240 } 241 242 /// \brief Check whether we're in an extern inline function and referring to a 243 /// variable or function with internal linkage (C11 6.7.4p3). 244 /// 245 /// This is only a warning because we used to silently accept this code, but 246 /// in many cases it will not behave correctly. This is not enabled in C++ mode 247 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 248 /// and so while there may still be user mistakes, most of the time we can't 249 /// prove that there are errors. 250 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 251 const NamedDecl *D, 252 SourceLocation Loc) { 253 // This is disabled under C++; there are too many ways for this to fire in 254 // contexts where the warning is a false positive, or where it is technically 255 // correct but benign. 256 if (S.getLangOpts().CPlusPlus) 257 return; 258 259 // Check if this is an inlined function or method. 260 FunctionDecl *Current = S.getCurFunctionDecl(); 261 if (!Current) 262 return; 263 if (!Current->isInlined()) 264 return; 265 if (!Current->isExternallyVisible()) 266 return; 267 268 // Check if the decl has internal linkage. 269 if (D->getFormalLinkage() != InternalLinkage) 270 return; 271 272 // Downgrade from ExtWarn to Extension if 273 // (1) the supposedly external inline function is in the main file, 274 // and probably won't be included anywhere else. 275 // (2) the thing we're referencing is a pure function. 276 // (3) the thing we're referencing is another inline function. 277 // This last can give us false negatives, but it's better than warning on 278 // wrappers for simple C library functions. 279 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 280 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 281 if (!DowngradeWarning && UsedFn) 282 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 283 284 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 285 : diag::ext_internal_in_extern_inline) 286 << /*IsVar=*/!UsedFn << D; 287 288 S.MaybeSuggestAddingStaticToDecl(Current); 289 290 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 291 << D; 292 } 293 294 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 295 const FunctionDecl *First = Cur->getFirstDecl(); 296 297 // Suggest "static" on the function, if possible. 298 if (!hasAnyExplicitStorageClass(First)) { 299 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 300 Diag(DeclBegin, diag::note_convert_inline_to_static) 301 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 302 } 303 } 304 305 /// \brief Determine whether the use of this declaration is valid, and 306 /// emit any corresponding diagnostics. 307 /// 308 /// This routine diagnoses various problems with referencing 309 /// declarations that can occur when using a declaration. For example, 310 /// it might warn if a deprecated or unavailable declaration is being 311 /// used, or produce an error (and return true) if a C++0x deleted 312 /// function is being used. 313 /// 314 /// \returns true if there was an error (this declaration cannot be 315 /// referenced), false otherwise. 316 /// 317 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 318 const ObjCInterfaceDecl *UnknownObjCClass, 319 bool ObjCPropertyAccess) { 320 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 321 // If there were any diagnostics suppressed by template argument deduction, 322 // emit them now. 323 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 324 if (Pos != SuppressedDiagnostics.end()) { 325 for (const PartialDiagnosticAt &Suppressed : Pos->second) 326 Diag(Suppressed.first, Suppressed.second); 327 328 // Clear out the list of suppressed diagnostics, so that we don't emit 329 // them again for this specialization. However, we don't obsolete this 330 // entry from the table, because we want to avoid ever emitting these 331 // diagnostics again. 332 Pos->second.clear(); 333 } 334 335 // C++ [basic.start.main]p3: 336 // The function 'main' shall not be used within a program. 337 if (cast<FunctionDecl>(D)->isMain()) 338 Diag(Loc, diag::ext_main_used); 339 } 340 341 // See if this is an auto-typed variable whose initializer we are parsing. 342 if (ParsingInitForAutoVars.count(D)) { 343 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 344 345 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 346 << D->getDeclName() << (unsigned)AT->getKeyword(); 347 return true; 348 } 349 350 // See if this is a deleted function. 351 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 352 if (FD->isDeleted()) { 353 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 354 if (Ctor && Ctor->isInheritingConstructor()) 355 Diag(Loc, diag::err_deleted_inherited_ctor_use) 356 << Ctor->getParent() 357 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 358 else 359 Diag(Loc, diag::err_deleted_function_use); 360 NoteDeletedFunction(FD); 361 return true; 362 } 363 364 // If the function has a deduced return type, and we can't deduce it, 365 // then we can't use it either. 366 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 367 DeduceReturnType(FD, Loc)) 368 return true; 369 } 370 371 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 372 // Only the variables omp_in and omp_out are allowed in the combiner. 373 // Only the variables omp_priv and omp_orig are allowed in the 374 // initializer-clause. 375 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 376 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 377 isa<VarDecl>(D)) { 378 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 379 << getCurFunction()->HasOMPDeclareReductionCombiner; 380 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 381 return true; 382 } 383 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 384 ObjCPropertyAccess); 385 386 DiagnoseUnusedOfDecl(*this, D, Loc); 387 388 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 389 390 return false; 391 } 392 393 /// \brief Retrieve the message suffix that should be added to a 394 /// diagnostic complaining about the given function being deleted or 395 /// unavailable. 396 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 397 std::string Message; 398 if (FD->getAvailability(&Message)) 399 return ": " + Message; 400 401 return std::string(); 402 } 403 404 /// DiagnoseSentinelCalls - This routine checks whether a call or 405 /// message-send is to a declaration with the sentinel attribute, and 406 /// if so, it checks that the requirements of the sentinel are 407 /// satisfied. 408 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 409 ArrayRef<Expr *> Args) { 410 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 411 if (!attr) 412 return; 413 414 // The number of formal parameters of the declaration. 415 unsigned numFormalParams; 416 417 // The kind of declaration. This is also an index into a %select in 418 // the diagnostic. 419 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 420 421 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 422 numFormalParams = MD->param_size(); 423 calleeType = CT_Method; 424 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 425 numFormalParams = FD->param_size(); 426 calleeType = CT_Function; 427 } else if (isa<VarDecl>(D)) { 428 QualType type = cast<ValueDecl>(D)->getType(); 429 const FunctionType *fn = nullptr; 430 if (const PointerType *ptr = type->getAs<PointerType>()) { 431 fn = ptr->getPointeeType()->getAs<FunctionType>(); 432 if (!fn) return; 433 calleeType = CT_Function; 434 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 435 fn = ptr->getPointeeType()->castAs<FunctionType>(); 436 calleeType = CT_Block; 437 } else { 438 return; 439 } 440 441 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 442 numFormalParams = proto->getNumParams(); 443 } else { 444 numFormalParams = 0; 445 } 446 } else { 447 return; 448 } 449 450 // "nullPos" is the number of formal parameters at the end which 451 // effectively count as part of the variadic arguments. This is 452 // useful if you would prefer to not have *any* formal parameters, 453 // but the language forces you to have at least one. 454 unsigned nullPos = attr->getNullPos(); 455 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 456 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 457 458 // The number of arguments which should follow the sentinel. 459 unsigned numArgsAfterSentinel = attr->getSentinel(); 460 461 // If there aren't enough arguments for all the formal parameters, 462 // the sentinel, and the args after the sentinel, complain. 463 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 464 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 465 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 466 return; 467 } 468 469 // Otherwise, find the sentinel expression. 470 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 471 if (!sentinelExpr) return; 472 if (sentinelExpr->isValueDependent()) return; 473 if (Context.isSentinelNullExpr(sentinelExpr)) return; 474 475 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 476 // or 'NULL' if those are actually defined in the context. Only use 477 // 'nil' for ObjC methods, where it's much more likely that the 478 // variadic arguments form a list of object pointers. 479 SourceLocation MissingNilLoc 480 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 481 std::string NullValue; 482 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 483 NullValue = "nil"; 484 else if (getLangOpts().CPlusPlus11) 485 NullValue = "nullptr"; 486 else if (PP.isMacroDefined("NULL")) 487 NullValue = "NULL"; 488 else 489 NullValue = "(void*) 0"; 490 491 if (MissingNilLoc.isInvalid()) 492 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 493 else 494 Diag(MissingNilLoc, diag::warn_missing_sentinel) 495 << int(calleeType) 496 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 497 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 498 } 499 500 SourceRange Sema::getExprRange(Expr *E) const { 501 return E ? E->getSourceRange() : SourceRange(); 502 } 503 504 //===----------------------------------------------------------------------===// 505 // Standard Promotions and Conversions 506 //===----------------------------------------------------------------------===// 507 508 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 509 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 510 // Handle any placeholder expressions which made it here. 511 if (E->getType()->isPlaceholderType()) { 512 ExprResult result = CheckPlaceholderExpr(E); 513 if (result.isInvalid()) return ExprError(); 514 E = result.get(); 515 } 516 517 QualType Ty = E->getType(); 518 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 519 520 if (Ty->isFunctionType()) { 521 // If we are here, we are not calling a function but taking 522 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 523 if (getLangOpts().OpenCL) { 524 if (Diagnose) 525 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 526 return ExprError(); 527 } 528 529 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 530 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 531 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 532 return ExprError(); 533 534 E = ImpCastExprToType(E, Context.getPointerType(Ty), 535 CK_FunctionToPointerDecay).get(); 536 } else if (Ty->isArrayType()) { 537 // In C90 mode, arrays only promote to pointers if the array expression is 538 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 539 // type 'array of type' is converted to an expression that has type 'pointer 540 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 541 // that has type 'array of type' ...". The relevant change is "an lvalue" 542 // (C90) to "an expression" (C99). 543 // 544 // C++ 4.2p1: 545 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 546 // T" can be converted to an rvalue of type "pointer to T". 547 // 548 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 549 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 550 CK_ArrayToPointerDecay).get(); 551 } 552 return E; 553 } 554 555 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 556 // Check to see if we are dereferencing a null pointer. If so, 557 // and if not volatile-qualified, this is undefined behavior that the 558 // optimizer will delete, so warn about it. People sometimes try to use this 559 // to get a deterministic trap and are surprised by clang's behavior. This 560 // only handles the pattern "*null", which is a very syntactic check. 561 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 562 if (UO->getOpcode() == UO_Deref && 563 UO->getSubExpr()->IgnoreParenCasts()-> 564 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 565 !UO->getType().isVolatileQualified()) { 566 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 567 S.PDiag(diag::warn_indirection_through_null) 568 << UO->getSubExpr()->getSourceRange()); 569 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 570 S.PDiag(diag::note_indirection_through_null)); 571 } 572 } 573 574 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 575 SourceLocation AssignLoc, 576 const Expr* RHS) { 577 const ObjCIvarDecl *IV = OIRE->getDecl(); 578 if (!IV) 579 return; 580 581 DeclarationName MemberName = IV->getDeclName(); 582 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 583 if (!Member || !Member->isStr("isa")) 584 return; 585 586 const Expr *Base = OIRE->getBase(); 587 QualType BaseType = Base->getType(); 588 if (OIRE->isArrow()) 589 BaseType = BaseType->getPointeeType(); 590 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 591 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 592 ObjCInterfaceDecl *ClassDeclared = nullptr; 593 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 594 if (!ClassDeclared->getSuperClass() 595 && (*ClassDeclared->ivar_begin()) == IV) { 596 if (RHS) { 597 NamedDecl *ObjectSetClass = 598 S.LookupSingleName(S.TUScope, 599 &S.Context.Idents.get("object_setClass"), 600 SourceLocation(), S.LookupOrdinaryName); 601 if (ObjectSetClass) { 602 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 603 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 604 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 605 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 606 AssignLoc), ",") << 607 FixItHint::CreateInsertion(RHSLocEnd, ")"); 608 } 609 else 610 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 611 } else { 612 NamedDecl *ObjectGetClass = 613 S.LookupSingleName(S.TUScope, 614 &S.Context.Idents.get("object_getClass"), 615 SourceLocation(), S.LookupOrdinaryName); 616 if (ObjectGetClass) 617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 618 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 619 FixItHint::CreateReplacement( 620 SourceRange(OIRE->getOpLoc(), 621 OIRE->getLocEnd()), ")"); 622 else 623 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 624 } 625 S.Diag(IV->getLocation(), diag::note_ivar_decl); 626 } 627 } 628 } 629 630 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 631 // Handle any placeholder expressions which made it here. 632 if (E->getType()->isPlaceholderType()) { 633 ExprResult result = CheckPlaceholderExpr(E); 634 if (result.isInvalid()) return ExprError(); 635 E = result.get(); 636 } 637 638 // C++ [conv.lval]p1: 639 // A glvalue of a non-function, non-array type T can be 640 // converted to a prvalue. 641 if (!E->isGLValue()) return E; 642 643 QualType T = E->getType(); 644 assert(!T.isNull() && "r-value conversion on typeless expression?"); 645 646 // We don't want to throw lvalue-to-rvalue casts on top of 647 // expressions of certain types in C++. 648 if (getLangOpts().CPlusPlus && 649 (E->getType() == Context.OverloadTy || 650 T->isDependentType() || 651 T->isRecordType())) 652 return E; 653 654 // The C standard is actually really unclear on this point, and 655 // DR106 tells us what the result should be but not why. It's 656 // generally best to say that void types just doesn't undergo 657 // lvalue-to-rvalue at all. Note that expressions of unqualified 658 // 'void' type are never l-values, but qualified void can be. 659 if (T->isVoidType()) 660 return E; 661 662 // OpenCL usually rejects direct accesses to values of 'half' type. 663 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 664 T->isHalfType()) { 665 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 666 << 0 << T; 667 return ExprError(); 668 } 669 670 CheckForNullPointerDereference(*this, E); 671 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 672 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 673 &Context.Idents.get("object_getClass"), 674 SourceLocation(), LookupOrdinaryName); 675 if (ObjectGetClass) 676 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 677 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 678 FixItHint::CreateReplacement( 679 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 680 else 681 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 682 } 683 else if (const ObjCIvarRefExpr *OIRE = 684 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 685 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 686 687 // C++ [conv.lval]p1: 688 // [...] If T is a non-class type, the type of the prvalue is the 689 // cv-unqualified version of T. Otherwise, the type of the 690 // rvalue is T. 691 // 692 // C99 6.3.2.1p2: 693 // If the lvalue has qualified type, the value has the unqualified 694 // version of the type of the lvalue; otherwise, the value has the 695 // type of the lvalue. 696 if (T.hasQualifiers()) 697 T = T.getUnqualifiedType(); 698 699 // Under the MS ABI, lock down the inheritance model now. 700 if (T->isMemberPointerType() && 701 Context.getTargetInfo().getCXXABI().isMicrosoft()) 702 (void)isCompleteType(E->getExprLoc(), T); 703 704 UpdateMarkingForLValueToRValue(E); 705 706 // Loading a __weak object implicitly retains the value, so we need a cleanup to 707 // balance that. 708 if (getLangOpts().ObjCAutoRefCount && 709 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 710 Cleanup.setExprNeedsCleanups(true); 711 712 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 713 nullptr, VK_RValue); 714 715 // C11 6.3.2.1p2: 716 // ... if the lvalue has atomic type, the value has the non-atomic version 717 // of the type of the lvalue ... 718 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 719 T = Atomic->getValueType().getUnqualifiedType(); 720 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 721 nullptr, VK_RValue); 722 } 723 724 return Res; 725 } 726 727 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 728 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 729 if (Res.isInvalid()) 730 return ExprError(); 731 Res = DefaultLvalueConversion(Res.get()); 732 if (Res.isInvalid()) 733 return ExprError(); 734 return Res; 735 } 736 737 /// CallExprUnaryConversions - a special case of an unary conversion 738 /// performed on a function designator of a call expression. 739 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 740 QualType Ty = E->getType(); 741 ExprResult Res = E; 742 // Only do implicit cast for a function type, but not for a pointer 743 // to function type. 744 if (Ty->isFunctionType()) { 745 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 746 CK_FunctionToPointerDecay).get(); 747 if (Res.isInvalid()) 748 return ExprError(); 749 } 750 Res = DefaultLvalueConversion(Res.get()); 751 if (Res.isInvalid()) 752 return ExprError(); 753 return Res.get(); 754 } 755 756 /// UsualUnaryConversions - Performs various conversions that are common to most 757 /// operators (C99 6.3). The conversions of array and function types are 758 /// sometimes suppressed. For example, the array->pointer conversion doesn't 759 /// apply if the array is an argument to the sizeof or address (&) operators. 760 /// In these instances, this routine should *not* be called. 761 ExprResult Sema::UsualUnaryConversions(Expr *E) { 762 // First, convert to an r-value. 763 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 764 if (Res.isInvalid()) 765 return ExprError(); 766 E = Res.get(); 767 768 QualType Ty = E->getType(); 769 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 770 771 // Half FP have to be promoted to float unless it is natively supported 772 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 773 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 774 775 // Try to perform integral promotions if the object has a theoretically 776 // promotable type. 777 if (Ty->isIntegralOrUnscopedEnumerationType()) { 778 // C99 6.3.1.1p2: 779 // 780 // The following may be used in an expression wherever an int or 781 // unsigned int may be used: 782 // - an object or expression with an integer type whose integer 783 // conversion rank is less than or equal to the rank of int 784 // and unsigned int. 785 // - A bit-field of type _Bool, int, signed int, or unsigned int. 786 // 787 // If an int can represent all values of the original type, the 788 // value is converted to an int; otherwise, it is converted to an 789 // unsigned int. These are called the integer promotions. All 790 // other types are unchanged by the integer promotions. 791 792 QualType PTy = Context.isPromotableBitField(E); 793 if (!PTy.isNull()) { 794 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 795 return E; 796 } 797 if (Ty->isPromotableIntegerType()) { 798 QualType PT = Context.getPromotedIntegerType(Ty); 799 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 800 return E; 801 } 802 } 803 return E; 804 } 805 806 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 807 /// do not have a prototype. Arguments that have type float or __fp16 808 /// are promoted to double. All other argument types are converted by 809 /// UsualUnaryConversions(). 810 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 811 QualType Ty = E->getType(); 812 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 813 814 ExprResult Res = UsualUnaryConversions(E); 815 if (Res.isInvalid()) 816 return ExprError(); 817 E = Res.get(); 818 819 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 820 // double. 821 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 822 if (BTy && (BTy->getKind() == BuiltinType::Half || 823 BTy->getKind() == BuiltinType::Float)) 824 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 825 826 // C++ performs lvalue-to-rvalue conversion as a default argument 827 // promotion, even on class types, but note: 828 // C++11 [conv.lval]p2: 829 // When an lvalue-to-rvalue conversion occurs in an unevaluated 830 // operand or a subexpression thereof the value contained in the 831 // referenced object is not accessed. Otherwise, if the glvalue 832 // has a class type, the conversion copy-initializes a temporary 833 // of type T from the glvalue and the result of the conversion 834 // is a prvalue for the temporary. 835 // FIXME: add some way to gate this entire thing for correctness in 836 // potentially potentially evaluated contexts. 837 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 838 ExprResult Temp = PerformCopyInitialization( 839 InitializedEntity::InitializeTemporary(E->getType()), 840 E->getExprLoc(), E); 841 if (Temp.isInvalid()) 842 return ExprError(); 843 E = Temp.get(); 844 } 845 846 return E; 847 } 848 849 /// Determine the degree of POD-ness for an expression. 850 /// Incomplete types are considered POD, since this check can be performed 851 /// when we're in an unevaluated context. 852 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 853 if (Ty->isIncompleteType()) { 854 // C++11 [expr.call]p7: 855 // After these conversions, if the argument does not have arithmetic, 856 // enumeration, pointer, pointer to member, or class type, the program 857 // is ill-formed. 858 // 859 // Since we've already performed array-to-pointer and function-to-pointer 860 // decay, the only such type in C++ is cv void. This also handles 861 // initializer lists as variadic arguments. 862 if (Ty->isVoidType()) 863 return VAK_Invalid; 864 865 if (Ty->isObjCObjectType()) 866 return VAK_Invalid; 867 return VAK_Valid; 868 } 869 870 if (Ty.isCXX98PODType(Context)) 871 return VAK_Valid; 872 873 // C++11 [expr.call]p7: 874 // Passing a potentially-evaluated argument of class type (Clause 9) 875 // having a non-trivial copy constructor, a non-trivial move constructor, 876 // or a non-trivial destructor, with no corresponding parameter, 877 // is conditionally-supported with implementation-defined semantics. 878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 880 if (!Record->hasNonTrivialCopyConstructor() && 881 !Record->hasNonTrivialMoveConstructor() && 882 !Record->hasNonTrivialDestructor()) 883 return VAK_ValidInCXX11; 884 885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 886 return VAK_Valid; 887 888 if (Ty->isObjCObjectType()) 889 return VAK_Invalid; 890 891 if (getLangOpts().MSVCCompat) 892 return VAK_MSVCUndefined; 893 894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 895 // permitted to reject them. We should consider doing so. 896 return VAK_Undefined; 897 } 898 899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 900 // Don't allow one to pass an Objective-C interface to a vararg. 901 const QualType &Ty = E->getType(); 902 VarArgKind VAK = isValidVarArgType(Ty); 903 904 // Complain about passing non-POD types through varargs. 905 switch (VAK) { 906 case VAK_ValidInCXX11: 907 DiagRuntimeBehavior( 908 E->getLocStart(), nullptr, 909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 910 << Ty << CT); 911 // Fall through. 912 case VAK_Valid: 913 if (Ty->isRecordType()) { 914 // This is unlikely to be what the user intended. If the class has a 915 // 'c_str' member function, the user probably meant to call that. 916 DiagRuntimeBehavior(E->getLocStart(), nullptr, 917 PDiag(diag::warn_pass_class_arg_to_vararg) 918 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 919 } 920 break; 921 922 case VAK_Undefined: 923 case VAK_MSVCUndefined: 924 DiagRuntimeBehavior( 925 E->getLocStart(), nullptr, 926 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 927 << getLangOpts().CPlusPlus11 << Ty << CT); 928 break; 929 930 case VAK_Invalid: 931 if (Ty->isObjCObjectType()) 932 DiagRuntimeBehavior( 933 E->getLocStart(), nullptr, 934 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 935 << Ty << CT); 936 else 937 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 938 << isa<InitListExpr>(E) << Ty << CT; 939 break; 940 } 941 } 942 943 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 944 /// will create a trap if the resulting type is not a POD type. 945 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 946 FunctionDecl *FDecl) { 947 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 948 // Strip the unbridged-cast placeholder expression off, if applicable. 949 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 950 (CT == VariadicMethod || 951 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 952 E = stripARCUnbridgedCast(E); 953 954 // Otherwise, do normal placeholder checking. 955 } else { 956 ExprResult ExprRes = CheckPlaceholderExpr(E); 957 if (ExprRes.isInvalid()) 958 return ExprError(); 959 E = ExprRes.get(); 960 } 961 } 962 963 ExprResult ExprRes = DefaultArgumentPromotion(E); 964 if (ExprRes.isInvalid()) 965 return ExprError(); 966 E = ExprRes.get(); 967 968 // Diagnostics regarding non-POD argument types are 969 // emitted along with format string checking in Sema::CheckFunctionCall(). 970 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 971 // Turn this into a trap. 972 CXXScopeSpec SS; 973 SourceLocation TemplateKWLoc; 974 UnqualifiedId Name; 975 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 976 E->getLocStart()); 977 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 978 Name, true, false); 979 if (TrapFn.isInvalid()) 980 return ExprError(); 981 982 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 983 E->getLocStart(), None, 984 E->getLocEnd()); 985 if (Call.isInvalid()) 986 return ExprError(); 987 988 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 989 Call.get(), E); 990 if (Comma.isInvalid()) 991 return ExprError(); 992 return Comma.get(); 993 } 994 995 if (!getLangOpts().CPlusPlus && 996 RequireCompleteType(E->getExprLoc(), E->getType(), 997 diag::err_call_incomplete_argument)) 998 return ExprError(); 999 1000 return E; 1001 } 1002 1003 /// \brief Converts an integer to complex float type. Helper function of 1004 /// UsualArithmeticConversions() 1005 /// 1006 /// \return false if the integer expression is an integer type and is 1007 /// successfully converted to the complex type. 1008 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1009 ExprResult &ComplexExpr, 1010 QualType IntTy, 1011 QualType ComplexTy, 1012 bool SkipCast) { 1013 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1014 if (SkipCast) return false; 1015 if (IntTy->isIntegerType()) { 1016 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1017 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1018 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1019 CK_FloatingRealToComplex); 1020 } else { 1021 assert(IntTy->isComplexIntegerType()); 1022 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1023 CK_IntegralComplexToFloatingComplex); 1024 } 1025 return false; 1026 } 1027 1028 /// \brief Handle arithmetic conversion with complex types. Helper function of 1029 /// UsualArithmeticConversions() 1030 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1031 ExprResult &RHS, QualType LHSType, 1032 QualType RHSType, 1033 bool IsCompAssign) { 1034 // if we have an integer operand, the result is the complex type. 1035 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1036 /*skipCast*/false)) 1037 return LHSType; 1038 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1039 /*skipCast*/IsCompAssign)) 1040 return RHSType; 1041 1042 // This handles complex/complex, complex/float, or float/complex. 1043 // When both operands are complex, the shorter operand is converted to the 1044 // type of the longer, and that is the type of the result. This corresponds 1045 // to what is done when combining two real floating-point operands. 1046 // The fun begins when size promotion occur across type domains. 1047 // From H&S 6.3.4: When one operand is complex and the other is a real 1048 // floating-point type, the less precise type is converted, within it's 1049 // real or complex domain, to the precision of the other type. For example, 1050 // when combining a "long double" with a "double _Complex", the 1051 // "double _Complex" is promoted to "long double _Complex". 1052 1053 // Compute the rank of the two types, regardless of whether they are complex. 1054 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1055 1056 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1057 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1058 QualType LHSElementType = 1059 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1060 QualType RHSElementType = 1061 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1062 1063 QualType ResultType = S.Context.getComplexType(LHSElementType); 1064 if (Order < 0) { 1065 // Promote the precision of the LHS if not an assignment. 1066 ResultType = S.Context.getComplexType(RHSElementType); 1067 if (!IsCompAssign) { 1068 if (LHSComplexType) 1069 LHS = 1070 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1071 else 1072 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1073 } 1074 } else if (Order > 0) { 1075 // Promote the precision of the RHS. 1076 if (RHSComplexType) 1077 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1078 else 1079 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1080 } 1081 return ResultType; 1082 } 1083 1084 /// \brief Hande arithmetic conversion from integer to float. Helper function 1085 /// of UsualArithmeticConversions() 1086 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1087 ExprResult &IntExpr, 1088 QualType FloatTy, QualType IntTy, 1089 bool ConvertFloat, bool ConvertInt) { 1090 if (IntTy->isIntegerType()) { 1091 if (ConvertInt) 1092 // Convert intExpr to the lhs floating point type. 1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1094 CK_IntegralToFloating); 1095 return FloatTy; 1096 } 1097 1098 // Convert both sides to the appropriate complex float. 1099 assert(IntTy->isComplexIntegerType()); 1100 QualType result = S.Context.getComplexType(FloatTy); 1101 1102 // _Complex int -> _Complex float 1103 if (ConvertInt) 1104 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1105 CK_IntegralComplexToFloatingComplex); 1106 1107 // float -> _Complex float 1108 if (ConvertFloat) 1109 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1110 CK_FloatingRealToComplex); 1111 1112 return result; 1113 } 1114 1115 /// \brief Handle arithmethic conversion with floating point types. Helper 1116 /// function of UsualArithmeticConversions() 1117 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1118 ExprResult &RHS, QualType LHSType, 1119 QualType RHSType, bool IsCompAssign) { 1120 bool LHSFloat = LHSType->isRealFloatingType(); 1121 bool RHSFloat = RHSType->isRealFloatingType(); 1122 1123 // If we have two real floating types, convert the smaller operand 1124 // to the bigger result. 1125 if (LHSFloat && RHSFloat) { 1126 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1127 if (order > 0) { 1128 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1129 return LHSType; 1130 } 1131 1132 assert(order < 0 && "illegal float comparison"); 1133 if (!IsCompAssign) 1134 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1135 return RHSType; 1136 } 1137 1138 if (LHSFloat) { 1139 // Half FP has to be promoted to float unless it is natively supported 1140 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1141 LHSType = S.Context.FloatTy; 1142 1143 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1144 /*convertFloat=*/!IsCompAssign, 1145 /*convertInt=*/ true); 1146 } 1147 assert(RHSFloat); 1148 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1149 /*convertInt=*/ true, 1150 /*convertFloat=*/!IsCompAssign); 1151 } 1152 1153 /// \brief Diagnose attempts to convert between __float128 and long double if 1154 /// there is no support for such conversion. Helper function of 1155 /// UsualArithmeticConversions(). 1156 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1157 QualType RHSType) { 1158 /* No issue converting if at least one of the types is not a floating point 1159 type or the two types have the same rank. 1160 */ 1161 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1162 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1163 return false; 1164 1165 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1166 "The remaining types must be floating point types."); 1167 1168 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1169 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1170 1171 QualType LHSElemType = LHSComplex ? 1172 LHSComplex->getElementType() : LHSType; 1173 QualType RHSElemType = RHSComplex ? 1174 RHSComplex->getElementType() : RHSType; 1175 1176 // No issue if the two types have the same representation 1177 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1178 &S.Context.getFloatTypeSemantics(RHSElemType)) 1179 return false; 1180 1181 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1182 RHSElemType == S.Context.LongDoubleTy); 1183 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1184 RHSElemType == S.Context.Float128Ty); 1185 1186 /* We've handled the situation where __float128 and long double have the same 1187 representation. The only other allowable conversion is if long double is 1188 really just double. 1189 */ 1190 return Float128AndLongDouble && 1191 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1192 &llvm::APFloat::IEEEdouble); 1193 } 1194 1195 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1196 1197 namespace { 1198 /// These helper callbacks are placed in an anonymous namespace to 1199 /// permit their use as function template parameters. 1200 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1201 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1202 } 1203 1204 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1205 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1206 CK_IntegralComplexCast); 1207 } 1208 } 1209 1210 /// \brief Handle integer arithmetic conversions. Helper function of 1211 /// UsualArithmeticConversions() 1212 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1213 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1214 ExprResult &RHS, QualType LHSType, 1215 QualType RHSType, bool IsCompAssign) { 1216 // The rules for this case are in C99 6.3.1.8 1217 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1218 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1219 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1220 if (LHSSigned == RHSSigned) { 1221 // Same signedness; use the higher-ranked type 1222 if (order >= 0) { 1223 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1224 return LHSType; 1225 } else if (!IsCompAssign) 1226 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1227 return RHSType; 1228 } else if (order != (LHSSigned ? 1 : -1)) { 1229 // The unsigned type has greater than or equal rank to the 1230 // signed type, so use the unsigned type 1231 if (RHSSigned) { 1232 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1233 return LHSType; 1234 } else if (!IsCompAssign) 1235 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1236 return RHSType; 1237 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1238 // The two types are different widths; if we are here, that 1239 // means the signed type is larger than the unsigned type, so 1240 // use the signed type. 1241 if (LHSSigned) { 1242 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1243 return LHSType; 1244 } else if (!IsCompAssign) 1245 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1246 return RHSType; 1247 } else { 1248 // The signed type is higher-ranked than the unsigned type, 1249 // but isn't actually any bigger (like unsigned int and long 1250 // on most 32-bit systems). Use the unsigned type corresponding 1251 // to the signed type. 1252 QualType result = 1253 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1254 RHS = (*doRHSCast)(S, RHS.get(), result); 1255 if (!IsCompAssign) 1256 LHS = (*doLHSCast)(S, LHS.get(), result); 1257 return result; 1258 } 1259 } 1260 1261 /// \brief Handle conversions with GCC complex int extension. Helper function 1262 /// of UsualArithmeticConversions() 1263 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1264 ExprResult &RHS, QualType LHSType, 1265 QualType RHSType, 1266 bool IsCompAssign) { 1267 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1268 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1269 1270 if (LHSComplexInt && RHSComplexInt) { 1271 QualType LHSEltType = LHSComplexInt->getElementType(); 1272 QualType RHSEltType = RHSComplexInt->getElementType(); 1273 QualType ScalarType = 1274 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1275 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1276 1277 return S.Context.getComplexType(ScalarType); 1278 } 1279 1280 if (LHSComplexInt) { 1281 QualType LHSEltType = LHSComplexInt->getElementType(); 1282 QualType ScalarType = 1283 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1284 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1285 QualType ComplexType = S.Context.getComplexType(ScalarType); 1286 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1287 CK_IntegralRealToComplex); 1288 1289 return ComplexType; 1290 } 1291 1292 assert(RHSComplexInt); 1293 1294 QualType RHSEltType = RHSComplexInt->getElementType(); 1295 QualType ScalarType = 1296 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1297 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1298 QualType ComplexType = S.Context.getComplexType(ScalarType); 1299 1300 if (!IsCompAssign) 1301 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1302 CK_IntegralRealToComplex); 1303 return ComplexType; 1304 } 1305 1306 /// UsualArithmeticConversions - Performs various conversions that are common to 1307 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1308 /// routine returns the first non-arithmetic type found. The client is 1309 /// responsible for emitting appropriate error diagnostics. 1310 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1311 bool IsCompAssign) { 1312 if (!IsCompAssign) { 1313 LHS = UsualUnaryConversions(LHS.get()); 1314 if (LHS.isInvalid()) 1315 return QualType(); 1316 } 1317 1318 RHS = UsualUnaryConversions(RHS.get()); 1319 if (RHS.isInvalid()) 1320 return QualType(); 1321 1322 // For conversion purposes, we ignore any qualifiers. 1323 // For example, "const float" and "float" are equivalent. 1324 QualType LHSType = 1325 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1326 QualType RHSType = 1327 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1328 1329 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1330 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1331 LHSType = AtomicLHS->getValueType(); 1332 1333 // If both types are identical, no conversion is needed. 1334 if (LHSType == RHSType) 1335 return LHSType; 1336 1337 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1338 // The caller can deal with this (e.g. pointer + int). 1339 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1340 return QualType(); 1341 1342 // Apply unary and bitfield promotions to the LHS's type. 1343 QualType LHSUnpromotedType = LHSType; 1344 if (LHSType->isPromotableIntegerType()) 1345 LHSType = Context.getPromotedIntegerType(LHSType); 1346 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1347 if (!LHSBitfieldPromoteTy.isNull()) 1348 LHSType = LHSBitfieldPromoteTy; 1349 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1350 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1351 1352 // If both types are identical, no conversion is needed. 1353 if (LHSType == RHSType) 1354 return LHSType; 1355 1356 // At this point, we have two different arithmetic types. 1357 1358 // Diagnose attempts to convert between __float128 and long double where 1359 // such conversions currently can't be handled. 1360 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1361 return QualType(); 1362 1363 // Handle complex types first (C99 6.3.1.8p1). 1364 if (LHSType->isComplexType() || RHSType->isComplexType()) 1365 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1366 IsCompAssign); 1367 1368 // Now handle "real" floating types (i.e. float, double, long double). 1369 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1370 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1371 IsCompAssign); 1372 1373 // Handle GCC complex int extension. 1374 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1375 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1376 IsCompAssign); 1377 1378 // Finally, we have two differing integer types. 1379 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1380 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1381 } 1382 1383 1384 //===----------------------------------------------------------------------===// 1385 // Semantic Analysis for various Expression Types 1386 //===----------------------------------------------------------------------===// 1387 1388 1389 ExprResult 1390 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1391 SourceLocation DefaultLoc, 1392 SourceLocation RParenLoc, 1393 Expr *ControllingExpr, 1394 ArrayRef<ParsedType> ArgTypes, 1395 ArrayRef<Expr *> ArgExprs) { 1396 unsigned NumAssocs = ArgTypes.size(); 1397 assert(NumAssocs == ArgExprs.size()); 1398 1399 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1400 for (unsigned i = 0; i < NumAssocs; ++i) { 1401 if (ArgTypes[i]) 1402 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1403 else 1404 Types[i] = nullptr; 1405 } 1406 1407 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1408 ControllingExpr, 1409 llvm::makeArrayRef(Types, NumAssocs), 1410 ArgExprs); 1411 delete [] Types; 1412 return ER; 1413 } 1414 1415 ExprResult 1416 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1417 SourceLocation DefaultLoc, 1418 SourceLocation RParenLoc, 1419 Expr *ControllingExpr, 1420 ArrayRef<TypeSourceInfo *> Types, 1421 ArrayRef<Expr *> Exprs) { 1422 unsigned NumAssocs = Types.size(); 1423 assert(NumAssocs == Exprs.size()); 1424 1425 // Decay and strip qualifiers for the controlling expression type, and handle 1426 // placeholder type replacement. See committee discussion from WG14 DR423. 1427 { 1428 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1429 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1430 if (R.isInvalid()) 1431 return ExprError(); 1432 ControllingExpr = R.get(); 1433 } 1434 1435 // The controlling expression is an unevaluated operand, so side effects are 1436 // likely unintended. 1437 if (ActiveTemplateInstantiations.empty() && 1438 ControllingExpr->HasSideEffects(Context, false)) 1439 Diag(ControllingExpr->getExprLoc(), 1440 diag::warn_side_effects_unevaluated_context); 1441 1442 bool TypeErrorFound = false, 1443 IsResultDependent = ControllingExpr->isTypeDependent(), 1444 ContainsUnexpandedParameterPack 1445 = ControllingExpr->containsUnexpandedParameterPack(); 1446 1447 for (unsigned i = 0; i < NumAssocs; ++i) { 1448 if (Exprs[i]->containsUnexpandedParameterPack()) 1449 ContainsUnexpandedParameterPack = true; 1450 1451 if (Types[i]) { 1452 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1453 ContainsUnexpandedParameterPack = true; 1454 1455 if (Types[i]->getType()->isDependentType()) { 1456 IsResultDependent = true; 1457 } else { 1458 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1459 // complete object type other than a variably modified type." 1460 unsigned D = 0; 1461 if (Types[i]->getType()->isIncompleteType()) 1462 D = diag::err_assoc_type_incomplete; 1463 else if (!Types[i]->getType()->isObjectType()) 1464 D = diag::err_assoc_type_nonobject; 1465 else if (Types[i]->getType()->isVariablyModifiedType()) 1466 D = diag::err_assoc_type_variably_modified; 1467 1468 if (D != 0) { 1469 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1470 << Types[i]->getTypeLoc().getSourceRange() 1471 << Types[i]->getType(); 1472 TypeErrorFound = true; 1473 } 1474 1475 // C11 6.5.1.1p2 "No two generic associations in the same generic 1476 // selection shall specify compatible types." 1477 for (unsigned j = i+1; j < NumAssocs; ++j) 1478 if (Types[j] && !Types[j]->getType()->isDependentType() && 1479 Context.typesAreCompatible(Types[i]->getType(), 1480 Types[j]->getType())) { 1481 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1482 diag::err_assoc_compatible_types) 1483 << Types[j]->getTypeLoc().getSourceRange() 1484 << Types[j]->getType() 1485 << Types[i]->getType(); 1486 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1487 diag::note_compat_assoc) 1488 << Types[i]->getTypeLoc().getSourceRange() 1489 << Types[i]->getType(); 1490 TypeErrorFound = true; 1491 } 1492 } 1493 } 1494 } 1495 if (TypeErrorFound) 1496 return ExprError(); 1497 1498 // If we determined that the generic selection is result-dependent, don't 1499 // try to compute the result expression. 1500 if (IsResultDependent) 1501 return new (Context) GenericSelectionExpr( 1502 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1503 ContainsUnexpandedParameterPack); 1504 1505 SmallVector<unsigned, 1> CompatIndices; 1506 unsigned DefaultIndex = -1U; 1507 for (unsigned i = 0; i < NumAssocs; ++i) { 1508 if (!Types[i]) 1509 DefaultIndex = i; 1510 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1511 Types[i]->getType())) 1512 CompatIndices.push_back(i); 1513 } 1514 1515 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1516 // type compatible with at most one of the types named in its generic 1517 // association list." 1518 if (CompatIndices.size() > 1) { 1519 // We strip parens here because the controlling expression is typically 1520 // parenthesized in macro definitions. 1521 ControllingExpr = ControllingExpr->IgnoreParens(); 1522 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1523 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1524 << (unsigned) CompatIndices.size(); 1525 for (unsigned I : CompatIndices) { 1526 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1527 diag::note_compat_assoc) 1528 << Types[I]->getTypeLoc().getSourceRange() 1529 << Types[I]->getType(); 1530 } 1531 return ExprError(); 1532 } 1533 1534 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1535 // its controlling expression shall have type compatible with exactly one of 1536 // the types named in its generic association list." 1537 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1538 // We strip parens here because the controlling expression is typically 1539 // parenthesized in macro definitions. 1540 ControllingExpr = ControllingExpr->IgnoreParens(); 1541 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1542 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1543 return ExprError(); 1544 } 1545 1546 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1547 // type name that is compatible with the type of the controlling expression, 1548 // then the result expression of the generic selection is the expression 1549 // in that generic association. Otherwise, the result expression of the 1550 // generic selection is the expression in the default generic association." 1551 unsigned ResultIndex = 1552 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1553 1554 return new (Context) GenericSelectionExpr( 1555 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1556 ContainsUnexpandedParameterPack, ResultIndex); 1557 } 1558 1559 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1560 /// location of the token and the offset of the ud-suffix within it. 1561 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1562 unsigned Offset) { 1563 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1564 S.getLangOpts()); 1565 } 1566 1567 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1568 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1569 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1570 IdentifierInfo *UDSuffix, 1571 SourceLocation UDSuffixLoc, 1572 ArrayRef<Expr*> Args, 1573 SourceLocation LitEndLoc) { 1574 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1575 1576 QualType ArgTy[2]; 1577 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1578 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1579 if (ArgTy[ArgIdx]->isArrayType()) 1580 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1581 } 1582 1583 DeclarationName OpName = 1584 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1585 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1586 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1587 1588 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1589 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1590 /*AllowRaw*/false, /*AllowTemplate*/false, 1591 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1592 return ExprError(); 1593 1594 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1595 } 1596 1597 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1598 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1599 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1600 /// multiple tokens. However, the common case is that StringToks points to one 1601 /// string. 1602 /// 1603 ExprResult 1604 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1605 assert(!StringToks.empty() && "Must have at least one string!"); 1606 1607 StringLiteralParser Literal(StringToks, PP); 1608 if (Literal.hadError) 1609 return ExprError(); 1610 1611 SmallVector<SourceLocation, 4> StringTokLocs; 1612 for (const Token &Tok : StringToks) 1613 StringTokLocs.push_back(Tok.getLocation()); 1614 1615 QualType CharTy = Context.CharTy; 1616 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1617 if (Literal.isWide()) { 1618 CharTy = Context.getWideCharType(); 1619 Kind = StringLiteral::Wide; 1620 } else if (Literal.isUTF8()) { 1621 Kind = StringLiteral::UTF8; 1622 } else if (Literal.isUTF16()) { 1623 CharTy = Context.Char16Ty; 1624 Kind = StringLiteral::UTF16; 1625 } else if (Literal.isUTF32()) { 1626 CharTy = Context.Char32Ty; 1627 Kind = StringLiteral::UTF32; 1628 } else if (Literal.isPascal()) { 1629 CharTy = Context.UnsignedCharTy; 1630 } 1631 1632 QualType CharTyConst = CharTy; 1633 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1634 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1635 CharTyConst.addConst(); 1636 1637 // Get an array type for the string, according to C99 6.4.5. This includes 1638 // the nul terminator character as well as the string length for pascal 1639 // strings. 1640 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1641 llvm::APInt(32, Literal.GetNumStringChars()+1), 1642 ArrayType::Normal, 0); 1643 1644 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1645 if (getLangOpts().OpenCL) { 1646 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1647 } 1648 1649 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1650 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1651 Kind, Literal.Pascal, StrTy, 1652 &StringTokLocs[0], 1653 StringTokLocs.size()); 1654 if (Literal.getUDSuffix().empty()) 1655 return Lit; 1656 1657 // We're building a user-defined literal. 1658 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1659 SourceLocation UDSuffixLoc = 1660 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1661 Literal.getUDSuffixOffset()); 1662 1663 // Make sure we're allowed user-defined literals here. 1664 if (!UDLScope) 1665 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1666 1667 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1668 // operator "" X (str, len) 1669 QualType SizeType = Context.getSizeType(); 1670 1671 DeclarationName OpName = 1672 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1673 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1674 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1675 1676 QualType ArgTy[] = { 1677 Context.getArrayDecayedType(StrTy), SizeType 1678 }; 1679 1680 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1681 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1682 /*AllowRaw*/false, /*AllowTemplate*/false, 1683 /*AllowStringTemplate*/true)) { 1684 1685 case LOLR_Cooked: { 1686 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1687 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1688 StringTokLocs[0]); 1689 Expr *Args[] = { Lit, LenArg }; 1690 1691 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1692 } 1693 1694 case LOLR_StringTemplate: { 1695 TemplateArgumentListInfo ExplicitArgs; 1696 1697 unsigned CharBits = Context.getIntWidth(CharTy); 1698 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1699 llvm::APSInt Value(CharBits, CharIsUnsigned); 1700 1701 TemplateArgument TypeArg(CharTy); 1702 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1703 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1704 1705 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1706 Value = Lit->getCodeUnit(I); 1707 TemplateArgument Arg(Context, Value, CharTy); 1708 TemplateArgumentLocInfo ArgInfo; 1709 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1710 } 1711 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1712 &ExplicitArgs); 1713 } 1714 case LOLR_Raw: 1715 case LOLR_Template: 1716 llvm_unreachable("unexpected literal operator lookup result"); 1717 case LOLR_Error: 1718 return ExprError(); 1719 } 1720 llvm_unreachable("unexpected literal operator lookup result"); 1721 } 1722 1723 ExprResult 1724 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1725 SourceLocation Loc, 1726 const CXXScopeSpec *SS) { 1727 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1728 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1729 } 1730 1731 /// BuildDeclRefExpr - Build an expression that references a 1732 /// declaration that does not require a closure capture. 1733 ExprResult 1734 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1735 const DeclarationNameInfo &NameInfo, 1736 const CXXScopeSpec *SS, NamedDecl *FoundD, 1737 const TemplateArgumentListInfo *TemplateArgs) { 1738 if (getLangOpts().CUDA) 1739 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1740 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1741 if (CheckCUDATarget(Caller, Callee)) { 1742 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1743 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1744 << IdentifyCUDATarget(Caller); 1745 Diag(D->getLocation(), diag::note_previous_decl) 1746 << D->getIdentifier(); 1747 return ExprError(); 1748 } 1749 } 1750 1751 bool RefersToCapturedVariable = 1752 isa<VarDecl>(D) && 1753 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1754 1755 DeclRefExpr *E; 1756 if (isa<VarTemplateSpecializationDecl>(D)) { 1757 VarTemplateSpecializationDecl *VarSpec = 1758 cast<VarTemplateSpecializationDecl>(D); 1759 1760 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1761 : NestedNameSpecifierLoc(), 1762 VarSpec->getTemplateKeywordLoc(), D, 1763 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1764 FoundD, TemplateArgs); 1765 } else { 1766 assert(!TemplateArgs && "No template arguments for non-variable" 1767 " template specialization references"); 1768 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1769 : NestedNameSpecifierLoc(), 1770 SourceLocation(), D, RefersToCapturedVariable, 1771 NameInfo, Ty, VK, FoundD); 1772 } 1773 1774 MarkDeclRefReferenced(E); 1775 1776 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1777 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1778 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1779 recordUseOfEvaluatedWeak(E); 1780 1781 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1782 UnusedPrivateFields.remove(FD); 1783 // Just in case we're building an illegal pointer-to-member. 1784 if (FD->isBitField()) 1785 E->setObjectKind(OK_BitField); 1786 } 1787 1788 return E; 1789 } 1790 1791 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1792 /// possibly a list of template arguments. 1793 /// 1794 /// If this produces template arguments, it is permitted to call 1795 /// DecomposeTemplateName. 1796 /// 1797 /// This actually loses a lot of source location information for 1798 /// non-standard name kinds; we should consider preserving that in 1799 /// some way. 1800 void 1801 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1802 TemplateArgumentListInfo &Buffer, 1803 DeclarationNameInfo &NameInfo, 1804 const TemplateArgumentListInfo *&TemplateArgs) { 1805 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1806 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1807 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1808 1809 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1810 Id.TemplateId->NumArgs); 1811 translateTemplateArguments(TemplateArgsPtr, Buffer); 1812 1813 TemplateName TName = Id.TemplateId->Template.get(); 1814 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1815 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1816 TemplateArgs = &Buffer; 1817 } else { 1818 NameInfo = GetNameFromUnqualifiedId(Id); 1819 TemplateArgs = nullptr; 1820 } 1821 } 1822 1823 static void emitEmptyLookupTypoDiagnostic( 1824 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1825 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1826 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1827 DeclContext *Ctx = 1828 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1829 if (!TC) { 1830 // Emit a special diagnostic for failed member lookups. 1831 // FIXME: computing the declaration context might fail here (?) 1832 if (Ctx) 1833 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1834 << SS.getRange(); 1835 else 1836 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1837 return; 1838 } 1839 1840 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1841 bool DroppedSpecifier = 1842 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1843 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1844 ? diag::note_implicit_param_decl 1845 : diag::note_previous_decl; 1846 if (!Ctx) 1847 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1848 SemaRef.PDiag(NoteID)); 1849 else 1850 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1851 << Typo << Ctx << DroppedSpecifier 1852 << SS.getRange(), 1853 SemaRef.PDiag(NoteID)); 1854 } 1855 1856 /// Diagnose an empty lookup. 1857 /// 1858 /// \return false if new lookup candidates were found 1859 bool 1860 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1861 std::unique_ptr<CorrectionCandidateCallback> CCC, 1862 TemplateArgumentListInfo *ExplicitTemplateArgs, 1863 ArrayRef<Expr *> Args, TypoExpr **Out) { 1864 DeclarationName Name = R.getLookupName(); 1865 1866 unsigned diagnostic = diag::err_undeclared_var_use; 1867 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1868 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1869 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1870 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1871 diagnostic = diag::err_undeclared_use; 1872 diagnostic_suggest = diag::err_undeclared_use_suggest; 1873 } 1874 1875 // If the original lookup was an unqualified lookup, fake an 1876 // unqualified lookup. This is useful when (for example) the 1877 // original lookup would not have found something because it was a 1878 // dependent name. 1879 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1880 while (DC) { 1881 if (isa<CXXRecordDecl>(DC)) { 1882 LookupQualifiedName(R, DC); 1883 1884 if (!R.empty()) { 1885 // Don't give errors about ambiguities in this lookup. 1886 R.suppressDiagnostics(); 1887 1888 // During a default argument instantiation the CurContext points 1889 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1890 // function parameter list, hence add an explicit check. 1891 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1892 ActiveTemplateInstantiations.back().Kind == 1893 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1894 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1895 bool isInstance = CurMethod && 1896 CurMethod->isInstance() && 1897 DC == CurMethod->getParent() && !isDefaultArgument; 1898 1899 // Give a code modification hint to insert 'this->'. 1900 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1901 // Actually quite difficult! 1902 if (getLangOpts().MSVCCompat) 1903 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1904 if (isInstance) { 1905 Diag(R.getNameLoc(), diagnostic) << Name 1906 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1907 CheckCXXThisCapture(R.getNameLoc()); 1908 } else { 1909 Diag(R.getNameLoc(), diagnostic) << Name; 1910 } 1911 1912 // Do we really want to note all of these? 1913 for (NamedDecl *D : R) 1914 Diag(D->getLocation(), diag::note_dependent_var_use); 1915 1916 // Return true if we are inside a default argument instantiation 1917 // and the found name refers to an instance member function, otherwise 1918 // the function calling DiagnoseEmptyLookup will try to create an 1919 // implicit member call and this is wrong for default argument. 1920 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1921 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1922 return true; 1923 } 1924 1925 // Tell the callee to try to recover. 1926 return false; 1927 } 1928 1929 R.clear(); 1930 } 1931 1932 // In Microsoft mode, if we are performing lookup from within a friend 1933 // function definition declared at class scope then we must set 1934 // DC to the lexical parent to be able to search into the parent 1935 // class. 1936 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1937 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1938 DC->getLexicalParent()->isRecord()) 1939 DC = DC->getLexicalParent(); 1940 else 1941 DC = DC->getParent(); 1942 } 1943 1944 // We didn't find anything, so try to correct for a typo. 1945 TypoCorrection Corrected; 1946 if (S && Out) { 1947 SourceLocation TypoLoc = R.getNameLoc(); 1948 assert(!ExplicitTemplateArgs && 1949 "Diagnosing an empty lookup with explicit template args!"); 1950 *Out = CorrectTypoDelayed( 1951 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1952 [=](const TypoCorrection &TC) { 1953 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1954 diagnostic, diagnostic_suggest); 1955 }, 1956 nullptr, CTK_ErrorRecovery); 1957 if (*Out) 1958 return true; 1959 } else if (S && (Corrected = 1960 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1961 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1962 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1963 bool DroppedSpecifier = 1964 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1965 R.setLookupName(Corrected.getCorrection()); 1966 1967 bool AcceptableWithRecovery = false; 1968 bool AcceptableWithoutRecovery = false; 1969 NamedDecl *ND = Corrected.getFoundDecl(); 1970 if (ND) { 1971 if (Corrected.isOverloaded()) { 1972 OverloadCandidateSet OCS(R.getNameLoc(), 1973 OverloadCandidateSet::CSK_Normal); 1974 OverloadCandidateSet::iterator Best; 1975 for (NamedDecl *CD : Corrected) { 1976 if (FunctionTemplateDecl *FTD = 1977 dyn_cast<FunctionTemplateDecl>(CD)) 1978 AddTemplateOverloadCandidate( 1979 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1980 Args, OCS); 1981 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1982 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1983 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1984 Args, OCS); 1985 } 1986 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1987 case OR_Success: 1988 ND = Best->FoundDecl; 1989 Corrected.setCorrectionDecl(ND); 1990 break; 1991 default: 1992 // FIXME: Arbitrarily pick the first declaration for the note. 1993 Corrected.setCorrectionDecl(ND); 1994 break; 1995 } 1996 } 1997 R.addDecl(ND); 1998 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1999 CXXRecordDecl *Record = nullptr; 2000 if (Corrected.getCorrectionSpecifier()) { 2001 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2002 Record = Ty->getAsCXXRecordDecl(); 2003 } 2004 if (!Record) 2005 Record = cast<CXXRecordDecl>( 2006 ND->getDeclContext()->getRedeclContext()); 2007 R.setNamingClass(Record); 2008 } 2009 2010 auto *UnderlyingND = ND->getUnderlyingDecl(); 2011 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2012 isa<FunctionTemplateDecl>(UnderlyingND); 2013 // FIXME: If we ended up with a typo for a type name or 2014 // Objective-C class name, we're in trouble because the parser 2015 // is in the wrong place to recover. Suggest the typo 2016 // correction, but don't make it a fix-it since we're not going 2017 // to recover well anyway. 2018 AcceptableWithoutRecovery = 2019 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2020 } else { 2021 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2022 // because we aren't able to recover. 2023 AcceptableWithoutRecovery = true; 2024 } 2025 2026 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2027 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2028 ? diag::note_implicit_param_decl 2029 : diag::note_previous_decl; 2030 if (SS.isEmpty()) 2031 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2032 PDiag(NoteID), AcceptableWithRecovery); 2033 else 2034 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2035 << Name << computeDeclContext(SS, false) 2036 << DroppedSpecifier << SS.getRange(), 2037 PDiag(NoteID), AcceptableWithRecovery); 2038 2039 // Tell the callee whether to try to recover. 2040 return !AcceptableWithRecovery; 2041 } 2042 } 2043 R.clear(); 2044 2045 // Emit a special diagnostic for failed member lookups. 2046 // FIXME: computing the declaration context might fail here (?) 2047 if (!SS.isEmpty()) { 2048 Diag(R.getNameLoc(), diag::err_no_member) 2049 << Name << computeDeclContext(SS, false) 2050 << SS.getRange(); 2051 return true; 2052 } 2053 2054 // Give up, we can't recover. 2055 Diag(R.getNameLoc(), diagnostic) << Name; 2056 return true; 2057 } 2058 2059 /// In Microsoft mode, if we are inside a template class whose parent class has 2060 /// dependent base classes, and we can't resolve an unqualified identifier, then 2061 /// assume the identifier is a member of a dependent base class. We can only 2062 /// recover successfully in static methods, instance methods, and other contexts 2063 /// where 'this' is available. This doesn't precisely match MSVC's 2064 /// instantiation model, but it's close enough. 2065 static Expr * 2066 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2067 DeclarationNameInfo &NameInfo, 2068 SourceLocation TemplateKWLoc, 2069 const TemplateArgumentListInfo *TemplateArgs) { 2070 // Only try to recover from lookup into dependent bases in static methods or 2071 // contexts where 'this' is available. 2072 QualType ThisType = S.getCurrentThisType(); 2073 const CXXRecordDecl *RD = nullptr; 2074 if (!ThisType.isNull()) 2075 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2076 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2077 RD = MD->getParent(); 2078 if (!RD || !RD->hasAnyDependentBases()) 2079 return nullptr; 2080 2081 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2082 // is available, suggest inserting 'this->' as a fixit. 2083 SourceLocation Loc = NameInfo.getLoc(); 2084 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2085 DB << NameInfo.getName() << RD; 2086 2087 if (!ThisType.isNull()) { 2088 DB << FixItHint::CreateInsertion(Loc, "this->"); 2089 return CXXDependentScopeMemberExpr::Create( 2090 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2091 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2092 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2093 } 2094 2095 // Synthesize a fake NNS that points to the derived class. This will 2096 // perform name lookup during template instantiation. 2097 CXXScopeSpec SS; 2098 auto *NNS = 2099 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2100 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2101 return DependentScopeDeclRefExpr::Create( 2102 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2103 TemplateArgs); 2104 } 2105 2106 ExprResult 2107 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2108 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2109 bool HasTrailingLParen, bool IsAddressOfOperand, 2110 std::unique_ptr<CorrectionCandidateCallback> CCC, 2111 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2112 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2113 "cannot be direct & operand and have a trailing lparen"); 2114 if (SS.isInvalid()) 2115 return ExprError(); 2116 2117 TemplateArgumentListInfo TemplateArgsBuffer; 2118 2119 // Decompose the UnqualifiedId into the following data. 2120 DeclarationNameInfo NameInfo; 2121 const TemplateArgumentListInfo *TemplateArgs; 2122 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2123 2124 DeclarationName Name = NameInfo.getName(); 2125 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2126 SourceLocation NameLoc = NameInfo.getLoc(); 2127 2128 // C++ [temp.dep.expr]p3: 2129 // An id-expression is type-dependent if it contains: 2130 // -- an identifier that was declared with a dependent type, 2131 // (note: handled after lookup) 2132 // -- a template-id that is dependent, 2133 // (note: handled in BuildTemplateIdExpr) 2134 // -- a conversion-function-id that specifies a dependent type, 2135 // -- a nested-name-specifier that contains a class-name that 2136 // names a dependent type. 2137 // Determine whether this is a member of an unknown specialization; 2138 // we need to handle these differently. 2139 bool DependentID = false; 2140 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2141 Name.getCXXNameType()->isDependentType()) { 2142 DependentID = true; 2143 } else if (SS.isSet()) { 2144 if (DeclContext *DC = computeDeclContext(SS, false)) { 2145 if (RequireCompleteDeclContext(SS, DC)) 2146 return ExprError(); 2147 } else { 2148 DependentID = true; 2149 } 2150 } 2151 2152 if (DependentID) 2153 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2154 IsAddressOfOperand, TemplateArgs); 2155 2156 // Perform the required lookup. 2157 LookupResult R(*this, NameInfo, 2158 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2159 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2160 if (TemplateArgs) { 2161 // Lookup the template name again to correctly establish the context in 2162 // which it was found. This is really unfortunate as we already did the 2163 // lookup to determine that it was a template name in the first place. If 2164 // this becomes a performance hit, we can work harder to preserve those 2165 // results until we get here but it's likely not worth it. 2166 bool MemberOfUnknownSpecialization; 2167 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2168 MemberOfUnknownSpecialization); 2169 2170 if (MemberOfUnknownSpecialization || 2171 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2172 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2173 IsAddressOfOperand, TemplateArgs); 2174 } else { 2175 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2176 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2177 2178 // If the result might be in a dependent base class, this is a dependent 2179 // id-expression. 2180 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2181 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2182 IsAddressOfOperand, TemplateArgs); 2183 2184 // If this reference is in an Objective-C method, then we need to do 2185 // some special Objective-C lookup, too. 2186 if (IvarLookupFollowUp) { 2187 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2188 if (E.isInvalid()) 2189 return ExprError(); 2190 2191 if (Expr *Ex = E.getAs<Expr>()) 2192 return Ex; 2193 } 2194 } 2195 2196 if (R.isAmbiguous()) 2197 return ExprError(); 2198 2199 // This could be an implicitly declared function reference (legal in C90, 2200 // extension in C99, forbidden in C++). 2201 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2202 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2203 if (D) R.addDecl(D); 2204 } 2205 2206 // Determine whether this name might be a candidate for 2207 // argument-dependent lookup. 2208 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2209 2210 if (R.empty() && !ADL) { 2211 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2212 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2213 TemplateKWLoc, TemplateArgs)) 2214 return E; 2215 } 2216 2217 // Don't diagnose an empty lookup for inline assembly. 2218 if (IsInlineAsmIdentifier) 2219 return ExprError(); 2220 2221 // If this name wasn't predeclared and if this is not a function 2222 // call, diagnose the problem. 2223 TypoExpr *TE = nullptr; 2224 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2225 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2226 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2227 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2228 "Typo correction callback misconfigured"); 2229 if (CCC) { 2230 // Make sure the callback knows what the typo being diagnosed is. 2231 CCC->setTypoName(II); 2232 if (SS.isValid()) 2233 CCC->setTypoNNS(SS.getScopeRep()); 2234 } 2235 if (DiagnoseEmptyLookup(S, SS, R, 2236 CCC ? std::move(CCC) : std::move(DefaultValidator), 2237 nullptr, None, &TE)) { 2238 if (TE && KeywordReplacement) { 2239 auto &State = getTypoExprState(TE); 2240 auto BestTC = State.Consumer->getNextCorrection(); 2241 if (BestTC.isKeyword()) { 2242 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2243 if (State.DiagHandler) 2244 State.DiagHandler(BestTC); 2245 KeywordReplacement->startToken(); 2246 KeywordReplacement->setKind(II->getTokenID()); 2247 KeywordReplacement->setIdentifierInfo(II); 2248 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2249 // Clean up the state associated with the TypoExpr, since it has 2250 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2251 clearDelayedTypo(TE); 2252 // Signal that a correction to a keyword was performed by returning a 2253 // valid-but-null ExprResult. 2254 return (Expr*)nullptr; 2255 } 2256 State.Consumer->resetCorrectionStream(); 2257 } 2258 return TE ? TE : ExprError(); 2259 } 2260 2261 assert(!R.empty() && 2262 "DiagnoseEmptyLookup returned false but added no results"); 2263 2264 // If we found an Objective-C instance variable, let 2265 // LookupInObjCMethod build the appropriate expression to 2266 // reference the ivar. 2267 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2268 R.clear(); 2269 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2270 // In a hopelessly buggy code, Objective-C instance variable 2271 // lookup fails and no expression will be built to reference it. 2272 if (!E.isInvalid() && !E.get()) 2273 return ExprError(); 2274 return E; 2275 } 2276 } 2277 2278 // This is guaranteed from this point on. 2279 assert(!R.empty() || ADL); 2280 2281 // Check whether this might be a C++ implicit instance member access. 2282 // C++ [class.mfct.non-static]p3: 2283 // When an id-expression that is not part of a class member access 2284 // syntax and not used to form a pointer to member is used in the 2285 // body of a non-static member function of class X, if name lookup 2286 // resolves the name in the id-expression to a non-static non-type 2287 // member of some class C, the id-expression is transformed into a 2288 // class member access expression using (*this) as the 2289 // postfix-expression to the left of the . operator. 2290 // 2291 // But we don't actually need to do this for '&' operands if R 2292 // resolved to a function or overloaded function set, because the 2293 // expression is ill-formed if it actually works out to be a 2294 // non-static member function: 2295 // 2296 // C++ [expr.ref]p4: 2297 // Otherwise, if E1.E2 refers to a non-static member function. . . 2298 // [t]he expression can be used only as the left-hand operand of a 2299 // member function call. 2300 // 2301 // There are other safeguards against such uses, but it's important 2302 // to get this right here so that we don't end up making a 2303 // spuriously dependent expression if we're inside a dependent 2304 // instance method. 2305 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2306 bool MightBeImplicitMember; 2307 if (!IsAddressOfOperand) 2308 MightBeImplicitMember = true; 2309 else if (!SS.isEmpty()) 2310 MightBeImplicitMember = false; 2311 else if (R.isOverloadedResult()) 2312 MightBeImplicitMember = false; 2313 else if (R.isUnresolvableResult()) 2314 MightBeImplicitMember = true; 2315 else 2316 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2317 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2318 isa<MSPropertyDecl>(R.getFoundDecl()); 2319 2320 if (MightBeImplicitMember) 2321 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2322 R, TemplateArgs, S); 2323 } 2324 2325 if (TemplateArgs || TemplateKWLoc.isValid()) { 2326 2327 // In C++1y, if this is a variable template id, then check it 2328 // in BuildTemplateIdExpr(). 2329 // The single lookup result must be a variable template declaration. 2330 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2331 Id.TemplateId->Kind == TNK_Var_template) { 2332 assert(R.getAsSingle<VarTemplateDecl>() && 2333 "There should only be one declaration found."); 2334 } 2335 2336 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2337 } 2338 2339 return BuildDeclarationNameExpr(SS, R, ADL); 2340 } 2341 2342 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2343 /// declaration name, generally during template instantiation. 2344 /// There's a large number of things which don't need to be done along 2345 /// this path. 2346 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2347 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2348 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2349 DeclContext *DC = computeDeclContext(SS, false); 2350 if (!DC) 2351 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2352 NameInfo, /*TemplateArgs=*/nullptr); 2353 2354 if (RequireCompleteDeclContext(SS, DC)) 2355 return ExprError(); 2356 2357 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2358 LookupQualifiedName(R, DC); 2359 2360 if (R.isAmbiguous()) 2361 return ExprError(); 2362 2363 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2364 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2365 NameInfo, /*TemplateArgs=*/nullptr); 2366 2367 if (R.empty()) { 2368 Diag(NameInfo.getLoc(), diag::err_no_member) 2369 << NameInfo.getName() << DC << SS.getRange(); 2370 return ExprError(); 2371 } 2372 2373 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2374 // Diagnose a missing typename if this resolved unambiguously to a type in 2375 // a dependent context. If we can recover with a type, downgrade this to 2376 // a warning in Microsoft compatibility mode. 2377 unsigned DiagID = diag::err_typename_missing; 2378 if (RecoveryTSI && getLangOpts().MSVCCompat) 2379 DiagID = diag::ext_typename_missing; 2380 SourceLocation Loc = SS.getBeginLoc(); 2381 auto D = Diag(Loc, DiagID); 2382 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2383 << SourceRange(Loc, NameInfo.getEndLoc()); 2384 2385 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2386 // context. 2387 if (!RecoveryTSI) 2388 return ExprError(); 2389 2390 // Only issue the fixit if we're prepared to recover. 2391 D << FixItHint::CreateInsertion(Loc, "typename "); 2392 2393 // Recover by pretending this was an elaborated type. 2394 QualType Ty = Context.getTypeDeclType(TD); 2395 TypeLocBuilder TLB; 2396 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2397 2398 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2399 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2400 QTL.setElaboratedKeywordLoc(SourceLocation()); 2401 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2402 2403 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2404 2405 return ExprEmpty(); 2406 } 2407 2408 // Defend against this resolving to an implicit member access. We usually 2409 // won't get here if this might be a legitimate a class member (we end up in 2410 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2411 // a pointer-to-member or in an unevaluated context in C++11. 2412 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2413 return BuildPossibleImplicitMemberExpr(SS, 2414 /*TemplateKWLoc=*/SourceLocation(), 2415 R, /*TemplateArgs=*/nullptr, S); 2416 2417 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2418 } 2419 2420 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2421 /// detected that we're currently inside an ObjC method. Perform some 2422 /// additional lookup. 2423 /// 2424 /// Ideally, most of this would be done by lookup, but there's 2425 /// actually quite a lot of extra work involved. 2426 /// 2427 /// Returns a null sentinel to indicate trivial success. 2428 ExprResult 2429 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2430 IdentifierInfo *II, bool AllowBuiltinCreation) { 2431 SourceLocation Loc = Lookup.getNameLoc(); 2432 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2433 2434 // Check for error condition which is already reported. 2435 if (!CurMethod) 2436 return ExprError(); 2437 2438 // There are two cases to handle here. 1) scoped lookup could have failed, 2439 // in which case we should look for an ivar. 2) scoped lookup could have 2440 // found a decl, but that decl is outside the current instance method (i.e. 2441 // a global variable). In these two cases, we do a lookup for an ivar with 2442 // this name, if the lookup sucedes, we replace it our current decl. 2443 2444 // If we're in a class method, we don't normally want to look for 2445 // ivars. But if we don't find anything else, and there's an 2446 // ivar, that's an error. 2447 bool IsClassMethod = CurMethod->isClassMethod(); 2448 2449 bool LookForIvars; 2450 if (Lookup.empty()) 2451 LookForIvars = true; 2452 else if (IsClassMethod) 2453 LookForIvars = false; 2454 else 2455 LookForIvars = (Lookup.isSingleResult() && 2456 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2457 ObjCInterfaceDecl *IFace = nullptr; 2458 if (LookForIvars) { 2459 IFace = CurMethod->getClassInterface(); 2460 ObjCInterfaceDecl *ClassDeclared; 2461 ObjCIvarDecl *IV = nullptr; 2462 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2463 // Diagnose using an ivar in a class method. 2464 if (IsClassMethod) 2465 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2466 << IV->getDeclName()); 2467 2468 // If we're referencing an invalid decl, just return this as a silent 2469 // error node. The error diagnostic was already emitted on the decl. 2470 if (IV->isInvalidDecl()) 2471 return ExprError(); 2472 2473 // Check if referencing a field with __attribute__((deprecated)). 2474 if (DiagnoseUseOfDecl(IV, Loc)) 2475 return ExprError(); 2476 2477 // Diagnose the use of an ivar outside of the declaring class. 2478 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2479 !declaresSameEntity(ClassDeclared, IFace) && 2480 !getLangOpts().DebuggerSupport) 2481 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2482 2483 // FIXME: This should use a new expr for a direct reference, don't 2484 // turn this into Self->ivar, just return a BareIVarExpr or something. 2485 IdentifierInfo &II = Context.Idents.get("self"); 2486 UnqualifiedId SelfName; 2487 SelfName.setIdentifier(&II, SourceLocation()); 2488 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2489 CXXScopeSpec SelfScopeSpec; 2490 SourceLocation TemplateKWLoc; 2491 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2492 SelfName, false, false); 2493 if (SelfExpr.isInvalid()) 2494 return ExprError(); 2495 2496 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2497 if (SelfExpr.isInvalid()) 2498 return ExprError(); 2499 2500 MarkAnyDeclReferenced(Loc, IV, true); 2501 2502 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2503 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2504 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2505 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2506 2507 ObjCIvarRefExpr *Result = new (Context) 2508 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2509 IV->getLocation(), SelfExpr.get(), true, true); 2510 2511 if (getLangOpts().ObjCAutoRefCount) { 2512 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2513 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2514 recordUseOfEvaluatedWeak(Result); 2515 } 2516 if (CurContext->isClosure()) 2517 Diag(Loc, diag::warn_implicitly_retains_self) 2518 << FixItHint::CreateInsertion(Loc, "self->"); 2519 } 2520 2521 return Result; 2522 } 2523 } else if (CurMethod->isInstanceMethod()) { 2524 // We should warn if a local variable hides an ivar. 2525 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2526 ObjCInterfaceDecl *ClassDeclared; 2527 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2528 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2529 declaresSameEntity(IFace, ClassDeclared)) 2530 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2531 } 2532 } 2533 } else if (Lookup.isSingleResult() && 2534 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2535 // If accessing a stand-alone ivar in a class method, this is an error. 2536 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2537 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2538 << IV->getDeclName()); 2539 } 2540 2541 if (Lookup.empty() && II && AllowBuiltinCreation) { 2542 // FIXME. Consolidate this with similar code in LookupName. 2543 if (unsigned BuiltinID = II->getBuiltinID()) { 2544 if (!(getLangOpts().CPlusPlus && 2545 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2546 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2547 S, Lookup.isForRedeclaration(), 2548 Lookup.getNameLoc()); 2549 if (D) Lookup.addDecl(D); 2550 } 2551 } 2552 } 2553 // Sentinel value saying that we didn't do anything special. 2554 return ExprResult((Expr *)nullptr); 2555 } 2556 2557 /// \brief Cast a base object to a member's actual type. 2558 /// 2559 /// Logically this happens in three phases: 2560 /// 2561 /// * First we cast from the base type to the naming class. 2562 /// The naming class is the class into which we were looking 2563 /// when we found the member; it's the qualifier type if a 2564 /// qualifier was provided, and otherwise it's the base type. 2565 /// 2566 /// * Next we cast from the naming class to the declaring class. 2567 /// If the member we found was brought into a class's scope by 2568 /// a using declaration, this is that class; otherwise it's 2569 /// the class declaring the member. 2570 /// 2571 /// * Finally we cast from the declaring class to the "true" 2572 /// declaring class of the member. This conversion does not 2573 /// obey access control. 2574 ExprResult 2575 Sema::PerformObjectMemberConversion(Expr *From, 2576 NestedNameSpecifier *Qualifier, 2577 NamedDecl *FoundDecl, 2578 NamedDecl *Member) { 2579 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2580 if (!RD) 2581 return From; 2582 2583 QualType DestRecordType; 2584 QualType DestType; 2585 QualType FromRecordType; 2586 QualType FromType = From->getType(); 2587 bool PointerConversions = false; 2588 if (isa<FieldDecl>(Member)) { 2589 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2590 2591 if (FromType->getAs<PointerType>()) { 2592 DestType = Context.getPointerType(DestRecordType); 2593 FromRecordType = FromType->getPointeeType(); 2594 PointerConversions = true; 2595 } else { 2596 DestType = DestRecordType; 2597 FromRecordType = FromType; 2598 } 2599 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2600 if (Method->isStatic()) 2601 return From; 2602 2603 DestType = Method->getThisType(Context); 2604 DestRecordType = DestType->getPointeeType(); 2605 2606 if (FromType->getAs<PointerType>()) { 2607 FromRecordType = FromType->getPointeeType(); 2608 PointerConversions = true; 2609 } else { 2610 FromRecordType = FromType; 2611 DestType = DestRecordType; 2612 } 2613 } else { 2614 // No conversion necessary. 2615 return From; 2616 } 2617 2618 if (DestType->isDependentType() || FromType->isDependentType()) 2619 return From; 2620 2621 // If the unqualified types are the same, no conversion is necessary. 2622 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2623 return From; 2624 2625 SourceRange FromRange = From->getSourceRange(); 2626 SourceLocation FromLoc = FromRange.getBegin(); 2627 2628 ExprValueKind VK = From->getValueKind(); 2629 2630 // C++ [class.member.lookup]p8: 2631 // [...] Ambiguities can often be resolved by qualifying a name with its 2632 // class name. 2633 // 2634 // If the member was a qualified name and the qualified referred to a 2635 // specific base subobject type, we'll cast to that intermediate type 2636 // first and then to the object in which the member is declared. That allows 2637 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2638 // 2639 // class Base { public: int x; }; 2640 // class Derived1 : public Base { }; 2641 // class Derived2 : public Base { }; 2642 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2643 // 2644 // void VeryDerived::f() { 2645 // x = 17; // error: ambiguous base subobjects 2646 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2647 // } 2648 if (Qualifier && Qualifier->getAsType()) { 2649 QualType QType = QualType(Qualifier->getAsType(), 0); 2650 assert(QType->isRecordType() && "lookup done with non-record type"); 2651 2652 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2653 2654 // In C++98, the qualifier type doesn't actually have to be a base 2655 // type of the object type, in which case we just ignore it. 2656 // Otherwise build the appropriate casts. 2657 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2658 CXXCastPath BasePath; 2659 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2660 FromLoc, FromRange, &BasePath)) 2661 return ExprError(); 2662 2663 if (PointerConversions) 2664 QType = Context.getPointerType(QType); 2665 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2666 VK, &BasePath).get(); 2667 2668 FromType = QType; 2669 FromRecordType = QRecordType; 2670 2671 // If the qualifier type was the same as the destination type, 2672 // we're done. 2673 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2674 return From; 2675 } 2676 } 2677 2678 bool IgnoreAccess = false; 2679 2680 // If we actually found the member through a using declaration, cast 2681 // down to the using declaration's type. 2682 // 2683 // Pointer equality is fine here because only one declaration of a 2684 // class ever has member declarations. 2685 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2686 assert(isa<UsingShadowDecl>(FoundDecl)); 2687 QualType URecordType = Context.getTypeDeclType( 2688 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2689 2690 // We only need to do this if the naming-class to declaring-class 2691 // conversion is non-trivial. 2692 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2693 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2694 CXXCastPath BasePath; 2695 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2696 FromLoc, FromRange, &BasePath)) 2697 return ExprError(); 2698 2699 QualType UType = URecordType; 2700 if (PointerConversions) 2701 UType = Context.getPointerType(UType); 2702 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2703 VK, &BasePath).get(); 2704 FromType = UType; 2705 FromRecordType = URecordType; 2706 } 2707 2708 // We don't do access control for the conversion from the 2709 // declaring class to the true declaring class. 2710 IgnoreAccess = true; 2711 } 2712 2713 CXXCastPath BasePath; 2714 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2715 FromLoc, FromRange, &BasePath, 2716 IgnoreAccess)) 2717 return ExprError(); 2718 2719 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2720 VK, &BasePath); 2721 } 2722 2723 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2724 const LookupResult &R, 2725 bool HasTrailingLParen) { 2726 // Only when used directly as the postfix-expression of a call. 2727 if (!HasTrailingLParen) 2728 return false; 2729 2730 // Never if a scope specifier was provided. 2731 if (SS.isSet()) 2732 return false; 2733 2734 // Only in C++ or ObjC++. 2735 if (!getLangOpts().CPlusPlus) 2736 return false; 2737 2738 // Turn off ADL when we find certain kinds of declarations during 2739 // normal lookup: 2740 for (NamedDecl *D : R) { 2741 // C++0x [basic.lookup.argdep]p3: 2742 // -- a declaration of a class member 2743 // Since using decls preserve this property, we check this on the 2744 // original decl. 2745 if (D->isCXXClassMember()) 2746 return false; 2747 2748 // C++0x [basic.lookup.argdep]p3: 2749 // -- a block-scope function declaration that is not a 2750 // using-declaration 2751 // NOTE: we also trigger this for function templates (in fact, we 2752 // don't check the decl type at all, since all other decl types 2753 // turn off ADL anyway). 2754 if (isa<UsingShadowDecl>(D)) 2755 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2756 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2757 return false; 2758 2759 // C++0x [basic.lookup.argdep]p3: 2760 // -- a declaration that is neither a function or a function 2761 // template 2762 // And also for builtin functions. 2763 if (isa<FunctionDecl>(D)) { 2764 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2765 2766 // But also builtin functions. 2767 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2768 return false; 2769 } else if (!isa<FunctionTemplateDecl>(D)) 2770 return false; 2771 } 2772 2773 return true; 2774 } 2775 2776 2777 /// Diagnoses obvious problems with the use of the given declaration 2778 /// as an expression. This is only actually called for lookups that 2779 /// were not overloaded, and it doesn't promise that the declaration 2780 /// will in fact be used. 2781 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2782 if (isa<TypedefNameDecl>(D)) { 2783 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2784 return true; 2785 } 2786 2787 if (isa<ObjCInterfaceDecl>(D)) { 2788 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2789 return true; 2790 } 2791 2792 if (isa<NamespaceDecl>(D)) { 2793 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2794 return true; 2795 } 2796 2797 return false; 2798 } 2799 2800 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2801 LookupResult &R, bool NeedsADL, 2802 bool AcceptInvalidDecl) { 2803 // If this is a single, fully-resolved result and we don't need ADL, 2804 // just build an ordinary singleton decl ref. 2805 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2806 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2807 R.getRepresentativeDecl(), nullptr, 2808 AcceptInvalidDecl); 2809 2810 // We only need to check the declaration if there's exactly one 2811 // result, because in the overloaded case the results can only be 2812 // functions and function templates. 2813 if (R.isSingleResult() && 2814 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2815 return ExprError(); 2816 2817 // Otherwise, just build an unresolved lookup expression. Suppress 2818 // any lookup-related diagnostics; we'll hash these out later, when 2819 // we've picked a target. 2820 R.suppressDiagnostics(); 2821 2822 UnresolvedLookupExpr *ULE 2823 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2824 SS.getWithLocInContext(Context), 2825 R.getLookupNameInfo(), 2826 NeedsADL, R.isOverloadedResult(), 2827 R.begin(), R.end()); 2828 2829 return ULE; 2830 } 2831 2832 /// \brief Complete semantic analysis for a reference to the given declaration. 2833 ExprResult Sema::BuildDeclarationNameExpr( 2834 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2835 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2836 bool AcceptInvalidDecl) { 2837 assert(D && "Cannot refer to a NULL declaration"); 2838 assert(!isa<FunctionTemplateDecl>(D) && 2839 "Cannot refer unambiguously to a function template"); 2840 2841 SourceLocation Loc = NameInfo.getLoc(); 2842 if (CheckDeclInExpr(*this, Loc, D)) 2843 return ExprError(); 2844 2845 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2846 // Specifically diagnose references to class templates that are missing 2847 // a template argument list. 2848 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2849 << Template << SS.getRange(); 2850 Diag(Template->getLocation(), diag::note_template_decl_here); 2851 return ExprError(); 2852 } 2853 2854 // Make sure that we're referring to a value. 2855 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2856 if (!VD) { 2857 Diag(Loc, diag::err_ref_non_value) 2858 << D << SS.getRange(); 2859 Diag(D->getLocation(), diag::note_declared_at); 2860 return ExprError(); 2861 } 2862 2863 // Check whether this declaration can be used. Note that we suppress 2864 // this check when we're going to perform argument-dependent lookup 2865 // on this function name, because this might not be the function 2866 // that overload resolution actually selects. 2867 if (DiagnoseUseOfDecl(VD, Loc)) 2868 return ExprError(); 2869 2870 // Only create DeclRefExpr's for valid Decl's. 2871 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2872 return ExprError(); 2873 2874 // Handle members of anonymous structs and unions. If we got here, 2875 // and the reference is to a class member indirect field, then this 2876 // must be the subject of a pointer-to-member expression. 2877 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2878 if (!indirectField->isCXXClassMember()) 2879 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2880 indirectField); 2881 2882 { 2883 QualType type = VD->getType(); 2884 ExprValueKind valueKind = VK_RValue; 2885 2886 switch (D->getKind()) { 2887 // Ignore all the non-ValueDecl kinds. 2888 #define ABSTRACT_DECL(kind) 2889 #define VALUE(type, base) 2890 #define DECL(type, base) \ 2891 case Decl::type: 2892 #include "clang/AST/DeclNodes.inc" 2893 llvm_unreachable("invalid value decl kind"); 2894 2895 // These shouldn't make it here. 2896 case Decl::ObjCAtDefsField: 2897 case Decl::ObjCIvar: 2898 llvm_unreachable("forming non-member reference to ivar?"); 2899 2900 // Enum constants are always r-values and never references. 2901 // Unresolved using declarations are dependent. 2902 case Decl::EnumConstant: 2903 case Decl::UnresolvedUsingValue: 2904 case Decl::OMPDeclareReduction: 2905 valueKind = VK_RValue; 2906 break; 2907 2908 // Fields and indirect fields that got here must be for 2909 // pointer-to-member expressions; we just call them l-values for 2910 // internal consistency, because this subexpression doesn't really 2911 // exist in the high-level semantics. 2912 case Decl::Field: 2913 case Decl::IndirectField: 2914 assert(getLangOpts().CPlusPlus && 2915 "building reference to field in C?"); 2916 2917 // These can't have reference type in well-formed programs, but 2918 // for internal consistency we do this anyway. 2919 type = type.getNonReferenceType(); 2920 valueKind = VK_LValue; 2921 break; 2922 2923 // Non-type template parameters are either l-values or r-values 2924 // depending on the type. 2925 case Decl::NonTypeTemplateParm: { 2926 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2927 type = reftype->getPointeeType(); 2928 valueKind = VK_LValue; // even if the parameter is an r-value reference 2929 break; 2930 } 2931 2932 // For non-references, we need to strip qualifiers just in case 2933 // the template parameter was declared as 'const int' or whatever. 2934 valueKind = VK_RValue; 2935 type = type.getUnqualifiedType(); 2936 break; 2937 } 2938 2939 case Decl::Var: 2940 case Decl::VarTemplateSpecialization: 2941 case Decl::VarTemplatePartialSpecialization: 2942 case Decl::OMPCapturedExpr: 2943 // In C, "extern void blah;" is valid and is an r-value. 2944 if (!getLangOpts().CPlusPlus && 2945 !type.hasQualifiers() && 2946 type->isVoidType()) { 2947 valueKind = VK_RValue; 2948 break; 2949 } 2950 // fallthrough 2951 2952 case Decl::ImplicitParam: 2953 case Decl::ParmVar: { 2954 // These are always l-values. 2955 valueKind = VK_LValue; 2956 type = type.getNonReferenceType(); 2957 2958 // FIXME: Does the addition of const really only apply in 2959 // potentially-evaluated contexts? Since the variable isn't actually 2960 // captured in an unevaluated context, it seems that the answer is no. 2961 if (!isUnevaluatedContext()) { 2962 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2963 if (!CapturedType.isNull()) 2964 type = CapturedType; 2965 } 2966 2967 break; 2968 } 2969 2970 case Decl::Function: { 2971 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2972 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2973 type = Context.BuiltinFnTy; 2974 valueKind = VK_RValue; 2975 break; 2976 } 2977 } 2978 2979 const FunctionType *fty = type->castAs<FunctionType>(); 2980 2981 // If we're referring to a function with an __unknown_anytype 2982 // result type, make the entire expression __unknown_anytype. 2983 if (fty->getReturnType() == Context.UnknownAnyTy) { 2984 type = Context.UnknownAnyTy; 2985 valueKind = VK_RValue; 2986 break; 2987 } 2988 2989 // Functions are l-values in C++. 2990 if (getLangOpts().CPlusPlus) { 2991 valueKind = VK_LValue; 2992 break; 2993 } 2994 2995 // C99 DR 316 says that, if a function type comes from a 2996 // function definition (without a prototype), that type is only 2997 // used for checking compatibility. Therefore, when referencing 2998 // the function, we pretend that we don't have the full function 2999 // type. 3000 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3001 isa<FunctionProtoType>(fty)) 3002 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3003 fty->getExtInfo()); 3004 3005 // Functions are r-values in C. 3006 valueKind = VK_RValue; 3007 break; 3008 } 3009 3010 case Decl::MSProperty: 3011 valueKind = VK_LValue; 3012 break; 3013 3014 case Decl::CXXMethod: 3015 // If we're referring to a method with an __unknown_anytype 3016 // result type, make the entire expression __unknown_anytype. 3017 // This should only be possible with a type written directly. 3018 if (const FunctionProtoType *proto 3019 = dyn_cast<FunctionProtoType>(VD->getType())) 3020 if (proto->getReturnType() == Context.UnknownAnyTy) { 3021 type = Context.UnknownAnyTy; 3022 valueKind = VK_RValue; 3023 break; 3024 } 3025 3026 // C++ methods are l-values if static, r-values if non-static. 3027 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3028 valueKind = VK_LValue; 3029 break; 3030 } 3031 // fallthrough 3032 3033 case Decl::CXXConversion: 3034 case Decl::CXXDestructor: 3035 case Decl::CXXConstructor: 3036 valueKind = VK_RValue; 3037 break; 3038 } 3039 3040 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3041 TemplateArgs); 3042 } 3043 } 3044 3045 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3046 SmallString<32> &Target) { 3047 Target.resize(CharByteWidth * (Source.size() + 1)); 3048 char *ResultPtr = &Target[0]; 3049 const UTF8 *ErrorPtr; 3050 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3051 (void)success; 3052 assert(success); 3053 Target.resize(ResultPtr - &Target[0]); 3054 } 3055 3056 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3057 PredefinedExpr::IdentType IT) { 3058 // Pick the current block, lambda, captured statement or function. 3059 Decl *currentDecl = nullptr; 3060 if (const BlockScopeInfo *BSI = getCurBlock()) 3061 currentDecl = BSI->TheDecl; 3062 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3063 currentDecl = LSI->CallOperator; 3064 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3065 currentDecl = CSI->TheCapturedDecl; 3066 else 3067 currentDecl = getCurFunctionOrMethodDecl(); 3068 3069 if (!currentDecl) { 3070 Diag(Loc, diag::ext_predef_outside_function); 3071 currentDecl = Context.getTranslationUnitDecl(); 3072 } 3073 3074 QualType ResTy; 3075 StringLiteral *SL = nullptr; 3076 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3077 ResTy = Context.DependentTy; 3078 else { 3079 // Pre-defined identifiers are of type char[x], where x is the length of 3080 // the string. 3081 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3082 unsigned Length = Str.length(); 3083 3084 llvm::APInt LengthI(32, Length + 1); 3085 if (IT == PredefinedExpr::LFunction) { 3086 ResTy = Context.WideCharTy.withConst(); 3087 SmallString<32> RawChars; 3088 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3089 Str, RawChars); 3090 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3091 /*IndexTypeQuals*/ 0); 3092 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3093 /*Pascal*/ false, ResTy, Loc); 3094 } else { 3095 ResTy = Context.CharTy.withConst(); 3096 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3097 /*IndexTypeQuals*/ 0); 3098 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3099 /*Pascal*/ false, ResTy, Loc); 3100 } 3101 } 3102 3103 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3104 } 3105 3106 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3107 PredefinedExpr::IdentType IT; 3108 3109 switch (Kind) { 3110 default: llvm_unreachable("Unknown simple primary expr!"); 3111 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3112 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3113 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3114 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3115 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3116 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3117 } 3118 3119 return BuildPredefinedExpr(Loc, IT); 3120 } 3121 3122 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3123 SmallString<16> CharBuffer; 3124 bool Invalid = false; 3125 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3126 if (Invalid) 3127 return ExprError(); 3128 3129 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3130 PP, Tok.getKind()); 3131 if (Literal.hadError()) 3132 return ExprError(); 3133 3134 QualType Ty; 3135 if (Literal.isWide()) 3136 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3137 else if (Literal.isUTF16()) 3138 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3139 else if (Literal.isUTF32()) 3140 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3141 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3142 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3143 else 3144 Ty = Context.CharTy; // 'x' -> char in C++ 3145 3146 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3147 if (Literal.isWide()) 3148 Kind = CharacterLiteral::Wide; 3149 else if (Literal.isUTF16()) 3150 Kind = CharacterLiteral::UTF16; 3151 else if (Literal.isUTF32()) 3152 Kind = CharacterLiteral::UTF32; 3153 else if (Literal.isUTF8()) 3154 Kind = CharacterLiteral::UTF8; 3155 3156 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3157 Tok.getLocation()); 3158 3159 if (Literal.getUDSuffix().empty()) 3160 return Lit; 3161 3162 // We're building a user-defined literal. 3163 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3164 SourceLocation UDSuffixLoc = 3165 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3166 3167 // Make sure we're allowed user-defined literals here. 3168 if (!UDLScope) 3169 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3170 3171 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3172 // operator "" X (ch) 3173 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3174 Lit, Tok.getLocation()); 3175 } 3176 3177 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3178 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3179 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3180 Context.IntTy, Loc); 3181 } 3182 3183 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3184 QualType Ty, SourceLocation Loc) { 3185 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3186 3187 using llvm::APFloat; 3188 APFloat Val(Format); 3189 3190 APFloat::opStatus result = Literal.GetFloatValue(Val); 3191 3192 // Overflow is always an error, but underflow is only an error if 3193 // we underflowed to zero (APFloat reports denormals as underflow). 3194 if ((result & APFloat::opOverflow) || 3195 ((result & APFloat::opUnderflow) && Val.isZero())) { 3196 unsigned diagnostic; 3197 SmallString<20> buffer; 3198 if (result & APFloat::opOverflow) { 3199 diagnostic = diag::warn_float_overflow; 3200 APFloat::getLargest(Format).toString(buffer); 3201 } else { 3202 diagnostic = diag::warn_float_underflow; 3203 APFloat::getSmallest(Format).toString(buffer); 3204 } 3205 3206 S.Diag(Loc, diagnostic) 3207 << Ty 3208 << StringRef(buffer.data(), buffer.size()); 3209 } 3210 3211 bool isExact = (result == APFloat::opOK); 3212 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3213 } 3214 3215 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3216 assert(E && "Invalid expression"); 3217 3218 if (E->isValueDependent()) 3219 return false; 3220 3221 QualType QT = E->getType(); 3222 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3223 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3224 return true; 3225 } 3226 3227 llvm::APSInt ValueAPS; 3228 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3229 3230 if (R.isInvalid()) 3231 return true; 3232 3233 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3234 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3235 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3236 << ValueAPS.toString(10) << ValueIsPositive; 3237 return true; 3238 } 3239 3240 return false; 3241 } 3242 3243 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3244 // Fast path for a single digit (which is quite common). A single digit 3245 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3246 if (Tok.getLength() == 1) { 3247 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3248 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3249 } 3250 3251 SmallString<128> SpellingBuffer; 3252 // NumericLiteralParser wants to overread by one character. Add padding to 3253 // the buffer in case the token is copied to the buffer. If getSpelling() 3254 // returns a StringRef to the memory buffer, it should have a null char at 3255 // the EOF, so it is also safe. 3256 SpellingBuffer.resize(Tok.getLength() + 1); 3257 3258 // Get the spelling of the token, which eliminates trigraphs, etc. 3259 bool Invalid = false; 3260 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3261 if (Invalid) 3262 return ExprError(); 3263 3264 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3265 if (Literal.hadError) 3266 return ExprError(); 3267 3268 if (Literal.hasUDSuffix()) { 3269 // We're building a user-defined literal. 3270 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3271 SourceLocation UDSuffixLoc = 3272 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3273 3274 // Make sure we're allowed user-defined literals here. 3275 if (!UDLScope) 3276 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3277 3278 QualType CookedTy; 3279 if (Literal.isFloatingLiteral()) { 3280 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3281 // long double, the literal is treated as a call of the form 3282 // operator "" X (f L) 3283 CookedTy = Context.LongDoubleTy; 3284 } else { 3285 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3286 // unsigned long long, the literal is treated as a call of the form 3287 // operator "" X (n ULL) 3288 CookedTy = Context.UnsignedLongLongTy; 3289 } 3290 3291 DeclarationName OpName = 3292 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3293 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3294 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3295 3296 SourceLocation TokLoc = Tok.getLocation(); 3297 3298 // Perform literal operator lookup to determine if we're building a raw 3299 // literal or a cooked one. 3300 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3301 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3302 /*AllowRaw*/true, /*AllowTemplate*/true, 3303 /*AllowStringTemplate*/false)) { 3304 case LOLR_Error: 3305 return ExprError(); 3306 3307 case LOLR_Cooked: { 3308 Expr *Lit; 3309 if (Literal.isFloatingLiteral()) { 3310 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3311 } else { 3312 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3313 if (Literal.GetIntegerValue(ResultVal)) 3314 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3315 << /* Unsigned */ 1; 3316 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3317 Tok.getLocation()); 3318 } 3319 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3320 } 3321 3322 case LOLR_Raw: { 3323 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3324 // literal is treated as a call of the form 3325 // operator "" X ("n") 3326 unsigned Length = Literal.getUDSuffixOffset(); 3327 QualType StrTy = Context.getConstantArrayType( 3328 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3329 ArrayType::Normal, 0); 3330 Expr *Lit = StringLiteral::Create( 3331 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3332 /*Pascal*/false, StrTy, &TokLoc, 1); 3333 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3334 } 3335 3336 case LOLR_Template: { 3337 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3338 // template), L is treated as a call fo the form 3339 // operator "" X <'c1', 'c2', ... 'ck'>() 3340 // where n is the source character sequence c1 c2 ... ck. 3341 TemplateArgumentListInfo ExplicitArgs; 3342 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3343 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3344 llvm::APSInt Value(CharBits, CharIsUnsigned); 3345 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3346 Value = TokSpelling[I]; 3347 TemplateArgument Arg(Context, Value, Context.CharTy); 3348 TemplateArgumentLocInfo ArgInfo; 3349 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3350 } 3351 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3352 &ExplicitArgs); 3353 } 3354 case LOLR_StringTemplate: 3355 llvm_unreachable("unexpected literal operator lookup result"); 3356 } 3357 } 3358 3359 Expr *Res; 3360 3361 if (Literal.isFloatingLiteral()) { 3362 QualType Ty; 3363 if (Literal.isHalf){ 3364 if (getOpenCLOptions().cl_khr_fp16) 3365 Ty = Context.HalfTy; 3366 else { 3367 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3368 return ExprError(); 3369 } 3370 } else if (Literal.isFloat) 3371 Ty = Context.FloatTy; 3372 else if (Literal.isLong) 3373 Ty = Context.LongDoubleTy; 3374 else if (Literal.isFloat128) 3375 Ty = Context.Float128Ty; 3376 else 3377 Ty = Context.DoubleTy; 3378 3379 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3380 3381 if (Ty == Context.DoubleTy) { 3382 if (getLangOpts().SinglePrecisionConstants) { 3383 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3384 } else if (getLangOpts().OpenCL && 3385 !((getLangOpts().OpenCLVersion >= 120) || 3386 getOpenCLOptions().cl_khr_fp64)) { 3387 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3388 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3389 } 3390 } 3391 } else if (!Literal.isIntegerLiteral()) { 3392 return ExprError(); 3393 } else { 3394 QualType Ty; 3395 3396 // 'long long' is a C99 or C++11 feature. 3397 if (!getLangOpts().C99 && Literal.isLongLong) { 3398 if (getLangOpts().CPlusPlus) 3399 Diag(Tok.getLocation(), 3400 getLangOpts().CPlusPlus11 ? 3401 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3402 else 3403 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3404 } 3405 3406 // Get the value in the widest-possible width. 3407 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3408 llvm::APInt ResultVal(MaxWidth, 0); 3409 3410 if (Literal.GetIntegerValue(ResultVal)) { 3411 // If this value didn't fit into uintmax_t, error and force to ull. 3412 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3413 << /* Unsigned */ 1; 3414 Ty = Context.UnsignedLongLongTy; 3415 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3416 "long long is not intmax_t?"); 3417 } else { 3418 // If this value fits into a ULL, try to figure out what else it fits into 3419 // according to the rules of C99 6.4.4.1p5. 3420 3421 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3422 // be an unsigned int. 3423 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3424 3425 // Check from smallest to largest, picking the smallest type we can. 3426 unsigned Width = 0; 3427 3428 // Microsoft specific integer suffixes are explicitly sized. 3429 if (Literal.MicrosoftInteger) { 3430 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3431 Width = 8; 3432 Ty = Context.CharTy; 3433 } else { 3434 Width = Literal.MicrosoftInteger; 3435 Ty = Context.getIntTypeForBitwidth(Width, 3436 /*Signed=*/!Literal.isUnsigned); 3437 } 3438 } 3439 3440 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3441 // Are int/unsigned possibilities? 3442 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3443 3444 // Does it fit in a unsigned int? 3445 if (ResultVal.isIntN(IntSize)) { 3446 // Does it fit in a signed int? 3447 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3448 Ty = Context.IntTy; 3449 else if (AllowUnsigned) 3450 Ty = Context.UnsignedIntTy; 3451 Width = IntSize; 3452 } 3453 } 3454 3455 // Are long/unsigned long possibilities? 3456 if (Ty.isNull() && !Literal.isLongLong) { 3457 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3458 3459 // Does it fit in a unsigned long? 3460 if (ResultVal.isIntN(LongSize)) { 3461 // Does it fit in a signed long? 3462 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3463 Ty = Context.LongTy; 3464 else if (AllowUnsigned) 3465 Ty = Context.UnsignedLongTy; 3466 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3467 // is compatible. 3468 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3469 const unsigned LongLongSize = 3470 Context.getTargetInfo().getLongLongWidth(); 3471 Diag(Tok.getLocation(), 3472 getLangOpts().CPlusPlus 3473 ? Literal.isLong 3474 ? diag::warn_old_implicitly_unsigned_long_cxx 3475 : /*C++98 UB*/ diag:: 3476 ext_old_implicitly_unsigned_long_cxx 3477 : diag::warn_old_implicitly_unsigned_long) 3478 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3479 : /*will be ill-formed*/ 1); 3480 Ty = Context.UnsignedLongTy; 3481 } 3482 Width = LongSize; 3483 } 3484 } 3485 3486 // Check long long if needed. 3487 if (Ty.isNull()) { 3488 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3489 3490 // Does it fit in a unsigned long long? 3491 if (ResultVal.isIntN(LongLongSize)) { 3492 // Does it fit in a signed long long? 3493 // To be compatible with MSVC, hex integer literals ending with the 3494 // LL or i64 suffix are always signed in Microsoft mode. 3495 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3496 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3497 Ty = Context.LongLongTy; 3498 else if (AllowUnsigned) 3499 Ty = Context.UnsignedLongLongTy; 3500 Width = LongLongSize; 3501 } 3502 } 3503 3504 // If we still couldn't decide a type, we probably have something that 3505 // does not fit in a signed long long, but has no U suffix. 3506 if (Ty.isNull()) { 3507 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3508 Ty = Context.UnsignedLongLongTy; 3509 Width = Context.getTargetInfo().getLongLongWidth(); 3510 } 3511 3512 if (ResultVal.getBitWidth() != Width) 3513 ResultVal = ResultVal.trunc(Width); 3514 } 3515 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3516 } 3517 3518 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3519 if (Literal.isImaginary) 3520 Res = new (Context) ImaginaryLiteral(Res, 3521 Context.getComplexType(Res->getType())); 3522 3523 return Res; 3524 } 3525 3526 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3527 assert(E && "ActOnParenExpr() missing expr"); 3528 return new (Context) ParenExpr(L, R, E); 3529 } 3530 3531 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3532 SourceLocation Loc, 3533 SourceRange ArgRange) { 3534 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3535 // scalar or vector data type argument..." 3536 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3537 // type (C99 6.2.5p18) or void. 3538 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3539 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3540 << T << ArgRange; 3541 return true; 3542 } 3543 3544 assert((T->isVoidType() || !T->isIncompleteType()) && 3545 "Scalar types should always be complete"); 3546 return false; 3547 } 3548 3549 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3550 SourceLocation Loc, 3551 SourceRange ArgRange, 3552 UnaryExprOrTypeTrait TraitKind) { 3553 // Invalid types must be hard errors for SFINAE in C++. 3554 if (S.LangOpts.CPlusPlus) 3555 return true; 3556 3557 // C99 6.5.3.4p1: 3558 if (T->isFunctionType() && 3559 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3560 // sizeof(function)/alignof(function) is allowed as an extension. 3561 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3562 << TraitKind << ArgRange; 3563 return false; 3564 } 3565 3566 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3567 // this is an error (OpenCL v1.1 s6.3.k) 3568 if (T->isVoidType()) { 3569 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3570 : diag::ext_sizeof_alignof_void_type; 3571 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3572 return false; 3573 } 3574 3575 return true; 3576 } 3577 3578 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3579 SourceLocation Loc, 3580 SourceRange ArgRange, 3581 UnaryExprOrTypeTrait TraitKind) { 3582 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3583 // runtime doesn't allow it. 3584 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3585 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3586 << T << (TraitKind == UETT_SizeOf) 3587 << ArgRange; 3588 return true; 3589 } 3590 3591 return false; 3592 } 3593 3594 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3595 /// pointer type is equal to T) and emit a warning if it is. 3596 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3597 Expr *E) { 3598 // Don't warn if the operation changed the type. 3599 if (T != E->getType()) 3600 return; 3601 3602 // Now look for array decays. 3603 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3604 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3605 return; 3606 3607 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3608 << ICE->getType() 3609 << ICE->getSubExpr()->getType(); 3610 } 3611 3612 /// \brief Check the constraints on expression operands to unary type expression 3613 /// and type traits. 3614 /// 3615 /// Completes any types necessary and validates the constraints on the operand 3616 /// expression. The logic mostly mirrors the type-based overload, but may modify 3617 /// the expression as it completes the type for that expression through template 3618 /// instantiation, etc. 3619 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3620 UnaryExprOrTypeTrait ExprKind) { 3621 QualType ExprTy = E->getType(); 3622 assert(!ExprTy->isReferenceType()); 3623 3624 if (ExprKind == UETT_VecStep) 3625 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3626 E->getSourceRange()); 3627 3628 // Whitelist some types as extensions 3629 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3630 E->getSourceRange(), ExprKind)) 3631 return false; 3632 3633 // 'alignof' applied to an expression only requires the base element type of 3634 // the expression to be complete. 'sizeof' requires the expression's type to 3635 // be complete (and will attempt to complete it if it's an array of unknown 3636 // bound). 3637 if (ExprKind == UETT_AlignOf) { 3638 if (RequireCompleteType(E->getExprLoc(), 3639 Context.getBaseElementType(E->getType()), 3640 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3641 E->getSourceRange())) 3642 return true; 3643 } else { 3644 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3645 ExprKind, E->getSourceRange())) 3646 return true; 3647 } 3648 3649 // Completing the expression's type may have changed it. 3650 ExprTy = E->getType(); 3651 assert(!ExprTy->isReferenceType()); 3652 3653 if (ExprTy->isFunctionType()) { 3654 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3655 << ExprKind << E->getSourceRange(); 3656 return true; 3657 } 3658 3659 // The operand for sizeof and alignof is in an unevaluated expression context, 3660 // so side effects could result in unintended consequences. 3661 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3662 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3663 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3664 3665 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3666 E->getSourceRange(), ExprKind)) 3667 return true; 3668 3669 if (ExprKind == UETT_SizeOf) { 3670 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3671 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3672 QualType OType = PVD->getOriginalType(); 3673 QualType Type = PVD->getType(); 3674 if (Type->isPointerType() && OType->isArrayType()) { 3675 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3676 << Type << OType; 3677 Diag(PVD->getLocation(), diag::note_declared_at); 3678 } 3679 } 3680 } 3681 3682 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3683 // decays into a pointer and returns an unintended result. This is most 3684 // likely a typo for "sizeof(array) op x". 3685 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3686 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3687 BO->getLHS()); 3688 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3689 BO->getRHS()); 3690 } 3691 } 3692 3693 return false; 3694 } 3695 3696 /// \brief Check the constraints on operands to unary expression and type 3697 /// traits. 3698 /// 3699 /// This will complete any types necessary, and validate the various constraints 3700 /// on those operands. 3701 /// 3702 /// The UsualUnaryConversions() function is *not* called by this routine. 3703 /// C99 6.3.2.1p[2-4] all state: 3704 /// Except when it is the operand of the sizeof operator ... 3705 /// 3706 /// C++ [expr.sizeof]p4 3707 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3708 /// standard conversions are not applied to the operand of sizeof. 3709 /// 3710 /// This policy is followed for all of the unary trait expressions. 3711 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3712 SourceLocation OpLoc, 3713 SourceRange ExprRange, 3714 UnaryExprOrTypeTrait ExprKind) { 3715 if (ExprType->isDependentType()) 3716 return false; 3717 3718 // C++ [expr.sizeof]p2: 3719 // When applied to a reference or a reference type, the result 3720 // is the size of the referenced type. 3721 // C++11 [expr.alignof]p3: 3722 // When alignof is applied to a reference type, the result 3723 // shall be the alignment of the referenced type. 3724 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3725 ExprType = Ref->getPointeeType(); 3726 3727 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3728 // When alignof or _Alignof is applied to an array type, the result 3729 // is the alignment of the element type. 3730 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3731 ExprType = Context.getBaseElementType(ExprType); 3732 3733 if (ExprKind == UETT_VecStep) 3734 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3735 3736 // Whitelist some types as extensions 3737 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3738 ExprKind)) 3739 return false; 3740 3741 if (RequireCompleteType(OpLoc, ExprType, 3742 diag::err_sizeof_alignof_incomplete_type, 3743 ExprKind, ExprRange)) 3744 return true; 3745 3746 if (ExprType->isFunctionType()) { 3747 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3748 << ExprKind << ExprRange; 3749 return true; 3750 } 3751 3752 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3753 ExprKind)) 3754 return true; 3755 3756 return false; 3757 } 3758 3759 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3760 E = E->IgnoreParens(); 3761 3762 // Cannot know anything else if the expression is dependent. 3763 if (E->isTypeDependent()) 3764 return false; 3765 3766 if (E->getObjectKind() == OK_BitField) { 3767 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3768 << 1 << E->getSourceRange(); 3769 return true; 3770 } 3771 3772 ValueDecl *D = nullptr; 3773 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3774 D = DRE->getDecl(); 3775 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3776 D = ME->getMemberDecl(); 3777 } 3778 3779 // If it's a field, require the containing struct to have a 3780 // complete definition so that we can compute the layout. 3781 // 3782 // This can happen in C++11 onwards, either by naming the member 3783 // in a way that is not transformed into a member access expression 3784 // (in an unevaluated operand, for instance), or by naming the member 3785 // in a trailing-return-type. 3786 // 3787 // For the record, since __alignof__ on expressions is a GCC 3788 // extension, GCC seems to permit this but always gives the 3789 // nonsensical answer 0. 3790 // 3791 // We don't really need the layout here --- we could instead just 3792 // directly check for all the appropriate alignment-lowing 3793 // attributes --- but that would require duplicating a lot of 3794 // logic that just isn't worth duplicating for such a marginal 3795 // use-case. 3796 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3797 // Fast path this check, since we at least know the record has a 3798 // definition if we can find a member of it. 3799 if (!FD->getParent()->isCompleteDefinition()) { 3800 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3801 << E->getSourceRange(); 3802 return true; 3803 } 3804 3805 // Otherwise, if it's a field, and the field doesn't have 3806 // reference type, then it must have a complete type (or be a 3807 // flexible array member, which we explicitly want to 3808 // white-list anyway), which makes the following checks trivial. 3809 if (!FD->getType()->isReferenceType()) 3810 return false; 3811 } 3812 3813 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3814 } 3815 3816 bool Sema::CheckVecStepExpr(Expr *E) { 3817 E = E->IgnoreParens(); 3818 3819 // Cannot know anything else if the expression is dependent. 3820 if (E->isTypeDependent()) 3821 return false; 3822 3823 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3824 } 3825 3826 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3827 CapturingScopeInfo *CSI) { 3828 assert(T->isVariablyModifiedType()); 3829 assert(CSI != nullptr); 3830 3831 // We're going to walk down into the type and look for VLA expressions. 3832 do { 3833 const Type *Ty = T.getTypePtr(); 3834 switch (Ty->getTypeClass()) { 3835 #define TYPE(Class, Base) 3836 #define ABSTRACT_TYPE(Class, Base) 3837 #define NON_CANONICAL_TYPE(Class, Base) 3838 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3839 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3840 #include "clang/AST/TypeNodes.def" 3841 T = QualType(); 3842 break; 3843 // These types are never variably-modified. 3844 case Type::Builtin: 3845 case Type::Complex: 3846 case Type::Vector: 3847 case Type::ExtVector: 3848 case Type::Record: 3849 case Type::Enum: 3850 case Type::Elaborated: 3851 case Type::TemplateSpecialization: 3852 case Type::ObjCObject: 3853 case Type::ObjCInterface: 3854 case Type::ObjCObjectPointer: 3855 case Type::Pipe: 3856 llvm_unreachable("type class is never variably-modified!"); 3857 case Type::Adjusted: 3858 T = cast<AdjustedType>(Ty)->getOriginalType(); 3859 break; 3860 case Type::Decayed: 3861 T = cast<DecayedType>(Ty)->getPointeeType(); 3862 break; 3863 case Type::Pointer: 3864 T = cast<PointerType>(Ty)->getPointeeType(); 3865 break; 3866 case Type::BlockPointer: 3867 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3868 break; 3869 case Type::LValueReference: 3870 case Type::RValueReference: 3871 T = cast<ReferenceType>(Ty)->getPointeeType(); 3872 break; 3873 case Type::MemberPointer: 3874 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3875 break; 3876 case Type::ConstantArray: 3877 case Type::IncompleteArray: 3878 // Losing element qualification here is fine. 3879 T = cast<ArrayType>(Ty)->getElementType(); 3880 break; 3881 case Type::VariableArray: { 3882 // Losing element qualification here is fine. 3883 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3884 3885 // Unknown size indication requires no size computation. 3886 // Otherwise, evaluate and record it. 3887 if (auto Size = VAT->getSizeExpr()) { 3888 if (!CSI->isVLATypeCaptured(VAT)) { 3889 RecordDecl *CapRecord = nullptr; 3890 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3891 CapRecord = LSI->Lambda; 3892 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3893 CapRecord = CRSI->TheRecordDecl; 3894 } 3895 if (CapRecord) { 3896 auto ExprLoc = Size->getExprLoc(); 3897 auto SizeType = Context.getSizeType(); 3898 // Build the non-static data member. 3899 auto Field = 3900 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3901 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3902 /*BW*/ nullptr, /*Mutable*/ false, 3903 /*InitStyle*/ ICIS_NoInit); 3904 Field->setImplicit(true); 3905 Field->setAccess(AS_private); 3906 Field->setCapturedVLAType(VAT); 3907 CapRecord->addDecl(Field); 3908 3909 CSI->addVLATypeCapture(ExprLoc, SizeType); 3910 } 3911 } 3912 } 3913 T = VAT->getElementType(); 3914 break; 3915 } 3916 case Type::FunctionProto: 3917 case Type::FunctionNoProto: 3918 T = cast<FunctionType>(Ty)->getReturnType(); 3919 break; 3920 case Type::Paren: 3921 case Type::TypeOf: 3922 case Type::UnaryTransform: 3923 case Type::Attributed: 3924 case Type::SubstTemplateTypeParm: 3925 case Type::PackExpansion: 3926 // Keep walking after single level desugaring. 3927 T = T.getSingleStepDesugaredType(Context); 3928 break; 3929 case Type::Typedef: 3930 T = cast<TypedefType>(Ty)->desugar(); 3931 break; 3932 case Type::Decltype: 3933 T = cast<DecltypeType>(Ty)->desugar(); 3934 break; 3935 case Type::Auto: 3936 T = cast<AutoType>(Ty)->getDeducedType(); 3937 break; 3938 case Type::TypeOfExpr: 3939 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3940 break; 3941 case Type::Atomic: 3942 T = cast<AtomicType>(Ty)->getValueType(); 3943 break; 3944 } 3945 } while (!T.isNull() && T->isVariablyModifiedType()); 3946 } 3947 3948 /// \brief Build a sizeof or alignof expression given a type operand. 3949 ExprResult 3950 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3951 SourceLocation OpLoc, 3952 UnaryExprOrTypeTrait ExprKind, 3953 SourceRange R) { 3954 if (!TInfo) 3955 return ExprError(); 3956 3957 QualType T = TInfo->getType(); 3958 3959 if (!T->isDependentType() && 3960 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3961 return ExprError(); 3962 3963 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3964 if (auto *TT = T->getAs<TypedefType>()) { 3965 for (auto I = FunctionScopes.rbegin(), 3966 E = std::prev(FunctionScopes.rend()); 3967 I != E; ++I) { 3968 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3969 if (CSI == nullptr) 3970 break; 3971 DeclContext *DC = nullptr; 3972 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3973 DC = LSI->CallOperator; 3974 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3975 DC = CRSI->TheCapturedDecl; 3976 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3977 DC = BSI->TheDecl; 3978 if (DC) { 3979 if (DC->containsDecl(TT->getDecl())) 3980 break; 3981 captureVariablyModifiedType(Context, T, CSI); 3982 } 3983 } 3984 } 3985 } 3986 3987 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3988 return new (Context) UnaryExprOrTypeTraitExpr( 3989 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3990 } 3991 3992 /// \brief Build a sizeof or alignof expression given an expression 3993 /// operand. 3994 ExprResult 3995 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3996 UnaryExprOrTypeTrait ExprKind) { 3997 ExprResult PE = CheckPlaceholderExpr(E); 3998 if (PE.isInvalid()) 3999 return ExprError(); 4000 4001 E = PE.get(); 4002 4003 // Verify that the operand is valid. 4004 bool isInvalid = false; 4005 if (E->isTypeDependent()) { 4006 // Delay type-checking for type-dependent expressions. 4007 } else if (ExprKind == UETT_AlignOf) { 4008 isInvalid = CheckAlignOfExpr(*this, E); 4009 } else if (ExprKind == UETT_VecStep) { 4010 isInvalid = CheckVecStepExpr(E); 4011 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4012 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4013 isInvalid = true; 4014 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4015 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4016 isInvalid = true; 4017 } else { 4018 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4019 } 4020 4021 if (isInvalid) 4022 return ExprError(); 4023 4024 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4025 PE = TransformToPotentiallyEvaluated(E); 4026 if (PE.isInvalid()) return ExprError(); 4027 E = PE.get(); 4028 } 4029 4030 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4031 return new (Context) UnaryExprOrTypeTraitExpr( 4032 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4033 } 4034 4035 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4036 /// expr and the same for @c alignof and @c __alignof 4037 /// Note that the ArgRange is invalid if isType is false. 4038 ExprResult 4039 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4040 UnaryExprOrTypeTrait ExprKind, bool IsType, 4041 void *TyOrEx, SourceRange ArgRange) { 4042 // If error parsing type, ignore. 4043 if (!TyOrEx) return ExprError(); 4044 4045 if (IsType) { 4046 TypeSourceInfo *TInfo; 4047 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4048 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4049 } 4050 4051 Expr *ArgEx = (Expr *)TyOrEx; 4052 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4053 return Result; 4054 } 4055 4056 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4057 bool IsReal) { 4058 if (V.get()->isTypeDependent()) 4059 return S.Context.DependentTy; 4060 4061 // _Real and _Imag are only l-values for normal l-values. 4062 if (V.get()->getObjectKind() != OK_Ordinary) { 4063 V = S.DefaultLvalueConversion(V.get()); 4064 if (V.isInvalid()) 4065 return QualType(); 4066 } 4067 4068 // These operators return the element type of a complex type. 4069 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4070 return CT->getElementType(); 4071 4072 // Otherwise they pass through real integer and floating point types here. 4073 if (V.get()->getType()->isArithmeticType()) 4074 return V.get()->getType(); 4075 4076 // Test for placeholders. 4077 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4078 if (PR.isInvalid()) return QualType(); 4079 if (PR.get() != V.get()) { 4080 V = PR; 4081 return CheckRealImagOperand(S, V, Loc, IsReal); 4082 } 4083 4084 // Reject anything else. 4085 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4086 << (IsReal ? "__real" : "__imag"); 4087 return QualType(); 4088 } 4089 4090 4091 4092 ExprResult 4093 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4094 tok::TokenKind Kind, Expr *Input) { 4095 UnaryOperatorKind Opc; 4096 switch (Kind) { 4097 default: llvm_unreachable("Unknown unary op!"); 4098 case tok::plusplus: Opc = UO_PostInc; break; 4099 case tok::minusminus: Opc = UO_PostDec; break; 4100 } 4101 4102 // Since this might is a postfix expression, get rid of ParenListExprs. 4103 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4104 if (Result.isInvalid()) return ExprError(); 4105 Input = Result.get(); 4106 4107 return BuildUnaryOp(S, OpLoc, Opc, Input); 4108 } 4109 4110 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4111 /// 4112 /// \return true on error 4113 static bool checkArithmeticOnObjCPointer(Sema &S, 4114 SourceLocation opLoc, 4115 Expr *op) { 4116 assert(op->getType()->isObjCObjectPointerType()); 4117 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4118 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4119 return false; 4120 4121 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4122 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4123 << op->getSourceRange(); 4124 return true; 4125 } 4126 4127 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4128 auto *BaseNoParens = Base->IgnoreParens(); 4129 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4130 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4131 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4132 } 4133 4134 ExprResult 4135 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4136 Expr *idx, SourceLocation rbLoc) { 4137 if (base && !base->getType().isNull() && 4138 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4139 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4140 /*Length=*/nullptr, rbLoc); 4141 4142 // Since this might be a postfix expression, get rid of ParenListExprs. 4143 if (isa<ParenListExpr>(base)) { 4144 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4145 if (result.isInvalid()) return ExprError(); 4146 base = result.get(); 4147 } 4148 4149 // Handle any non-overload placeholder types in the base and index 4150 // expressions. We can't handle overloads here because the other 4151 // operand might be an overloadable type, in which case the overload 4152 // resolution for the operator overload should get the first crack 4153 // at the overload. 4154 bool IsMSPropertySubscript = false; 4155 if (base->getType()->isNonOverloadPlaceholderType()) { 4156 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4157 if (!IsMSPropertySubscript) { 4158 ExprResult result = CheckPlaceholderExpr(base); 4159 if (result.isInvalid()) 4160 return ExprError(); 4161 base = result.get(); 4162 } 4163 } 4164 if (idx->getType()->isNonOverloadPlaceholderType()) { 4165 ExprResult result = CheckPlaceholderExpr(idx); 4166 if (result.isInvalid()) return ExprError(); 4167 idx = result.get(); 4168 } 4169 4170 // Build an unanalyzed expression if either operand is type-dependent. 4171 if (getLangOpts().CPlusPlus && 4172 (base->isTypeDependent() || idx->isTypeDependent())) { 4173 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4174 VK_LValue, OK_Ordinary, rbLoc); 4175 } 4176 4177 // MSDN, property (C++) 4178 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4179 // This attribute can also be used in the declaration of an empty array in a 4180 // class or structure definition. For example: 4181 // __declspec(property(get=GetX, put=PutX)) int x[]; 4182 // The above statement indicates that x[] can be used with one or more array 4183 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4184 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4185 if (IsMSPropertySubscript) { 4186 // Build MS property subscript expression if base is MS property reference 4187 // or MS property subscript. 4188 return new (Context) MSPropertySubscriptExpr( 4189 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4190 } 4191 4192 // Use C++ overloaded-operator rules if either operand has record 4193 // type. The spec says to do this if either type is *overloadable*, 4194 // but enum types can't declare subscript operators or conversion 4195 // operators, so there's nothing interesting for overload resolution 4196 // to do if there aren't any record types involved. 4197 // 4198 // ObjC pointers have their own subscripting logic that is not tied 4199 // to overload resolution and so should not take this path. 4200 if (getLangOpts().CPlusPlus && 4201 (base->getType()->isRecordType() || 4202 (!base->getType()->isObjCObjectPointerType() && 4203 idx->getType()->isRecordType()))) { 4204 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4205 } 4206 4207 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4208 } 4209 4210 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4211 Expr *LowerBound, 4212 SourceLocation ColonLoc, Expr *Length, 4213 SourceLocation RBLoc) { 4214 if (Base->getType()->isPlaceholderType() && 4215 !Base->getType()->isSpecificPlaceholderType( 4216 BuiltinType::OMPArraySection)) { 4217 ExprResult Result = CheckPlaceholderExpr(Base); 4218 if (Result.isInvalid()) 4219 return ExprError(); 4220 Base = Result.get(); 4221 } 4222 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4223 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4224 if (Result.isInvalid()) 4225 return ExprError(); 4226 Result = DefaultLvalueConversion(Result.get()); 4227 if (Result.isInvalid()) 4228 return ExprError(); 4229 LowerBound = Result.get(); 4230 } 4231 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4232 ExprResult Result = CheckPlaceholderExpr(Length); 4233 if (Result.isInvalid()) 4234 return ExprError(); 4235 Result = DefaultLvalueConversion(Result.get()); 4236 if (Result.isInvalid()) 4237 return ExprError(); 4238 Length = Result.get(); 4239 } 4240 4241 // Build an unanalyzed expression if either operand is type-dependent. 4242 if (Base->isTypeDependent() || 4243 (LowerBound && 4244 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4245 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4246 return new (Context) 4247 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4248 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4249 } 4250 4251 // Perform default conversions. 4252 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4253 QualType ResultTy; 4254 if (OriginalTy->isAnyPointerType()) { 4255 ResultTy = OriginalTy->getPointeeType(); 4256 } else if (OriginalTy->isArrayType()) { 4257 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4258 } else { 4259 return ExprError( 4260 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4261 << Base->getSourceRange()); 4262 } 4263 // C99 6.5.2.1p1 4264 if (LowerBound) { 4265 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4266 LowerBound); 4267 if (Res.isInvalid()) 4268 return ExprError(Diag(LowerBound->getExprLoc(), 4269 diag::err_omp_typecheck_section_not_integer) 4270 << 0 << LowerBound->getSourceRange()); 4271 LowerBound = Res.get(); 4272 4273 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4274 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4275 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4276 << 0 << LowerBound->getSourceRange(); 4277 } 4278 if (Length) { 4279 auto Res = 4280 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4281 if (Res.isInvalid()) 4282 return ExprError(Diag(Length->getExprLoc(), 4283 diag::err_omp_typecheck_section_not_integer) 4284 << 1 << Length->getSourceRange()); 4285 Length = Res.get(); 4286 4287 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4288 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4289 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4290 << 1 << Length->getSourceRange(); 4291 } 4292 4293 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4294 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4295 // type. Note that functions are not objects, and that (in C99 parlance) 4296 // incomplete types are not object types. 4297 if (ResultTy->isFunctionType()) { 4298 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4299 << ResultTy << Base->getSourceRange(); 4300 return ExprError(); 4301 } 4302 4303 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4304 diag::err_omp_section_incomplete_type, Base)) 4305 return ExprError(); 4306 4307 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4308 llvm::APSInt LowerBoundValue; 4309 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4310 // OpenMP 4.5, [2.4 Array Sections] 4311 // The array section must be a subset of the original array. 4312 if (LowerBoundValue.isNegative()) { 4313 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4314 << LowerBound->getSourceRange(); 4315 return ExprError(); 4316 } 4317 } 4318 } 4319 4320 if (Length) { 4321 llvm::APSInt LengthValue; 4322 if (Length->EvaluateAsInt(LengthValue, Context)) { 4323 // OpenMP 4.5, [2.4 Array Sections] 4324 // The length must evaluate to non-negative integers. 4325 if (LengthValue.isNegative()) { 4326 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4327 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4328 << Length->getSourceRange(); 4329 return ExprError(); 4330 } 4331 } 4332 } else if (ColonLoc.isValid() && 4333 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4334 !OriginalTy->isVariableArrayType()))) { 4335 // OpenMP 4.5, [2.4 Array Sections] 4336 // When the size of the array dimension is not known, the length must be 4337 // specified explicitly. 4338 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4339 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4340 return ExprError(); 4341 } 4342 4343 if (!Base->getType()->isSpecificPlaceholderType( 4344 BuiltinType::OMPArraySection)) { 4345 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4346 if (Result.isInvalid()) 4347 return ExprError(); 4348 Base = Result.get(); 4349 } 4350 return new (Context) 4351 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4352 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4353 } 4354 4355 ExprResult 4356 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4357 Expr *Idx, SourceLocation RLoc) { 4358 Expr *LHSExp = Base; 4359 Expr *RHSExp = Idx; 4360 4361 // Perform default conversions. 4362 if (!LHSExp->getType()->getAs<VectorType>()) { 4363 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4364 if (Result.isInvalid()) 4365 return ExprError(); 4366 LHSExp = Result.get(); 4367 } 4368 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4369 if (Result.isInvalid()) 4370 return ExprError(); 4371 RHSExp = Result.get(); 4372 4373 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4374 ExprValueKind VK = VK_LValue; 4375 ExprObjectKind OK = OK_Ordinary; 4376 4377 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4378 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4379 // in the subscript position. As a result, we need to derive the array base 4380 // and index from the expression types. 4381 Expr *BaseExpr, *IndexExpr; 4382 QualType ResultType; 4383 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4384 BaseExpr = LHSExp; 4385 IndexExpr = RHSExp; 4386 ResultType = Context.DependentTy; 4387 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4388 BaseExpr = LHSExp; 4389 IndexExpr = RHSExp; 4390 ResultType = PTy->getPointeeType(); 4391 } else if (const ObjCObjectPointerType *PTy = 4392 LHSTy->getAs<ObjCObjectPointerType>()) { 4393 BaseExpr = LHSExp; 4394 IndexExpr = RHSExp; 4395 4396 // Use custom logic if this should be the pseudo-object subscript 4397 // expression. 4398 if (!LangOpts.isSubscriptPointerArithmetic()) 4399 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4400 nullptr); 4401 4402 ResultType = PTy->getPointeeType(); 4403 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4404 // Handle the uncommon case of "123[Ptr]". 4405 BaseExpr = RHSExp; 4406 IndexExpr = LHSExp; 4407 ResultType = PTy->getPointeeType(); 4408 } else if (const ObjCObjectPointerType *PTy = 4409 RHSTy->getAs<ObjCObjectPointerType>()) { 4410 // Handle the uncommon case of "123[Ptr]". 4411 BaseExpr = RHSExp; 4412 IndexExpr = LHSExp; 4413 ResultType = PTy->getPointeeType(); 4414 if (!LangOpts.isSubscriptPointerArithmetic()) { 4415 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4416 << ResultType << BaseExpr->getSourceRange(); 4417 return ExprError(); 4418 } 4419 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4420 BaseExpr = LHSExp; // vectors: V[123] 4421 IndexExpr = RHSExp; 4422 VK = LHSExp->getValueKind(); 4423 if (VK != VK_RValue) 4424 OK = OK_VectorComponent; 4425 4426 // FIXME: need to deal with const... 4427 ResultType = VTy->getElementType(); 4428 } else if (LHSTy->isArrayType()) { 4429 // If we see an array that wasn't promoted by 4430 // DefaultFunctionArrayLvalueConversion, it must be an array that 4431 // wasn't promoted because of the C90 rule that doesn't 4432 // allow promoting non-lvalue arrays. Warn, then 4433 // force the promotion here. 4434 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4435 LHSExp->getSourceRange(); 4436 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4437 CK_ArrayToPointerDecay).get(); 4438 LHSTy = LHSExp->getType(); 4439 4440 BaseExpr = LHSExp; 4441 IndexExpr = RHSExp; 4442 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4443 } else if (RHSTy->isArrayType()) { 4444 // Same as previous, except for 123[f().a] case 4445 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4446 RHSExp->getSourceRange(); 4447 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4448 CK_ArrayToPointerDecay).get(); 4449 RHSTy = RHSExp->getType(); 4450 4451 BaseExpr = RHSExp; 4452 IndexExpr = LHSExp; 4453 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4454 } else { 4455 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4456 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4457 } 4458 // C99 6.5.2.1p1 4459 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4460 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4461 << IndexExpr->getSourceRange()); 4462 4463 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4464 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4465 && !IndexExpr->isTypeDependent()) 4466 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4467 4468 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4469 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4470 // type. Note that Functions are not objects, and that (in C99 parlance) 4471 // incomplete types are not object types. 4472 if (ResultType->isFunctionType()) { 4473 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4474 << ResultType << BaseExpr->getSourceRange(); 4475 return ExprError(); 4476 } 4477 4478 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4479 // GNU extension: subscripting on pointer to void 4480 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4481 << BaseExpr->getSourceRange(); 4482 4483 // C forbids expressions of unqualified void type from being l-values. 4484 // See IsCForbiddenLValueType. 4485 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4486 } else if (!ResultType->isDependentType() && 4487 RequireCompleteType(LLoc, ResultType, 4488 diag::err_subscript_incomplete_type, BaseExpr)) 4489 return ExprError(); 4490 4491 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4492 !ResultType.isCForbiddenLValueType()); 4493 4494 return new (Context) 4495 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4496 } 4497 4498 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4499 FunctionDecl *FD, 4500 ParmVarDecl *Param) { 4501 if (Param->hasUnparsedDefaultArg()) { 4502 Diag(CallLoc, 4503 diag::err_use_of_default_argument_to_function_declared_later) << 4504 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4505 Diag(UnparsedDefaultArgLocs[Param], 4506 diag::note_default_argument_declared_here); 4507 return ExprError(); 4508 } 4509 4510 if (Param->hasUninstantiatedDefaultArg()) { 4511 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4512 4513 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4514 Param); 4515 4516 // Instantiate the expression. 4517 MultiLevelTemplateArgumentList MutiLevelArgList 4518 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4519 4520 InstantiatingTemplate Inst(*this, CallLoc, Param, 4521 MutiLevelArgList.getInnermost()); 4522 if (Inst.isInvalid()) 4523 return ExprError(); 4524 4525 ExprResult Result; 4526 { 4527 // C++ [dcl.fct.default]p5: 4528 // The names in the [default argument] expression are bound, and 4529 // the semantic constraints are checked, at the point where the 4530 // default argument expression appears. 4531 ContextRAII SavedContext(*this, FD); 4532 LocalInstantiationScope Local(*this); 4533 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4534 } 4535 if (Result.isInvalid()) 4536 return ExprError(); 4537 4538 // Check the expression as an initializer for the parameter. 4539 InitializedEntity Entity 4540 = InitializedEntity::InitializeParameter(Context, Param); 4541 InitializationKind Kind 4542 = InitializationKind::CreateCopy(Param->getLocation(), 4543 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4544 Expr *ResultE = Result.getAs<Expr>(); 4545 4546 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4547 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4548 if (Result.isInvalid()) 4549 return ExprError(); 4550 4551 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4552 Param->getOuterLocStart()); 4553 if (Result.isInvalid()) 4554 return ExprError(); 4555 4556 // Remember the instantiated default argument. 4557 Param->setDefaultArg(Result.getAs<Expr>()); 4558 if (ASTMutationListener *L = getASTMutationListener()) { 4559 L->DefaultArgumentInstantiated(Param); 4560 } 4561 } 4562 4563 // If the default argument expression is not set yet, we are building it now. 4564 if (!Param->hasInit()) { 4565 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4566 Param->setInvalidDecl(); 4567 return ExprError(); 4568 } 4569 4570 // If the default expression creates temporaries, we need to 4571 // push them to the current stack of expression temporaries so they'll 4572 // be properly destroyed. 4573 // FIXME: We should really be rebuilding the default argument with new 4574 // bound temporaries; see the comment in PR5810. 4575 // We don't need to do that with block decls, though, because 4576 // blocks in default argument expression can never capture anything. 4577 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4578 // Set the "needs cleanups" bit regardless of whether there are 4579 // any explicit objects. 4580 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4581 4582 // Append all the objects to the cleanup list. Right now, this 4583 // should always be a no-op, because blocks in default argument 4584 // expressions should never be able to capture anything. 4585 assert(!Init->getNumObjects() && 4586 "default argument expression has capturing blocks?"); 4587 } 4588 4589 // We already type-checked the argument, so we know it works. 4590 // Just mark all of the declarations in this potentially-evaluated expression 4591 // as being "referenced". 4592 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4593 /*SkipLocalVariables=*/true); 4594 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4595 } 4596 4597 4598 Sema::VariadicCallType 4599 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4600 Expr *Fn) { 4601 if (Proto && Proto->isVariadic()) { 4602 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4603 return VariadicConstructor; 4604 else if (Fn && Fn->getType()->isBlockPointerType()) 4605 return VariadicBlock; 4606 else if (FDecl) { 4607 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4608 if (Method->isInstance()) 4609 return VariadicMethod; 4610 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4611 return VariadicMethod; 4612 return VariadicFunction; 4613 } 4614 return VariadicDoesNotApply; 4615 } 4616 4617 namespace { 4618 class FunctionCallCCC : public FunctionCallFilterCCC { 4619 public: 4620 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4621 unsigned NumArgs, MemberExpr *ME) 4622 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4623 FunctionName(FuncName) {} 4624 4625 bool ValidateCandidate(const TypoCorrection &candidate) override { 4626 if (!candidate.getCorrectionSpecifier() || 4627 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4628 return false; 4629 } 4630 4631 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4632 } 4633 4634 private: 4635 const IdentifierInfo *const FunctionName; 4636 }; 4637 } 4638 4639 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4640 FunctionDecl *FDecl, 4641 ArrayRef<Expr *> Args) { 4642 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4643 DeclarationName FuncName = FDecl->getDeclName(); 4644 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4645 4646 if (TypoCorrection Corrected = S.CorrectTypo( 4647 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4648 S.getScopeForContext(S.CurContext), nullptr, 4649 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4650 Args.size(), ME), 4651 Sema::CTK_ErrorRecovery)) { 4652 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4653 if (Corrected.isOverloaded()) { 4654 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4655 OverloadCandidateSet::iterator Best; 4656 for (NamedDecl *CD : Corrected) { 4657 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4658 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4659 OCS); 4660 } 4661 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4662 case OR_Success: 4663 ND = Best->FoundDecl; 4664 Corrected.setCorrectionDecl(ND); 4665 break; 4666 default: 4667 break; 4668 } 4669 } 4670 ND = ND->getUnderlyingDecl(); 4671 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4672 return Corrected; 4673 } 4674 } 4675 return TypoCorrection(); 4676 } 4677 4678 /// ConvertArgumentsForCall - Converts the arguments specified in 4679 /// Args/NumArgs to the parameter types of the function FDecl with 4680 /// function prototype Proto. Call is the call expression itself, and 4681 /// Fn is the function expression. For a C++ member function, this 4682 /// routine does not attempt to convert the object argument. Returns 4683 /// true if the call is ill-formed. 4684 bool 4685 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4686 FunctionDecl *FDecl, 4687 const FunctionProtoType *Proto, 4688 ArrayRef<Expr *> Args, 4689 SourceLocation RParenLoc, 4690 bool IsExecConfig) { 4691 // Bail out early if calling a builtin with custom typechecking. 4692 if (FDecl) 4693 if (unsigned ID = FDecl->getBuiltinID()) 4694 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4695 return false; 4696 4697 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4698 // assignment, to the types of the corresponding parameter, ... 4699 unsigned NumParams = Proto->getNumParams(); 4700 bool Invalid = false; 4701 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4702 unsigned FnKind = Fn->getType()->isBlockPointerType() 4703 ? 1 /* block */ 4704 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4705 : 0 /* function */); 4706 4707 // If too few arguments are available (and we don't have default 4708 // arguments for the remaining parameters), don't make the call. 4709 if (Args.size() < NumParams) { 4710 if (Args.size() < MinArgs) { 4711 TypoCorrection TC; 4712 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4713 unsigned diag_id = 4714 MinArgs == NumParams && !Proto->isVariadic() 4715 ? diag::err_typecheck_call_too_few_args_suggest 4716 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4717 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4718 << static_cast<unsigned>(Args.size()) 4719 << TC.getCorrectionRange()); 4720 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4721 Diag(RParenLoc, 4722 MinArgs == NumParams && !Proto->isVariadic() 4723 ? diag::err_typecheck_call_too_few_args_one 4724 : diag::err_typecheck_call_too_few_args_at_least_one) 4725 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4726 else 4727 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4728 ? diag::err_typecheck_call_too_few_args 4729 : diag::err_typecheck_call_too_few_args_at_least) 4730 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4731 << Fn->getSourceRange(); 4732 4733 // Emit the location of the prototype. 4734 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4735 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4736 << FDecl; 4737 4738 return true; 4739 } 4740 Call->setNumArgs(Context, NumParams); 4741 } 4742 4743 // If too many are passed and not variadic, error on the extras and drop 4744 // them. 4745 if (Args.size() > NumParams) { 4746 if (!Proto->isVariadic()) { 4747 TypoCorrection TC; 4748 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4749 unsigned diag_id = 4750 MinArgs == NumParams && !Proto->isVariadic() 4751 ? diag::err_typecheck_call_too_many_args_suggest 4752 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4753 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4754 << static_cast<unsigned>(Args.size()) 4755 << TC.getCorrectionRange()); 4756 } else if (NumParams == 1 && FDecl && 4757 FDecl->getParamDecl(0)->getDeclName()) 4758 Diag(Args[NumParams]->getLocStart(), 4759 MinArgs == NumParams 4760 ? diag::err_typecheck_call_too_many_args_one 4761 : diag::err_typecheck_call_too_many_args_at_most_one) 4762 << FnKind << FDecl->getParamDecl(0) 4763 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4764 << SourceRange(Args[NumParams]->getLocStart(), 4765 Args.back()->getLocEnd()); 4766 else 4767 Diag(Args[NumParams]->getLocStart(), 4768 MinArgs == NumParams 4769 ? diag::err_typecheck_call_too_many_args 4770 : diag::err_typecheck_call_too_many_args_at_most) 4771 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4772 << Fn->getSourceRange() 4773 << SourceRange(Args[NumParams]->getLocStart(), 4774 Args.back()->getLocEnd()); 4775 4776 // Emit the location of the prototype. 4777 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4778 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4779 << FDecl; 4780 4781 // This deletes the extra arguments. 4782 Call->setNumArgs(Context, NumParams); 4783 return true; 4784 } 4785 } 4786 SmallVector<Expr *, 8> AllArgs; 4787 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4788 4789 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4790 Proto, 0, Args, AllArgs, CallType); 4791 if (Invalid) 4792 return true; 4793 unsigned TotalNumArgs = AllArgs.size(); 4794 for (unsigned i = 0; i < TotalNumArgs; ++i) 4795 Call->setArg(i, AllArgs[i]); 4796 4797 return false; 4798 } 4799 4800 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4801 const FunctionProtoType *Proto, 4802 unsigned FirstParam, ArrayRef<Expr *> Args, 4803 SmallVectorImpl<Expr *> &AllArgs, 4804 VariadicCallType CallType, bool AllowExplicit, 4805 bool IsListInitialization) { 4806 unsigned NumParams = Proto->getNumParams(); 4807 bool Invalid = false; 4808 size_t ArgIx = 0; 4809 // Continue to check argument types (even if we have too few/many args). 4810 for (unsigned i = FirstParam; i < NumParams; i++) { 4811 QualType ProtoArgType = Proto->getParamType(i); 4812 4813 Expr *Arg; 4814 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4815 if (ArgIx < Args.size()) { 4816 Arg = Args[ArgIx++]; 4817 4818 if (RequireCompleteType(Arg->getLocStart(), 4819 ProtoArgType, 4820 diag::err_call_incomplete_argument, Arg)) 4821 return true; 4822 4823 // Strip the unbridged-cast placeholder expression off, if applicable. 4824 bool CFAudited = false; 4825 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4826 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4827 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4828 Arg = stripARCUnbridgedCast(Arg); 4829 else if (getLangOpts().ObjCAutoRefCount && 4830 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4831 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4832 CFAudited = true; 4833 4834 InitializedEntity Entity = 4835 Param ? InitializedEntity::InitializeParameter(Context, Param, 4836 ProtoArgType) 4837 : InitializedEntity::InitializeParameter( 4838 Context, ProtoArgType, Proto->isParamConsumed(i)); 4839 4840 // Remember that parameter belongs to a CF audited API. 4841 if (CFAudited) 4842 Entity.setParameterCFAudited(); 4843 4844 ExprResult ArgE = PerformCopyInitialization( 4845 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4846 if (ArgE.isInvalid()) 4847 return true; 4848 4849 Arg = ArgE.getAs<Expr>(); 4850 } else { 4851 assert(Param && "can't use default arguments without a known callee"); 4852 4853 ExprResult ArgExpr = 4854 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4855 if (ArgExpr.isInvalid()) 4856 return true; 4857 4858 Arg = ArgExpr.getAs<Expr>(); 4859 } 4860 4861 // Check for array bounds violations for each argument to the call. This 4862 // check only triggers warnings when the argument isn't a more complex Expr 4863 // with its own checking, such as a BinaryOperator. 4864 CheckArrayAccess(Arg); 4865 4866 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4867 CheckStaticArrayArgument(CallLoc, Param, Arg); 4868 4869 AllArgs.push_back(Arg); 4870 } 4871 4872 // If this is a variadic call, handle args passed through "...". 4873 if (CallType != VariadicDoesNotApply) { 4874 // Assume that extern "C" functions with variadic arguments that 4875 // return __unknown_anytype aren't *really* variadic. 4876 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4877 FDecl->isExternC()) { 4878 for (Expr *A : Args.slice(ArgIx)) { 4879 QualType paramType; // ignored 4880 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4881 Invalid |= arg.isInvalid(); 4882 AllArgs.push_back(arg.get()); 4883 } 4884 4885 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4886 } else { 4887 for (Expr *A : Args.slice(ArgIx)) { 4888 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4889 Invalid |= Arg.isInvalid(); 4890 AllArgs.push_back(Arg.get()); 4891 } 4892 } 4893 4894 // Check for array bounds violations. 4895 for (Expr *A : Args.slice(ArgIx)) 4896 CheckArrayAccess(A); 4897 } 4898 return Invalid; 4899 } 4900 4901 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4902 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4903 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4904 TL = DTL.getOriginalLoc(); 4905 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4906 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4907 << ATL.getLocalSourceRange(); 4908 } 4909 4910 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4911 /// array parameter, check that it is non-null, and that if it is formed by 4912 /// array-to-pointer decay, the underlying array is sufficiently large. 4913 /// 4914 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4915 /// array type derivation, then for each call to the function, the value of the 4916 /// corresponding actual argument shall provide access to the first element of 4917 /// an array with at least as many elements as specified by the size expression. 4918 void 4919 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4920 ParmVarDecl *Param, 4921 const Expr *ArgExpr) { 4922 // Static array parameters are not supported in C++. 4923 if (!Param || getLangOpts().CPlusPlus) 4924 return; 4925 4926 QualType OrigTy = Param->getOriginalType(); 4927 4928 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4929 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4930 return; 4931 4932 if (ArgExpr->isNullPointerConstant(Context, 4933 Expr::NPC_NeverValueDependent)) { 4934 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4935 DiagnoseCalleeStaticArrayParam(*this, Param); 4936 return; 4937 } 4938 4939 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4940 if (!CAT) 4941 return; 4942 4943 const ConstantArrayType *ArgCAT = 4944 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4945 if (!ArgCAT) 4946 return; 4947 4948 if (ArgCAT->getSize().ult(CAT->getSize())) { 4949 Diag(CallLoc, diag::warn_static_array_too_small) 4950 << ArgExpr->getSourceRange() 4951 << (unsigned) ArgCAT->getSize().getZExtValue() 4952 << (unsigned) CAT->getSize().getZExtValue(); 4953 DiagnoseCalleeStaticArrayParam(*this, Param); 4954 } 4955 } 4956 4957 /// Given a function expression of unknown-any type, try to rebuild it 4958 /// to have a function type. 4959 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4960 4961 /// Is the given type a placeholder that we need to lower out 4962 /// immediately during argument processing? 4963 static bool isPlaceholderToRemoveAsArg(QualType type) { 4964 // Placeholders are never sugared. 4965 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4966 if (!placeholder) return false; 4967 4968 switch (placeholder->getKind()) { 4969 // Ignore all the non-placeholder types. 4970 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4971 case BuiltinType::Id: 4972 #include "clang/Basic/OpenCLImageTypes.def" 4973 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4974 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4975 #include "clang/AST/BuiltinTypes.def" 4976 return false; 4977 4978 // We cannot lower out overload sets; they might validly be resolved 4979 // by the call machinery. 4980 case BuiltinType::Overload: 4981 return false; 4982 4983 // Unbridged casts in ARC can be handled in some call positions and 4984 // should be left in place. 4985 case BuiltinType::ARCUnbridgedCast: 4986 return false; 4987 4988 // Pseudo-objects should be converted as soon as possible. 4989 case BuiltinType::PseudoObject: 4990 return true; 4991 4992 // The debugger mode could theoretically but currently does not try 4993 // to resolve unknown-typed arguments based on known parameter types. 4994 case BuiltinType::UnknownAny: 4995 return true; 4996 4997 // These are always invalid as call arguments and should be reported. 4998 case BuiltinType::BoundMember: 4999 case BuiltinType::BuiltinFn: 5000 case BuiltinType::OMPArraySection: 5001 return true; 5002 5003 } 5004 llvm_unreachable("bad builtin type kind"); 5005 } 5006 5007 /// Check an argument list for placeholders that we won't try to 5008 /// handle later. 5009 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5010 // Apply this processing to all the arguments at once instead of 5011 // dying at the first failure. 5012 bool hasInvalid = false; 5013 for (size_t i = 0, e = args.size(); i != e; i++) { 5014 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5015 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5016 if (result.isInvalid()) hasInvalid = true; 5017 else args[i] = result.get(); 5018 } else if (hasInvalid) { 5019 (void)S.CorrectDelayedTyposInExpr(args[i]); 5020 } 5021 } 5022 return hasInvalid; 5023 } 5024 5025 /// If a builtin function has a pointer argument with no explicit address 5026 /// space, then it should be able to accept a pointer to any address 5027 /// space as input. In order to do this, we need to replace the 5028 /// standard builtin declaration with one that uses the same address space 5029 /// as the call. 5030 /// 5031 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5032 /// it does not contain any pointer arguments without 5033 /// an address space qualifer. Otherwise the rewritten 5034 /// FunctionDecl is returned. 5035 /// TODO: Handle pointer return types. 5036 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5037 const FunctionDecl *FDecl, 5038 MultiExprArg ArgExprs) { 5039 5040 QualType DeclType = FDecl->getType(); 5041 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5042 5043 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5044 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5045 return nullptr; 5046 5047 bool NeedsNewDecl = false; 5048 unsigned i = 0; 5049 SmallVector<QualType, 8> OverloadParams; 5050 5051 for (QualType ParamType : FT->param_types()) { 5052 5053 // Convert array arguments to pointer to simplify type lookup. 5054 ExprResult ArgRes = 5055 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5056 if (ArgRes.isInvalid()) 5057 return nullptr; 5058 Expr *Arg = ArgRes.get(); 5059 QualType ArgType = Arg->getType(); 5060 if (!ParamType->isPointerType() || 5061 ParamType.getQualifiers().hasAddressSpace() || 5062 !ArgType->isPointerType() || 5063 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5064 OverloadParams.push_back(ParamType); 5065 continue; 5066 } 5067 5068 NeedsNewDecl = true; 5069 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5070 5071 QualType PointeeType = ParamType->getPointeeType(); 5072 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5073 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5074 } 5075 5076 if (!NeedsNewDecl) 5077 return nullptr; 5078 5079 FunctionProtoType::ExtProtoInfo EPI; 5080 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5081 OverloadParams, EPI); 5082 DeclContext *Parent = Context.getTranslationUnitDecl(); 5083 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5084 FDecl->getLocation(), 5085 FDecl->getLocation(), 5086 FDecl->getIdentifier(), 5087 OverloadTy, 5088 /*TInfo=*/nullptr, 5089 SC_Extern, false, 5090 /*hasPrototype=*/true); 5091 SmallVector<ParmVarDecl*, 16> Params; 5092 FT = cast<FunctionProtoType>(OverloadTy); 5093 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5094 QualType ParamType = FT->getParamType(i); 5095 ParmVarDecl *Parm = 5096 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5097 SourceLocation(), nullptr, ParamType, 5098 /*TInfo=*/nullptr, SC_None, nullptr); 5099 Parm->setScopeInfo(0, i); 5100 Params.push_back(Parm); 5101 } 5102 OverloadDecl->setParams(Params); 5103 return OverloadDecl; 5104 } 5105 5106 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee, 5107 std::size_t NumArgs) { 5108 if (S.TooManyArguments(Callee->getNumParams(), NumArgs, 5109 /*PartialOverloading=*/false)) 5110 return Callee->isVariadic(); 5111 return Callee->getMinRequiredArguments() <= NumArgs; 5112 } 5113 5114 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5115 /// This provides the location of the left/right parens and a list of comma 5116 /// locations. 5117 ExprResult 5118 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5119 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5120 Expr *ExecConfig, bool IsExecConfig) { 5121 // Since this might be a postfix expression, get rid of ParenListExprs. 5122 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 5123 if (Result.isInvalid()) return ExprError(); 5124 Fn = Result.get(); 5125 5126 if (checkArgsForPlaceholders(*this, ArgExprs)) 5127 return ExprError(); 5128 5129 if (getLangOpts().CPlusPlus) { 5130 // If this is a pseudo-destructor expression, build the call immediately. 5131 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5132 if (!ArgExprs.empty()) { 5133 // Pseudo-destructor calls should not have any arguments. 5134 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5135 << FixItHint::CreateRemoval( 5136 SourceRange(ArgExprs.front()->getLocStart(), 5137 ArgExprs.back()->getLocEnd())); 5138 } 5139 5140 return new (Context) 5141 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5142 } 5143 if (Fn->getType() == Context.PseudoObjectTy) { 5144 ExprResult result = CheckPlaceholderExpr(Fn); 5145 if (result.isInvalid()) return ExprError(); 5146 Fn = result.get(); 5147 } 5148 5149 // Determine whether this is a dependent call inside a C++ template, 5150 // in which case we won't do any semantic analysis now. 5151 bool Dependent = false; 5152 if (Fn->isTypeDependent()) 5153 Dependent = true; 5154 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5155 Dependent = true; 5156 5157 if (Dependent) { 5158 if (ExecConfig) { 5159 return new (Context) CUDAKernelCallExpr( 5160 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5161 Context.DependentTy, VK_RValue, RParenLoc); 5162 } else { 5163 return new (Context) CallExpr( 5164 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5165 } 5166 } 5167 5168 // Determine whether this is a call to an object (C++ [over.call.object]). 5169 if (Fn->getType()->isRecordType()) 5170 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 5171 RParenLoc); 5172 5173 if (Fn->getType() == Context.UnknownAnyTy) { 5174 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5175 if (result.isInvalid()) return ExprError(); 5176 Fn = result.get(); 5177 } 5178 5179 if (Fn->getType() == Context.BoundMemberTy) { 5180 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5181 } 5182 } 5183 5184 // Check for overloaded calls. This can happen even in C due to extensions. 5185 if (Fn->getType() == Context.OverloadTy) { 5186 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5187 5188 // We aren't supposed to apply this logic for if there's an '&' involved. 5189 if (!find.HasFormOfMemberPointer) { 5190 OverloadExpr *ovl = find.Expression; 5191 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5192 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 5193 RParenLoc, ExecConfig, 5194 /*AllowTypoCorrection=*/true, 5195 find.IsAddressOfOperand); 5196 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5197 } 5198 } 5199 5200 // If we're directly calling a function, get the appropriate declaration. 5201 if (Fn->getType() == Context.UnknownAnyTy) { 5202 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5203 if (result.isInvalid()) return ExprError(); 5204 Fn = result.get(); 5205 } 5206 5207 Expr *NakedFn = Fn->IgnoreParens(); 5208 5209 bool CallingNDeclIndirectly = false; 5210 NamedDecl *NDecl = nullptr; 5211 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5212 if (UnOp->getOpcode() == UO_AddrOf) { 5213 CallingNDeclIndirectly = true; 5214 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5215 } 5216 } 5217 5218 if (isa<DeclRefExpr>(NakedFn)) { 5219 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5220 5221 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5222 if (FDecl && FDecl->getBuiltinID()) { 5223 // Rewrite the function decl for this builtin by replacing parameters 5224 // with no explicit address space with the address space of the arguments 5225 // in ArgExprs. 5226 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5227 NDecl = FDecl; 5228 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 5229 SourceLocation(), FDecl, false, 5230 SourceLocation(), FDecl->getType(), 5231 Fn->getValueKind(), FDecl); 5232 } 5233 } 5234 } else if (isa<MemberExpr>(NakedFn)) 5235 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5236 5237 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5238 if (CallingNDeclIndirectly && 5239 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5240 Fn->getLocStart())) 5241 return ExprError(); 5242 5243 // CheckEnableIf assumes that the we're passing in a sane number of args for 5244 // FD, but that doesn't always hold true here. This is because, in some 5245 // cases, we'll emit a diag about an ill-formed function call, but then 5246 // we'll continue on as if the function call wasn't ill-formed. So, if the 5247 // number of args looks incorrect, don't do enable_if checks; we should've 5248 // already emitted an error about the bad call. 5249 if (FD->hasAttr<EnableIfAttr>() && 5250 isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) { 5251 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5252 Diag(Fn->getLocStart(), 5253 isa<CXXMethodDecl>(FD) ? 5254 diag::err_ovl_no_viable_member_function_in_call : 5255 diag::err_ovl_no_viable_function_in_call) 5256 << FD << FD->getSourceRange(); 5257 Diag(FD->getLocation(), 5258 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5259 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5260 } 5261 } 5262 } 5263 5264 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5265 ExecConfig, IsExecConfig); 5266 } 5267 5268 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5269 /// 5270 /// __builtin_astype( value, dst type ) 5271 /// 5272 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5273 SourceLocation BuiltinLoc, 5274 SourceLocation RParenLoc) { 5275 ExprValueKind VK = VK_RValue; 5276 ExprObjectKind OK = OK_Ordinary; 5277 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5278 QualType SrcTy = E->getType(); 5279 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5280 return ExprError(Diag(BuiltinLoc, 5281 diag::err_invalid_astype_of_different_size) 5282 << DstTy 5283 << SrcTy 5284 << E->getSourceRange()); 5285 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5286 } 5287 5288 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5289 /// provided arguments. 5290 /// 5291 /// __builtin_convertvector( value, dst type ) 5292 /// 5293 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5294 SourceLocation BuiltinLoc, 5295 SourceLocation RParenLoc) { 5296 TypeSourceInfo *TInfo; 5297 GetTypeFromParser(ParsedDestTy, &TInfo); 5298 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5299 } 5300 5301 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5302 /// i.e. an expression not of \p OverloadTy. The expression should 5303 /// unary-convert to an expression of function-pointer or 5304 /// block-pointer type. 5305 /// 5306 /// \param NDecl the declaration being called, if available 5307 ExprResult 5308 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5309 SourceLocation LParenLoc, 5310 ArrayRef<Expr *> Args, 5311 SourceLocation RParenLoc, 5312 Expr *Config, bool IsExecConfig) { 5313 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5314 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5315 5316 // Functions with 'interrupt' attribute cannot be called directly. 5317 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5318 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5319 return ExprError(); 5320 } 5321 5322 // Promote the function operand. 5323 // We special-case function promotion here because we only allow promoting 5324 // builtin functions to function pointers in the callee of a call. 5325 ExprResult Result; 5326 if (BuiltinID && 5327 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5328 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5329 CK_BuiltinFnToFnPtr).get(); 5330 } else { 5331 Result = CallExprUnaryConversions(Fn); 5332 } 5333 if (Result.isInvalid()) 5334 return ExprError(); 5335 Fn = Result.get(); 5336 5337 // Make the call expr early, before semantic checks. This guarantees cleanup 5338 // of arguments and function on error. 5339 CallExpr *TheCall; 5340 if (Config) 5341 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5342 cast<CallExpr>(Config), Args, 5343 Context.BoolTy, VK_RValue, 5344 RParenLoc); 5345 else 5346 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5347 VK_RValue, RParenLoc); 5348 5349 if (!getLangOpts().CPlusPlus) { 5350 // C cannot always handle TypoExpr nodes in builtin calls and direct 5351 // function calls as their argument checking don't necessarily handle 5352 // dependent types properly, so make sure any TypoExprs have been 5353 // dealt with. 5354 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5355 if (!Result.isUsable()) return ExprError(); 5356 TheCall = dyn_cast<CallExpr>(Result.get()); 5357 if (!TheCall) return Result; 5358 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5359 } 5360 5361 // Bail out early if calling a builtin with custom typechecking. 5362 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5363 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5364 5365 retry: 5366 const FunctionType *FuncT; 5367 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5368 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5369 // have type pointer to function". 5370 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5371 if (!FuncT) 5372 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5373 << Fn->getType() << Fn->getSourceRange()); 5374 } else if (const BlockPointerType *BPT = 5375 Fn->getType()->getAs<BlockPointerType>()) { 5376 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5377 } else { 5378 // Handle calls to expressions of unknown-any type. 5379 if (Fn->getType() == Context.UnknownAnyTy) { 5380 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5381 if (rewrite.isInvalid()) return ExprError(); 5382 Fn = rewrite.get(); 5383 TheCall->setCallee(Fn); 5384 goto retry; 5385 } 5386 5387 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5388 << Fn->getType() << Fn->getSourceRange()); 5389 } 5390 5391 if (getLangOpts().CUDA) { 5392 if (Config) { 5393 // CUDA: Kernel calls must be to global functions 5394 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5395 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5396 << FDecl->getName() << Fn->getSourceRange()); 5397 5398 // CUDA: Kernel function must have 'void' return type 5399 if (!FuncT->getReturnType()->isVoidType()) 5400 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5401 << Fn->getType() << Fn->getSourceRange()); 5402 } else { 5403 // CUDA: Calls to global functions must be configured 5404 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5405 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5406 << FDecl->getName() << Fn->getSourceRange()); 5407 } 5408 } 5409 5410 // Check for a valid return type 5411 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5412 FDecl)) 5413 return ExprError(); 5414 5415 // We know the result type of the call, set it. 5416 TheCall->setType(FuncT->getCallResultType(Context)); 5417 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5418 5419 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5420 if (Proto) { 5421 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5422 IsExecConfig)) 5423 return ExprError(); 5424 } else { 5425 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5426 5427 if (FDecl) { 5428 // Check if we have too few/too many template arguments, based 5429 // on our knowledge of the function definition. 5430 const FunctionDecl *Def = nullptr; 5431 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5432 Proto = Def->getType()->getAs<FunctionProtoType>(); 5433 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5434 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5435 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5436 } 5437 5438 // If the function we're calling isn't a function prototype, but we have 5439 // a function prototype from a prior declaratiom, use that prototype. 5440 if (!FDecl->hasPrototype()) 5441 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5442 } 5443 5444 // Promote the arguments (C99 6.5.2.2p6). 5445 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5446 Expr *Arg = Args[i]; 5447 5448 if (Proto && i < Proto->getNumParams()) { 5449 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5450 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5451 ExprResult ArgE = 5452 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5453 if (ArgE.isInvalid()) 5454 return true; 5455 5456 Arg = ArgE.getAs<Expr>(); 5457 5458 } else { 5459 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5460 5461 if (ArgE.isInvalid()) 5462 return true; 5463 5464 Arg = ArgE.getAs<Expr>(); 5465 } 5466 5467 if (RequireCompleteType(Arg->getLocStart(), 5468 Arg->getType(), 5469 diag::err_call_incomplete_argument, Arg)) 5470 return ExprError(); 5471 5472 TheCall->setArg(i, Arg); 5473 } 5474 } 5475 5476 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5477 if (!Method->isStatic()) 5478 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5479 << Fn->getSourceRange()); 5480 5481 // Check for sentinels 5482 if (NDecl) 5483 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5484 5485 // Do special checking on direct calls to functions. 5486 if (FDecl) { 5487 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5488 return ExprError(); 5489 5490 if (BuiltinID) 5491 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5492 } else if (NDecl) { 5493 if (CheckPointerCall(NDecl, TheCall, Proto)) 5494 return ExprError(); 5495 } else { 5496 if (CheckOtherCall(TheCall, Proto)) 5497 return ExprError(); 5498 } 5499 5500 return MaybeBindToTemporary(TheCall); 5501 } 5502 5503 ExprResult 5504 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5505 SourceLocation RParenLoc, Expr *InitExpr) { 5506 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5507 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5508 5509 TypeSourceInfo *TInfo; 5510 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5511 if (!TInfo) 5512 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5513 5514 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5515 } 5516 5517 ExprResult 5518 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5519 SourceLocation RParenLoc, Expr *LiteralExpr) { 5520 QualType literalType = TInfo->getType(); 5521 5522 if (literalType->isArrayType()) { 5523 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5524 diag::err_illegal_decl_array_incomplete_type, 5525 SourceRange(LParenLoc, 5526 LiteralExpr->getSourceRange().getEnd()))) 5527 return ExprError(); 5528 if (literalType->isVariableArrayType()) 5529 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5530 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5531 } else if (!literalType->isDependentType() && 5532 RequireCompleteType(LParenLoc, literalType, 5533 diag::err_typecheck_decl_incomplete_type, 5534 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5535 return ExprError(); 5536 5537 InitializedEntity Entity 5538 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5539 InitializationKind Kind 5540 = InitializationKind::CreateCStyleCast(LParenLoc, 5541 SourceRange(LParenLoc, RParenLoc), 5542 /*InitList=*/true); 5543 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5544 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5545 &literalType); 5546 if (Result.isInvalid()) 5547 return ExprError(); 5548 LiteralExpr = Result.get(); 5549 5550 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5551 if (isFileScope && 5552 !LiteralExpr->isTypeDependent() && 5553 !LiteralExpr->isValueDependent() && 5554 !literalType->isDependentType()) { // 6.5.2.5p3 5555 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5556 return ExprError(); 5557 } 5558 5559 // In C, compound literals are l-values for some reason. 5560 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5561 5562 return MaybeBindToTemporary( 5563 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5564 VK, LiteralExpr, isFileScope)); 5565 } 5566 5567 ExprResult 5568 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5569 SourceLocation RBraceLoc) { 5570 // Immediately handle non-overload placeholders. Overloads can be 5571 // resolved contextually, but everything else here can't. 5572 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5573 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5574 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5575 5576 // Ignore failures; dropping the entire initializer list because 5577 // of one failure would be terrible for indexing/etc. 5578 if (result.isInvalid()) continue; 5579 5580 InitArgList[I] = result.get(); 5581 } 5582 } 5583 5584 // Semantic analysis for initializers is done by ActOnDeclarator() and 5585 // CheckInitializer() - it requires knowledge of the object being intialized. 5586 5587 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5588 RBraceLoc); 5589 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5590 return E; 5591 } 5592 5593 /// Do an explicit extend of the given block pointer if we're in ARC. 5594 void Sema::maybeExtendBlockObject(ExprResult &E) { 5595 assert(E.get()->getType()->isBlockPointerType()); 5596 assert(E.get()->isRValue()); 5597 5598 // Only do this in an r-value context. 5599 if (!getLangOpts().ObjCAutoRefCount) return; 5600 5601 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5602 CK_ARCExtendBlockObject, E.get(), 5603 /*base path*/ nullptr, VK_RValue); 5604 Cleanup.setExprNeedsCleanups(true); 5605 } 5606 5607 /// Prepare a conversion of the given expression to an ObjC object 5608 /// pointer type. 5609 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5610 QualType type = E.get()->getType(); 5611 if (type->isObjCObjectPointerType()) { 5612 return CK_BitCast; 5613 } else if (type->isBlockPointerType()) { 5614 maybeExtendBlockObject(E); 5615 return CK_BlockPointerToObjCPointerCast; 5616 } else { 5617 assert(type->isPointerType()); 5618 return CK_CPointerToObjCPointerCast; 5619 } 5620 } 5621 5622 /// Prepares for a scalar cast, performing all the necessary stages 5623 /// except the final cast and returning the kind required. 5624 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5625 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5626 // Also, callers should have filtered out the invalid cases with 5627 // pointers. Everything else should be possible. 5628 5629 QualType SrcTy = Src.get()->getType(); 5630 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5631 return CK_NoOp; 5632 5633 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5634 case Type::STK_MemberPointer: 5635 llvm_unreachable("member pointer type in C"); 5636 5637 case Type::STK_CPointer: 5638 case Type::STK_BlockPointer: 5639 case Type::STK_ObjCObjectPointer: 5640 switch (DestTy->getScalarTypeKind()) { 5641 case Type::STK_CPointer: { 5642 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5643 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5644 if (SrcAS != DestAS) 5645 return CK_AddressSpaceConversion; 5646 return CK_BitCast; 5647 } 5648 case Type::STK_BlockPointer: 5649 return (SrcKind == Type::STK_BlockPointer 5650 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5651 case Type::STK_ObjCObjectPointer: 5652 if (SrcKind == Type::STK_ObjCObjectPointer) 5653 return CK_BitCast; 5654 if (SrcKind == Type::STK_CPointer) 5655 return CK_CPointerToObjCPointerCast; 5656 maybeExtendBlockObject(Src); 5657 return CK_BlockPointerToObjCPointerCast; 5658 case Type::STK_Bool: 5659 return CK_PointerToBoolean; 5660 case Type::STK_Integral: 5661 return CK_PointerToIntegral; 5662 case Type::STK_Floating: 5663 case Type::STK_FloatingComplex: 5664 case Type::STK_IntegralComplex: 5665 case Type::STK_MemberPointer: 5666 llvm_unreachable("illegal cast from pointer"); 5667 } 5668 llvm_unreachable("Should have returned before this"); 5669 5670 case Type::STK_Bool: // casting from bool is like casting from an integer 5671 case Type::STK_Integral: 5672 switch (DestTy->getScalarTypeKind()) { 5673 case Type::STK_CPointer: 5674 case Type::STK_ObjCObjectPointer: 5675 case Type::STK_BlockPointer: 5676 if (Src.get()->isNullPointerConstant(Context, 5677 Expr::NPC_ValueDependentIsNull)) 5678 return CK_NullToPointer; 5679 return CK_IntegralToPointer; 5680 case Type::STK_Bool: 5681 return CK_IntegralToBoolean; 5682 case Type::STK_Integral: 5683 return CK_IntegralCast; 5684 case Type::STK_Floating: 5685 return CK_IntegralToFloating; 5686 case Type::STK_IntegralComplex: 5687 Src = ImpCastExprToType(Src.get(), 5688 DestTy->castAs<ComplexType>()->getElementType(), 5689 CK_IntegralCast); 5690 return CK_IntegralRealToComplex; 5691 case Type::STK_FloatingComplex: 5692 Src = ImpCastExprToType(Src.get(), 5693 DestTy->castAs<ComplexType>()->getElementType(), 5694 CK_IntegralToFloating); 5695 return CK_FloatingRealToComplex; 5696 case Type::STK_MemberPointer: 5697 llvm_unreachable("member pointer type in C"); 5698 } 5699 llvm_unreachable("Should have returned before this"); 5700 5701 case Type::STK_Floating: 5702 switch (DestTy->getScalarTypeKind()) { 5703 case Type::STK_Floating: 5704 return CK_FloatingCast; 5705 case Type::STK_Bool: 5706 return CK_FloatingToBoolean; 5707 case Type::STK_Integral: 5708 return CK_FloatingToIntegral; 5709 case Type::STK_FloatingComplex: 5710 Src = ImpCastExprToType(Src.get(), 5711 DestTy->castAs<ComplexType>()->getElementType(), 5712 CK_FloatingCast); 5713 return CK_FloatingRealToComplex; 5714 case Type::STK_IntegralComplex: 5715 Src = ImpCastExprToType(Src.get(), 5716 DestTy->castAs<ComplexType>()->getElementType(), 5717 CK_FloatingToIntegral); 5718 return CK_IntegralRealToComplex; 5719 case Type::STK_CPointer: 5720 case Type::STK_ObjCObjectPointer: 5721 case Type::STK_BlockPointer: 5722 llvm_unreachable("valid float->pointer cast?"); 5723 case Type::STK_MemberPointer: 5724 llvm_unreachable("member pointer type in C"); 5725 } 5726 llvm_unreachable("Should have returned before this"); 5727 5728 case Type::STK_FloatingComplex: 5729 switch (DestTy->getScalarTypeKind()) { 5730 case Type::STK_FloatingComplex: 5731 return CK_FloatingComplexCast; 5732 case Type::STK_IntegralComplex: 5733 return CK_FloatingComplexToIntegralComplex; 5734 case Type::STK_Floating: { 5735 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5736 if (Context.hasSameType(ET, DestTy)) 5737 return CK_FloatingComplexToReal; 5738 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5739 return CK_FloatingCast; 5740 } 5741 case Type::STK_Bool: 5742 return CK_FloatingComplexToBoolean; 5743 case Type::STK_Integral: 5744 Src = ImpCastExprToType(Src.get(), 5745 SrcTy->castAs<ComplexType>()->getElementType(), 5746 CK_FloatingComplexToReal); 5747 return CK_FloatingToIntegral; 5748 case Type::STK_CPointer: 5749 case Type::STK_ObjCObjectPointer: 5750 case Type::STK_BlockPointer: 5751 llvm_unreachable("valid complex float->pointer cast?"); 5752 case Type::STK_MemberPointer: 5753 llvm_unreachable("member pointer type in C"); 5754 } 5755 llvm_unreachable("Should have returned before this"); 5756 5757 case Type::STK_IntegralComplex: 5758 switch (DestTy->getScalarTypeKind()) { 5759 case Type::STK_FloatingComplex: 5760 return CK_IntegralComplexToFloatingComplex; 5761 case Type::STK_IntegralComplex: 5762 return CK_IntegralComplexCast; 5763 case Type::STK_Integral: { 5764 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5765 if (Context.hasSameType(ET, DestTy)) 5766 return CK_IntegralComplexToReal; 5767 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5768 return CK_IntegralCast; 5769 } 5770 case Type::STK_Bool: 5771 return CK_IntegralComplexToBoolean; 5772 case Type::STK_Floating: 5773 Src = ImpCastExprToType(Src.get(), 5774 SrcTy->castAs<ComplexType>()->getElementType(), 5775 CK_IntegralComplexToReal); 5776 return CK_IntegralToFloating; 5777 case Type::STK_CPointer: 5778 case Type::STK_ObjCObjectPointer: 5779 case Type::STK_BlockPointer: 5780 llvm_unreachable("valid complex int->pointer cast?"); 5781 case Type::STK_MemberPointer: 5782 llvm_unreachable("member pointer type in C"); 5783 } 5784 llvm_unreachable("Should have returned before this"); 5785 } 5786 5787 llvm_unreachable("Unhandled scalar cast"); 5788 } 5789 5790 static bool breakDownVectorType(QualType type, uint64_t &len, 5791 QualType &eltType) { 5792 // Vectors are simple. 5793 if (const VectorType *vecType = type->getAs<VectorType>()) { 5794 len = vecType->getNumElements(); 5795 eltType = vecType->getElementType(); 5796 assert(eltType->isScalarType()); 5797 return true; 5798 } 5799 5800 // We allow lax conversion to and from non-vector types, but only if 5801 // they're real types (i.e. non-complex, non-pointer scalar types). 5802 if (!type->isRealType()) return false; 5803 5804 len = 1; 5805 eltType = type; 5806 return true; 5807 } 5808 5809 /// Are the two types lax-compatible vector types? That is, given 5810 /// that one of them is a vector, do they have equal storage sizes, 5811 /// where the storage size is the number of elements times the element 5812 /// size? 5813 /// 5814 /// This will also return false if either of the types is neither a 5815 /// vector nor a real type. 5816 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5817 assert(destTy->isVectorType() || srcTy->isVectorType()); 5818 5819 // Disallow lax conversions between scalars and ExtVectors (these 5820 // conversions are allowed for other vector types because common headers 5821 // depend on them). Most scalar OP ExtVector cases are handled by the 5822 // splat path anyway, which does what we want (convert, not bitcast). 5823 // What this rules out for ExtVectors is crazy things like char4*float. 5824 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5825 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5826 5827 uint64_t srcLen, destLen; 5828 QualType srcEltTy, destEltTy; 5829 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5830 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5831 5832 // ASTContext::getTypeSize will return the size rounded up to a 5833 // power of 2, so instead of using that, we need to use the raw 5834 // element size multiplied by the element count. 5835 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5836 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5837 5838 return (srcLen * srcEltSize == destLen * destEltSize); 5839 } 5840 5841 /// Is this a legal conversion between two types, one of which is 5842 /// known to be a vector type? 5843 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5844 assert(destTy->isVectorType() || srcTy->isVectorType()); 5845 5846 if (!Context.getLangOpts().LaxVectorConversions) 5847 return false; 5848 return areLaxCompatibleVectorTypes(srcTy, destTy); 5849 } 5850 5851 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5852 CastKind &Kind) { 5853 assert(VectorTy->isVectorType() && "Not a vector type!"); 5854 5855 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5856 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5857 return Diag(R.getBegin(), 5858 Ty->isVectorType() ? 5859 diag::err_invalid_conversion_between_vectors : 5860 diag::err_invalid_conversion_between_vector_and_integer) 5861 << VectorTy << Ty << R; 5862 } else 5863 return Diag(R.getBegin(), 5864 diag::err_invalid_conversion_between_vector_and_scalar) 5865 << VectorTy << Ty << R; 5866 5867 Kind = CK_BitCast; 5868 return false; 5869 } 5870 5871 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5872 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5873 5874 if (DestElemTy == SplattedExpr->getType()) 5875 return SplattedExpr; 5876 5877 assert(DestElemTy->isFloatingType() || 5878 DestElemTy->isIntegralOrEnumerationType()); 5879 5880 CastKind CK; 5881 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5882 // OpenCL requires that we convert `true` boolean expressions to -1, but 5883 // only when splatting vectors. 5884 if (DestElemTy->isFloatingType()) { 5885 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5886 // in two steps: boolean to signed integral, then to floating. 5887 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5888 CK_BooleanToSignedIntegral); 5889 SplattedExpr = CastExprRes.get(); 5890 CK = CK_IntegralToFloating; 5891 } else { 5892 CK = CK_BooleanToSignedIntegral; 5893 } 5894 } else { 5895 ExprResult CastExprRes = SplattedExpr; 5896 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5897 if (CastExprRes.isInvalid()) 5898 return ExprError(); 5899 SplattedExpr = CastExprRes.get(); 5900 } 5901 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5902 } 5903 5904 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5905 Expr *CastExpr, CastKind &Kind) { 5906 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5907 5908 QualType SrcTy = CastExpr->getType(); 5909 5910 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5911 // an ExtVectorType. 5912 // In OpenCL, casts between vectors of different types are not allowed. 5913 // (See OpenCL 6.2). 5914 if (SrcTy->isVectorType()) { 5915 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5916 || (getLangOpts().OpenCL && 5917 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5918 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5919 << DestTy << SrcTy << R; 5920 return ExprError(); 5921 } 5922 Kind = CK_BitCast; 5923 return CastExpr; 5924 } 5925 5926 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5927 // conversion will take place first from scalar to elt type, and then 5928 // splat from elt type to vector. 5929 if (SrcTy->isPointerType()) 5930 return Diag(R.getBegin(), 5931 diag::err_invalid_conversion_between_vector_and_scalar) 5932 << DestTy << SrcTy << R; 5933 5934 Kind = CK_VectorSplat; 5935 return prepareVectorSplat(DestTy, CastExpr); 5936 } 5937 5938 ExprResult 5939 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5940 Declarator &D, ParsedType &Ty, 5941 SourceLocation RParenLoc, Expr *CastExpr) { 5942 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5943 "ActOnCastExpr(): missing type or expr"); 5944 5945 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5946 if (D.isInvalidType()) 5947 return ExprError(); 5948 5949 if (getLangOpts().CPlusPlus) { 5950 // Check that there are no default arguments (C++ only). 5951 CheckExtraCXXDefaultArguments(D); 5952 } else { 5953 // Make sure any TypoExprs have been dealt with. 5954 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5955 if (!Res.isUsable()) 5956 return ExprError(); 5957 CastExpr = Res.get(); 5958 } 5959 5960 checkUnusedDeclAttributes(D); 5961 5962 QualType castType = castTInfo->getType(); 5963 Ty = CreateParsedType(castType, castTInfo); 5964 5965 bool isVectorLiteral = false; 5966 5967 // Check for an altivec or OpenCL literal, 5968 // i.e. all the elements are integer constants. 5969 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5970 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5971 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5972 && castType->isVectorType() && (PE || PLE)) { 5973 if (PLE && PLE->getNumExprs() == 0) { 5974 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5975 return ExprError(); 5976 } 5977 if (PE || PLE->getNumExprs() == 1) { 5978 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5979 if (!E->getType()->isVectorType()) 5980 isVectorLiteral = true; 5981 } 5982 else 5983 isVectorLiteral = true; 5984 } 5985 5986 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5987 // then handle it as such. 5988 if (isVectorLiteral) 5989 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5990 5991 // If the Expr being casted is a ParenListExpr, handle it specially. 5992 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5993 // sequence of BinOp comma operators. 5994 if (isa<ParenListExpr>(CastExpr)) { 5995 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5996 if (Result.isInvalid()) return ExprError(); 5997 CastExpr = Result.get(); 5998 } 5999 6000 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6001 !getSourceManager().isInSystemMacro(LParenLoc)) 6002 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6003 6004 CheckTollFreeBridgeCast(castType, CastExpr); 6005 6006 CheckObjCBridgeRelatedCast(castType, CastExpr); 6007 6008 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6009 } 6010 6011 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6012 SourceLocation RParenLoc, Expr *E, 6013 TypeSourceInfo *TInfo) { 6014 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6015 "Expected paren or paren list expression"); 6016 6017 Expr **exprs; 6018 unsigned numExprs; 6019 Expr *subExpr; 6020 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6021 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6022 LiteralLParenLoc = PE->getLParenLoc(); 6023 LiteralRParenLoc = PE->getRParenLoc(); 6024 exprs = PE->getExprs(); 6025 numExprs = PE->getNumExprs(); 6026 } else { // isa<ParenExpr> by assertion at function entrance 6027 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6028 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6029 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6030 exprs = &subExpr; 6031 numExprs = 1; 6032 } 6033 6034 QualType Ty = TInfo->getType(); 6035 assert(Ty->isVectorType() && "Expected vector type"); 6036 6037 SmallVector<Expr *, 8> initExprs; 6038 const VectorType *VTy = Ty->getAs<VectorType>(); 6039 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6040 6041 // '(...)' form of vector initialization in AltiVec: the number of 6042 // initializers must be one or must match the size of the vector. 6043 // If a single value is specified in the initializer then it will be 6044 // replicated to all the components of the vector 6045 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6046 // The number of initializers must be one or must match the size of the 6047 // vector. If a single value is specified in the initializer then it will 6048 // be replicated to all the components of the vector 6049 if (numExprs == 1) { 6050 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6051 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6052 if (Literal.isInvalid()) 6053 return ExprError(); 6054 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6055 PrepareScalarCast(Literal, ElemTy)); 6056 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6057 } 6058 else if (numExprs < numElems) { 6059 Diag(E->getExprLoc(), 6060 diag::err_incorrect_number_of_vector_initializers); 6061 return ExprError(); 6062 } 6063 else 6064 initExprs.append(exprs, exprs + numExprs); 6065 } 6066 else { 6067 // For OpenCL, when the number of initializers is a single value, 6068 // it will be replicated to all components of the vector. 6069 if (getLangOpts().OpenCL && 6070 VTy->getVectorKind() == VectorType::GenericVector && 6071 numExprs == 1) { 6072 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6073 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6074 if (Literal.isInvalid()) 6075 return ExprError(); 6076 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6077 PrepareScalarCast(Literal, ElemTy)); 6078 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6079 } 6080 6081 initExprs.append(exprs, exprs + numExprs); 6082 } 6083 // FIXME: This means that pretty-printing the final AST will produce curly 6084 // braces instead of the original commas. 6085 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6086 initExprs, LiteralRParenLoc); 6087 initE->setType(Ty); 6088 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6089 } 6090 6091 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6092 /// the ParenListExpr into a sequence of comma binary operators. 6093 ExprResult 6094 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6095 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6096 if (!E) 6097 return OrigExpr; 6098 6099 ExprResult Result(E->getExpr(0)); 6100 6101 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6102 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6103 E->getExpr(i)); 6104 6105 if (Result.isInvalid()) return ExprError(); 6106 6107 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6108 } 6109 6110 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6111 SourceLocation R, 6112 MultiExprArg Val) { 6113 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6114 return expr; 6115 } 6116 6117 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6118 /// constant and the other is not a pointer. Returns true if a diagnostic is 6119 /// emitted. 6120 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6121 SourceLocation QuestionLoc) { 6122 Expr *NullExpr = LHSExpr; 6123 Expr *NonPointerExpr = RHSExpr; 6124 Expr::NullPointerConstantKind NullKind = 6125 NullExpr->isNullPointerConstant(Context, 6126 Expr::NPC_ValueDependentIsNotNull); 6127 6128 if (NullKind == Expr::NPCK_NotNull) { 6129 NullExpr = RHSExpr; 6130 NonPointerExpr = LHSExpr; 6131 NullKind = 6132 NullExpr->isNullPointerConstant(Context, 6133 Expr::NPC_ValueDependentIsNotNull); 6134 } 6135 6136 if (NullKind == Expr::NPCK_NotNull) 6137 return false; 6138 6139 if (NullKind == Expr::NPCK_ZeroExpression) 6140 return false; 6141 6142 if (NullKind == Expr::NPCK_ZeroLiteral) { 6143 // In this case, check to make sure that we got here from a "NULL" 6144 // string in the source code. 6145 NullExpr = NullExpr->IgnoreParenImpCasts(); 6146 SourceLocation loc = NullExpr->getExprLoc(); 6147 if (!findMacroSpelling(loc, "NULL")) 6148 return false; 6149 } 6150 6151 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6152 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6153 << NonPointerExpr->getType() << DiagType 6154 << NonPointerExpr->getSourceRange(); 6155 return true; 6156 } 6157 6158 /// \brief Return false if the condition expression is valid, true otherwise. 6159 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6160 QualType CondTy = Cond->getType(); 6161 6162 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6163 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6164 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6165 << CondTy << Cond->getSourceRange(); 6166 return true; 6167 } 6168 6169 // C99 6.5.15p2 6170 if (CondTy->isScalarType()) return false; 6171 6172 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6173 << CondTy << Cond->getSourceRange(); 6174 return true; 6175 } 6176 6177 /// \brief Handle when one or both operands are void type. 6178 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6179 ExprResult &RHS) { 6180 Expr *LHSExpr = LHS.get(); 6181 Expr *RHSExpr = RHS.get(); 6182 6183 if (!LHSExpr->getType()->isVoidType()) 6184 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6185 << RHSExpr->getSourceRange(); 6186 if (!RHSExpr->getType()->isVoidType()) 6187 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6188 << LHSExpr->getSourceRange(); 6189 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6190 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6191 return S.Context.VoidTy; 6192 } 6193 6194 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6195 /// true otherwise. 6196 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6197 QualType PointerTy) { 6198 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6199 !NullExpr.get()->isNullPointerConstant(S.Context, 6200 Expr::NPC_ValueDependentIsNull)) 6201 return true; 6202 6203 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6204 return false; 6205 } 6206 6207 /// \brief Checks compatibility between two pointers and return the resulting 6208 /// type. 6209 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6210 ExprResult &RHS, 6211 SourceLocation Loc) { 6212 QualType LHSTy = LHS.get()->getType(); 6213 QualType RHSTy = RHS.get()->getType(); 6214 6215 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6216 // Two identical pointers types are always compatible. 6217 return LHSTy; 6218 } 6219 6220 QualType lhptee, rhptee; 6221 6222 // Get the pointee types. 6223 bool IsBlockPointer = false; 6224 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6225 lhptee = LHSBTy->getPointeeType(); 6226 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6227 IsBlockPointer = true; 6228 } else { 6229 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6230 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6231 } 6232 6233 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6234 // differently qualified versions of compatible types, the result type is 6235 // a pointer to an appropriately qualified version of the composite 6236 // type. 6237 6238 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6239 // clause doesn't make sense for our extensions. E.g. address space 2 should 6240 // be incompatible with address space 3: they may live on different devices or 6241 // anything. 6242 Qualifiers lhQual = lhptee.getQualifiers(); 6243 Qualifiers rhQual = rhptee.getQualifiers(); 6244 6245 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6246 lhQual.removeCVRQualifiers(); 6247 rhQual.removeCVRQualifiers(); 6248 6249 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6250 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6251 6252 // For OpenCL: 6253 // 1. If LHS and RHS types match exactly and: 6254 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6255 // (b) AS overlap => generate addrspacecast 6256 // (c) AS don't overlap => give an error 6257 // 2. if LHS and RHS types don't match: 6258 // (a) AS match => use standard C rules, generate bitcast 6259 // (b) AS overlap => generate addrspacecast instead of bitcast 6260 // (c) AS don't overlap => give an error 6261 6262 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6263 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6264 6265 // OpenCL cases 1c, 2a, 2b, and 2c. 6266 if (CompositeTy.isNull()) { 6267 // In this situation, we assume void* type. No especially good 6268 // reason, but this is what gcc does, and we do have to pick 6269 // to get a consistent AST. 6270 QualType incompatTy; 6271 if (S.getLangOpts().OpenCL) { 6272 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6273 // spaces is disallowed. 6274 unsigned ResultAddrSpace; 6275 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6276 // Cases 2a and 2b. 6277 ResultAddrSpace = lhQual.getAddressSpace(); 6278 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6279 // Cases 2a and 2b. 6280 ResultAddrSpace = rhQual.getAddressSpace(); 6281 } else { 6282 // Cases 1c and 2c. 6283 S.Diag(Loc, 6284 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6285 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6286 << RHS.get()->getSourceRange(); 6287 return QualType(); 6288 } 6289 6290 // Continue handling cases 2a and 2b. 6291 incompatTy = S.Context.getPointerType( 6292 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6293 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6294 (lhQual.getAddressSpace() != ResultAddrSpace) 6295 ? CK_AddressSpaceConversion /* 2b */ 6296 : CK_BitCast /* 2a */); 6297 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6298 (rhQual.getAddressSpace() != ResultAddrSpace) 6299 ? CK_AddressSpaceConversion /* 2b */ 6300 : CK_BitCast /* 2a */); 6301 } else { 6302 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6303 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6304 << RHS.get()->getSourceRange(); 6305 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6306 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6307 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6308 } 6309 return incompatTy; 6310 } 6311 6312 // The pointer types are compatible. 6313 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6314 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6315 if (IsBlockPointer) 6316 ResultTy = S.Context.getBlockPointerType(ResultTy); 6317 else { 6318 // Cases 1a and 1b for OpenCL. 6319 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6320 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6321 ? CK_BitCast /* 1a */ 6322 : CK_AddressSpaceConversion /* 1b */; 6323 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6324 ? CK_BitCast /* 1a */ 6325 : CK_AddressSpaceConversion /* 1b */; 6326 ResultTy = S.Context.getPointerType(ResultTy); 6327 } 6328 6329 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6330 // if the target type does not change. 6331 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6332 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6333 return ResultTy; 6334 } 6335 6336 /// \brief Return the resulting type when the operands are both block pointers. 6337 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6338 ExprResult &LHS, 6339 ExprResult &RHS, 6340 SourceLocation Loc) { 6341 QualType LHSTy = LHS.get()->getType(); 6342 QualType RHSTy = RHS.get()->getType(); 6343 6344 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6345 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6346 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6347 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6348 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6349 return destType; 6350 } 6351 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6352 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6353 << RHS.get()->getSourceRange(); 6354 return QualType(); 6355 } 6356 6357 // We have 2 block pointer types. 6358 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6359 } 6360 6361 /// \brief Return the resulting type when the operands are both pointers. 6362 static QualType 6363 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6364 ExprResult &RHS, 6365 SourceLocation Loc) { 6366 // get the pointer types 6367 QualType LHSTy = LHS.get()->getType(); 6368 QualType RHSTy = RHS.get()->getType(); 6369 6370 // get the "pointed to" types 6371 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6372 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6373 6374 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6375 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6376 // Figure out necessary qualifiers (C99 6.5.15p6) 6377 QualType destPointee 6378 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6379 QualType destType = S.Context.getPointerType(destPointee); 6380 // Add qualifiers if necessary. 6381 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6382 // Promote to void*. 6383 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6384 return destType; 6385 } 6386 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6387 QualType destPointee 6388 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6389 QualType destType = S.Context.getPointerType(destPointee); 6390 // Add qualifiers if necessary. 6391 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6392 // Promote to void*. 6393 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6394 return destType; 6395 } 6396 6397 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6398 } 6399 6400 /// \brief Return false if the first expression is not an integer and the second 6401 /// expression is not a pointer, true otherwise. 6402 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6403 Expr* PointerExpr, SourceLocation Loc, 6404 bool IsIntFirstExpr) { 6405 if (!PointerExpr->getType()->isPointerType() || 6406 !Int.get()->getType()->isIntegerType()) 6407 return false; 6408 6409 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6410 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6411 6412 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6413 << Expr1->getType() << Expr2->getType() 6414 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6415 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6416 CK_IntegralToPointer); 6417 return true; 6418 } 6419 6420 /// \brief Simple conversion between integer and floating point types. 6421 /// 6422 /// Used when handling the OpenCL conditional operator where the 6423 /// condition is a vector while the other operands are scalar. 6424 /// 6425 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6426 /// types are either integer or floating type. Between the two 6427 /// operands, the type with the higher rank is defined as the "result 6428 /// type". The other operand needs to be promoted to the same type. No 6429 /// other type promotion is allowed. We cannot use 6430 /// UsualArithmeticConversions() for this purpose, since it always 6431 /// promotes promotable types. 6432 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6433 ExprResult &RHS, 6434 SourceLocation QuestionLoc) { 6435 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6436 if (LHS.isInvalid()) 6437 return QualType(); 6438 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6439 if (RHS.isInvalid()) 6440 return QualType(); 6441 6442 // For conversion purposes, we ignore any qualifiers. 6443 // For example, "const float" and "float" are equivalent. 6444 QualType LHSType = 6445 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6446 QualType RHSType = 6447 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6448 6449 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6450 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6451 << LHSType << LHS.get()->getSourceRange(); 6452 return QualType(); 6453 } 6454 6455 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6456 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6457 << RHSType << RHS.get()->getSourceRange(); 6458 return QualType(); 6459 } 6460 6461 // If both types are identical, no conversion is needed. 6462 if (LHSType == RHSType) 6463 return LHSType; 6464 6465 // Now handle "real" floating types (i.e. float, double, long double). 6466 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6467 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6468 /*IsCompAssign = */ false); 6469 6470 // Finally, we have two differing integer types. 6471 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6472 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6473 } 6474 6475 /// \brief Convert scalar operands to a vector that matches the 6476 /// condition in length. 6477 /// 6478 /// Used when handling the OpenCL conditional operator where the 6479 /// condition is a vector while the other operands are scalar. 6480 /// 6481 /// We first compute the "result type" for the scalar operands 6482 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6483 /// into a vector of that type where the length matches the condition 6484 /// vector type. s6.11.6 requires that the element types of the result 6485 /// and the condition must have the same number of bits. 6486 static QualType 6487 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6488 QualType CondTy, SourceLocation QuestionLoc) { 6489 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6490 if (ResTy.isNull()) return QualType(); 6491 6492 const VectorType *CV = CondTy->getAs<VectorType>(); 6493 assert(CV); 6494 6495 // Determine the vector result type 6496 unsigned NumElements = CV->getNumElements(); 6497 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6498 6499 // Ensure that all types have the same number of bits 6500 if (S.Context.getTypeSize(CV->getElementType()) 6501 != S.Context.getTypeSize(ResTy)) { 6502 // Since VectorTy is created internally, it does not pretty print 6503 // with an OpenCL name. Instead, we just print a description. 6504 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6505 SmallString<64> Str; 6506 llvm::raw_svector_ostream OS(Str); 6507 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6508 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6509 << CondTy << OS.str(); 6510 return QualType(); 6511 } 6512 6513 // Convert operands to the vector result type 6514 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6515 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6516 6517 return VectorTy; 6518 } 6519 6520 /// \brief Return false if this is a valid OpenCL condition vector 6521 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6522 SourceLocation QuestionLoc) { 6523 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6524 // integral type. 6525 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6526 assert(CondTy); 6527 QualType EleTy = CondTy->getElementType(); 6528 if (EleTy->isIntegerType()) return false; 6529 6530 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6531 << Cond->getType() << Cond->getSourceRange(); 6532 return true; 6533 } 6534 6535 /// \brief Return false if the vector condition type and the vector 6536 /// result type are compatible. 6537 /// 6538 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6539 /// number of elements, and their element types have the same number 6540 /// of bits. 6541 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6542 SourceLocation QuestionLoc) { 6543 const VectorType *CV = CondTy->getAs<VectorType>(); 6544 const VectorType *RV = VecResTy->getAs<VectorType>(); 6545 assert(CV && RV); 6546 6547 if (CV->getNumElements() != RV->getNumElements()) { 6548 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6549 << CondTy << VecResTy; 6550 return true; 6551 } 6552 6553 QualType CVE = CV->getElementType(); 6554 QualType RVE = RV->getElementType(); 6555 6556 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6557 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6558 << CondTy << VecResTy; 6559 return true; 6560 } 6561 6562 return false; 6563 } 6564 6565 /// \brief Return the resulting type for the conditional operator in 6566 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6567 /// s6.3.i) when the condition is a vector type. 6568 static QualType 6569 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6570 ExprResult &LHS, ExprResult &RHS, 6571 SourceLocation QuestionLoc) { 6572 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6573 if (Cond.isInvalid()) 6574 return QualType(); 6575 QualType CondTy = Cond.get()->getType(); 6576 6577 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6578 return QualType(); 6579 6580 // If either operand is a vector then find the vector type of the 6581 // result as specified in OpenCL v1.1 s6.3.i. 6582 if (LHS.get()->getType()->isVectorType() || 6583 RHS.get()->getType()->isVectorType()) { 6584 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6585 /*isCompAssign*/false, 6586 /*AllowBothBool*/true, 6587 /*AllowBoolConversions*/false); 6588 if (VecResTy.isNull()) return QualType(); 6589 // The result type must match the condition type as specified in 6590 // OpenCL v1.1 s6.11.6. 6591 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6592 return QualType(); 6593 return VecResTy; 6594 } 6595 6596 // Both operands are scalar. 6597 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6598 } 6599 6600 /// \brief Return true if the Expr is block type 6601 static bool checkBlockType(Sema &S, const Expr *E) { 6602 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6603 QualType Ty = CE->getCallee()->getType(); 6604 if (Ty->isBlockPointerType()) { 6605 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6606 return true; 6607 } 6608 } 6609 return false; 6610 } 6611 6612 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6613 /// In that case, LHS = cond. 6614 /// C99 6.5.15 6615 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6616 ExprResult &RHS, ExprValueKind &VK, 6617 ExprObjectKind &OK, 6618 SourceLocation QuestionLoc) { 6619 6620 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6621 if (!LHSResult.isUsable()) return QualType(); 6622 LHS = LHSResult; 6623 6624 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6625 if (!RHSResult.isUsable()) return QualType(); 6626 RHS = RHSResult; 6627 6628 // C++ is sufficiently different to merit its own checker. 6629 if (getLangOpts().CPlusPlus) 6630 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6631 6632 VK = VK_RValue; 6633 OK = OK_Ordinary; 6634 6635 // The OpenCL operator with a vector condition is sufficiently 6636 // different to merit its own checker. 6637 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6638 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6639 6640 // First, check the condition. 6641 Cond = UsualUnaryConversions(Cond.get()); 6642 if (Cond.isInvalid()) 6643 return QualType(); 6644 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6645 return QualType(); 6646 6647 // Now check the two expressions. 6648 if (LHS.get()->getType()->isVectorType() || 6649 RHS.get()->getType()->isVectorType()) 6650 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6651 /*AllowBothBool*/true, 6652 /*AllowBoolConversions*/false); 6653 6654 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6655 if (LHS.isInvalid() || RHS.isInvalid()) 6656 return QualType(); 6657 6658 QualType LHSTy = LHS.get()->getType(); 6659 QualType RHSTy = RHS.get()->getType(); 6660 6661 // Diagnose attempts to convert between __float128 and long double where 6662 // such conversions currently can't be handled. 6663 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6664 Diag(QuestionLoc, 6665 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6666 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6667 return QualType(); 6668 } 6669 6670 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6671 // selection operator (?:). 6672 if (getLangOpts().OpenCL && 6673 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6674 return QualType(); 6675 } 6676 6677 // If both operands have arithmetic type, do the usual arithmetic conversions 6678 // to find a common type: C99 6.5.15p3,5. 6679 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6680 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6681 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6682 6683 return ResTy; 6684 } 6685 6686 // If both operands are the same structure or union type, the result is that 6687 // type. 6688 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6689 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6690 if (LHSRT->getDecl() == RHSRT->getDecl()) 6691 // "If both the operands have structure or union type, the result has 6692 // that type." This implies that CV qualifiers are dropped. 6693 return LHSTy.getUnqualifiedType(); 6694 // FIXME: Type of conditional expression must be complete in C mode. 6695 } 6696 6697 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6698 // The following || allows only one side to be void (a GCC-ism). 6699 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6700 return checkConditionalVoidType(*this, LHS, RHS); 6701 } 6702 6703 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6704 // the type of the other operand." 6705 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6706 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6707 6708 // All objective-c pointer type analysis is done here. 6709 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6710 QuestionLoc); 6711 if (LHS.isInvalid() || RHS.isInvalid()) 6712 return QualType(); 6713 if (!compositeType.isNull()) 6714 return compositeType; 6715 6716 6717 // Handle block pointer types. 6718 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6719 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6720 QuestionLoc); 6721 6722 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6723 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6724 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6725 QuestionLoc); 6726 6727 // GCC compatibility: soften pointer/integer mismatch. Note that 6728 // null pointers have been filtered out by this point. 6729 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6730 /*isIntFirstExpr=*/true)) 6731 return RHSTy; 6732 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6733 /*isIntFirstExpr=*/false)) 6734 return LHSTy; 6735 6736 // Emit a better diagnostic if one of the expressions is a null pointer 6737 // constant and the other is not a pointer type. In this case, the user most 6738 // likely forgot to take the address of the other expression. 6739 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6740 return QualType(); 6741 6742 // Otherwise, the operands are not compatible. 6743 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6744 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6745 << RHS.get()->getSourceRange(); 6746 return QualType(); 6747 } 6748 6749 /// FindCompositeObjCPointerType - Helper method to find composite type of 6750 /// two objective-c pointer types of the two input expressions. 6751 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6752 SourceLocation QuestionLoc) { 6753 QualType LHSTy = LHS.get()->getType(); 6754 QualType RHSTy = RHS.get()->getType(); 6755 6756 // Handle things like Class and struct objc_class*. Here we case the result 6757 // to the pseudo-builtin, because that will be implicitly cast back to the 6758 // redefinition type if an attempt is made to access its fields. 6759 if (LHSTy->isObjCClassType() && 6760 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6761 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6762 return LHSTy; 6763 } 6764 if (RHSTy->isObjCClassType() && 6765 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6766 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6767 return RHSTy; 6768 } 6769 // And the same for struct objc_object* / id 6770 if (LHSTy->isObjCIdType() && 6771 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6772 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6773 return LHSTy; 6774 } 6775 if (RHSTy->isObjCIdType() && 6776 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6777 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6778 return RHSTy; 6779 } 6780 // And the same for struct objc_selector* / SEL 6781 if (Context.isObjCSelType(LHSTy) && 6782 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6783 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6784 return LHSTy; 6785 } 6786 if (Context.isObjCSelType(RHSTy) && 6787 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6788 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6789 return RHSTy; 6790 } 6791 // Check constraints for Objective-C object pointers types. 6792 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6793 6794 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6795 // Two identical object pointer types are always compatible. 6796 return LHSTy; 6797 } 6798 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6799 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6800 QualType compositeType = LHSTy; 6801 6802 // If both operands are interfaces and either operand can be 6803 // assigned to the other, use that type as the composite 6804 // type. This allows 6805 // xxx ? (A*) a : (B*) b 6806 // where B is a subclass of A. 6807 // 6808 // Additionally, as for assignment, if either type is 'id' 6809 // allow silent coercion. Finally, if the types are 6810 // incompatible then make sure to use 'id' as the composite 6811 // type so the result is acceptable for sending messages to. 6812 6813 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6814 // It could return the composite type. 6815 if (!(compositeType = 6816 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6817 // Nothing more to do. 6818 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6819 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6820 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6821 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6822 } else if ((LHSTy->isObjCQualifiedIdType() || 6823 RHSTy->isObjCQualifiedIdType()) && 6824 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6825 // Need to handle "id<xx>" explicitly. 6826 // GCC allows qualified id and any Objective-C type to devolve to 6827 // id. Currently localizing to here until clear this should be 6828 // part of ObjCQualifiedIdTypesAreCompatible. 6829 compositeType = Context.getObjCIdType(); 6830 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6831 compositeType = Context.getObjCIdType(); 6832 } else { 6833 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6834 << LHSTy << RHSTy 6835 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6836 QualType incompatTy = Context.getObjCIdType(); 6837 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6838 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6839 return incompatTy; 6840 } 6841 // The object pointer types are compatible. 6842 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6843 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6844 return compositeType; 6845 } 6846 // Check Objective-C object pointer types and 'void *' 6847 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6848 if (getLangOpts().ObjCAutoRefCount) { 6849 // ARC forbids the implicit conversion of object pointers to 'void *', 6850 // so these types are not compatible. 6851 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6852 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6853 LHS = RHS = true; 6854 return QualType(); 6855 } 6856 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6857 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6858 QualType destPointee 6859 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6860 QualType destType = Context.getPointerType(destPointee); 6861 // Add qualifiers if necessary. 6862 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6863 // Promote to void*. 6864 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6865 return destType; 6866 } 6867 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6868 if (getLangOpts().ObjCAutoRefCount) { 6869 // ARC forbids the implicit conversion of object pointers to 'void *', 6870 // so these types are not compatible. 6871 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6872 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6873 LHS = RHS = true; 6874 return QualType(); 6875 } 6876 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6877 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6878 QualType destPointee 6879 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6880 QualType destType = Context.getPointerType(destPointee); 6881 // Add qualifiers if necessary. 6882 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6883 // Promote to void*. 6884 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6885 return destType; 6886 } 6887 return QualType(); 6888 } 6889 6890 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6891 /// ParenRange in parentheses. 6892 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6893 const PartialDiagnostic &Note, 6894 SourceRange ParenRange) { 6895 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6896 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6897 EndLoc.isValid()) { 6898 Self.Diag(Loc, Note) 6899 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6900 << FixItHint::CreateInsertion(EndLoc, ")"); 6901 } else { 6902 // We can't display the parentheses, so just show the bare note. 6903 Self.Diag(Loc, Note) << ParenRange; 6904 } 6905 } 6906 6907 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6908 return BinaryOperator::isAdditiveOp(Opc) || 6909 BinaryOperator::isMultiplicativeOp(Opc) || 6910 BinaryOperator::isShiftOp(Opc); 6911 } 6912 6913 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6914 /// expression, either using a built-in or overloaded operator, 6915 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6916 /// expression. 6917 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6918 Expr **RHSExprs) { 6919 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6920 E = E->IgnoreImpCasts(); 6921 E = E->IgnoreConversionOperator(); 6922 E = E->IgnoreImpCasts(); 6923 6924 // Built-in binary operator. 6925 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6926 if (IsArithmeticOp(OP->getOpcode())) { 6927 *Opcode = OP->getOpcode(); 6928 *RHSExprs = OP->getRHS(); 6929 return true; 6930 } 6931 } 6932 6933 // Overloaded operator. 6934 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6935 if (Call->getNumArgs() != 2) 6936 return false; 6937 6938 // Make sure this is really a binary operator that is safe to pass into 6939 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6940 OverloadedOperatorKind OO = Call->getOperator(); 6941 if (OO < OO_Plus || OO > OO_Arrow || 6942 OO == OO_PlusPlus || OO == OO_MinusMinus) 6943 return false; 6944 6945 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6946 if (IsArithmeticOp(OpKind)) { 6947 *Opcode = OpKind; 6948 *RHSExprs = Call->getArg(1); 6949 return true; 6950 } 6951 } 6952 6953 return false; 6954 } 6955 6956 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6957 /// or is a logical expression such as (x==y) which has int type, but is 6958 /// commonly interpreted as boolean. 6959 static bool ExprLooksBoolean(Expr *E) { 6960 E = E->IgnoreParenImpCasts(); 6961 6962 if (E->getType()->isBooleanType()) 6963 return true; 6964 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6965 return OP->isComparisonOp() || OP->isLogicalOp(); 6966 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6967 return OP->getOpcode() == UO_LNot; 6968 if (E->getType()->isPointerType()) 6969 return true; 6970 6971 return false; 6972 } 6973 6974 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6975 /// and binary operator are mixed in a way that suggests the programmer assumed 6976 /// the conditional operator has higher precedence, for example: 6977 /// "int x = a + someBinaryCondition ? 1 : 2". 6978 static void DiagnoseConditionalPrecedence(Sema &Self, 6979 SourceLocation OpLoc, 6980 Expr *Condition, 6981 Expr *LHSExpr, 6982 Expr *RHSExpr) { 6983 BinaryOperatorKind CondOpcode; 6984 Expr *CondRHS; 6985 6986 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6987 return; 6988 if (!ExprLooksBoolean(CondRHS)) 6989 return; 6990 6991 // The condition is an arithmetic binary expression, with a right- 6992 // hand side that looks boolean, so warn. 6993 6994 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6995 << Condition->getSourceRange() 6996 << BinaryOperator::getOpcodeStr(CondOpcode); 6997 6998 SuggestParentheses(Self, OpLoc, 6999 Self.PDiag(diag::note_precedence_silence) 7000 << BinaryOperator::getOpcodeStr(CondOpcode), 7001 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7002 7003 SuggestParentheses(Self, OpLoc, 7004 Self.PDiag(diag::note_precedence_conditional_first), 7005 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7006 } 7007 7008 /// Compute the nullability of a conditional expression. 7009 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7010 QualType LHSTy, QualType RHSTy, 7011 ASTContext &Ctx) { 7012 if (!ResTy->isPointerType()) 7013 return ResTy; 7014 7015 auto GetNullability = [&Ctx](QualType Ty) { 7016 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7017 if (Kind) 7018 return *Kind; 7019 return NullabilityKind::Unspecified; 7020 }; 7021 7022 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7023 NullabilityKind MergedKind; 7024 7025 // Compute nullability of a binary conditional expression. 7026 if (IsBin) { 7027 if (LHSKind == NullabilityKind::NonNull) 7028 MergedKind = NullabilityKind::NonNull; 7029 else 7030 MergedKind = RHSKind; 7031 // Compute nullability of a normal conditional expression. 7032 } else { 7033 if (LHSKind == NullabilityKind::Nullable || 7034 RHSKind == NullabilityKind::Nullable) 7035 MergedKind = NullabilityKind::Nullable; 7036 else if (LHSKind == NullabilityKind::NonNull) 7037 MergedKind = RHSKind; 7038 else if (RHSKind == NullabilityKind::NonNull) 7039 MergedKind = LHSKind; 7040 else 7041 MergedKind = NullabilityKind::Unspecified; 7042 } 7043 7044 // Return if ResTy already has the correct nullability. 7045 if (GetNullability(ResTy) == MergedKind) 7046 return ResTy; 7047 7048 // Strip all nullability from ResTy. 7049 while (ResTy->getNullability(Ctx)) 7050 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7051 7052 // Create a new AttributedType with the new nullability kind. 7053 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7054 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7055 } 7056 7057 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7058 /// in the case of a the GNU conditional expr extension. 7059 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7060 SourceLocation ColonLoc, 7061 Expr *CondExpr, Expr *LHSExpr, 7062 Expr *RHSExpr) { 7063 if (!getLangOpts().CPlusPlus) { 7064 // C cannot handle TypoExpr nodes in the condition because it 7065 // doesn't handle dependent types properly, so make sure any TypoExprs have 7066 // been dealt with before checking the operands. 7067 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7068 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7069 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7070 7071 if (!CondResult.isUsable()) 7072 return ExprError(); 7073 7074 if (LHSExpr) { 7075 if (!LHSResult.isUsable()) 7076 return ExprError(); 7077 } 7078 7079 if (!RHSResult.isUsable()) 7080 return ExprError(); 7081 7082 CondExpr = CondResult.get(); 7083 LHSExpr = LHSResult.get(); 7084 RHSExpr = RHSResult.get(); 7085 } 7086 7087 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7088 // was the condition. 7089 OpaqueValueExpr *opaqueValue = nullptr; 7090 Expr *commonExpr = nullptr; 7091 if (!LHSExpr) { 7092 commonExpr = CondExpr; 7093 // Lower out placeholder types first. This is important so that we don't 7094 // try to capture a placeholder. This happens in few cases in C++; such 7095 // as Objective-C++'s dictionary subscripting syntax. 7096 if (commonExpr->hasPlaceholderType()) { 7097 ExprResult result = CheckPlaceholderExpr(commonExpr); 7098 if (!result.isUsable()) return ExprError(); 7099 commonExpr = result.get(); 7100 } 7101 // We usually want to apply unary conversions *before* saving, except 7102 // in the special case of a C++ l-value conditional. 7103 if (!(getLangOpts().CPlusPlus 7104 && !commonExpr->isTypeDependent() 7105 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7106 && commonExpr->isGLValue() 7107 && commonExpr->isOrdinaryOrBitFieldObject() 7108 && RHSExpr->isOrdinaryOrBitFieldObject() 7109 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7110 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7111 if (commonRes.isInvalid()) 7112 return ExprError(); 7113 commonExpr = commonRes.get(); 7114 } 7115 7116 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7117 commonExpr->getType(), 7118 commonExpr->getValueKind(), 7119 commonExpr->getObjectKind(), 7120 commonExpr); 7121 LHSExpr = CondExpr = opaqueValue; 7122 } 7123 7124 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7125 ExprValueKind VK = VK_RValue; 7126 ExprObjectKind OK = OK_Ordinary; 7127 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7128 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7129 VK, OK, QuestionLoc); 7130 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7131 RHS.isInvalid()) 7132 return ExprError(); 7133 7134 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7135 RHS.get()); 7136 7137 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7138 7139 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7140 Context); 7141 7142 if (!commonExpr) 7143 return new (Context) 7144 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7145 RHS.get(), result, VK, OK); 7146 7147 return new (Context) BinaryConditionalOperator( 7148 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7149 ColonLoc, result, VK, OK); 7150 } 7151 7152 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7153 // being closely modeled after the C99 spec:-). The odd characteristic of this 7154 // routine is it effectively iqnores the qualifiers on the top level pointee. 7155 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7156 // FIXME: add a couple examples in this comment. 7157 static Sema::AssignConvertType 7158 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7159 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7160 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7161 7162 // get the "pointed to" type (ignoring qualifiers at the top level) 7163 const Type *lhptee, *rhptee; 7164 Qualifiers lhq, rhq; 7165 std::tie(lhptee, lhq) = 7166 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7167 std::tie(rhptee, rhq) = 7168 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7169 7170 Sema::AssignConvertType ConvTy = Sema::Compatible; 7171 7172 // C99 6.5.16.1p1: This following citation is common to constraints 7173 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7174 // qualifiers of the type *pointed to* by the right; 7175 7176 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7177 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7178 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7179 // Ignore lifetime for further calculation. 7180 lhq.removeObjCLifetime(); 7181 rhq.removeObjCLifetime(); 7182 } 7183 7184 if (!lhq.compatiblyIncludes(rhq)) { 7185 // Treat address-space mismatches as fatal. TODO: address subspaces 7186 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7187 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7188 7189 // It's okay to add or remove GC or lifetime qualifiers when converting to 7190 // and from void*. 7191 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7192 .compatiblyIncludes( 7193 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7194 && (lhptee->isVoidType() || rhptee->isVoidType())) 7195 ; // keep old 7196 7197 // Treat lifetime mismatches as fatal. 7198 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7199 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7200 7201 // For GCC/MS compatibility, other qualifier mismatches are treated 7202 // as still compatible in C. 7203 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7204 } 7205 7206 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7207 // incomplete type and the other is a pointer to a qualified or unqualified 7208 // version of void... 7209 if (lhptee->isVoidType()) { 7210 if (rhptee->isIncompleteOrObjectType()) 7211 return ConvTy; 7212 7213 // As an extension, we allow cast to/from void* to function pointer. 7214 assert(rhptee->isFunctionType()); 7215 return Sema::FunctionVoidPointer; 7216 } 7217 7218 if (rhptee->isVoidType()) { 7219 if (lhptee->isIncompleteOrObjectType()) 7220 return ConvTy; 7221 7222 // As an extension, we allow cast to/from void* to function pointer. 7223 assert(lhptee->isFunctionType()); 7224 return Sema::FunctionVoidPointer; 7225 } 7226 7227 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7228 // unqualified versions of compatible types, ... 7229 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7230 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7231 // Check if the pointee types are compatible ignoring the sign. 7232 // We explicitly check for char so that we catch "char" vs 7233 // "unsigned char" on systems where "char" is unsigned. 7234 if (lhptee->isCharType()) 7235 ltrans = S.Context.UnsignedCharTy; 7236 else if (lhptee->hasSignedIntegerRepresentation()) 7237 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7238 7239 if (rhptee->isCharType()) 7240 rtrans = S.Context.UnsignedCharTy; 7241 else if (rhptee->hasSignedIntegerRepresentation()) 7242 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7243 7244 if (ltrans == rtrans) { 7245 // Types are compatible ignoring the sign. Qualifier incompatibility 7246 // takes priority over sign incompatibility because the sign 7247 // warning can be disabled. 7248 if (ConvTy != Sema::Compatible) 7249 return ConvTy; 7250 7251 return Sema::IncompatiblePointerSign; 7252 } 7253 7254 // If we are a multi-level pointer, it's possible that our issue is simply 7255 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7256 // the eventual target type is the same and the pointers have the same 7257 // level of indirection, this must be the issue. 7258 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7259 do { 7260 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7261 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7262 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7263 7264 if (lhptee == rhptee) 7265 return Sema::IncompatibleNestedPointerQualifiers; 7266 } 7267 7268 // General pointer incompatibility takes priority over qualifiers. 7269 return Sema::IncompatiblePointer; 7270 } 7271 if (!S.getLangOpts().CPlusPlus && 7272 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7273 return Sema::IncompatiblePointer; 7274 return ConvTy; 7275 } 7276 7277 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7278 /// block pointer types are compatible or whether a block and normal pointer 7279 /// are compatible. It is more restrict than comparing two function pointer 7280 // types. 7281 static Sema::AssignConvertType 7282 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7283 QualType RHSType) { 7284 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7285 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7286 7287 QualType lhptee, rhptee; 7288 7289 // get the "pointed to" type (ignoring qualifiers at the top level) 7290 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7291 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7292 7293 // In C++, the types have to match exactly. 7294 if (S.getLangOpts().CPlusPlus) 7295 return Sema::IncompatibleBlockPointer; 7296 7297 Sema::AssignConvertType ConvTy = Sema::Compatible; 7298 7299 // For blocks we enforce that qualifiers are identical. 7300 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7301 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7302 7303 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7304 return Sema::IncompatibleBlockPointer; 7305 7306 return ConvTy; 7307 } 7308 7309 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7310 /// for assignment compatibility. 7311 static Sema::AssignConvertType 7312 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7313 QualType RHSType) { 7314 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7315 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7316 7317 if (LHSType->isObjCBuiltinType()) { 7318 // Class is not compatible with ObjC object pointers. 7319 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7320 !RHSType->isObjCQualifiedClassType()) 7321 return Sema::IncompatiblePointer; 7322 return Sema::Compatible; 7323 } 7324 if (RHSType->isObjCBuiltinType()) { 7325 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7326 !LHSType->isObjCQualifiedClassType()) 7327 return Sema::IncompatiblePointer; 7328 return Sema::Compatible; 7329 } 7330 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7331 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7332 7333 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7334 // make an exception for id<P> 7335 !LHSType->isObjCQualifiedIdType()) 7336 return Sema::CompatiblePointerDiscardsQualifiers; 7337 7338 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7339 return Sema::Compatible; 7340 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7341 return Sema::IncompatibleObjCQualifiedId; 7342 return Sema::IncompatiblePointer; 7343 } 7344 7345 Sema::AssignConvertType 7346 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7347 QualType LHSType, QualType RHSType) { 7348 // Fake up an opaque expression. We don't actually care about what 7349 // cast operations are required, so if CheckAssignmentConstraints 7350 // adds casts to this they'll be wasted, but fortunately that doesn't 7351 // usually happen on valid code. 7352 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7353 ExprResult RHSPtr = &RHSExpr; 7354 CastKind K = CK_Invalid; 7355 7356 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7357 } 7358 7359 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7360 /// has code to accommodate several GCC extensions when type checking 7361 /// pointers. Here are some objectionable examples that GCC considers warnings: 7362 /// 7363 /// int a, *pint; 7364 /// short *pshort; 7365 /// struct foo *pfoo; 7366 /// 7367 /// pint = pshort; // warning: assignment from incompatible pointer type 7368 /// a = pint; // warning: assignment makes integer from pointer without a cast 7369 /// pint = a; // warning: assignment makes pointer from integer without a cast 7370 /// pint = pfoo; // warning: assignment from incompatible pointer type 7371 /// 7372 /// As a result, the code for dealing with pointers is more complex than the 7373 /// C99 spec dictates. 7374 /// 7375 /// Sets 'Kind' for any result kind except Incompatible. 7376 Sema::AssignConvertType 7377 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7378 CastKind &Kind, bool ConvertRHS) { 7379 QualType RHSType = RHS.get()->getType(); 7380 QualType OrigLHSType = LHSType; 7381 7382 // Get canonical types. We're not formatting these types, just comparing 7383 // them. 7384 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7385 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7386 7387 // Common case: no conversion required. 7388 if (LHSType == RHSType) { 7389 Kind = CK_NoOp; 7390 return Compatible; 7391 } 7392 7393 // If we have an atomic type, try a non-atomic assignment, then just add an 7394 // atomic qualification step. 7395 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7396 Sema::AssignConvertType result = 7397 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7398 if (result != Compatible) 7399 return result; 7400 if (Kind != CK_NoOp && ConvertRHS) 7401 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7402 Kind = CK_NonAtomicToAtomic; 7403 return Compatible; 7404 } 7405 7406 // If the left-hand side is a reference type, then we are in a 7407 // (rare!) case where we've allowed the use of references in C, 7408 // e.g., as a parameter type in a built-in function. In this case, 7409 // just make sure that the type referenced is compatible with the 7410 // right-hand side type. The caller is responsible for adjusting 7411 // LHSType so that the resulting expression does not have reference 7412 // type. 7413 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7414 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7415 Kind = CK_LValueBitCast; 7416 return Compatible; 7417 } 7418 return Incompatible; 7419 } 7420 7421 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7422 // to the same ExtVector type. 7423 if (LHSType->isExtVectorType()) { 7424 if (RHSType->isExtVectorType()) 7425 return Incompatible; 7426 if (RHSType->isArithmeticType()) { 7427 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7428 if (ConvertRHS) 7429 RHS = prepareVectorSplat(LHSType, RHS.get()); 7430 Kind = CK_VectorSplat; 7431 return Compatible; 7432 } 7433 } 7434 7435 // Conversions to or from vector type. 7436 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7437 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7438 // Allow assignments of an AltiVec vector type to an equivalent GCC 7439 // vector type and vice versa 7440 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7441 Kind = CK_BitCast; 7442 return Compatible; 7443 } 7444 7445 // If we are allowing lax vector conversions, and LHS and RHS are both 7446 // vectors, the total size only needs to be the same. This is a bitcast; 7447 // no bits are changed but the result type is different. 7448 if (isLaxVectorConversion(RHSType, LHSType)) { 7449 Kind = CK_BitCast; 7450 return IncompatibleVectors; 7451 } 7452 } 7453 7454 // When the RHS comes from another lax conversion (e.g. binops between 7455 // scalars and vectors) the result is canonicalized as a vector. When the 7456 // LHS is also a vector, the lax is allowed by the condition above. Handle 7457 // the case where LHS is a scalar. 7458 if (LHSType->isScalarType()) { 7459 const VectorType *VecType = RHSType->getAs<VectorType>(); 7460 if (VecType && VecType->getNumElements() == 1 && 7461 isLaxVectorConversion(RHSType, LHSType)) { 7462 ExprResult *VecExpr = &RHS; 7463 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7464 Kind = CK_BitCast; 7465 return Compatible; 7466 } 7467 } 7468 7469 return Incompatible; 7470 } 7471 7472 // Diagnose attempts to convert between __float128 and long double where 7473 // such conversions currently can't be handled. 7474 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7475 return Incompatible; 7476 7477 // Arithmetic conversions. 7478 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7479 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7480 if (ConvertRHS) 7481 Kind = PrepareScalarCast(RHS, LHSType); 7482 return Compatible; 7483 } 7484 7485 // Conversions to normal pointers. 7486 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7487 // U* -> T* 7488 if (isa<PointerType>(RHSType)) { 7489 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7490 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7491 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7492 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7493 } 7494 7495 // int -> T* 7496 if (RHSType->isIntegerType()) { 7497 Kind = CK_IntegralToPointer; // FIXME: null? 7498 return IntToPointer; 7499 } 7500 7501 // C pointers are not compatible with ObjC object pointers, 7502 // with two exceptions: 7503 if (isa<ObjCObjectPointerType>(RHSType)) { 7504 // - conversions to void* 7505 if (LHSPointer->getPointeeType()->isVoidType()) { 7506 Kind = CK_BitCast; 7507 return Compatible; 7508 } 7509 7510 // - conversions from 'Class' to the redefinition type 7511 if (RHSType->isObjCClassType() && 7512 Context.hasSameType(LHSType, 7513 Context.getObjCClassRedefinitionType())) { 7514 Kind = CK_BitCast; 7515 return Compatible; 7516 } 7517 7518 Kind = CK_BitCast; 7519 return IncompatiblePointer; 7520 } 7521 7522 // U^ -> void* 7523 if (RHSType->getAs<BlockPointerType>()) { 7524 if (LHSPointer->getPointeeType()->isVoidType()) { 7525 Kind = CK_BitCast; 7526 return Compatible; 7527 } 7528 } 7529 7530 return Incompatible; 7531 } 7532 7533 // Conversions to block pointers. 7534 if (isa<BlockPointerType>(LHSType)) { 7535 // U^ -> T^ 7536 if (RHSType->isBlockPointerType()) { 7537 Kind = CK_BitCast; 7538 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7539 } 7540 7541 // int or null -> T^ 7542 if (RHSType->isIntegerType()) { 7543 Kind = CK_IntegralToPointer; // FIXME: null 7544 return IntToBlockPointer; 7545 } 7546 7547 // id -> T^ 7548 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7549 Kind = CK_AnyPointerToBlockPointerCast; 7550 return Compatible; 7551 } 7552 7553 // void* -> T^ 7554 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7555 if (RHSPT->getPointeeType()->isVoidType()) { 7556 Kind = CK_AnyPointerToBlockPointerCast; 7557 return Compatible; 7558 } 7559 7560 return Incompatible; 7561 } 7562 7563 // Conversions to Objective-C pointers. 7564 if (isa<ObjCObjectPointerType>(LHSType)) { 7565 // A* -> B* 7566 if (RHSType->isObjCObjectPointerType()) { 7567 Kind = CK_BitCast; 7568 Sema::AssignConvertType result = 7569 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7570 if (getLangOpts().ObjCAutoRefCount && 7571 result == Compatible && 7572 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7573 result = IncompatibleObjCWeakRef; 7574 return result; 7575 } 7576 7577 // int or null -> A* 7578 if (RHSType->isIntegerType()) { 7579 Kind = CK_IntegralToPointer; // FIXME: null 7580 return IntToPointer; 7581 } 7582 7583 // In general, C pointers are not compatible with ObjC object pointers, 7584 // with two exceptions: 7585 if (isa<PointerType>(RHSType)) { 7586 Kind = CK_CPointerToObjCPointerCast; 7587 7588 // - conversions from 'void*' 7589 if (RHSType->isVoidPointerType()) { 7590 return Compatible; 7591 } 7592 7593 // - conversions to 'Class' from its redefinition type 7594 if (LHSType->isObjCClassType() && 7595 Context.hasSameType(RHSType, 7596 Context.getObjCClassRedefinitionType())) { 7597 return Compatible; 7598 } 7599 7600 return IncompatiblePointer; 7601 } 7602 7603 // Only under strict condition T^ is compatible with an Objective-C pointer. 7604 if (RHSType->isBlockPointerType() && 7605 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7606 if (ConvertRHS) 7607 maybeExtendBlockObject(RHS); 7608 Kind = CK_BlockPointerToObjCPointerCast; 7609 return Compatible; 7610 } 7611 7612 return Incompatible; 7613 } 7614 7615 // Conversions from pointers that are not covered by the above. 7616 if (isa<PointerType>(RHSType)) { 7617 // T* -> _Bool 7618 if (LHSType == Context.BoolTy) { 7619 Kind = CK_PointerToBoolean; 7620 return Compatible; 7621 } 7622 7623 // T* -> int 7624 if (LHSType->isIntegerType()) { 7625 Kind = CK_PointerToIntegral; 7626 return PointerToInt; 7627 } 7628 7629 return Incompatible; 7630 } 7631 7632 // Conversions from Objective-C pointers that are not covered by the above. 7633 if (isa<ObjCObjectPointerType>(RHSType)) { 7634 // T* -> _Bool 7635 if (LHSType == Context.BoolTy) { 7636 Kind = CK_PointerToBoolean; 7637 return Compatible; 7638 } 7639 7640 // T* -> int 7641 if (LHSType->isIntegerType()) { 7642 Kind = CK_PointerToIntegral; 7643 return PointerToInt; 7644 } 7645 7646 return Incompatible; 7647 } 7648 7649 // struct A -> struct B 7650 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7651 if (Context.typesAreCompatible(LHSType, RHSType)) { 7652 Kind = CK_NoOp; 7653 return Compatible; 7654 } 7655 } 7656 7657 return Incompatible; 7658 } 7659 7660 /// \brief Constructs a transparent union from an expression that is 7661 /// used to initialize the transparent union. 7662 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7663 ExprResult &EResult, QualType UnionType, 7664 FieldDecl *Field) { 7665 // Build an initializer list that designates the appropriate member 7666 // of the transparent union. 7667 Expr *E = EResult.get(); 7668 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7669 E, SourceLocation()); 7670 Initializer->setType(UnionType); 7671 Initializer->setInitializedFieldInUnion(Field); 7672 7673 // Build a compound literal constructing a value of the transparent 7674 // union type from this initializer list. 7675 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7676 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7677 VK_RValue, Initializer, false); 7678 } 7679 7680 Sema::AssignConvertType 7681 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7682 ExprResult &RHS) { 7683 QualType RHSType = RHS.get()->getType(); 7684 7685 // If the ArgType is a Union type, we want to handle a potential 7686 // transparent_union GCC extension. 7687 const RecordType *UT = ArgType->getAsUnionType(); 7688 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7689 return Incompatible; 7690 7691 // The field to initialize within the transparent union. 7692 RecordDecl *UD = UT->getDecl(); 7693 FieldDecl *InitField = nullptr; 7694 // It's compatible if the expression matches any of the fields. 7695 for (auto *it : UD->fields()) { 7696 if (it->getType()->isPointerType()) { 7697 // If the transparent union contains a pointer type, we allow: 7698 // 1) void pointer 7699 // 2) null pointer constant 7700 if (RHSType->isPointerType()) 7701 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7702 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7703 InitField = it; 7704 break; 7705 } 7706 7707 if (RHS.get()->isNullPointerConstant(Context, 7708 Expr::NPC_ValueDependentIsNull)) { 7709 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7710 CK_NullToPointer); 7711 InitField = it; 7712 break; 7713 } 7714 } 7715 7716 CastKind Kind = CK_Invalid; 7717 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7718 == Compatible) { 7719 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7720 InitField = it; 7721 break; 7722 } 7723 } 7724 7725 if (!InitField) 7726 return Incompatible; 7727 7728 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7729 return Compatible; 7730 } 7731 7732 Sema::AssignConvertType 7733 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7734 bool Diagnose, 7735 bool DiagnoseCFAudited, 7736 bool ConvertRHS) { 7737 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7738 // we can't avoid *all* modifications at the moment, so we need some somewhere 7739 // to put the updated value. 7740 ExprResult LocalRHS = CallerRHS; 7741 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7742 7743 if (getLangOpts().CPlusPlus) { 7744 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7745 // C++ 5.17p3: If the left operand is not of class type, the 7746 // expression is implicitly converted (C++ 4) to the 7747 // cv-unqualified type of the left operand. 7748 ExprResult Res; 7749 if (Diagnose) { 7750 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7751 AA_Assigning); 7752 } else { 7753 ImplicitConversionSequence ICS = 7754 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7755 /*SuppressUserConversions=*/false, 7756 /*AllowExplicit=*/false, 7757 /*InOverloadResolution=*/false, 7758 /*CStyle=*/false, 7759 /*AllowObjCWritebackConversion=*/false); 7760 if (ICS.isFailure()) 7761 return Incompatible; 7762 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7763 ICS, AA_Assigning); 7764 } 7765 if (Res.isInvalid()) 7766 return Incompatible; 7767 Sema::AssignConvertType result = Compatible; 7768 if (getLangOpts().ObjCAutoRefCount && 7769 !CheckObjCARCUnavailableWeakConversion(LHSType, 7770 RHS.get()->getType())) 7771 result = IncompatibleObjCWeakRef; 7772 RHS = Res; 7773 return result; 7774 } 7775 7776 // FIXME: Currently, we fall through and treat C++ classes like C 7777 // structures. 7778 // FIXME: We also fall through for atomics; not sure what should 7779 // happen there, though. 7780 } else if (RHS.get()->getType() == Context.OverloadTy) { 7781 // As a set of extensions to C, we support overloading on functions. These 7782 // functions need to be resolved here. 7783 DeclAccessPair DAP; 7784 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7785 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7786 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7787 else 7788 return Incompatible; 7789 } 7790 7791 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7792 // a null pointer constant. 7793 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7794 LHSType->isBlockPointerType()) && 7795 RHS.get()->isNullPointerConstant(Context, 7796 Expr::NPC_ValueDependentIsNull)) { 7797 if (Diagnose || ConvertRHS) { 7798 CastKind Kind; 7799 CXXCastPath Path; 7800 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7801 /*IgnoreBaseAccess=*/false, Diagnose); 7802 if (ConvertRHS) 7803 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7804 } 7805 return Compatible; 7806 } 7807 7808 // This check seems unnatural, however it is necessary to ensure the proper 7809 // conversion of functions/arrays. If the conversion were done for all 7810 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7811 // expressions that suppress this implicit conversion (&, sizeof). 7812 // 7813 // Suppress this for references: C++ 8.5.3p5. 7814 if (!LHSType->isReferenceType()) { 7815 // FIXME: We potentially allocate here even if ConvertRHS is false. 7816 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7817 if (RHS.isInvalid()) 7818 return Incompatible; 7819 } 7820 7821 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7822 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7823 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7824 if (PDecl && !PDecl->hasDefinition()) { 7825 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7826 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7827 } 7828 } 7829 7830 CastKind Kind = CK_Invalid; 7831 Sema::AssignConvertType result = 7832 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7833 7834 // C99 6.5.16.1p2: The value of the right operand is converted to the 7835 // type of the assignment expression. 7836 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7837 // so that we can use references in built-in functions even in C. 7838 // The getNonReferenceType() call makes sure that the resulting expression 7839 // does not have reference type. 7840 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7841 QualType Ty = LHSType.getNonLValueExprType(Context); 7842 Expr *E = RHS.get(); 7843 7844 // Check for various Objective-C errors. If we are not reporting 7845 // diagnostics and just checking for errors, e.g., during overload 7846 // resolution, return Incompatible to indicate the failure. 7847 if (getLangOpts().ObjCAutoRefCount && 7848 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7849 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7850 if (!Diagnose) 7851 return Incompatible; 7852 } 7853 if (getLangOpts().ObjC1 && 7854 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7855 E->getType(), E, Diagnose) || 7856 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7857 if (!Diagnose) 7858 return Incompatible; 7859 // Replace the expression with a corrected version and continue so we 7860 // can find further errors. 7861 RHS = E; 7862 return Compatible; 7863 } 7864 7865 if (ConvertRHS) 7866 RHS = ImpCastExprToType(E, Ty, Kind); 7867 } 7868 return result; 7869 } 7870 7871 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7872 ExprResult &RHS) { 7873 Diag(Loc, diag::err_typecheck_invalid_operands) 7874 << LHS.get()->getType() << RHS.get()->getType() 7875 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7876 return QualType(); 7877 } 7878 7879 /// Try to convert a value of non-vector type to a vector type by converting 7880 /// the type to the element type of the vector and then performing a splat. 7881 /// If the language is OpenCL, we only use conversions that promote scalar 7882 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7883 /// for float->int. 7884 /// 7885 /// \param scalar - if non-null, actually perform the conversions 7886 /// \return true if the operation fails (but without diagnosing the failure) 7887 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7888 QualType scalarTy, 7889 QualType vectorEltTy, 7890 QualType vectorTy) { 7891 // The conversion to apply to the scalar before splatting it, 7892 // if necessary. 7893 CastKind scalarCast = CK_Invalid; 7894 7895 if (vectorEltTy->isIntegralType(S.Context)) { 7896 if (!scalarTy->isIntegralType(S.Context)) 7897 return true; 7898 if (S.getLangOpts().OpenCL && 7899 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7900 return true; 7901 scalarCast = CK_IntegralCast; 7902 } else if (vectorEltTy->isRealFloatingType()) { 7903 if (scalarTy->isRealFloatingType()) { 7904 if (S.getLangOpts().OpenCL && 7905 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7906 return true; 7907 scalarCast = CK_FloatingCast; 7908 } 7909 else if (scalarTy->isIntegralType(S.Context)) 7910 scalarCast = CK_IntegralToFloating; 7911 else 7912 return true; 7913 } else { 7914 return true; 7915 } 7916 7917 // Adjust scalar if desired. 7918 if (scalar) { 7919 if (scalarCast != CK_Invalid) 7920 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7921 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7922 } 7923 return false; 7924 } 7925 7926 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7927 SourceLocation Loc, bool IsCompAssign, 7928 bool AllowBothBool, 7929 bool AllowBoolConversions) { 7930 if (!IsCompAssign) { 7931 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7932 if (LHS.isInvalid()) 7933 return QualType(); 7934 } 7935 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7936 if (RHS.isInvalid()) 7937 return QualType(); 7938 7939 // For conversion purposes, we ignore any qualifiers. 7940 // For example, "const float" and "float" are equivalent. 7941 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7942 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7943 7944 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7945 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7946 assert(LHSVecType || RHSVecType); 7947 7948 // AltiVec-style "vector bool op vector bool" combinations are allowed 7949 // for some operators but not others. 7950 if (!AllowBothBool && 7951 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7952 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7953 return InvalidOperands(Loc, LHS, RHS); 7954 7955 // If the vector types are identical, return. 7956 if (Context.hasSameType(LHSType, RHSType)) 7957 return LHSType; 7958 7959 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7960 if (LHSVecType && RHSVecType && 7961 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7962 if (isa<ExtVectorType>(LHSVecType)) { 7963 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7964 return LHSType; 7965 } 7966 7967 if (!IsCompAssign) 7968 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7969 return RHSType; 7970 } 7971 7972 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7973 // can be mixed, with the result being the non-bool type. The non-bool 7974 // operand must have integer element type. 7975 if (AllowBoolConversions && LHSVecType && RHSVecType && 7976 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7977 (Context.getTypeSize(LHSVecType->getElementType()) == 7978 Context.getTypeSize(RHSVecType->getElementType()))) { 7979 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7980 LHSVecType->getElementType()->isIntegerType() && 7981 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7982 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7983 return LHSType; 7984 } 7985 if (!IsCompAssign && 7986 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7987 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7988 RHSVecType->getElementType()->isIntegerType()) { 7989 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7990 return RHSType; 7991 } 7992 } 7993 7994 // If there's an ext-vector type and a scalar, try to convert the scalar to 7995 // the vector element type and splat. 7996 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7997 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7998 LHSVecType->getElementType(), LHSType)) 7999 return LHSType; 8000 } 8001 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8002 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8003 LHSType, RHSVecType->getElementType(), 8004 RHSType)) 8005 return RHSType; 8006 } 8007 8008 // If we're allowing lax vector conversions, only the total (data) size needs 8009 // to be the same. If one of the types is scalar, the result is always the 8010 // vector type. Don't allow this if the scalar operand is an lvalue. 8011 QualType VecType = LHSVecType ? LHSType : RHSType; 8012 QualType ScalarType = LHSVecType ? RHSType : LHSType; 8013 ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS; 8014 if (isLaxVectorConversion(ScalarType, VecType) && 8015 !ScalarExpr->get()->isLValue()) { 8016 *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast); 8017 return VecType; 8018 } 8019 8020 // Okay, the expression is invalid. 8021 8022 // If there's a non-vector, non-real operand, diagnose that. 8023 if ((!RHSVecType && !RHSType->isRealType()) || 8024 (!LHSVecType && !LHSType->isRealType())) { 8025 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8026 << LHSType << RHSType 8027 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8028 return QualType(); 8029 } 8030 8031 // OpenCL V1.1 6.2.6.p1: 8032 // If the operands are of more than one vector type, then an error shall 8033 // occur. Implicit conversions between vector types are not permitted, per 8034 // section 6.2.1. 8035 if (getLangOpts().OpenCL && 8036 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8037 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8038 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8039 << RHSType; 8040 return QualType(); 8041 } 8042 8043 // Otherwise, use the generic diagnostic. 8044 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8045 << LHSType << RHSType 8046 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8047 return QualType(); 8048 } 8049 8050 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8051 // expression. These are mainly cases where the null pointer is used as an 8052 // integer instead of a pointer. 8053 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8054 SourceLocation Loc, bool IsCompare) { 8055 // The canonical way to check for a GNU null is with isNullPointerConstant, 8056 // but we use a bit of a hack here for speed; this is a relatively 8057 // hot path, and isNullPointerConstant is slow. 8058 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8059 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8060 8061 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8062 8063 // Avoid analyzing cases where the result will either be invalid (and 8064 // diagnosed as such) or entirely valid and not something to warn about. 8065 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8066 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8067 return; 8068 8069 // Comparison operations would not make sense with a null pointer no matter 8070 // what the other expression is. 8071 if (!IsCompare) { 8072 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8073 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8074 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8075 return; 8076 } 8077 8078 // The rest of the operations only make sense with a null pointer 8079 // if the other expression is a pointer. 8080 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8081 NonNullType->canDecayToPointerType()) 8082 return; 8083 8084 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8085 << LHSNull /* LHS is NULL */ << NonNullType 8086 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8087 } 8088 8089 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8090 ExprResult &RHS, 8091 SourceLocation Loc, bool IsDiv) { 8092 // Check for division/remainder by zero. 8093 llvm::APSInt RHSValue; 8094 if (!RHS.get()->isValueDependent() && 8095 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8096 S.DiagRuntimeBehavior(Loc, RHS.get(), 8097 S.PDiag(diag::warn_remainder_division_by_zero) 8098 << IsDiv << RHS.get()->getSourceRange()); 8099 } 8100 8101 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8102 SourceLocation Loc, 8103 bool IsCompAssign, bool IsDiv) { 8104 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8105 8106 if (LHS.get()->getType()->isVectorType() || 8107 RHS.get()->getType()->isVectorType()) 8108 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8109 /*AllowBothBool*/getLangOpts().AltiVec, 8110 /*AllowBoolConversions*/false); 8111 8112 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8113 if (LHS.isInvalid() || RHS.isInvalid()) 8114 return QualType(); 8115 8116 8117 if (compType.isNull() || !compType->isArithmeticType()) 8118 return InvalidOperands(Loc, LHS, RHS); 8119 if (IsDiv) 8120 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8121 return compType; 8122 } 8123 8124 QualType Sema::CheckRemainderOperands( 8125 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8126 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8127 8128 if (LHS.get()->getType()->isVectorType() || 8129 RHS.get()->getType()->isVectorType()) { 8130 if (LHS.get()->getType()->hasIntegerRepresentation() && 8131 RHS.get()->getType()->hasIntegerRepresentation()) 8132 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8133 /*AllowBothBool*/getLangOpts().AltiVec, 8134 /*AllowBoolConversions*/false); 8135 return InvalidOperands(Loc, LHS, RHS); 8136 } 8137 8138 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8139 if (LHS.isInvalid() || RHS.isInvalid()) 8140 return QualType(); 8141 8142 if (compType.isNull() || !compType->isIntegerType()) 8143 return InvalidOperands(Loc, LHS, RHS); 8144 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8145 return compType; 8146 } 8147 8148 /// \brief Diagnose invalid arithmetic on two void pointers. 8149 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8150 Expr *LHSExpr, Expr *RHSExpr) { 8151 S.Diag(Loc, S.getLangOpts().CPlusPlus 8152 ? diag::err_typecheck_pointer_arith_void_type 8153 : diag::ext_gnu_void_ptr) 8154 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8155 << RHSExpr->getSourceRange(); 8156 } 8157 8158 /// \brief Diagnose invalid arithmetic on a void pointer. 8159 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8160 Expr *Pointer) { 8161 S.Diag(Loc, S.getLangOpts().CPlusPlus 8162 ? diag::err_typecheck_pointer_arith_void_type 8163 : diag::ext_gnu_void_ptr) 8164 << 0 /* one pointer */ << Pointer->getSourceRange(); 8165 } 8166 8167 /// \brief Diagnose invalid arithmetic on two function pointers. 8168 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8169 Expr *LHS, Expr *RHS) { 8170 assert(LHS->getType()->isAnyPointerType()); 8171 assert(RHS->getType()->isAnyPointerType()); 8172 S.Diag(Loc, S.getLangOpts().CPlusPlus 8173 ? diag::err_typecheck_pointer_arith_function_type 8174 : diag::ext_gnu_ptr_func_arith) 8175 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8176 // We only show the second type if it differs from the first. 8177 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8178 RHS->getType()) 8179 << RHS->getType()->getPointeeType() 8180 << LHS->getSourceRange() << RHS->getSourceRange(); 8181 } 8182 8183 /// \brief Diagnose invalid arithmetic on a function pointer. 8184 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8185 Expr *Pointer) { 8186 assert(Pointer->getType()->isAnyPointerType()); 8187 S.Diag(Loc, S.getLangOpts().CPlusPlus 8188 ? diag::err_typecheck_pointer_arith_function_type 8189 : diag::ext_gnu_ptr_func_arith) 8190 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8191 << 0 /* one pointer, so only one type */ 8192 << Pointer->getSourceRange(); 8193 } 8194 8195 /// \brief Emit error if Operand is incomplete pointer type 8196 /// 8197 /// \returns True if pointer has incomplete type 8198 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8199 Expr *Operand) { 8200 QualType ResType = Operand->getType(); 8201 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8202 ResType = ResAtomicType->getValueType(); 8203 8204 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8205 QualType PointeeTy = ResType->getPointeeType(); 8206 return S.RequireCompleteType(Loc, PointeeTy, 8207 diag::err_typecheck_arithmetic_incomplete_type, 8208 PointeeTy, Operand->getSourceRange()); 8209 } 8210 8211 /// \brief Check the validity of an arithmetic pointer operand. 8212 /// 8213 /// If the operand has pointer type, this code will check for pointer types 8214 /// which are invalid in arithmetic operations. These will be diagnosed 8215 /// appropriately, including whether or not the use is supported as an 8216 /// extension. 8217 /// 8218 /// \returns True when the operand is valid to use (even if as an extension). 8219 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8220 Expr *Operand) { 8221 QualType ResType = Operand->getType(); 8222 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8223 ResType = ResAtomicType->getValueType(); 8224 8225 if (!ResType->isAnyPointerType()) return true; 8226 8227 QualType PointeeTy = ResType->getPointeeType(); 8228 if (PointeeTy->isVoidType()) { 8229 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8230 return !S.getLangOpts().CPlusPlus; 8231 } 8232 if (PointeeTy->isFunctionType()) { 8233 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8234 return !S.getLangOpts().CPlusPlus; 8235 } 8236 8237 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8238 8239 return true; 8240 } 8241 8242 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8243 /// operands. 8244 /// 8245 /// This routine will diagnose any invalid arithmetic on pointer operands much 8246 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8247 /// for emitting a single diagnostic even for operations where both LHS and RHS 8248 /// are (potentially problematic) pointers. 8249 /// 8250 /// \returns True when the operand is valid to use (even if as an extension). 8251 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8252 Expr *LHSExpr, Expr *RHSExpr) { 8253 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8254 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8255 if (!isLHSPointer && !isRHSPointer) return true; 8256 8257 QualType LHSPointeeTy, RHSPointeeTy; 8258 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8259 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8260 8261 // if both are pointers check if operation is valid wrt address spaces 8262 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8263 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8264 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8265 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8266 S.Diag(Loc, 8267 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8268 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8269 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8270 return false; 8271 } 8272 } 8273 8274 // Check for arithmetic on pointers to incomplete types. 8275 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8276 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8277 if (isLHSVoidPtr || isRHSVoidPtr) { 8278 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8279 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8280 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8281 8282 return !S.getLangOpts().CPlusPlus; 8283 } 8284 8285 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8286 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8287 if (isLHSFuncPtr || isRHSFuncPtr) { 8288 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8289 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8290 RHSExpr); 8291 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8292 8293 return !S.getLangOpts().CPlusPlus; 8294 } 8295 8296 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8297 return false; 8298 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8299 return false; 8300 8301 return true; 8302 } 8303 8304 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8305 /// literal. 8306 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8307 Expr *LHSExpr, Expr *RHSExpr) { 8308 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8309 Expr* IndexExpr = RHSExpr; 8310 if (!StrExpr) { 8311 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8312 IndexExpr = LHSExpr; 8313 } 8314 8315 bool IsStringPlusInt = StrExpr && 8316 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8317 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8318 return; 8319 8320 llvm::APSInt index; 8321 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8322 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8323 if (index.isNonNegative() && 8324 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8325 index.isUnsigned())) 8326 return; 8327 } 8328 8329 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8330 Self.Diag(OpLoc, diag::warn_string_plus_int) 8331 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8332 8333 // Only print a fixit for "str" + int, not for int + "str". 8334 if (IndexExpr == RHSExpr) { 8335 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8336 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8337 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8338 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8339 << FixItHint::CreateInsertion(EndLoc, "]"); 8340 } else 8341 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8342 } 8343 8344 /// \brief Emit a warning when adding a char literal to a string. 8345 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8346 Expr *LHSExpr, Expr *RHSExpr) { 8347 const Expr *StringRefExpr = LHSExpr; 8348 const CharacterLiteral *CharExpr = 8349 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8350 8351 if (!CharExpr) { 8352 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8353 StringRefExpr = RHSExpr; 8354 } 8355 8356 if (!CharExpr || !StringRefExpr) 8357 return; 8358 8359 const QualType StringType = StringRefExpr->getType(); 8360 8361 // Return if not a PointerType. 8362 if (!StringType->isAnyPointerType()) 8363 return; 8364 8365 // Return if not a CharacterType. 8366 if (!StringType->getPointeeType()->isAnyCharacterType()) 8367 return; 8368 8369 ASTContext &Ctx = Self.getASTContext(); 8370 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8371 8372 const QualType CharType = CharExpr->getType(); 8373 if (!CharType->isAnyCharacterType() && 8374 CharType->isIntegerType() && 8375 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8376 Self.Diag(OpLoc, diag::warn_string_plus_char) 8377 << DiagRange << Ctx.CharTy; 8378 } else { 8379 Self.Diag(OpLoc, diag::warn_string_plus_char) 8380 << DiagRange << CharExpr->getType(); 8381 } 8382 8383 // Only print a fixit for str + char, not for char + str. 8384 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8385 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8386 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8387 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8388 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8389 << FixItHint::CreateInsertion(EndLoc, "]"); 8390 } else { 8391 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8392 } 8393 } 8394 8395 /// \brief Emit error when two pointers are incompatible. 8396 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8397 Expr *LHSExpr, Expr *RHSExpr) { 8398 assert(LHSExpr->getType()->isAnyPointerType()); 8399 assert(RHSExpr->getType()->isAnyPointerType()); 8400 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8401 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8402 << RHSExpr->getSourceRange(); 8403 } 8404 8405 // C99 6.5.6 8406 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8407 SourceLocation Loc, BinaryOperatorKind Opc, 8408 QualType* CompLHSTy) { 8409 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8410 8411 if (LHS.get()->getType()->isVectorType() || 8412 RHS.get()->getType()->isVectorType()) { 8413 QualType compType = CheckVectorOperands( 8414 LHS, RHS, Loc, CompLHSTy, 8415 /*AllowBothBool*/getLangOpts().AltiVec, 8416 /*AllowBoolConversions*/getLangOpts().ZVector); 8417 if (CompLHSTy) *CompLHSTy = compType; 8418 return compType; 8419 } 8420 8421 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8422 if (LHS.isInvalid() || RHS.isInvalid()) 8423 return QualType(); 8424 8425 // Diagnose "string literal" '+' int and string '+' "char literal". 8426 if (Opc == BO_Add) { 8427 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8428 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8429 } 8430 8431 // handle the common case first (both operands are arithmetic). 8432 if (!compType.isNull() && compType->isArithmeticType()) { 8433 if (CompLHSTy) *CompLHSTy = compType; 8434 return compType; 8435 } 8436 8437 // Type-checking. Ultimately the pointer's going to be in PExp; 8438 // note that we bias towards the LHS being the pointer. 8439 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8440 8441 bool isObjCPointer; 8442 if (PExp->getType()->isPointerType()) { 8443 isObjCPointer = false; 8444 } else if (PExp->getType()->isObjCObjectPointerType()) { 8445 isObjCPointer = true; 8446 } else { 8447 std::swap(PExp, IExp); 8448 if (PExp->getType()->isPointerType()) { 8449 isObjCPointer = false; 8450 } else if (PExp->getType()->isObjCObjectPointerType()) { 8451 isObjCPointer = true; 8452 } else { 8453 return InvalidOperands(Loc, LHS, RHS); 8454 } 8455 } 8456 assert(PExp->getType()->isAnyPointerType()); 8457 8458 if (!IExp->getType()->isIntegerType()) 8459 return InvalidOperands(Loc, LHS, RHS); 8460 8461 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8462 return QualType(); 8463 8464 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8465 return QualType(); 8466 8467 // Check array bounds for pointer arithemtic 8468 CheckArrayAccess(PExp, IExp); 8469 8470 if (CompLHSTy) { 8471 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8472 if (LHSTy.isNull()) { 8473 LHSTy = LHS.get()->getType(); 8474 if (LHSTy->isPromotableIntegerType()) 8475 LHSTy = Context.getPromotedIntegerType(LHSTy); 8476 } 8477 *CompLHSTy = LHSTy; 8478 } 8479 8480 return PExp->getType(); 8481 } 8482 8483 // C99 6.5.6 8484 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8485 SourceLocation Loc, 8486 QualType* CompLHSTy) { 8487 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8488 8489 if (LHS.get()->getType()->isVectorType() || 8490 RHS.get()->getType()->isVectorType()) { 8491 QualType compType = CheckVectorOperands( 8492 LHS, RHS, Loc, CompLHSTy, 8493 /*AllowBothBool*/getLangOpts().AltiVec, 8494 /*AllowBoolConversions*/getLangOpts().ZVector); 8495 if (CompLHSTy) *CompLHSTy = compType; 8496 return compType; 8497 } 8498 8499 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8500 if (LHS.isInvalid() || RHS.isInvalid()) 8501 return QualType(); 8502 8503 // Enforce type constraints: C99 6.5.6p3. 8504 8505 // Handle the common case first (both operands are arithmetic). 8506 if (!compType.isNull() && compType->isArithmeticType()) { 8507 if (CompLHSTy) *CompLHSTy = compType; 8508 return compType; 8509 } 8510 8511 // Either ptr - int or ptr - ptr. 8512 if (LHS.get()->getType()->isAnyPointerType()) { 8513 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8514 8515 // Diagnose bad cases where we step over interface counts. 8516 if (LHS.get()->getType()->isObjCObjectPointerType() && 8517 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8518 return QualType(); 8519 8520 // The result type of a pointer-int computation is the pointer type. 8521 if (RHS.get()->getType()->isIntegerType()) { 8522 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8523 return QualType(); 8524 8525 // Check array bounds for pointer arithemtic 8526 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8527 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8528 8529 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8530 return LHS.get()->getType(); 8531 } 8532 8533 // Handle pointer-pointer subtractions. 8534 if (const PointerType *RHSPTy 8535 = RHS.get()->getType()->getAs<PointerType>()) { 8536 QualType rpointee = RHSPTy->getPointeeType(); 8537 8538 if (getLangOpts().CPlusPlus) { 8539 // Pointee types must be the same: C++ [expr.add] 8540 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8541 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8542 } 8543 } else { 8544 // Pointee types must be compatible C99 6.5.6p3 8545 if (!Context.typesAreCompatible( 8546 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8547 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8548 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8549 return QualType(); 8550 } 8551 } 8552 8553 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8554 LHS.get(), RHS.get())) 8555 return QualType(); 8556 8557 // The pointee type may have zero size. As an extension, a structure or 8558 // union may have zero size or an array may have zero length. In this 8559 // case subtraction does not make sense. 8560 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8561 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8562 if (ElementSize.isZero()) { 8563 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8564 << rpointee.getUnqualifiedType() 8565 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8566 } 8567 } 8568 8569 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8570 return Context.getPointerDiffType(); 8571 } 8572 } 8573 8574 return InvalidOperands(Loc, LHS, RHS); 8575 } 8576 8577 static bool isScopedEnumerationType(QualType T) { 8578 if (const EnumType *ET = T->getAs<EnumType>()) 8579 return ET->getDecl()->isScoped(); 8580 return false; 8581 } 8582 8583 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8584 SourceLocation Loc, BinaryOperatorKind Opc, 8585 QualType LHSType) { 8586 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8587 // so skip remaining warnings as we don't want to modify values within Sema. 8588 if (S.getLangOpts().OpenCL) 8589 return; 8590 8591 llvm::APSInt Right; 8592 // Check right/shifter operand 8593 if (RHS.get()->isValueDependent() || 8594 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8595 return; 8596 8597 if (Right.isNegative()) { 8598 S.DiagRuntimeBehavior(Loc, RHS.get(), 8599 S.PDiag(diag::warn_shift_negative) 8600 << RHS.get()->getSourceRange()); 8601 return; 8602 } 8603 llvm::APInt LeftBits(Right.getBitWidth(), 8604 S.Context.getTypeSize(LHS.get()->getType())); 8605 if (Right.uge(LeftBits)) { 8606 S.DiagRuntimeBehavior(Loc, RHS.get(), 8607 S.PDiag(diag::warn_shift_gt_typewidth) 8608 << RHS.get()->getSourceRange()); 8609 return; 8610 } 8611 if (Opc != BO_Shl) 8612 return; 8613 8614 // When left shifting an ICE which is signed, we can check for overflow which 8615 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8616 // integers have defined behavior modulo one more than the maximum value 8617 // representable in the result type, so never warn for those. 8618 llvm::APSInt Left; 8619 if (LHS.get()->isValueDependent() || 8620 LHSType->hasUnsignedIntegerRepresentation() || 8621 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8622 return; 8623 8624 // If LHS does not have a signed type and non-negative value 8625 // then, the behavior is undefined. Warn about it. 8626 if (Left.isNegative()) { 8627 S.DiagRuntimeBehavior(Loc, LHS.get(), 8628 S.PDiag(diag::warn_shift_lhs_negative) 8629 << LHS.get()->getSourceRange()); 8630 return; 8631 } 8632 8633 llvm::APInt ResultBits = 8634 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8635 if (LeftBits.uge(ResultBits)) 8636 return; 8637 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8638 Result = Result.shl(Right); 8639 8640 // Print the bit representation of the signed integer as an unsigned 8641 // hexadecimal number. 8642 SmallString<40> HexResult; 8643 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8644 8645 // If we are only missing a sign bit, this is less likely to result in actual 8646 // bugs -- if the result is cast back to an unsigned type, it will have the 8647 // expected value. Thus we place this behind a different warning that can be 8648 // turned off separately if needed. 8649 if (LeftBits == ResultBits - 1) { 8650 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8651 << HexResult << LHSType 8652 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8653 return; 8654 } 8655 8656 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8657 << HexResult.str() << Result.getMinSignedBits() << LHSType 8658 << Left.getBitWidth() << LHS.get()->getSourceRange() 8659 << RHS.get()->getSourceRange(); 8660 } 8661 8662 /// \brief Return the resulting type when an OpenCL vector is shifted 8663 /// by a scalar or vector shift amount. 8664 static QualType checkOpenCLVectorShift(Sema &S, 8665 ExprResult &LHS, ExprResult &RHS, 8666 SourceLocation Loc, bool IsCompAssign) { 8667 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8668 if (!LHS.get()->getType()->isVectorType()) { 8669 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8670 << RHS.get()->getType() << LHS.get()->getType() 8671 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8672 return QualType(); 8673 } 8674 8675 if (!IsCompAssign) { 8676 LHS = S.UsualUnaryConversions(LHS.get()); 8677 if (LHS.isInvalid()) return QualType(); 8678 } 8679 8680 RHS = S.UsualUnaryConversions(RHS.get()); 8681 if (RHS.isInvalid()) return QualType(); 8682 8683 QualType LHSType = LHS.get()->getType(); 8684 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8685 QualType LHSEleType = LHSVecTy->getElementType(); 8686 8687 // Note that RHS might not be a vector. 8688 QualType RHSType = RHS.get()->getType(); 8689 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8690 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8691 8692 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8693 if (!LHSEleType->isIntegerType()) { 8694 S.Diag(Loc, diag::err_typecheck_expect_int) 8695 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8696 return QualType(); 8697 } 8698 8699 if (!RHSEleType->isIntegerType()) { 8700 S.Diag(Loc, diag::err_typecheck_expect_int) 8701 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8702 return QualType(); 8703 } 8704 8705 if (RHSVecTy) { 8706 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8707 // are applied component-wise. So if RHS is a vector, then ensure 8708 // that the number of elements is the same as LHS... 8709 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8710 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8711 << LHS.get()->getType() << RHS.get()->getType() 8712 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8713 return QualType(); 8714 } 8715 } else { 8716 // ...else expand RHS to match the number of elements in LHS. 8717 QualType VecTy = 8718 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8719 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8720 } 8721 8722 return LHSType; 8723 } 8724 8725 // C99 6.5.7 8726 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8727 SourceLocation Loc, BinaryOperatorKind Opc, 8728 bool IsCompAssign) { 8729 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8730 8731 // Vector shifts promote their scalar inputs to vector type. 8732 if (LHS.get()->getType()->isVectorType() || 8733 RHS.get()->getType()->isVectorType()) { 8734 if (LangOpts.OpenCL) 8735 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8736 if (LangOpts.ZVector) { 8737 // The shift operators for the z vector extensions work basically 8738 // like OpenCL shifts, except that neither the LHS nor the RHS is 8739 // allowed to be a "vector bool". 8740 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8741 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8742 return InvalidOperands(Loc, LHS, RHS); 8743 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8744 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8745 return InvalidOperands(Loc, LHS, RHS); 8746 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8747 } 8748 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8749 /*AllowBothBool*/true, 8750 /*AllowBoolConversions*/false); 8751 } 8752 8753 // Shifts don't perform usual arithmetic conversions, they just do integer 8754 // promotions on each operand. C99 6.5.7p3 8755 8756 // For the LHS, do usual unary conversions, but then reset them away 8757 // if this is a compound assignment. 8758 ExprResult OldLHS = LHS; 8759 LHS = UsualUnaryConversions(LHS.get()); 8760 if (LHS.isInvalid()) 8761 return QualType(); 8762 QualType LHSType = LHS.get()->getType(); 8763 if (IsCompAssign) LHS = OldLHS; 8764 8765 // The RHS is simpler. 8766 RHS = UsualUnaryConversions(RHS.get()); 8767 if (RHS.isInvalid()) 8768 return QualType(); 8769 QualType RHSType = RHS.get()->getType(); 8770 8771 // C99 6.5.7p2: Each of the operands shall have integer type. 8772 if (!LHSType->hasIntegerRepresentation() || 8773 !RHSType->hasIntegerRepresentation()) 8774 return InvalidOperands(Loc, LHS, RHS); 8775 8776 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8777 // hasIntegerRepresentation() above instead of this. 8778 if (isScopedEnumerationType(LHSType) || 8779 isScopedEnumerationType(RHSType)) { 8780 return InvalidOperands(Loc, LHS, RHS); 8781 } 8782 // Sanity-check shift operands 8783 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8784 8785 // "The type of the result is that of the promoted left operand." 8786 return LHSType; 8787 } 8788 8789 static bool IsWithinTemplateSpecialization(Decl *D) { 8790 if (DeclContext *DC = D->getDeclContext()) { 8791 if (isa<ClassTemplateSpecializationDecl>(DC)) 8792 return true; 8793 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8794 return FD->isFunctionTemplateSpecialization(); 8795 } 8796 return false; 8797 } 8798 8799 /// If two different enums are compared, raise a warning. 8800 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8801 Expr *RHS) { 8802 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8803 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8804 8805 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8806 if (!LHSEnumType) 8807 return; 8808 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8809 if (!RHSEnumType) 8810 return; 8811 8812 // Ignore anonymous enums. 8813 if (!LHSEnumType->getDecl()->getIdentifier()) 8814 return; 8815 if (!RHSEnumType->getDecl()->getIdentifier()) 8816 return; 8817 8818 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8819 return; 8820 8821 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8822 << LHSStrippedType << RHSStrippedType 8823 << LHS->getSourceRange() << RHS->getSourceRange(); 8824 } 8825 8826 /// \brief Diagnose bad pointer comparisons. 8827 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8828 ExprResult &LHS, ExprResult &RHS, 8829 bool IsError) { 8830 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8831 : diag::ext_typecheck_comparison_of_distinct_pointers) 8832 << LHS.get()->getType() << RHS.get()->getType() 8833 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8834 } 8835 8836 /// \brief Returns false if the pointers are converted to a composite type, 8837 /// true otherwise. 8838 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8839 ExprResult &LHS, ExprResult &RHS) { 8840 // C++ [expr.rel]p2: 8841 // [...] Pointer conversions (4.10) and qualification 8842 // conversions (4.4) are performed on pointer operands (or on 8843 // a pointer operand and a null pointer constant) to bring 8844 // them to their composite pointer type. [...] 8845 // 8846 // C++ [expr.eq]p1 uses the same notion for (in)equality 8847 // comparisons of pointers. 8848 8849 // C++ [expr.eq]p2: 8850 // In addition, pointers to members can be compared, or a pointer to 8851 // member and a null pointer constant. Pointer to member conversions 8852 // (4.11) and qualification conversions (4.4) are performed to bring 8853 // them to a common type. If one operand is a null pointer constant, 8854 // the common type is the type of the other operand. Otherwise, the 8855 // common type is a pointer to member type similar (4.4) to the type 8856 // of one of the operands, with a cv-qualification signature (4.4) 8857 // that is the union of the cv-qualification signatures of the operand 8858 // types. 8859 8860 QualType LHSType = LHS.get()->getType(); 8861 QualType RHSType = RHS.get()->getType(); 8862 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8863 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8864 8865 bool NonStandardCompositeType = false; 8866 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8867 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8868 if (T.isNull()) { 8869 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8870 return true; 8871 } 8872 8873 if (NonStandardCompositeType) 8874 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8875 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8876 << RHS.get()->getSourceRange(); 8877 8878 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8879 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8880 return false; 8881 } 8882 8883 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8884 ExprResult &LHS, 8885 ExprResult &RHS, 8886 bool IsError) { 8887 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8888 : diag::ext_typecheck_comparison_of_fptr_to_void) 8889 << LHS.get()->getType() << RHS.get()->getType() 8890 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8891 } 8892 8893 static bool isObjCObjectLiteral(ExprResult &E) { 8894 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8895 case Stmt::ObjCArrayLiteralClass: 8896 case Stmt::ObjCDictionaryLiteralClass: 8897 case Stmt::ObjCStringLiteralClass: 8898 case Stmt::ObjCBoxedExprClass: 8899 return true; 8900 default: 8901 // Note that ObjCBoolLiteral is NOT an object literal! 8902 return false; 8903 } 8904 } 8905 8906 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8907 const ObjCObjectPointerType *Type = 8908 LHS->getType()->getAs<ObjCObjectPointerType>(); 8909 8910 // If this is not actually an Objective-C object, bail out. 8911 if (!Type) 8912 return false; 8913 8914 // Get the LHS object's interface type. 8915 QualType InterfaceType = Type->getPointeeType(); 8916 8917 // If the RHS isn't an Objective-C object, bail out. 8918 if (!RHS->getType()->isObjCObjectPointerType()) 8919 return false; 8920 8921 // Try to find the -isEqual: method. 8922 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8923 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8924 InterfaceType, 8925 /*instance=*/true); 8926 if (!Method) { 8927 if (Type->isObjCIdType()) { 8928 // For 'id', just check the global pool. 8929 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8930 /*receiverId=*/true); 8931 } else { 8932 // Check protocols. 8933 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8934 /*instance=*/true); 8935 } 8936 } 8937 8938 if (!Method) 8939 return false; 8940 8941 QualType T = Method->parameters()[0]->getType(); 8942 if (!T->isObjCObjectPointerType()) 8943 return false; 8944 8945 QualType R = Method->getReturnType(); 8946 if (!R->isScalarType()) 8947 return false; 8948 8949 return true; 8950 } 8951 8952 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8953 FromE = FromE->IgnoreParenImpCasts(); 8954 switch (FromE->getStmtClass()) { 8955 default: 8956 break; 8957 case Stmt::ObjCStringLiteralClass: 8958 // "string literal" 8959 return LK_String; 8960 case Stmt::ObjCArrayLiteralClass: 8961 // "array literal" 8962 return LK_Array; 8963 case Stmt::ObjCDictionaryLiteralClass: 8964 // "dictionary literal" 8965 return LK_Dictionary; 8966 case Stmt::BlockExprClass: 8967 return LK_Block; 8968 case Stmt::ObjCBoxedExprClass: { 8969 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8970 switch (Inner->getStmtClass()) { 8971 case Stmt::IntegerLiteralClass: 8972 case Stmt::FloatingLiteralClass: 8973 case Stmt::CharacterLiteralClass: 8974 case Stmt::ObjCBoolLiteralExprClass: 8975 case Stmt::CXXBoolLiteralExprClass: 8976 // "numeric literal" 8977 return LK_Numeric; 8978 case Stmt::ImplicitCastExprClass: { 8979 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8980 // Boolean literals can be represented by implicit casts. 8981 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8982 return LK_Numeric; 8983 break; 8984 } 8985 default: 8986 break; 8987 } 8988 return LK_Boxed; 8989 } 8990 } 8991 return LK_None; 8992 } 8993 8994 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8995 ExprResult &LHS, ExprResult &RHS, 8996 BinaryOperator::Opcode Opc){ 8997 Expr *Literal; 8998 Expr *Other; 8999 if (isObjCObjectLiteral(LHS)) { 9000 Literal = LHS.get(); 9001 Other = RHS.get(); 9002 } else { 9003 Literal = RHS.get(); 9004 Other = LHS.get(); 9005 } 9006 9007 // Don't warn on comparisons against nil. 9008 Other = Other->IgnoreParenCasts(); 9009 if (Other->isNullPointerConstant(S.getASTContext(), 9010 Expr::NPC_ValueDependentIsNotNull)) 9011 return; 9012 9013 // This should be kept in sync with warn_objc_literal_comparison. 9014 // LK_String should always be after the other literals, since it has its own 9015 // warning flag. 9016 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9017 assert(LiteralKind != Sema::LK_Block); 9018 if (LiteralKind == Sema::LK_None) { 9019 llvm_unreachable("Unknown Objective-C object literal kind"); 9020 } 9021 9022 if (LiteralKind == Sema::LK_String) 9023 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9024 << Literal->getSourceRange(); 9025 else 9026 S.Diag(Loc, diag::warn_objc_literal_comparison) 9027 << LiteralKind << Literal->getSourceRange(); 9028 9029 if (BinaryOperator::isEqualityOp(Opc) && 9030 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9031 SourceLocation Start = LHS.get()->getLocStart(); 9032 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9033 CharSourceRange OpRange = 9034 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9035 9036 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9037 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9038 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9039 << FixItHint::CreateInsertion(End, "]"); 9040 } 9041 } 9042 9043 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 9044 ExprResult &RHS, 9045 SourceLocation Loc, 9046 BinaryOperatorKind Opc) { 9047 // Check that left hand side is !something. 9048 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9049 if (!UO || UO->getOpcode() != UO_LNot) return; 9050 9051 // Only check if the right hand side is non-bool arithmetic type. 9052 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9053 9054 // Make sure that the something in !something is not bool. 9055 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9056 if (SubExpr->isKnownToHaveBooleanValue()) return; 9057 9058 // Emit warning. 9059 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 9060 << Loc; 9061 9062 // First note suggest !(x < y) 9063 SourceLocation FirstOpen = SubExpr->getLocStart(); 9064 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9065 FirstClose = S.getLocForEndOfToken(FirstClose); 9066 if (FirstClose.isInvalid()) 9067 FirstOpen = SourceLocation(); 9068 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9069 << FixItHint::CreateInsertion(FirstOpen, "(") 9070 << FixItHint::CreateInsertion(FirstClose, ")"); 9071 9072 // Second note suggests (!x) < y 9073 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9074 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9075 SecondClose = S.getLocForEndOfToken(SecondClose); 9076 if (SecondClose.isInvalid()) 9077 SecondOpen = SourceLocation(); 9078 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9079 << FixItHint::CreateInsertion(SecondOpen, "(") 9080 << FixItHint::CreateInsertion(SecondClose, ")"); 9081 } 9082 9083 // Get the decl for a simple expression: a reference to a variable, 9084 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9085 static ValueDecl *getCompareDecl(Expr *E) { 9086 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9087 return DR->getDecl(); 9088 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9089 if (Ivar->isFreeIvar()) 9090 return Ivar->getDecl(); 9091 } 9092 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9093 if (Mem->isImplicitAccess()) 9094 return Mem->getMemberDecl(); 9095 } 9096 return nullptr; 9097 } 9098 9099 // C99 6.5.8, C++ [expr.rel] 9100 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9101 SourceLocation Loc, BinaryOperatorKind Opc, 9102 bool IsRelational) { 9103 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9104 9105 // Handle vector comparisons separately. 9106 if (LHS.get()->getType()->isVectorType() || 9107 RHS.get()->getType()->isVectorType()) 9108 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9109 9110 QualType LHSType = LHS.get()->getType(); 9111 QualType RHSType = RHS.get()->getType(); 9112 9113 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9114 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9115 9116 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9117 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 9118 9119 if (!LHSType->hasFloatingRepresentation() && 9120 !(LHSType->isBlockPointerType() && IsRelational) && 9121 !LHS.get()->getLocStart().isMacroID() && 9122 !RHS.get()->getLocStart().isMacroID() && 9123 ActiveTemplateInstantiations.empty()) { 9124 // For non-floating point types, check for self-comparisons of the form 9125 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9126 // often indicate logic errors in the program. 9127 // 9128 // NOTE: Don't warn about comparison expressions resulting from macro 9129 // expansion. Also don't warn about comparisons which are only self 9130 // comparisons within a template specialization. The warnings should catch 9131 // obvious cases in the definition of the template anyways. The idea is to 9132 // warn when the typed comparison operator will always evaluate to the same 9133 // result. 9134 ValueDecl *DL = getCompareDecl(LHSStripped); 9135 ValueDecl *DR = getCompareDecl(RHSStripped); 9136 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9137 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9138 << 0 // self- 9139 << (Opc == BO_EQ 9140 || Opc == BO_LE 9141 || Opc == BO_GE)); 9142 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9143 !DL->getType()->isReferenceType() && 9144 !DR->getType()->isReferenceType()) { 9145 // what is it always going to eval to? 9146 char always_evals_to; 9147 switch(Opc) { 9148 case BO_EQ: // e.g. array1 == array2 9149 always_evals_to = 0; // false 9150 break; 9151 case BO_NE: // e.g. array1 != array2 9152 always_evals_to = 1; // true 9153 break; 9154 default: 9155 // best we can say is 'a constant' 9156 always_evals_to = 2; // e.g. array1 <= array2 9157 break; 9158 } 9159 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9160 << 1 // array 9161 << always_evals_to); 9162 } 9163 9164 if (isa<CastExpr>(LHSStripped)) 9165 LHSStripped = LHSStripped->IgnoreParenCasts(); 9166 if (isa<CastExpr>(RHSStripped)) 9167 RHSStripped = RHSStripped->IgnoreParenCasts(); 9168 9169 // Warn about comparisons against a string constant (unless the other 9170 // operand is null), the user probably wants strcmp. 9171 Expr *literalString = nullptr; 9172 Expr *literalStringStripped = nullptr; 9173 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9174 !RHSStripped->isNullPointerConstant(Context, 9175 Expr::NPC_ValueDependentIsNull)) { 9176 literalString = LHS.get(); 9177 literalStringStripped = LHSStripped; 9178 } else if ((isa<StringLiteral>(RHSStripped) || 9179 isa<ObjCEncodeExpr>(RHSStripped)) && 9180 !LHSStripped->isNullPointerConstant(Context, 9181 Expr::NPC_ValueDependentIsNull)) { 9182 literalString = RHS.get(); 9183 literalStringStripped = RHSStripped; 9184 } 9185 9186 if (literalString) { 9187 DiagRuntimeBehavior(Loc, nullptr, 9188 PDiag(diag::warn_stringcompare) 9189 << isa<ObjCEncodeExpr>(literalStringStripped) 9190 << literalString->getSourceRange()); 9191 } 9192 } 9193 9194 // C99 6.5.8p3 / C99 6.5.9p4 9195 UsualArithmeticConversions(LHS, RHS); 9196 if (LHS.isInvalid() || RHS.isInvalid()) 9197 return QualType(); 9198 9199 LHSType = LHS.get()->getType(); 9200 RHSType = RHS.get()->getType(); 9201 9202 // The result of comparisons is 'bool' in C++, 'int' in C. 9203 QualType ResultTy = Context.getLogicalOperationType(); 9204 9205 if (IsRelational) { 9206 if (LHSType->isRealType() && RHSType->isRealType()) 9207 return ResultTy; 9208 } else { 9209 // Check for comparisons of floating point operands using != and ==. 9210 if (LHSType->hasFloatingRepresentation()) 9211 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9212 9213 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9214 return ResultTy; 9215 } 9216 9217 const Expr::NullPointerConstantKind LHSNullKind = 9218 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9219 const Expr::NullPointerConstantKind RHSNullKind = 9220 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9221 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9222 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9223 9224 if (!IsRelational && LHSIsNull != RHSIsNull) { 9225 bool IsEquality = Opc == BO_EQ; 9226 if (RHSIsNull) 9227 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9228 RHS.get()->getSourceRange()); 9229 else 9230 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9231 LHS.get()->getSourceRange()); 9232 } 9233 9234 // All of the following pointer-related warnings are GCC extensions, except 9235 // when handling null pointer constants. 9236 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 9237 QualType LCanPointeeTy = 9238 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9239 QualType RCanPointeeTy = 9240 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9241 9242 if (getLangOpts().CPlusPlus) { 9243 if (LCanPointeeTy == RCanPointeeTy) 9244 return ResultTy; 9245 if (!IsRelational && 9246 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9247 // Valid unless comparison between non-null pointer and function pointer 9248 // This is a gcc extension compatibility comparison. 9249 // In a SFINAE context, we treat this as a hard error to maintain 9250 // conformance with the C++ standard. 9251 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9252 && !LHSIsNull && !RHSIsNull) { 9253 diagnoseFunctionPointerToVoidComparison( 9254 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9255 9256 if (isSFINAEContext()) 9257 return QualType(); 9258 9259 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9260 return ResultTy; 9261 } 9262 } 9263 9264 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9265 return QualType(); 9266 else 9267 return ResultTy; 9268 } 9269 // C99 6.5.9p2 and C99 6.5.8p2 9270 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9271 RCanPointeeTy.getUnqualifiedType())) { 9272 // Valid unless a relational comparison of function pointers 9273 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9274 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9275 << LHSType << RHSType << LHS.get()->getSourceRange() 9276 << RHS.get()->getSourceRange(); 9277 } 9278 } else if (!IsRelational && 9279 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9280 // Valid unless comparison between non-null pointer and function pointer 9281 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9282 && !LHSIsNull && !RHSIsNull) 9283 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9284 /*isError*/false); 9285 } else { 9286 // Invalid 9287 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9288 } 9289 if (LCanPointeeTy != RCanPointeeTy) { 9290 // Treat NULL constant as a special case in OpenCL. 9291 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9292 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9293 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9294 Diag(Loc, 9295 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9296 << LHSType << RHSType << 0 /* comparison */ 9297 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9298 } 9299 } 9300 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9301 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9302 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9303 : CK_BitCast; 9304 if (LHSIsNull && !RHSIsNull) 9305 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9306 else 9307 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9308 } 9309 return ResultTy; 9310 } 9311 9312 if (getLangOpts().CPlusPlus) { 9313 // Comparison of nullptr_t with itself. 9314 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9315 return ResultTy; 9316 9317 // Comparison of pointers with null pointer constants and equality 9318 // comparisons of member pointers to null pointer constants. 9319 if (RHSIsNull && 9320 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9321 (!IsRelational && 9322 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9323 RHS = ImpCastExprToType(RHS.get(), LHSType, 9324 LHSType->isMemberPointerType() 9325 ? CK_NullToMemberPointer 9326 : CK_NullToPointer); 9327 return ResultTy; 9328 } 9329 if (LHSIsNull && 9330 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9331 (!IsRelational && 9332 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9333 LHS = ImpCastExprToType(LHS.get(), RHSType, 9334 RHSType->isMemberPointerType() 9335 ? CK_NullToMemberPointer 9336 : CK_NullToPointer); 9337 return ResultTy; 9338 } 9339 9340 // Comparison of member pointers. 9341 if (!IsRelational && 9342 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9343 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9344 return QualType(); 9345 else 9346 return ResultTy; 9347 } 9348 9349 // Handle scoped enumeration types specifically, since they don't promote 9350 // to integers. 9351 if (LHS.get()->getType()->isEnumeralType() && 9352 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9353 RHS.get()->getType())) 9354 return ResultTy; 9355 } 9356 9357 // Handle block pointer types. 9358 if (!IsRelational && LHSType->isBlockPointerType() && 9359 RHSType->isBlockPointerType()) { 9360 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9361 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9362 9363 if (!LHSIsNull && !RHSIsNull && 9364 !Context.typesAreCompatible(lpointee, rpointee)) { 9365 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9366 << LHSType << RHSType << LHS.get()->getSourceRange() 9367 << RHS.get()->getSourceRange(); 9368 } 9369 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9370 return ResultTy; 9371 } 9372 9373 // Allow block pointers to be compared with null pointer constants. 9374 if (!IsRelational 9375 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9376 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9377 if (!LHSIsNull && !RHSIsNull) { 9378 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9379 ->getPointeeType()->isVoidType()) 9380 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9381 ->getPointeeType()->isVoidType()))) 9382 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9383 << LHSType << RHSType << LHS.get()->getSourceRange() 9384 << RHS.get()->getSourceRange(); 9385 } 9386 if (LHSIsNull && !RHSIsNull) 9387 LHS = ImpCastExprToType(LHS.get(), RHSType, 9388 RHSType->isPointerType() ? CK_BitCast 9389 : CK_AnyPointerToBlockPointerCast); 9390 else 9391 RHS = ImpCastExprToType(RHS.get(), LHSType, 9392 LHSType->isPointerType() ? CK_BitCast 9393 : CK_AnyPointerToBlockPointerCast); 9394 return ResultTy; 9395 } 9396 9397 if (LHSType->isObjCObjectPointerType() || 9398 RHSType->isObjCObjectPointerType()) { 9399 const PointerType *LPT = LHSType->getAs<PointerType>(); 9400 const PointerType *RPT = RHSType->getAs<PointerType>(); 9401 if (LPT || RPT) { 9402 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9403 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9404 9405 if (!LPtrToVoid && !RPtrToVoid && 9406 !Context.typesAreCompatible(LHSType, RHSType)) { 9407 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9408 /*isError*/false); 9409 } 9410 if (LHSIsNull && !RHSIsNull) { 9411 Expr *E = LHS.get(); 9412 if (getLangOpts().ObjCAutoRefCount) 9413 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9414 LHS = ImpCastExprToType(E, RHSType, 9415 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9416 } 9417 else { 9418 Expr *E = RHS.get(); 9419 if (getLangOpts().ObjCAutoRefCount) 9420 CheckObjCARCConversion(SourceRange(), LHSType, E, 9421 CCK_ImplicitConversion, /*Diagnose=*/true, 9422 /*DiagnoseCFAudited=*/false, Opc); 9423 RHS = ImpCastExprToType(E, LHSType, 9424 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9425 } 9426 return ResultTy; 9427 } 9428 if (LHSType->isObjCObjectPointerType() && 9429 RHSType->isObjCObjectPointerType()) { 9430 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9431 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9432 /*isError*/false); 9433 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9434 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9435 9436 if (LHSIsNull && !RHSIsNull) 9437 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9438 else 9439 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9440 return ResultTy; 9441 } 9442 } 9443 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9444 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9445 unsigned DiagID = 0; 9446 bool isError = false; 9447 if (LangOpts.DebuggerSupport) { 9448 // Under a debugger, allow the comparison of pointers to integers, 9449 // since users tend to want to compare addresses. 9450 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9451 (RHSIsNull && RHSType->isIntegerType())) { 9452 if (IsRelational && !getLangOpts().CPlusPlus) 9453 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9454 } else if (IsRelational && !getLangOpts().CPlusPlus) 9455 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9456 else if (getLangOpts().CPlusPlus) { 9457 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9458 isError = true; 9459 } else 9460 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9461 9462 if (DiagID) { 9463 Diag(Loc, DiagID) 9464 << LHSType << RHSType << LHS.get()->getSourceRange() 9465 << RHS.get()->getSourceRange(); 9466 if (isError) 9467 return QualType(); 9468 } 9469 9470 if (LHSType->isIntegerType()) 9471 LHS = ImpCastExprToType(LHS.get(), RHSType, 9472 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9473 else 9474 RHS = ImpCastExprToType(RHS.get(), LHSType, 9475 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9476 return ResultTy; 9477 } 9478 9479 // Handle block pointers. 9480 if (!IsRelational && RHSIsNull 9481 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9482 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9483 return ResultTy; 9484 } 9485 if (!IsRelational && LHSIsNull 9486 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9487 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9488 return ResultTy; 9489 } 9490 9491 return InvalidOperands(Loc, LHS, RHS); 9492 } 9493 9494 9495 // Return a signed type that is of identical size and number of elements. 9496 // For floating point vectors, return an integer type of identical size 9497 // and number of elements. 9498 QualType Sema::GetSignedVectorType(QualType V) { 9499 const VectorType *VTy = V->getAs<VectorType>(); 9500 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9501 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9502 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9503 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9504 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9505 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9506 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9507 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9508 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9509 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9510 "Unhandled vector element size in vector compare"); 9511 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9512 } 9513 9514 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9515 /// operates on extended vector types. Instead of producing an IntTy result, 9516 /// like a scalar comparison, a vector comparison produces a vector of integer 9517 /// types. 9518 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9519 SourceLocation Loc, 9520 bool IsRelational) { 9521 // Check to make sure we're operating on vectors of the same type and width, 9522 // Allowing one side to be a scalar of element type. 9523 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9524 /*AllowBothBool*/true, 9525 /*AllowBoolConversions*/getLangOpts().ZVector); 9526 if (vType.isNull()) 9527 return vType; 9528 9529 QualType LHSType = LHS.get()->getType(); 9530 9531 // If AltiVec, the comparison results in a numeric type, i.e. 9532 // bool for C++, int for C 9533 if (getLangOpts().AltiVec && 9534 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9535 return Context.getLogicalOperationType(); 9536 9537 // For non-floating point types, check for self-comparisons of the form 9538 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9539 // often indicate logic errors in the program. 9540 if (!LHSType->hasFloatingRepresentation() && 9541 ActiveTemplateInstantiations.empty()) { 9542 if (DeclRefExpr* DRL 9543 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9544 if (DeclRefExpr* DRR 9545 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9546 if (DRL->getDecl() == DRR->getDecl()) 9547 DiagRuntimeBehavior(Loc, nullptr, 9548 PDiag(diag::warn_comparison_always) 9549 << 0 // self- 9550 << 2 // "a constant" 9551 ); 9552 } 9553 9554 // Check for comparisons of floating point operands using != and ==. 9555 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9556 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9557 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9558 } 9559 9560 // Return a signed type for the vector. 9561 return GetSignedVectorType(vType); 9562 } 9563 9564 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9565 SourceLocation Loc) { 9566 // Ensure that either both operands are of the same vector type, or 9567 // one operand is of a vector type and the other is of its element type. 9568 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9569 /*AllowBothBool*/true, 9570 /*AllowBoolConversions*/false); 9571 if (vType.isNull()) 9572 return InvalidOperands(Loc, LHS, RHS); 9573 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9574 vType->hasFloatingRepresentation()) 9575 return InvalidOperands(Loc, LHS, RHS); 9576 9577 return GetSignedVectorType(LHS.get()->getType()); 9578 } 9579 9580 inline QualType Sema::CheckBitwiseOperands( 9581 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9582 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9583 9584 if (LHS.get()->getType()->isVectorType() || 9585 RHS.get()->getType()->isVectorType()) { 9586 if (LHS.get()->getType()->hasIntegerRepresentation() && 9587 RHS.get()->getType()->hasIntegerRepresentation()) 9588 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9589 /*AllowBothBool*/true, 9590 /*AllowBoolConversions*/getLangOpts().ZVector); 9591 return InvalidOperands(Loc, LHS, RHS); 9592 } 9593 9594 ExprResult LHSResult = LHS, RHSResult = RHS; 9595 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9596 IsCompAssign); 9597 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9598 return QualType(); 9599 LHS = LHSResult.get(); 9600 RHS = RHSResult.get(); 9601 9602 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9603 return compType; 9604 return InvalidOperands(Loc, LHS, RHS); 9605 } 9606 9607 // C99 6.5.[13,14] 9608 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9609 SourceLocation Loc, 9610 BinaryOperatorKind Opc) { 9611 // Check vector operands differently. 9612 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9613 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9614 9615 // Diagnose cases where the user write a logical and/or but probably meant a 9616 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9617 // is a constant. 9618 if (LHS.get()->getType()->isIntegerType() && 9619 !LHS.get()->getType()->isBooleanType() && 9620 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9621 // Don't warn in macros or template instantiations. 9622 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9623 // If the RHS can be constant folded, and if it constant folds to something 9624 // that isn't 0 or 1 (which indicate a potential logical operation that 9625 // happened to fold to true/false) then warn. 9626 // Parens on the RHS are ignored. 9627 llvm::APSInt Result; 9628 if (RHS.get()->EvaluateAsInt(Result, Context)) 9629 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9630 !RHS.get()->getExprLoc().isMacroID()) || 9631 (Result != 0 && Result != 1)) { 9632 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9633 << RHS.get()->getSourceRange() 9634 << (Opc == BO_LAnd ? "&&" : "||"); 9635 // Suggest replacing the logical operator with the bitwise version 9636 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9637 << (Opc == BO_LAnd ? "&" : "|") 9638 << FixItHint::CreateReplacement(SourceRange( 9639 Loc, getLocForEndOfToken(Loc)), 9640 Opc == BO_LAnd ? "&" : "|"); 9641 if (Opc == BO_LAnd) 9642 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9643 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9644 << FixItHint::CreateRemoval( 9645 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9646 RHS.get()->getLocEnd())); 9647 } 9648 } 9649 9650 if (!Context.getLangOpts().CPlusPlus) { 9651 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9652 // not operate on the built-in scalar and vector float types. 9653 if (Context.getLangOpts().OpenCL && 9654 Context.getLangOpts().OpenCLVersion < 120) { 9655 if (LHS.get()->getType()->isFloatingType() || 9656 RHS.get()->getType()->isFloatingType()) 9657 return InvalidOperands(Loc, LHS, RHS); 9658 } 9659 9660 LHS = UsualUnaryConversions(LHS.get()); 9661 if (LHS.isInvalid()) 9662 return QualType(); 9663 9664 RHS = UsualUnaryConversions(RHS.get()); 9665 if (RHS.isInvalid()) 9666 return QualType(); 9667 9668 if (!LHS.get()->getType()->isScalarType() || 9669 !RHS.get()->getType()->isScalarType()) 9670 return InvalidOperands(Loc, LHS, RHS); 9671 9672 return Context.IntTy; 9673 } 9674 9675 // The following is safe because we only use this method for 9676 // non-overloadable operands. 9677 9678 // C++ [expr.log.and]p1 9679 // C++ [expr.log.or]p1 9680 // The operands are both contextually converted to type bool. 9681 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9682 if (LHSRes.isInvalid()) 9683 return InvalidOperands(Loc, LHS, RHS); 9684 LHS = LHSRes; 9685 9686 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9687 if (RHSRes.isInvalid()) 9688 return InvalidOperands(Loc, LHS, RHS); 9689 RHS = RHSRes; 9690 9691 // C++ [expr.log.and]p2 9692 // C++ [expr.log.or]p2 9693 // The result is a bool. 9694 return Context.BoolTy; 9695 } 9696 9697 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9698 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9699 if (!ME) return false; 9700 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9701 ObjCMessageExpr *Base = 9702 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9703 if (!Base) return false; 9704 return Base->getMethodDecl() != nullptr; 9705 } 9706 9707 /// Is the given expression (which must be 'const') a reference to a 9708 /// variable which was originally non-const, but which has become 9709 /// 'const' due to being captured within a block? 9710 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9711 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9712 assert(E->isLValue() && E->getType().isConstQualified()); 9713 E = E->IgnoreParens(); 9714 9715 // Must be a reference to a declaration from an enclosing scope. 9716 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9717 if (!DRE) return NCCK_None; 9718 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9719 9720 // The declaration must be a variable which is not declared 'const'. 9721 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9722 if (!var) return NCCK_None; 9723 if (var->getType().isConstQualified()) return NCCK_None; 9724 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9725 9726 // Decide whether the first capture was for a block or a lambda. 9727 DeclContext *DC = S.CurContext, *Prev = nullptr; 9728 // Decide whether the first capture was for a block or a lambda. 9729 while (DC) { 9730 // For init-capture, it is possible that the variable belongs to the 9731 // template pattern of the current context. 9732 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9733 if (var->isInitCapture() && 9734 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9735 break; 9736 if (DC == var->getDeclContext()) 9737 break; 9738 Prev = DC; 9739 DC = DC->getParent(); 9740 } 9741 // Unless we have an init-capture, we've gone one step too far. 9742 if (!var->isInitCapture()) 9743 DC = Prev; 9744 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9745 } 9746 9747 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9748 Ty = Ty.getNonReferenceType(); 9749 if (IsDereference && Ty->isPointerType()) 9750 Ty = Ty->getPointeeType(); 9751 return !Ty.isConstQualified(); 9752 } 9753 9754 /// Emit the "read-only variable not assignable" error and print notes to give 9755 /// more information about why the variable is not assignable, such as pointing 9756 /// to the declaration of a const variable, showing that a method is const, or 9757 /// that the function is returning a const reference. 9758 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9759 SourceLocation Loc) { 9760 // Update err_typecheck_assign_const and note_typecheck_assign_const 9761 // when this enum is changed. 9762 enum { 9763 ConstFunction, 9764 ConstVariable, 9765 ConstMember, 9766 ConstMethod, 9767 ConstUnknown, // Keep as last element 9768 }; 9769 9770 SourceRange ExprRange = E->getSourceRange(); 9771 9772 // Only emit one error on the first const found. All other consts will emit 9773 // a note to the error. 9774 bool DiagnosticEmitted = false; 9775 9776 // Track if the current expression is the result of a derefence, and if the 9777 // next checked expression is the result of a derefence. 9778 bool IsDereference = false; 9779 bool NextIsDereference = false; 9780 9781 // Loop to process MemberExpr chains. 9782 while (true) { 9783 IsDereference = NextIsDereference; 9784 NextIsDereference = false; 9785 9786 E = E->IgnoreParenImpCasts(); 9787 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9788 NextIsDereference = ME->isArrow(); 9789 const ValueDecl *VD = ME->getMemberDecl(); 9790 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9791 // Mutable fields can be modified even if the class is const. 9792 if (Field->isMutable()) { 9793 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9794 break; 9795 } 9796 9797 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9798 if (!DiagnosticEmitted) { 9799 S.Diag(Loc, diag::err_typecheck_assign_const) 9800 << ExprRange << ConstMember << false /*static*/ << Field 9801 << Field->getType(); 9802 DiagnosticEmitted = true; 9803 } 9804 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9805 << ConstMember << false /*static*/ << Field << Field->getType() 9806 << Field->getSourceRange(); 9807 } 9808 E = ME->getBase(); 9809 continue; 9810 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9811 if (VDecl->getType().isConstQualified()) { 9812 if (!DiagnosticEmitted) { 9813 S.Diag(Loc, diag::err_typecheck_assign_const) 9814 << ExprRange << ConstMember << true /*static*/ << VDecl 9815 << VDecl->getType(); 9816 DiagnosticEmitted = true; 9817 } 9818 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9819 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9820 << VDecl->getSourceRange(); 9821 } 9822 // Static fields do not inherit constness from parents. 9823 break; 9824 } 9825 break; 9826 } // End MemberExpr 9827 break; 9828 } 9829 9830 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9831 // Function calls 9832 const FunctionDecl *FD = CE->getDirectCallee(); 9833 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9834 if (!DiagnosticEmitted) { 9835 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9836 << ConstFunction << FD; 9837 DiagnosticEmitted = true; 9838 } 9839 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9840 diag::note_typecheck_assign_const) 9841 << ConstFunction << FD << FD->getReturnType() 9842 << FD->getReturnTypeSourceRange(); 9843 } 9844 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9845 // Point to variable declaration. 9846 if (const ValueDecl *VD = DRE->getDecl()) { 9847 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9848 if (!DiagnosticEmitted) { 9849 S.Diag(Loc, diag::err_typecheck_assign_const) 9850 << ExprRange << ConstVariable << VD << VD->getType(); 9851 DiagnosticEmitted = true; 9852 } 9853 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9854 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9855 } 9856 } 9857 } else if (isa<CXXThisExpr>(E)) { 9858 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9859 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9860 if (MD->isConst()) { 9861 if (!DiagnosticEmitted) { 9862 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9863 << ConstMethod << MD; 9864 DiagnosticEmitted = true; 9865 } 9866 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9867 << ConstMethod << MD << MD->getSourceRange(); 9868 } 9869 } 9870 } 9871 } 9872 9873 if (DiagnosticEmitted) 9874 return; 9875 9876 // Can't determine a more specific message, so display the generic error. 9877 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9878 } 9879 9880 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9881 /// emit an error and return true. If so, return false. 9882 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9883 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9884 9885 S.CheckShadowingDeclModification(E, Loc); 9886 9887 SourceLocation OrigLoc = Loc; 9888 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9889 &Loc); 9890 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9891 IsLV = Expr::MLV_InvalidMessageExpression; 9892 if (IsLV == Expr::MLV_Valid) 9893 return false; 9894 9895 unsigned DiagID = 0; 9896 bool NeedType = false; 9897 switch (IsLV) { // C99 6.5.16p2 9898 case Expr::MLV_ConstQualified: 9899 // Use a specialized diagnostic when we're assigning to an object 9900 // from an enclosing function or block. 9901 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9902 if (NCCK == NCCK_Block) 9903 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9904 else 9905 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9906 break; 9907 } 9908 9909 // In ARC, use some specialized diagnostics for occasions where we 9910 // infer 'const'. These are always pseudo-strong variables. 9911 if (S.getLangOpts().ObjCAutoRefCount) { 9912 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9913 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9914 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9915 9916 // Use the normal diagnostic if it's pseudo-__strong but the 9917 // user actually wrote 'const'. 9918 if (var->isARCPseudoStrong() && 9919 (!var->getTypeSourceInfo() || 9920 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9921 // There are two pseudo-strong cases: 9922 // - self 9923 ObjCMethodDecl *method = S.getCurMethodDecl(); 9924 if (method && var == method->getSelfDecl()) 9925 DiagID = method->isClassMethod() 9926 ? diag::err_typecheck_arc_assign_self_class_method 9927 : diag::err_typecheck_arc_assign_self; 9928 9929 // - fast enumeration variables 9930 else 9931 DiagID = diag::err_typecheck_arr_assign_enumeration; 9932 9933 SourceRange Assign; 9934 if (Loc != OrigLoc) 9935 Assign = SourceRange(OrigLoc, OrigLoc); 9936 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9937 // We need to preserve the AST regardless, so migration tool 9938 // can do its job. 9939 return false; 9940 } 9941 } 9942 } 9943 9944 // If none of the special cases above are triggered, then this is a 9945 // simple const assignment. 9946 if (DiagID == 0) { 9947 DiagnoseConstAssignment(S, E, Loc); 9948 return true; 9949 } 9950 9951 break; 9952 case Expr::MLV_ConstAddrSpace: 9953 DiagnoseConstAssignment(S, E, Loc); 9954 return true; 9955 case Expr::MLV_ArrayType: 9956 case Expr::MLV_ArrayTemporary: 9957 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9958 NeedType = true; 9959 break; 9960 case Expr::MLV_NotObjectType: 9961 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9962 NeedType = true; 9963 break; 9964 case Expr::MLV_LValueCast: 9965 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9966 break; 9967 case Expr::MLV_Valid: 9968 llvm_unreachable("did not take early return for MLV_Valid"); 9969 case Expr::MLV_InvalidExpression: 9970 case Expr::MLV_MemberFunction: 9971 case Expr::MLV_ClassTemporary: 9972 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9973 break; 9974 case Expr::MLV_IncompleteType: 9975 case Expr::MLV_IncompleteVoidType: 9976 return S.RequireCompleteType(Loc, E->getType(), 9977 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9978 case Expr::MLV_DuplicateVectorComponents: 9979 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9980 break; 9981 case Expr::MLV_NoSetterProperty: 9982 llvm_unreachable("readonly properties should be processed differently"); 9983 case Expr::MLV_InvalidMessageExpression: 9984 DiagID = diag::error_readonly_message_assignment; 9985 break; 9986 case Expr::MLV_SubObjCPropertySetting: 9987 DiagID = diag::error_no_subobject_property_setting; 9988 break; 9989 } 9990 9991 SourceRange Assign; 9992 if (Loc != OrigLoc) 9993 Assign = SourceRange(OrigLoc, OrigLoc); 9994 if (NeedType) 9995 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9996 else 9997 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9998 return true; 9999 } 10000 10001 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10002 SourceLocation Loc, 10003 Sema &Sema) { 10004 // C / C++ fields 10005 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10006 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10007 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10008 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10009 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10010 } 10011 10012 // Objective-C instance variables 10013 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10014 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10015 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10016 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10017 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10018 if (RL && RR && RL->getDecl() == RR->getDecl()) 10019 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10020 } 10021 } 10022 10023 // C99 6.5.16.1 10024 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10025 SourceLocation Loc, 10026 QualType CompoundType) { 10027 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10028 10029 // Verify that LHS is a modifiable lvalue, and emit error if not. 10030 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10031 return QualType(); 10032 10033 QualType LHSType = LHSExpr->getType(); 10034 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10035 CompoundType; 10036 AssignConvertType ConvTy; 10037 if (CompoundType.isNull()) { 10038 Expr *RHSCheck = RHS.get(); 10039 10040 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10041 10042 QualType LHSTy(LHSType); 10043 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10044 if (RHS.isInvalid()) 10045 return QualType(); 10046 // Special case of NSObject attributes on c-style pointer types. 10047 if (ConvTy == IncompatiblePointer && 10048 ((Context.isObjCNSObjectType(LHSType) && 10049 RHSType->isObjCObjectPointerType()) || 10050 (Context.isObjCNSObjectType(RHSType) && 10051 LHSType->isObjCObjectPointerType()))) 10052 ConvTy = Compatible; 10053 10054 if (ConvTy == Compatible && 10055 LHSType->isObjCObjectType()) 10056 Diag(Loc, diag::err_objc_object_assignment) 10057 << LHSType; 10058 10059 // If the RHS is a unary plus or minus, check to see if they = and + are 10060 // right next to each other. If so, the user may have typo'd "x =+ 4" 10061 // instead of "x += 4". 10062 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10063 RHSCheck = ICE->getSubExpr(); 10064 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10065 if ((UO->getOpcode() == UO_Plus || 10066 UO->getOpcode() == UO_Minus) && 10067 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10068 // Only if the two operators are exactly adjacent. 10069 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10070 // And there is a space or other character before the subexpr of the 10071 // unary +/-. We don't want to warn on "x=-1". 10072 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10073 UO->getSubExpr()->getLocStart().isFileID()) { 10074 Diag(Loc, diag::warn_not_compound_assign) 10075 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10076 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10077 } 10078 } 10079 10080 if (ConvTy == Compatible) { 10081 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10082 // Warn about retain cycles where a block captures the LHS, but 10083 // not if the LHS is a simple variable into which the block is 10084 // being stored...unless that variable can be captured by reference! 10085 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10086 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10087 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10088 checkRetainCycles(LHSExpr, RHS.get()); 10089 10090 // It is safe to assign a weak reference into a strong variable. 10091 // Although this code can still have problems: 10092 // id x = self.weakProp; 10093 // id y = self.weakProp; 10094 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10095 // paths through the function. This should be revisited if 10096 // -Wrepeated-use-of-weak is made flow-sensitive. 10097 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10098 RHS.get()->getLocStart())) 10099 getCurFunction()->markSafeWeakUse(RHS.get()); 10100 10101 } else if (getLangOpts().ObjCAutoRefCount) { 10102 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10103 } 10104 } 10105 } else { 10106 // Compound assignment "x += y" 10107 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10108 } 10109 10110 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10111 RHS.get(), AA_Assigning)) 10112 return QualType(); 10113 10114 CheckForNullPointerDereference(*this, LHSExpr); 10115 10116 // C99 6.5.16p3: The type of an assignment expression is the type of the 10117 // left operand unless the left operand has qualified type, in which case 10118 // it is the unqualified version of the type of the left operand. 10119 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10120 // is converted to the type of the assignment expression (above). 10121 // C++ 5.17p1: the type of the assignment expression is that of its left 10122 // operand. 10123 return (getLangOpts().CPlusPlus 10124 ? LHSType : LHSType.getUnqualifiedType()); 10125 } 10126 10127 // Only ignore explicit casts to void. 10128 static bool IgnoreCommaOperand(const Expr *E) { 10129 E = E->IgnoreParens(); 10130 10131 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10132 if (CE->getCastKind() == CK_ToVoid) { 10133 return true; 10134 } 10135 } 10136 10137 return false; 10138 } 10139 10140 // Look for instances where it is likely the comma operator is confused with 10141 // another operator. There is a whitelist of acceptable expressions for the 10142 // left hand side of the comma operator, otherwise emit a warning. 10143 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10144 // No warnings in macros 10145 if (Loc.isMacroID()) 10146 return; 10147 10148 // Don't warn in template instantiations. 10149 if (!ActiveTemplateInstantiations.empty()) 10150 return; 10151 10152 // Scope isn't fine-grained enough to whitelist the specific cases, so 10153 // instead, skip more than needed, then call back into here with the 10154 // CommaVisitor in SemaStmt.cpp. 10155 // The whitelisted locations are the initialization and increment portions 10156 // of a for loop. The additional checks are on the condition of 10157 // if statements, do/while loops, and for loops. 10158 const unsigned ForIncrementFlags = 10159 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10160 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10161 const unsigned ScopeFlags = getCurScope()->getFlags(); 10162 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10163 (ScopeFlags & ForInitFlags) == ForInitFlags) 10164 return; 10165 10166 // If there are multiple comma operators used together, get the RHS of the 10167 // of the comma operator as the LHS. 10168 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10169 if (BO->getOpcode() != BO_Comma) 10170 break; 10171 LHS = BO->getRHS(); 10172 } 10173 10174 // Only allow some expressions on LHS to not warn. 10175 if (IgnoreCommaOperand(LHS)) 10176 return; 10177 10178 Diag(Loc, diag::warn_comma_operator); 10179 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10180 << LHS->getSourceRange() 10181 << FixItHint::CreateInsertion(LHS->getLocStart(), 10182 LangOpts.CPlusPlus ? "static_cast<void>(" 10183 : "(void)(") 10184 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10185 ")"); 10186 } 10187 10188 // C99 6.5.17 10189 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10190 SourceLocation Loc) { 10191 LHS = S.CheckPlaceholderExpr(LHS.get()); 10192 RHS = S.CheckPlaceholderExpr(RHS.get()); 10193 if (LHS.isInvalid() || RHS.isInvalid()) 10194 return QualType(); 10195 10196 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10197 // operands, but not unary promotions. 10198 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10199 10200 // So we treat the LHS as a ignored value, and in C++ we allow the 10201 // containing site to determine what should be done with the RHS. 10202 LHS = S.IgnoredValueConversions(LHS.get()); 10203 if (LHS.isInvalid()) 10204 return QualType(); 10205 10206 S.DiagnoseUnusedExprResult(LHS.get()); 10207 10208 if (!S.getLangOpts().CPlusPlus) { 10209 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10210 if (RHS.isInvalid()) 10211 return QualType(); 10212 if (!RHS.get()->getType()->isVoidType()) 10213 S.RequireCompleteType(Loc, RHS.get()->getType(), 10214 diag::err_incomplete_type); 10215 } 10216 10217 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10218 S.DiagnoseCommaOperator(LHS.get(), Loc); 10219 10220 return RHS.get()->getType(); 10221 } 10222 10223 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10224 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10225 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10226 ExprValueKind &VK, 10227 ExprObjectKind &OK, 10228 SourceLocation OpLoc, 10229 bool IsInc, bool IsPrefix) { 10230 if (Op->isTypeDependent()) 10231 return S.Context.DependentTy; 10232 10233 QualType ResType = Op->getType(); 10234 // Atomic types can be used for increment / decrement where the non-atomic 10235 // versions can, so ignore the _Atomic() specifier for the purpose of 10236 // checking. 10237 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10238 ResType = ResAtomicType->getValueType(); 10239 10240 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10241 10242 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10243 // Decrement of bool is not allowed. 10244 if (!IsInc) { 10245 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10246 return QualType(); 10247 } 10248 // Increment of bool sets it to true, but is deprecated. 10249 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10250 : diag::warn_increment_bool) 10251 << Op->getSourceRange(); 10252 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10253 // Error on enum increments and decrements in C++ mode 10254 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10255 return QualType(); 10256 } else if (ResType->isRealType()) { 10257 // OK! 10258 } else if (ResType->isPointerType()) { 10259 // C99 6.5.2.4p2, 6.5.6p2 10260 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10261 return QualType(); 10262 } else if (ResType->isObjCObjectPointerType()) { 10263 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10264 // Otherwise, we just need a complete type. 10265 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10266 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10267 return QualType(); 10268 } else if (ResType->isAnyComplexType()) { 10269 // C99 does not support ++/-- on complex types, we allow as an extension. 10270 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10271 << ResType << Op->getSourceRange(); 10272 } else if (ResType->isPlaceholderType()) { 10273 ExprResult PR = S.CheckPlaceholderExpr(Op); 10274 if (PR.isInvalid()) return QualType(); 10275 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10276 IsInc, IsPrefix); 10277 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10278 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10279 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10280 (ResType->getAs<VectorType>()->getVectorKind() != 10281 VectorType::AltiVecBool)) { 10282 // The z vector extensions allow ++ and -- for non-bool vectors. 10283 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10284 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10285 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10286 } else { 10287 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10288 << ResType << int(IsInc) << Op->getSourceRange(); 10289 return QualType(); 10290 } 10291 // At this point, we know we have a real, complex or pointer type. 10292 // Now make sure the operand is a modifiable lvalue. 10293 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10294 return QualType(); 10295 // In C++, a prefix increment is the same type as the operand. Otherwise 10296 // (in C or with postfix), the increment is the unqualified type of the 10297 // operand. 10298 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10299 VK = VK_LValue; 10300 OK = Op->getObjectKind(); 10301 return ResType; 10302 } else { 10303 VK = VK_RValue; 10304 return ResType.getUnqualifiedType(); 10305 } 10306 } 10307 10308 10309 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10310 /// This routine allows us to typecheck complex/recursive expressions 10311 /// where the declaration is needed for type checking. We only need to 10312 /// handle cases when the expression references a function designator 10313 /// or is an lvalue. Here are some examples: 10314 /// - &(x) => x 10315 /// - &*****f => f for f a function designator. 10316 /// - &s.xx => s 10317 /// - &s.zz[1].yy -> s, if zz is an array 10318 /// - *(x + 1) -> x, if x is an array 10319 /// - &"123"[2] -> 0 10320 /// - & __real__ x -> x 10321 static ValueDecl *getPrimaryDecl(Expr *E) { 10322 switch (E->getStmtClass()) { 10323 case Stmt::DeclRefExprClass: 10324 return cast<DeclRefExpr>(E)->getDecl(); 10325 case Stmt::MemberExprClass: 10326 // If this is an arrow operator, the address is an offset from 10327 // the base's value, so the object the base refers to is 10328 // irrelevant. 10329 if (cast<MemberExpr>(E)->isArrow()) 10330 return nullptr; 10331 // Otherwise, the expression refers to a part of the base 10332 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10333 case Stmt::ArraySubscriptExprClass: { 10334 // FIXME: This code shouldn't be necessary! We should catch the implicit 10335 // promotion of register arrays earlier. 10336 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10337 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10338 if (ICE->getSubExpr()->getType()->isArrayType()) 10339 return getPrimaryDecl(ICE->getSubExpr()); 10340 } 10341 return nullptr; 10342 } 10343 case Stmt::UnaryOperatorClass: { 10344 UnaryOperator *UO = cast<UnaryOperator>(E); 10345 10346 switch(UO->getOpcode()) { 10347 case UO_Real: 10348 case UO_Imag: 10349 case UO_Extension: 10350 return getPrimaryDecl(UO->getSubExpr()); 10351 default: 10352 return nullptr; 10353 } 10354 } 10355 case Stmt::ParenExprClass: 10356 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10357 case Stmt::ImplicitCastExprClass: 10358 // If the result of an implicit cast is an l-value, we care about 10359 // the sub-expression; otherwise, the result here doesn't matter. 10360 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10361 default: 10362 return nullptr; 10363 } 10364 } 10365 10366 namespace { 10367 enum { 10368 AO_Bit_Field = 0, 10369 AO_Vector_Element = 1, 10370 AO_Property_Expansion = 2, 10371 AO_Register_Variable = 3, 10372 AO_No_Error = 4 10373 }; 10374 } 10375 /// \brief Diagnose invalid operand for address of operations. 10376 /// 10377 /// \param Type The type of operand which cannot have its address taken. 10378 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10379 Expr *E, unsigned Type) { 10380 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10381 } 10382 10383 /// CheckAddressOfOperand - The operand of & must be either a function 10384 /// designator or an lvalue designating an object. If it is an lvalue, the 10385 /// object cannot be declared with storage class register or be a bit field. 10386 /// Note: The usual conversions are *not* applied to the operand of the & 10387 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10388 /// In C++, the operand might be an overloaded function name, in which case 10389 /// we allow the '&' but retain the overloaded-function type. 10390 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10391 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10392 if (PTy->getKind() == BuiltinType::Overload) { 10393 Expr *E = OrigOp.get()->IgnoreParens(); 10394 if (!isa<OverloadExpr>(E)) { 10395 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10396 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10397 << OrigOp.get()->getSourceRange(); 10398 return QualType(); 10399 } 10400 10401 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10402 if (isa<UnresolvedMemberExpr>(Ovl)) 10403 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10404 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10405 << OrigOp.get()->getSourceRange(); 10406 return QualType(); 10407 } 10408 10409 return Context.OverloadTy; 10410 } 10411 10412 if (PTy->getKind() == BuiltinType::UnknownAny) 10413 return Context.UnknownAnyTy; 10414 10415 if (PTy->getKind() == BuiltinType::BoundMember) { 10416 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10417 << OrigOp.get()->getSourceRange(); 10418 return QualType(); 10419 } 10420 10421 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10422 if (OrigOp.isInvalid()) return QualType(); 10423 } 10424 10425 if (OrigOp.get()->isTypeDependent()) 10426 return Context.DependentTy; 10427 10428 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10429 10430 // Make sure to ignore parentheses in subsequent checks 10431 Expr *op = OrigOp.get()->IgnoreParens(); 10432 10433 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10434 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10435 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10436 return QualType(); 10437 } 10438 10439 if (getLangOpts().C99) { 10440 // Implement C99-only parts of addressof rules. 10441 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10442 if (uOp->getOpcode() == UO_Deref) 10443 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10444 // (assuming the deref expression is valid). 10445 return uOp->getSubExpr()->getType(); 10446 } 10447 // Technically, there should be a check for array subscript 10448 // expressions here, but the result of one is always an lvalue anyway. 10449 } 10450 ValueDecl *dcl = getPrimaryDecl(op); 10451 10452 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10453 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10454 op->getLocStart())) 10455 return QualType(); 10456 10457 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10458 unsigned AddressOfError = AO_No_Error; 10459 10460 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10461 bool sfinae = (bool)isSFINAEContext(); 10462 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10463 : diag::ext_typecheck_addrof_temporary) 10464 << op->getType() << op->getSourceRange(); 10465 if (sfinae) 10466 return QualType(); 10467 // Materialize the temporary as an lvalue so that we can take its address. 10468 OrigOp = op = 10469 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10470 } else if (isa<ObjCSelectorExpr>(op)) { 10471 return Context.getPointerType(op->getType()); 10472 } else if (lval == Expr::LV_MemberFunction) { 10473 // If it's an instance method, make a member pointer. 10474 // The expression must have exactly the form &A::foo. 10475 10476 // If the underlying expression isn't a decl ref, give up. 10477 if (!isa<DeclRefExpr>(op)) { 10478 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10479 << OrigOp.get()->getSourceRange(); 10480 return QualType(); 10481 } 10482 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10483 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10484 10485 // The id-expression was parenthesized. 10486 if (OrigOp.get() != DRE) { 10487 Diag(OpLoc, diag::err_parens_pointer_member_function) 10488 << OrigOp.get()->getSourceRange(); 10489 10490 // The method was named without a qualifier. 10491 } else if (!DRE->getQualifier()) { 10492 if (MD->getParent()->getName().empty()) 10493 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10494 << op->getSourceRange(); 10495 else { 10496 SmallString<32> Str; 10497 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10498 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10499 << op->getSourceRange() 10500 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10501 } 10502 } 10503 10504 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10505 if (isa<CXXDestructorDecl>(MD)) 10506 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10507 10508 QualType MPTy = Context.getMemberPointerType( 10509 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10510 // Under the MS ABI, lock down the inheritance model now. 10511 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10512 (void)isCompleteType(OpLoc, MPTy); 10513 return MPTy; 10514 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10515 // C99 6.5.3.2p1 10516 // The operand must be either an l-value or a function designator 10517 if (!op->getType()->isFunctionType()) { 10518 // Use a special diagnostic for loads from property references. 10519 if (isa<PseudoObjectExpr>(op)) { 10520 AddressOfError = AO_Property_Expansion; 10521 } else { 10522 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10523 << op->getType() << op->getSourceRange(); 10524 return QualType(); 10525 } 10526 } 10527 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10528 // The operand cannot be a bit-field 10529 AddressOfError = AO_Bit_Field; 10530 } else if (op->getObjectKind() == OK_VectorComponent) { 10531 // The operand cannot be an element of a vector 10532 AddressOfError = AO_Vector_Element; 10533 } else if (dcl) { // C99 6.5.3.2p1 10534 // We have an lvalue with a decl. Make sure the decl is not declared 10535 // with the register storage-class specifier. 10536 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10537 // in C++ it is not error to take address of a register 10538 // variable (c++03 7.1.1P3) 10539 if (vd->getStorageClass() == SC_Register && 10540 !getLangOpts().CPlusPlus) { 10541 AddressOfError = AO_Register_Variable; 10542 } 10543 } else if (isa<MSPropertyDecl>(dcl)) { 10544 AddressOfError = AO_Property_Expansion; 10545 } else if (isa<FunctionTemplateDecl>(dcl)) { 10546 return Context.OverloadTy; 10547 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10548 // Okay: we can take the address of a field. 10549 // Could be a pointer to member, though, if there is an explicit 10550 // scope qualifier for the class. 10551 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10552 DeclContext *Ctx = dcl->getDeclContext(); 10553 if (Ctx && Ctx->isRecord()) { 10554 if (dcl->getType()->isReferenceType()) { 10555 Diag(OpLoc, 10556 diag::err_cannot_form_pointer_to_member_of_reference_type) 10557 << dcl->getDeclName() << dcl->getType(); 10558 return QualType(); 10559 } 10560 10561 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10562 Ctx = Ctx->getParent(); 10563 10564 QualType MPTy = Context.getMemberPointerType( 10565 op->getType(), 10566 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10567 // Under the MS ABI, lock down the inheritance model now. 10568 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10569 (void)isCompleteType(OpLoc, MPTy); 10570 return MPTy; 10571 } 10572 } 10573 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10574 llvm_unreachable("Unknown/unexpected decl type"); 10575 } 10576 10577 if (AddressOfError != AO_No_Error) { 10578 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10579 return QualType(); 10580 } 10581 10582 if (lval == Expr::LV_IncompleteVoidType) { 10583 // Taking the address of a void variable is technically illegal, but we 10584 // allow it in cases which are otherwise valid. 10585 // Example: "extern void x; void* y = &x;". 10586 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10587 } 10588 10589 // If the operand has type "type", the result has type "pointer to type". 10590 if (op->getType()->isObjCObjectType()) 10591 return Context.getObjCObjectPointerType(op->getType()); 10592 10593 return Context.getPointerType(op->getType()); 10594 } 10595 10596 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10597 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10598 if (!DRE) 10599 return; 10600 const Decl *D = DRE->getDecl(); 10601 if (!D) 10602 return; 10603 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10604 if (!Param) 10605 return; 10606 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10607 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10608 return; 10609 if (FunctionScopeInfo *FD = S.getCurFunction()) 10610 if (!FD->ModifiedNonNullParams.count(Param)) 10611 FD->ModifiedNonNullParams.insert(Param); 10612 } 10613 10614 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10615 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10616 SourceLocation OpLoc) { 10617 if (Op->isTypeDependent()) 10618 return S.Context.DependentTy; 10619 10620 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10621 if (ConvResult.isInvalid()) 10622 return QualType(); 10623 Op = ConvResult.get(); 10624 QualType OpTy = Op->getType(); 10625 QualType Result; 10626 10627 if (isa<CXXReinterpretCastExpr>(Op)) { 10628 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10629 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10630 Op->getSourceRange()); 10631 } 10632 10633 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10634 { 10635 Result = PT->getPointeeType(); 10636 } 10637 else if (const ObjCObjectPointerType *OPT = 10638 OpTy->getAs<ObjCObjectPointerType>()) 10639 Result = OPT->getPointeeType(); 10640 else { 10641 ExprResult PR = S.CheckPlaceholderExpr(Op); 10642 if (PR.isInvalid()) return QualType(); 10643 if (PR.get() != Op) 10644 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10645 } 10646 10647 if (Result.isNull()) { 10648 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10649 << OpTy << Op->getSourceRange(); 10650 return QualType(); 10651 } 10652 10653 // Note that per both C89 and C99, indirection is always legal, even if Result 10654 // is an incomplete type or void. It would be possible to warn about 10655 // dereferencing a void pointer, but it's completely well-defined, and such a 10656 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10657 // for pointers to 'void' but is fine for any other pointer type: 10658 // 10659 // C++ [expr.unary.op]p1: 10660 // [...] the expression to which [the unary * operator] is applied shall 10661 // be a pointer to an object type, or a pointer to a function type 10662 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10663 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10664 << OpTy << Op->getSourceRange(); 10665 10666 // Dereferences are usually l-values... 10667 VK = VK_LValue; 10668 10669 // ...except that certain expressions are never l-values in C. 10670 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10671 VK = VK_RValue; 10672 10673 return Result; 10674 } 10675 10676 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10677 BinaryOperatorKind Opc; 10678 switch (Kind) { 10679 default: llvm_unreachable("Unknown binop!"); 10680 case tok::periodstar: Opc = BO_PtrMemD; break; 10681 case tok::arrowstar: Opc = BO_PtrMemI; break; 10682 case tok::star: Opc = BO_Mul; break; 10683 case tok::slash: Opc = BO_Div; break; 10684 case tok::percent: Opc = BO_Rem; break; 10685 case tok::plus: Opc = BO_Add; break; 10686 case tok::minus: Opc = BO_Sub; break; 10687 case tok::lessless: Opc = BO_Shl; break; 10688 case tok::greatergreater: Opc = BO_Shr; break; 10689 case tok::lessequal: Opc = BO_LE; break; 10690 case tok::less: Opc = BO_LT; break; 10691 case tok::greaterequal: Opc = BO_GE; break; 10692 case tok::greater: Opc = BO_GT; break; 10693 case tok::exclaimequal: Opc = BO_NE; break; 10694 case tok::equalequal: Opc = BO_EQ; break; 10695 case tok::amp: Opc = BO_And; break; 10696 case tok::caret: Opc = BO_Xor; break; 10697 case tok::pipe: Opc = BO_Or; break; 10698 case tok::ampamp: Opc = BO_LAnd; break; 10699 case tok::pipepipe: Opc = BO_LOr; break; 10700 case tok::equal: Opc = BO_Assign; break; 10701 case tok::starequal: Opc = BO_MulAssign; break; 10702 case tok::slashequal: Opc = BO_DivAssign; break; 10703 case tok::percentequal: Opc = BO_RemAssign; break; 10704 case tok::plusequal: Opc = BO_AddAssign; break; 10705 case tok::minusequal: Opc = BO_SubAssign; break; 10706 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10707 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10708 case tok::ampequal: Opc = BO_AndAssign; break; 10709 case tok::caretequal: Opc = BO_XorAssign; break; 10710 case tok::pipeequal: Opc = BO_OrAssign; break; 10711 case tok::comma: Opc = BO_Comma; break; 10712 } 10713 return Opc; 10714 } 10715 10716 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10717 tok::TokenKind Kind) { 10718 UnaryOperatorKind Opc; 10719 switch (Kind) { 10720 default: llvm_unreachable("Unknown unary op!"); 10721 case tok::plusplus: Opc = UO_PreInc; break; 10722 case tok::minusminus: Opc = UO_PreDec; break; 10723 case tok::amp: Opc = UO_AddrOf; break; 10724 case tok::star: Opc = UO_Deref; break; 10725 case tok::plus: Opc = UO_Plus; break; 10726 case tok::minus: Opc = UO_Minus; break; 10727 case tok::tilde: Opc = UO_Not; break; 10728 case tok::exclaim: Opc = UO_LNot; break; 10729 case tok::kw___real: Opc = UO_Real; break; 10730 case tok::kw___imag: Opc = UO_Imag; break; 10731 case tok::kw___extension__: Opc = UO_Extension; break; 10732 } 10733 return Opc; 10734 } 10735 10736 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10737 /// This warning is only emitted for builtin assignment operations. It is also 10738 /// suppressed in the event of macro expansions. 10739 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10740 SourceLocation OpLoc) { 10741 if (!S.ActiveTemplateInstantiations.empty()) 10742 return; 10743 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10744 return; 10745 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10746 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10747 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10748 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10749 if (!LHSDeclRef || !RHSDeclRef || 10750 LHSDeclRef->getLocation().isMacroID() || 10751 RHSDeclRef->getLocation().isMacroID()) 10752 return; 10753 const ValueDecl *LHSDecl = 10754 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10755 const ValueDecl *RHSDecl = 10756 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10757 if (LHSDecl != RHSDecl) 10758 return; 10759 if (LHSDecl->getType().isVolatileQualified()) 10760 return; 10761 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10762 if (RefTy->getPointeeType().isVolatileQualified()) 10763 return; 10764 10765 S.Diag(OpLoc, diag::warn_self_assignment) 10766 << LHSDeclRef->getType() 10767 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10768 } 10769 10770 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10771 /// is usually indicative of introspection within the Objective-C pointer. 10772 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10773 SourceLocation OpLoc) { 10774 if (!S.getLangOpts().ObjC1) 10775 return; 10776 10777 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10778 const Expr *LHS = L.get(); 10779 const Expr *RHS = R.get(); 10780 10781 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10782 ObjCPointerExpr = LHS; 10783 OtherExpr = RHS; 10784 } 10785 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10786 ObjCPointerExpr = RHS; 10787 OtherExpr = LHS; 10788 } 10789 10790 // This warning is deliberately made very specific to reduce false 10791 // positives with logic that uses '&' for hashing. This logic mainly 10792 // looks for code trying to introspect into tagged pointers, which 10793 // code should generally never do. 10794 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10795 unsigned Diag = diag::warn_objc_pointer_masking; 10796 // Determine if we are introspecting the result of performSelectorXXX. 10797 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10798 // Special case messages to -performSelector and friends, which 10799 // can return non-pointer values boxed in a pointer value. 10800 // Some clients may wish to silence warnings in this subcase. 10801 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10802 Selector S = ME->getSelector(); 10803 StringRef SelArg0 = S.getNameForSlot(0); 10804 if (SelArg0.startswith("performSelector")) 10805 Diag = diag::warn_objc_pointer_masking_performSelector; 10806 } 10807 10808 S.Diag(OpLoc, Diag) 10809 << ObjCPointerExpr->getSourceRange(); 10810 } 10811 } 10812 10813 static NamedDecl *getDeclFromExpr(Expr *E) { 10814 if (!E) 10815 return nullptr; 10816 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10817 return DRE->getDecl(); 10818 if (auto *ME = dyn_cast<MemberExpr>(E)) 10819 return ME->getMemberDecl(); 10820 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10821 return IRE->getDecl(); 10822 return nullptr; 10823 } 10824 10825 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10826 /// operator @p Opc at location @c TokLoc. This routine only supports 10827 /// built-in operations; ActOnBinOp handles overloaded operators. 10828 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10829 BinaryOperatorKind Opc, 10830 Expr *LHSExpr, Expr *RHSExpr) { 10831 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10832 // The syntax only allows initializer lists on the RHS of assignment, 10833 // so we don't need to worry about accepting invalid code for 10834 // non-assignment operators. 10835 // C++11 5.17p9: 10836 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10837 // of x = {} is x = T(). 10838 InitializationKind Kind = 10839 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10840 InitializedEntity Entity = 10841 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10842 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10843 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10844 if (Init.isInvalid()) 10845 return Init; 10846 RHSExpr = Init.get(); 10847 } 10848 10849 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10850 QualType ResultTy; // Result type of the binary operator. 10851 // The following two variables are used for compound assignment operators 10852 QualType CompLHSTy; // Type of LHS after promotions for computation 10853 QualType CompResultTy; // Type of computation result 10854 ExprValueKind VK = VK_RValue; 10855 ExprObjectKind OK = OK_Ordinary; 10856 10857 if (!getLangOpts().CPlusPlus) { 10858 // C cannot handle TypoExpr nodes on either side of a binop because it 10859 // doesn't handle dependent types properly, so make sure any TypoExprs have 10860 // been dealt with before checking the operands. 10861 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10862 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10863 if (Opc != BO_Assign) 10864 return ExprResult(E); 10865 // Avoid correcting the RHS to the same Expr as the LHS. 10866 Decl *D = getDeclFromExpr(E); 10867 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10868 }); 10869 if (!LHS.isUsable() || !RHS.isUsable()) 10870 return ExprError(); 10871 } 10872 10873 if (getLangOpts().OpenCL) { 10874 QualType LHSTy = LHSExpr->getType(); 10875 QualType RHSTy = RHSExpr->getType(); 10876 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10877 // the ATOMIC_VAR_INIT macro. 10878 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 10879 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10880 if (BO_Assign == Opc) 10881 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10882 else 10883 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10884 return ExprError(); 10885 } 10886 10887 // OpenCL special types - image, sampler, pipe, and blocks are to be used 10888 // only with a builtin functions and therefore should be disallowed here. 10889 if (LHSTy->isImageType() || RHSTy->isImageType() || 10890 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 10891 LHSTy->isPipeType() || RHSTy->isPipeType() || 10892 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 10893 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10894 return ExprError(); 10895 } 10896 } 10897 10898 switch (Opc) { 10899 case BO_Assign: 10900 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10901 if (getLangOpts().CPlusPlus && 10902 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10903 VK = LHS.get()->getValueKind(); 10904 OK = LHS.get()->getObjectKind(); 10905 } 10906 if (!ResultTy.isNull()) { 10907 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10908 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10909 } 10910 RecordModifiableNonNullParam(*this, LHS.get()); 10911 break; 10912 case BO_PtrMemD: 10913 case BO_PtrMemI: 10914 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10915 Opc == BO_PtrMemI); 10916 break; 10917 case BO_Mul: 10918 case BO_Div: 10919 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10920 Opc == BO_Div); 10921 break; 10922 case BO_Rem: 10923 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10924 break; 10925 case BO_Add: 10926 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10927 break; 10928 case BO_Sub: 10929 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10930 break; 10931 case BO_Shl: 10932 case BO_Shr: 10933 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10934 break; 10935 case BO_LE: 10936 case BO_LT: 10937 case BO_GE: 10938 case BO_GT: 10939 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10940 break; 10941 case BO_EQ: 10942 case BO_NE: 10943 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10944 break; 10945 case BO_And: 10946 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10947 case BO_Xor: 10948 case BO_Or: 10949 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10950 break; 10951 case BO_LAnd: 10952 case BO_LOr: 10953 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10954 break; 10955 case BO_MulAssign: 10956 case BO_DivAssign: 10957 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10958 Opc == BO_DivAssign); 10959 CompLHSTy = CompResultTy; 10960 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10961 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10962 break; 10963 case BO_RemAssign: 10964 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10965 CompLHSTy = CompResultTy; 10966 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10967 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10968 break; 10969 case BO_AddAssign: 10970 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10971 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10972 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10973 break; 10974 case BO_SubAssign: 10975 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10976 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10977 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10978 break; 10979 case BO_ShlAssign: 10980 case BO_ShrAssign: 10981 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10982 CompLHSTy = CompResultTy; 10983 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10984 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10985 break; 10986 case BO_AndAssign: 10987 case BO_OrAssign: // fallthrough 10988 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10989 case BO_XorAssign: 10990 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10991 CompLHSTy = CompResultTy; 10992 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10993 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10994 break; 10995 case BO_Comma: 10996 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10997 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10998 VK = RHS.get()->getValueKind(); 10999 OK = RHS.get()->getObjectKind(); 11000 } 11001 break; 11002 } 11003 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11004 return ExprError(); 11005 11006 // Check for array bounds violations for both sides of the BinaryOperator 11007 CheckArrayAccess(LHS.get()); 11008 CheckArrayAccess(RHS.get()); 11009 11010 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11011 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11012 &Context.Idents.get("object_setClass"), 11013 SourceLocation(), LookupOrdinaryName); 11014 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11015 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11016 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11017 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11018 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11019 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11020 } 11021 else 11022 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11023 } 11024 else if (const ObjCIvarRefExpr *OIRE = 11025 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11026 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11027 11028 if (CompResultTy.isNull()) 11029 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11030 OK, OpLoc, FPFeatures.fp_contract); 11031 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11032 OK_ObjCProperty) { 11033 VK = VK_LValue; 11034 OK = LHS.get()->getObjectKind(); 11035 } 11036 return new (Context) CompoundAssignOperator( 11037 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11038 OpLoc, FPFeatures.fp_contract); 11039 } 11040 11041 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11042 /// operators are mixed in a way that suggests that the programmer forgot that 11043 /// comparison operators have higher precedence. The most typical example of 11044 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11045 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11046 SourceLocation OpLoc, Expr *LHSExpr, 11047 Expr *RHSExpr) { 11048 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11049 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11050 11051 // Check that one of the sides is a comparison operator and the other isn't. 11052 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11053 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11054 if (isLeftComp == isRightComp) 11055 return; 11056 11057 // Bitwise operations are sometimes used as eager logical ops. 11058 // Don't diagnose this. 11059 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11060 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11061 if (isLeftBitwise || isRightBitwise) 11062 return; 11063 11064 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11065 OpLoc) 11066 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11067 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11068 SourceRange ParensRange = isLeftComp ? 11069 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11070 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11071 11072 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11073 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11074 SuggestParentheses(Self, OpLoc, 11075 Self.PDiag(diag::note_precedence_silence) << OpStr, 11076 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11077 SuggestParentheses(Self, OpLoc, 11078 Self.PDiag(diag::note_precedence_bitwise_first) 11079 << BinaryOperator::getOpcodeStr(Opc), 11080 ParensRange); 11081 } 11082 11083 /// \brief It accepts a '&&' expr that is inside a '||' one. 11084 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11085 /// in parentheses. 11086 static void 11087 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11088 BinaryOperator *Bop) { 11089 assert(Bop->getOpcode() == BO_LAnd); 11090 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11091 << Bop->getSourceRange() << OpLoc; 11092 SuggestParentheses(Self, Bop->getOperatorLoc(), 11093 Self.PDiag(diag::note_precedence_silence) 11094 << Bop->getOpcodeStr(), 11095 Bop->getSourceRange()); 11096 } 11097 11098 /// \brief Returns true if the given expression can be evaluated as a constant 11099 /// 'true'. 11100 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11101 bool Res; 11102 return !E->isValueDependent() && 11103 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11104 } 11105 11106 /// \brief Returns true if the given expression can be evaluated as a constant 11107 /// 'false'. 11108 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11109 bool Res; 11110 return !E->isValueDependent() && 11111 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11112 } 11113 11114 /// \brief Look for '&&' in the left hand of a '||' expr. 11115 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11116 Expr *LHSExpr, Expr *RHSExpr) { 11117 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11118 if (Bop->getOpcode() == BO_LAnd) { 11119 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11120 if (EvaluatesAsFalse(S, RHSExpr)) 11121 return; 11122 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11123 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11124 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11125 } else if (Bop->getOpcode() == BO_LOr) { 11126 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11127 // If it's "a || b && 1 || c" we didn't warn earlier for 11128 // "a || b && 1", but warn now. 11129 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11130 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11131 } 11132 } 11133 } 11134 } 11135 11136 /// \brief Look for '&&' in the right hand of a '||' expr. 11137 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11138 Expr *LHSExpr, Expr *RHSExpr) { 11139 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11140 if (Bop->getOpcode() == BO_LAnd) { 11141 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11142 if (EvaluatesAsFalse(S, LHSExpr)) 11143 return; 11144 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11145 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11146 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11147 } 11148 } 11149 } 11150 11151 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11152 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11153 /// the '&' expression in parentheses. 11154 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11155 SourceLocation OpLoc, Expr *SubExpr) { 11156 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11157 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11158 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11159 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11160 << Bop->getSourceRange() << OpLoc; 11161 SuggestParentheses(S, Bop->getOperatorLoc(), 11162 S.PDiag(diag::note_precedence_silence) 11163 << Bop->getOpcodeStr(), 11164 Bop->getSourceRange()); 11165 } 11166 } 11167 } 11168 11169 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11170 Expr *SubExpr, StringRef Shift) { 11171 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11172 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11173 StringRef Op = Bop->getOpcodeStr(); 11174 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11175 << Bop->getSourceRange() << OpLoc << Shift << Op; 11176 SuggestParentheses(S, Bop->getOperatorLoc(), 11177 S.PDiag(diag::note_precedence_silence) << Op, 11178 Bop->getSourceRange()); 11179 } 11180 } 11181 } 11182 11183 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11184 Expr *LHSExpr, Expr *RHSExpr) { 11185 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11186 if (!OCE) 11187 return; 11188 11189 FunctionDecl *FD = OCE->getDirectCallee(); 11190 if (!FD || !FD->isOverloadedOperator()) 11191 return; 11192 11193 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11194 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11195 return; 11196 11197 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11198 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11199 << (Kind == OO_LessLess); 11200 SuggestParentheses(S, OCE->getOperatorLoc(), 11201 S.PDiag(diag::note_precedence_silence) 11202 << (Kind == OO_LessLess ? "<<" : ">>"), 11203 OCE->getSourceRange()); 11204 SuggestParentheses(S, OpLoc, 11205 S.PDiag(diag::note_evaluate_comparison_first), 11206 SourceRange(OCE->getArg(1)->getLocStart(), 11207 RHSExpr->getLocEnd())); 11208 } 11209 11210 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11211 /// precedence. 11212 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11213 SourceLocation OpLoc, Expr *LHSExpr, 11214 Expr *RHSExpr){ 11215 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11216 if (BinaryOperator::isBitwiseOp(Opc)) 11217 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11218 11219 // Diagnose "arg1 & arg2 | arg3" 11220 if ((Opc == BO_Or || Opc == BO_Xor) && 11221 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11222 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11223 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11224 } 11225 11226 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11227 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11228 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11229 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11230 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11231 } 11232 11233 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11234 || Opc == BO_Shr) { 11235 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11236 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11237 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11238 } 11239 11240 // Warn on overloaded shift operators and comparisons, such as: 11241 // cout << 5 == 4; 11242 if (BinaryOperator::isComparisonOp(Opc)) 11243 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11244 } 11245 11246 // Binary Operators. 'Tok' is the token for the operator. 11247 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11248 tok::TokenKind Kind, 11249 Expr *LHSExpr, Expr *RHSExpr) { 11250 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11251 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11252 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11253 11254 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11255 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11256 11257 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11258 } 11259 11260 /// Build an overloaded binary operator expression in the given scope. 11261 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11262 BinaryOperatorKind Opc, 11263 Expr *LHS, Expr *RHS) { 11264 // Find all of the overloaded operators visible from this 11265 // point. We perform both an operator-name lookup from the local 11266 // scope and an argument-dependent lookup based on the types of 11267 // the arguments. 11268 UnresolvedSet<16> Functions; 11269 OverloadedOperatorKind OverOp 11270 = BinaryOperator::getOverloadedOperator(Opc); 11271 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11272 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11273 RHS->getType(), Functions); 11274 11275 // Build the (potentially-overloaded, potentially-dependent) 11276 // binary operation. 11277 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11278 } 11279 11280 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11281 BinaryOperatorKind Opc, 11282 Expr *LHSExpr, Expr *RHSExpr) { 11283 // We want to end up calling one of checkPseudoObjectAssignment 11284 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11285 // both expressions are overloadable or either is type-dependent), 11286 // or CreateBuiltinBinOp (in any other case). We also want to get 11287 // any placeholder types out of the way. 11288 11289 // Handle pseudo-objects in the LHS. 11290 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11291 // Assignments with a pseudo-object l-value need special analysis. 11292 if (pty->getKind() == BuiltinType::PseudoObject && 11293 BinaryOperator::isAssignmentOp(Opc)) 11294 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11295 11296 // Don't resolve overloads if the other type is overloadable. 11297 if (pty->getKind() == BuiltinType::Overload) { 11298 // We can't actually test that if we still have a placeholder, 11299 // though. Fortunately, none of the exceptions we see in that 11300 // code below are valid when the LHS is an overload set. Note 11301 // that an overload set can be dependently-typed, but it never 11302 // instantiates to having an overloadable type. 11303 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11304 if (resolvedRHS.isInvalid()) return ExprError(); 11305 RHSExpr = resolvedRHS.get(); 11306 11307 if (RHSExpr->isTypeDependent() || 11308 RHSExpr->getType()->isOverloadableType()) 11309 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11310 } 11311 11312 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11313 if (LHS.isInvalid()) return ExprError(); 11314 LHSExpr = LHS.get(); 11315 } 11316 11317 // Handle pseudo-objects in the RHS. 11318 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11319 // An overload in the RHS can potentially be resolved by the type 11320 // being assigned to. 11321 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11322 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11323 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11324 11325 if (LHSExpr->getType()->isOverloadableType()) 11326 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11327 11328 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11329 } 11330 11331 // Don't resolve overloads if the other type is overloadable. 11332 if (pty->getKind() == BuiltinType::Overload && 11333 LHSExpr->getType()->isOverloadableType()) 11334 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11335 11336 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11337 if (!resolvedRHS.isUsable()) return ExprError(); 11338 RHSExpr = resolvedRHS.get(); 11339 } 11340 11341 if (getLangOpts().CPlusPlus) { 11342 // If either expression is type-dependent, always build an 11343 // overloaded op. 11344 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11345 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11346 11347 // Otherwise, build an overloaded op if either expression has an 11348 // overloadable type. 11349 if (LHSExpr->getType()->isOverloadableType() || 11350 RHSExpr->getType()->isOverloadableType()) 11351 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11352 } 11353 11354 // Build a built-in binary operation. 11355 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11356 } 11357 11358 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11359 UnaryOperatorKind Opc, 11360 Expr *InputExpr) { 11361 ExprResult Input = InputExpr; 11362 ExprValueKind VK = VK_RValue; 11363 ExprObjectKind OK = OK_Ordinary; 11364 QualType resultType; 11365 if (getLangOpts().OpenCL) { 11366 QualType Ty = InputExpr->getType(); 11367 // The only legal unary operation for atomics is '&'. 11368 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11369 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11370 // only with a builtin functions and therefore should be disallowed here. 11371 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11372 || Ty->isBlockPointerType())) { 11373 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11374 << InputExpr->getType() 11375 << Input.get()->getSourceRange()); 11376 } 11377 } 11378 switch (Opc) { 11379 case UO_PreInc: 11380 case UO_PreDec: 11381 case UO_PostInc: 11382 case UO_PostDec: 11383 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11384 OpLoc, 11385 Opc == UO_PreInc || 11386 Opc == UO_PostInc, 11387 Opc == UO_PreInc || 11388 Opc == UO_PreDec); 11389 break; 11390 case UO_AddrOf: 11391 resultType = CheckAddressOfOperand(Input, OpLoc); 11392 RecordModifiableNonNullParam(*this, InputExpr); 11393 break; 11394 case UO_Deref: { 11395 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11396 if (Input.isInvalid()) return ExprError(); 11397 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11398 break; 11399 } 11400 case UO_Plus: 11401 case UO_Minus: 11402 Input = UsualUnaryConversions(Input.get()); 11403 if (Input.isInvalid()) return ExprError(); 11404 resultType = Input.get()->getType(); 11405 if (resultType->isDependentType()) 11406 break; 11407 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11408 break; 11409 else if (resultType->isVectorType() && 11410 // The z vector extensions don't allow + or - with bool vectors. 11411 (!Context.getLangOpts().ZVector || 11412 resultType->getAs<VectorType>()->getVectorKind() != 11413 VectorType::AltiVecBool)) 11414 break; 11415 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11416 Opc == UO_Plus && 11417 resultType->isPointerType()) 11418 break; 11419 11420 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11421 << resultType << Input.get()->getSourceRange()); 11422 11423 case UO_Not: // bitwise complement 11424 Input = UsualUnaryConversions(Input.get()); 11425 if (Input.isInvalid()) 11426 return ExprError(); 11427 resultType = Input.get()->getType(); 11428 if (resultType->isDependentType()) 11429 break; 11430 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11431 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11432 // C99 does not support '~' for complex conjugation. 11433 Diag(OpLoc, diag::ext_integer_complement_complex) 11434 << resultType << Input.get()->getSourceRange(); 11435 else if (resultType->hasIntegerRepresentation()) 11436 break; 11437 else if (resultType->isExtVectorType()) { 11438 if (Context.getLangOpts().OpenCL) { 11439 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11440 // on vector float types. 11441 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11442 if (!T->isIntegerType()) 11443 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11444 << resultType << Input.get()->getSourceRange()); 11445 } 11446 break; 11447 } else { 11448 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11449 << resultType << Input.get()->getSourceRange()); 11450 } 11451 break; 11452 11453 case UO_LNot: // logical negation 11454 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11455 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11456 if (Input.isInvalid()) return ExprError(); 11457 resultType = Input.get()->getType(); 11458 11459 // Though we still have to promote half FP to float... 11460 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11461 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11462 resultType = Context.FloatTy; 11463 } 11464 11465 if (resultType->isDependentType()) 11466 break; 11467 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11468 // C99 6.5.3.3p1: ok, fallthrough; 11469 if (Context.getLangOpts().CPlusPlus) { 11470 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11471 // operand contextually converted to bool. 11472 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11473 ScalarTypeToBooleanCastKind(resultType)); 11474 } else if (Context.getLangOpts().OpenCL && 11475 Context.getLangOpts().OpenCLVersion < 120) { 11476 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11477 // operate on scalar float types. 11478 if (!resultType->isIntegerType()) 11479 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11480 << resultType << Input.get()->getSourceRange()); 11481 } 11482 } else if (resultType->isExtVectorType()) { 11483 if (Context.getLangOpts().OpenCL && 11484 Context.getLangOpts().OpenCLVersion < 120) { 11485 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11486 // operate on vector float types. 11487 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11488 if (!T->isIntegerType()) 11489 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11490 << resultType << Input.get()->getSourceRange()); 11491 } 11492 // Vector logical not returns the signed variant of the operand type. 11493 resultType = GetSignedVectorType(resultType); 11494 break; 11495 } else { 11496 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11497 << resultType << Input.get()->getSourceRange()); 11498 } 11499 11500 // LNot always has type int. C99 6.5.3.3p5. 11501 // In C++, it's bool. C++ 5.3.1p8 11502 resultType = Context.getLogicalOperationType(); 11503 break; 11504 case UO_Real: 11505 case UO_Imag: 11506 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11507 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11508 // complex l-values to ordinary l-values and all other values to r-values. 11509 if (Input.isInvalid()) return ExprError(); 11510 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11511 if (Input.get()->getValueKind() != VK_RValue && 11512 Input.get()->getObjectKind() == OK_Ordinary) 11513 VK = Input.get()->getValueKind(); 11514 } else if (!getLangOpts().CPlusPlus) { 11515 // In C, a volatile scalar is read by __imag. In C++, it is not. 11516 Input = DefaultLvalueConversion(Input.get()); 11517 } 11518 break; 11519 case UO_Extension: 11520 case UO_Coawait: 11521 resultType = Input.get()->getType(); 11522 VK = Input.get()->getValueKind(); 11523 OK = Input.get()->getObjectKind(); 11524 break; 11525 } 11526 if (resultType.isNull() || Input.isInvalid()) 11527 return ExprError(); 11528 11529 // Check for array bounds violations in the operand of the UnaryOperator, 11530 // except for the '*' and '&' operators that have to be handled specially 11531 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11532 // that are explicitly defined as valid by the standard). 11533 if (Opc != UO_AddrOf && Opc != UO_Deref) 11534 CheckArrayAccess(Input.get()); 11535 11536 return new (Context) 11537 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11538 } 11539 11540 /// \brief Determine whether the given expression is a qualified member 11541 /// access expression, of a form that could be turned into a pointer to member 11542 /// with the address-of operator. 11543 static bool isQualifiedMemberAccess(Expr *E) { 11544 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11545 if (!DRE->getQualifier()) 11546 return false; 11547 11548 ValueDecl *VD = DRE->getDecl(); 11549 if (!VD->isCXXClassMember()) 11550 return false; 11551 11552 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11553 return true; 11554 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11555 return Method->isInstance(); 11556 11557 return false; 11558 } 11559 11560 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11561 if (!ULE->getQualifier()) 11562 return false; 11563 11564 for (NamedDecl *D : ULE->decls()) { 11565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11566 if (Method->isInstance()) 11567 return true; 11568 } else { 11569 // Overload set does not contain methods. 11570 break; 11571 } 11572 } 11573 11574 return false; 11575 } 11576 11577 return false; 11578 } 11579 11580 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11581 UnaryOperatorKind Opc, Expr *Input) { 11582 // First things first: handle placeholders so that the 11583 // overloaded-operator check considers the right type. 11584 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11585 // Increment and decrement of pseudo-object references. 11586 if (pty->getKind() == BuiltinType::PseudoObject && 11587 UnaryOperator::isIncrementDecrementOp(Opc)) 11588 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11589 11590 // extension is always a builtin operator. 11591 if (Opc == UO_Extension) 11592 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11593 11594 // & gets special logic for several kinds of placeholder. 11595 // The builtin code knows what to do. 11596 if (Opc == UO_AddrOf && 11597 (pty->getKind() == BuiltinType::Overload || 11598 pty->getKind() == BuiltinType::UnknownAny || 11599 pty->getKind() == BuiltinType::BoundMember)) 11600 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11601 11602 // Anything else needs to be handled now. 11603 ExprResult Result = CheckPlaceholderExpr(Input); 11604 if (Result.isInvalid()) return ExprError(); 11605 Input = Result.get(); 11606 } 11607 11608 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11609 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11610 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11611 // Find all of the overloaded operators visible from this 11612 // point. We perform both an operator-name lookup from the local 11613 // scope and an argument-dependent lookup based on the types of 11614 // the arguments. 11615 UnresolvedSet<16> Functions; 11616 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11617 if (S && OverOp != OO_None) 11618 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11619 Functions); 11620 11621 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11622 } 11623 11624 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11625 } 11626 11627 // Unary Operators. 'Tok' is the token for the operator. 11628 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11629 tok::TokenKind Op, Expr *Input) { 11630 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11631 } 11632 11633 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11634 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11635 LabelDecl *TheDecl) { 11636 TheDecl->markUsed(Context); 11637 // Create the AST node. The address of a label always has type 'void*'. 11638 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11639 Context.getPointerType(Context.VoidTy)); 11640 } 11641 11642 /// Given the last statement in a statement-expression, check whether 11643 /// the result is a producing expression (like a call to an 11644 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11645 /// release out of the full-expression. Otherwise, return null. 11646 /// Cannot fail. 11647 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11648 // Should always be wrapped with one of these. 11649 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11650 if (!cleanups) return nullptr; 11651 11652 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11653 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11654 return nullptr; 11655 11656 // Splice out the cast. This shouldn't modify any interesting 11657 // features of the statement. 11658 Expr *producer = cast->getSubExpr(); 11659 assert(producer->getType() == cast->getType()); 11660 assert(producer->getValueKind() == cast->getValueKind()); 11661 cleanups->setSubExpr(producer); 11662 return cleanups; 11663 } 11664 11665 void Sema::ActOnStartStmtExpr() { 11666 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11667 } 11668 11669 void Sema::ActOnStmtExprError() { 11670 // Note that function is also called by TreeTransform when leaving a 11671 // StmtExpr scope without rebuilding anything. 11672 11673 DiscardCleanupsInEvaluationContext(); 11674 PopExpressionEvaluationContext(); 11675 } 11676 11677 ExprResult 11678 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11679 SourceLocation RPLoc) { // "({..})" 11680 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11681 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11682 11683 if (hasAnyUnrecoverableErrorsInThisFunction()) 11684 DiscardCleanupsInEvaluationContext(); 11685 assert(!Cleanup.exprNeedsCleanups() && 11686 "cleanups within StmtExpr not correctly bound!"); 11687 PopExpressionEvaluationContext(); 11688 11689 // FIXME: there are a variety of strange constraints to enforce here, for 11690 // example, it is not possible to goto into a stmt expression apparently. 11691 // More semantic analysis is needed. 11692 11693 // If there are sub-stmts in the compound stmt, take the type of the last one 11694 // as the type of the stmtexpr. 11695 QualType Ty = Context.VoidTy; 11696 bool StmtExprMayBindToTemp = false; 11697 if (!Compound->body_empty()) { 11698 Stmt *LastStmt = Compound->body_back(); 11699 LabelStmt *LastLabelStmt = nullptr; 11700 // If LastStmt is a label, skip down through into the body. 11701 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11702 LastLabelStmt = Label; 11703 LastStmt = Label->getSubStmt(); 11704 } 11705 11706 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11707 // Do function/array conversion on the last expression, but not 11708 // lvalue-to-rvalue. However, initialize an unqualified type. 11709 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11710 if (LastExpr.isInvalid()) 11711 return ExprError(); 11712 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11713 11714 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11715 // In ARC, if the final expression ends in a consume, splice 11716 // the consume out and bind it later. In the alternate case 11717 // (when dealing with a retainable type), the result 11718 // initialization will create a produce. In both cases the 11719 // result will be +1, and we'll need to balance that out with 11720 // a bind. 11721 if (Expr *rebuiltLastStmt 11722 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11723 LastExpr = rebuiltLastStmt; 11724 } else { 11725 LastExpr = PerformCopyInitialization( 11726 InitializedEntity::InitializeResult(LPLoc, 11727 Ty, 11728 false), 11729 SourceLocation(), 11730 LastExpr); 11731 } 11732 11733 if (LastExpr.isInvalid()) 11734 return ExprError(); 11735 if (LastExpr.get() != nullptr) { 11736 if (!LastLabelStmt) 11737 Compound->setLastStmt(LastExpr.get()); 11738 else 11739 LastLabelStmt->setSubStmt(LastExpr.get()); 11740 StmtExprMayBindToTemp = true; 11741 } 11742 } 11743 } 11744 } 11745 11746 // FIXME: Check that expression type is complete/non-abstract; statement 11747 // expressions are not lvalues. 11748 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11749 if (StmtExprMayBindToTemp) 11750 return MaybeBindToTemporary(ResStmtExpr); 11751 return ResStmtExpr; 11752 } 11753 11754 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11755 TypeSourceInfo *TInfo, 11756 ArrayRef<OffsetOfComponent> Components, 11757 SourceLocation RParenLoc) { 11758 QualType ArgTy = TInfo->getType(); 11759 bool Dependent = ArgTy->isDependentType(); 11760 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11761 11762 // We must have at least one component that refers to the type, and the first 11763 // one is known to be a field designator. Verify that the ArgTy represents 11764 // a struct/union/class. 11765 if (!Dependent && !ArgTy->isRecordType()) 11766 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11767 << ArgTy << TypeRange); 11768 11769 // Type must be complete per C99 7.17p3 because a declaring a variable 11770 // with an incomplete type would be ill-formed. 11771 if (!Dependent 11772 && RequireCompleteType(BuiltinLoc, ArgTy, 11773 diag::err_offsetof_incomplete_type, TypeRange)) 11774 return ExprError(); 11775 11776 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11777 // GCC extension, diagnose them. 11778 // FIXME: This diagnostic isn't actually visible because the location is in 11779 // a system header! 11780 if (Components.size() != 1) 11781 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11782 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11783 11784 bool DidWarnAboutNonPOD = false; 11785 QualType CurrentType = ArgTy; 11786 SmallVector<OffsetOfNode, 4> Comps; 11787 SmallVector<Expr*, 4> Exprs; 11788 for (const OffsetOfComponent &OC : Components) { 11789 if (OC.isBrackets) { 11790 // Offset of an array sub-field. TODO: Should we allow vector elements? 11791 if (!CurrentType->isDependentType()) { 11792 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11793 if(!AT) 11794 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11795 << CurrentType); 11796 CurrentType = AT->getElementType(); 11797 } else 11798 CurrentType = Context.DependentTy; 11799 11800 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11801 if (IdxRval.isInvalid()) 11802 return ExprError(); 11803 Expr *Idx = IdxRval.get(); 11804 11805 // The expression must be an integral expression. 11806 // FIXME: An integral constant expression? 11807 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11808 !Idx->getType()->isIntegerType()) 11809 return ExprError(Diag(Idx->getLocStart(), 11810 diag::err_typecheck_subscript_not_integer) 11811 << Idx->getSourceRange()); 11812 11813 // Record this array index. 11814 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11815 Exprs.push_back(Idx); 11816 continue; 11817 } 11818 11819 // Offset of a field. 11820 if (CurrentType->isDependentType()) { 11821 // We have the offset of a field, but we can't look into the dependent 11822 // type. Just record the identifier of the field. 11823 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11824 CurrentType = Context.DependentTy; 11825 continue; 11826 } 11827 11828 // We need to have a complete type to look into. 11829 if (RequireCompleteType(OC.LocStart, CurrentType, 11830 diag::err_offsetof_incomplete_type)) 11831 return ExprError(); 11832 11833 // Look for the designated field. 11834 const RecordType *RC = CurrentType->getAs<RecordType>(); 11835 if (!RC) 11836 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11837 << CurrentType); 11838 RecordDecl *RD = RC->getDecl(); 11839 11840 // C++ [lib.support.types]p5: 11841 // The macro offsetof accepts a restricted set of type arguments in this 11842 // International Standard. type shall be a POD structure or a POD union 11843 // (clause 9). 11844 // C++11 [support.types]p4: 11845 // If type is not a standard-layout class (Clause 9), the results are 11846 // undefined. 11847 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11848 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11849 unsigned DiagID = 11850 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11851 : diag::ext_offsetof_non_pod_type; 11852 11853 if (!IsSafe && !DidWarnAboutNonPOD && 11854 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11855 PDiag(DiagID) 11856 << SourceRange(Components[0].LocStart, OC.LocEnd) 11857 << CurrentType)) 11858 DidWarnAboutNonPOD = true; 11859 } 11860 11861 // Look for the field. 11862 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11863 LookupQualifiedName(R, RD); 11864 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11865 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11866 if (!MemberDecl) { 11867 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11868 MemberDecl = IndirectMemberDecl->getAnonField(); 11869 } 11870 11871 if (!MemberDecl) 11872 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11873 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11874 OC.LocEnd)); 11875 11876 // C99 7.17p3: 11877 // (If the specified member is a bit-field, the behavior is undefined.) 11878 // 11879 // We diagnose this as an error. 11880 if (MemberDecl->isBitField()) { 11881 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11882 << MemberDecl->getDeclName() 11883 << SourceRange(BuiltinLoc, RParenLoc); 11884 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11885 return ExprError(); 11886 } 11887 11888 RecordDecl *Parent = MemberDecl->getParent(); 11889 if (IndirectMemberDecl) 11890 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11891 11892 // If the member was found in a base class, introduce OffsetOfNodes for 11893 // the base class indirections. 11894 CXXBasePaths Paths; 11895 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11896 Paths)) { 11897 if (Paths.getDetectedVirtual()) { 11898 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11899 << MemberDecl->getDeclName() 11900 << SourceRange(BuiltinLoc, RParenLoc); 11901 return ExprError(); 11902 } 11903 11904 CXXBasePath &Path = Paths.front(); 11905 for (const CXXBasePathElement &B : Path) 11906 Comps.push_back(OffsetOfNode(B.Base)); 11907 } 11908 11909 if (IndirectMemberDecl) { 11910 for (auto *FI : IndirectMemberDecl->chain()) { 11911 assert(isa<FieldDecl>(FI)); 11912 Comps.push_back(OffsetOfNode(OC.LocStart, 11913 cast<FieldDecl>(FI), OC.LocEnd)); 11914 } 11915 } else 11916 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11917 11918 CurrentType = MemberDecl->getType().getNonReferenceType(); 11919 } 11920 11921 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11922 Comps, Exprs, RParenLoc); 11923 } 11924 11925 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11926 SourceLocation BuiltinLoc, 11927 SourceLocation TypeLoc, 11928 ParsedType ParsedArgTy, 11929 ArrayRef<OffsetOfComponent> Components, 11930 SourceLocation RParenLoc) { 11931 11932 TypeSourceInfo *ArgTInfo; 11933 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11934 if (ArgTy.isNull()) 11935 return ExprError(); 11936 11937 if (!ArgTInfo) 11938 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11939 11940 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11941 } 11942 11943 11944 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11945 Expr *CondExpr, 11946 Expr *LHSExpr, Expr *RHSExpr, 11947 SourceLocation RPLoc) { 11948 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11949 11950 ExprValueKind VK = VK_RValue; 11951 ExprObjectKind OK = OK_Ordinary; 11952 QualType resType; 11953 bool ValueDependent = false; 11954 bool CondIsTrue = false; 11955 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11956 resType = Context.DependentTy; 11957 ValueDependent = true; 11958 } else { 11959 // The conditional expression is required to be a constant expression. 11960 llvm::APSInt condEval(32); 11961 ExprResult CondICE 11962 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11963 diag::err_typecheck_choose_expr_requires_constant, false); 11964 if (CondICE.isInvalid()) 11965 return ExprError(); 11966 CondExpr = CondICE.get(); 11967 CondIsTrue = condEval.getZExtValue(); 11968 11969 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11970 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11971 11972 resType = ActiveExpr->getType(); 11973 ValueDependent = ActiveExpr->isValueDependent(); 11974 VK = ActiveExpr->getValueKind(); 11975 OK = ActiveExpr->getObjectKind(); 11976 } 11977 11978 return new (Context) 11979 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11980 CondIsTrue, resType->isDependentType(), ValueDependent); 11981 } 11982 11983 //===----------------------------------------------------------------------===// 11984 // Clang Extensions. 11985 //===----------------------------------------------------------------------===// 11986 11987 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11988 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11989 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11990 11991 if (LangOpts.CPlusPlus) { 11992 Decl *ManglingContextDecl; 11993 if (MangleNumberingContext *MCtx = 11994 getCurrentMangleNumberContext(Block->getDeclContext(), 11995 ManglingContextDecl)) { 11996 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11997 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11998 } 11999 } 12000 12001 PushBlockScope(CurScope, Block); 12002 CurContext->addDecl(Block); 12003 if (CurScope) 12004 PushDeclContext(CurScope, Block); 12005 else 12006 CurContext = Block; 12007 12008 getCurBlock()->HasImplicitReturnType = true; 12009 12010 // Enter a new evaluation context to insulate the block from any 12011 // cleanups from the enclosing full-expression. 12012 PushExpressionEvaluationContext(PotentiallyEvaluated); 12013 } 12014 12015 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12016 Scope *CurScope) { 12017 assert(ParamInfo.getIdentifier() == nullptr && 12018 "block-id should have no identifier!"); 12019 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12020 BlockScopeInfo *CurBlock = getCurBlock(); 12021 12022 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12023 QualType T = Sig->getType(); 12024 12025 // FIXME: We should allow unexpanded parameter packs here, but that would, 12026 // in turn, make the block expression contain unexpanded parameter packs. 12027 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12028 // Drop the parameters. 12029 FunctionProtoType::ExtProtoInfo EPI; 12030 EPI.HasTrailingReturn = false; 12031 EPI.TypeQuals |= DeclSpec::TQ_const; 12032 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12033 Sig = Context.getTrivialTypeSourceInfo(T); 12034 } 12035 12036 // GetTypeForDeclarator always produces a function type for a block 12037 // literal signature. Furthermore, it is always a FunctionProtoType 12038 // unless the function was written with a typedef. 12039 assert(T->isFunctionType() && 12040 "GetTypeForDeclarator made a non-function block signature"); 12041 12042 // Look for an explicit signature in that function type. 12043 FunctionProtoTypeLoc ExplicitSignature; 12044 12045 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12046 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12047 12048 // Check whether that explicit signature was synthesized by 12049 // GetTypeForDeclarator. If so, don't save that as part of the 12050 // written signature. 12051 if (ExplicitSignature.getLocalRangeBegin() == 12052 ExplicitSignature.getLocalRangeEnd()) { 12053 // This would be much cheaper if we stored TypeLocs instead of 12054 // TypeSourceInfos. 12055 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12056 unsigned Size = Result.getFullDataSize(); 12057 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12058 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12059 12060 ExplicitSignature = FunctionProtoTypeLoc(); 12061 } 12062 } 12063 12064 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12065 CurBlock->FunctionType = T; 12066 12067 const FunctionType *Fn = T->getAs<FunctionType>(); 12068 QualType RetTy = Fn->getReturnType(); 12069 bool isVariadic = 12070 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12071 12072 CurBlock->TheDecl->setIsVariadic(isVariadic); 12073 12074 // Context.DependentTy is used as a placeholder for a missing block 12075 // return type. TODO: what should we do with declarators like: 12076 // ^ * { ... } 12077 // If the answer is "apply template argument deduction".... 12078 if (RetTy != Context.DependentTy) { 12079 CurBlock->ReturnType = RetTy; 12080 CurBlock->TheDecl->setBlockMissingReturnType(false); 12081 CurBlock->HasImplicitReturnType = false; 12082 } 12083 12084 // Push block parameters from the declarator if we had them. 12085 SmallVector<ParmVarDecl*, 8> Params; 12086 if (ExplicitSignature) { 12087 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12088 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12089 if (Param->getIdentifier() == nullptr && 12090 !Param->isImplicit() && 12091 !Param->isInvalidDecl() && 12092 !getLangOpts().CPlusPlus) 12093 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12094 Params.push_back(Param); 12095 } 12096 12097 // Fake up parameter variables if we have a typedef, like 12098 // ^ fntype { ... } 12099 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12100 for (const auto &I : Fn->param_types()) { 12101 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12102 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12103 Params.push_back(Param); 12104 } 12105 } 12106 12107 // Set the parameters on the block decl. 12108 if (!Params.empty()) { 12109 CurBlock->TheDecl->setParams(Params); 12110 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12111 /*CheckParameterNames=*/false); 12112 } 12113 12114 // Finally we can process decl attributes. 12115 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12116 12117 // Put the parameter variables in scope. 12118 for (auto AI : CurBlock->TheDecl->parameters()) { 12119 AI->setOwningFunction(CurBlock->TheDecl); 12120 12121 // If this has an identifier, add it to the scope stack. 12122 if (AI->getIdentifier()) { 12123 CheckShadow(CurBlock->TheScope, AI); 12124 12125 PushOnScopeChains(AI, CurBlock->TheScope); 12126 } 12127 } 12128 } 12129 12130 /// ActOnBlockError - If there is an error parsing a block, this callback 12131 /// is invoked to pop the information about the block from the action impl. 12132 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12133 // Leave the expression-evaluation context. 12134 DiscardCleanupsInEvaluationContext(); 12135 PopExpressionEvaluationContext(); 12136 12137 // Pop off CurBlock, handle nested blocks. 12138 PopDeclContext(); 12139 PopFunctionScopeInfo(); 12140 } 12141 12142 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12143 /// literal was successfully completed. ^(int x){...} 12144 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12145 Stmt *Body, Scope *CurScope) { 12146 // If blocks are disabled, emit an error. 12147 if (!LangOpts.Blocks) 12148 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12149 12150 // Leave the expression-evaluation context. 12151 if (hasAnyUnrecoverableErrorsInThisFunction()) 12152 DiscardCleanupsInEvaluationContext(); 12153 assert(!Cleanup.exprNeedsCleanups() && 12154 "cleanups within block not correctly bound!"); 12155 PopExpressionEvaluationContext(); 12156 12157 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12158 12159 if (BSI->HasImplicitReturnType) 12160 deduceClosureReturnType(*BSI); 12161 12162 PopDeclContext(); 12163 12164 QualType RetTy = Context.VoidTy; 12165 if (!BSI->ReturnType.isNull()) 12166 RetTy = BSI->ReturnType; 12167 12168 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12169 QualType BlockTy; 12170 12171 // Set the captured variables on the block. 12172 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12173 SmallVector<BlockDecl::Capture, 4> Captures; 12174 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12175 if (Cap.isThisCapture()) 12176 continue; 12177 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12178 Cap.isNested(), Cap.getInitExpr()); 12179 Captures.push_back(NewCap); 12180 } 12181 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12182 12183 // If the user wrote a function type in some form, try to use that. 12184 if (!BSI->FunctionType.isNull()) { 12185 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12186 12187 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12188 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12189 12190 // Turn protoless block types into nullary block types. 12191 if (isa<FunctionNoProtoType>(FTy)) { 12192 FunctionProtoType::ExtProtoInfo EPI; 12193 EPI.ExtInfo = Ext; 12194 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12195 12196 // Otherwise, if we don't need to change anything about the function type, 12197 // preserve its sugar structure. 12198 } else if (FTy->getReturnType() == RetTy && 12199 (!NoReturn || FTy->getNoReturnAttr())) { 12200 BlockTy = BSI->FunctionType; 12201 12202 // Otherwise, make the minimal modifications to the function type. 12203 } else { 12204 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12205 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12206 EPI.TypeQuals = 0; // FIXME: silently? 12207 EPI.ExtInfo = Ext; 12208 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12209 } 12210 12211 // If we don't have a function type, just build one from nothing. 12212 } else { 12213 FunctionProtoType::ExtProtoInfo EPI; 12214 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12215 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12216 } 12217 12218 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12219 BlockTy = Context.getBlockPointerType(BlockTy); 12220 12221 // If needed, diagnose invalid gotos and switches in the block. 12222 if (getCurFunction()->NeedsScopeChecking() && 12223 !PP.isCodeCompletionEnabled()) 12224 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12225 12226 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12227 12228 // Try to apply the named return value optimization. We have to check again 12229 // if we can do this, though, because blocks keep return statements around 12230 // to deduce an implicit return type. 12231 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12232 !BSI->TheDecl->isDependentContext()) 12233 computeNRVO(Body, BSI); 12234 12235 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12236 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12237 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12238 12239 // If the block isn't obviously global, i.e. it captures anything at 12240 // all, then we need to do a few things in the surrounding context: 12241 if (Result->getBlockDecl()->hasCaptures()) { 12242 // First, this expression has a new cleanup object. 12243 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12244 Cleanup.setExprNeedsCleanups(true); 12245 12246 // It also gets a branch-protected scope if any of the captured 12247 // variables needs destruction. 12248 for (const auto &CI : Result->getBlockDecl()->captures()) { 12249 const VarDecl *var = CI.getVariable(); 12250 if (var->getType().isDestructedType() != QualType::DK_none) { 12251 getCurFunction()->setHasBranchProtectedScope(); 12252 break; 12253 } 12254 } 12255 } 12256 12257 return Result; 12258 } 12259 12260 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12261 SourceLocation RPLoc) { 12262 TypeSourceInfo *TInfo; 12263 GetTypeFromParser(Ty, &TInfo); 12264 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12265 } 12266 12267 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12268 Expr *E, TypeSourceInfo *TInfo, 12269 SourceLocation RPLoc) { 12270 Expr *OrigExpr = E; 12271 bool IsMS = false; 12272 12273 // CUDA device code does not support varargs. 12274 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12275 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12276 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12277 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12278 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12279 } 12280 } 12281 12282 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12283 // as Microsoft ABI on an actual Microsoft platform, where 12284 // __builtin_ms_va_list and __builtin_va_list are the same.) 12285 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12286 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12287 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12288 if (Context.hasSameType(MSVaListType, E->getType())) { 12289 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12290 return ExprError(); 12291 IsMS = true; 12292 } 12293 } 12294 12295 // Get the va_list type 12296 QualType VaListType = Context.getBuiltinVaListType(); 12297 if (!IsMS) { 12298 if (VaListType->isArrayType()) { 12299 // Deal with implicit array decay; for example, on x86-64, 12300 // va_list is an array, but it's supposed to decay to 12301 // a pointer for va_arg. 12302 VaListType = Context.getArrayDecayedType(VaListType); 12303 // Make sure the input expression also decays appropriately. 12304 ExprResult Result = UsualUnaryConversions(E); 12305 if (Result.isInvalid()) 12306 return ExprError(); 12307 E = Result.get(); 12308 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12309 // If va_list is a record type and we are compiling in C++ mode, 12310 // check the argument using reference binding. 12311 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12312 Context, Context.getLValueReferenceType(VaListType), false); 12313 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12314 if (Init.isInvalid()) 12315 return ExprError(); 12316 E = Init.getAs<Expr>(); 12317 } else { 12318 // Otherwise, the va_list argument must be an l-value because 12319 // it is modified by va_arg. 12320 if (!E->isTypeDependent() && 12321 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12322 return ExprError(); 12323 } 12324 } 12325 12326 if (!IsMS && !E->isTypeDependent() && 12327 !Context.hasSameType(VaListType, E->getType())) 12328 return ExprError(Diag(E->getLocStart(), 12329 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12330 << OrigExpr->getType() << E->getSourceRange()); 12331 12332 if (!TInfo->getType()->isDependentType()) { 12333 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12334 diag::err_second_parameter_to_va_arg_incomplete, 12335 TInfo->getTypeLoc())) 12336 return ExprError(); 12337 12338 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12339 TInfo->getType(), 12340 diag::err_second_parameter_to_va_arg_abstract, 12341 TInfo->getTypeLoc())) 12342 return ExprError(); 12343 12344 if (!TInfo->getType().isPODType(Context)) { 12345 Diag(TInfo->getTypeLoc().getBeginLoc(), 12346 TInfo->getType()->isObjCLifetimeType() 12347 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12348 : diag::warn_second_parameter_to_va_arg_not_pod) 12349 << TInfo->getType() 12350 << TInfo->getTypeLoc().getSourceRange(); 12351 } 12352 12353 // Check for va_arg where arguments of the given type will be promoted 12354 // (i.e. this va_arg is guaranteed to have undefined behavior). 12355 QualType PromoteType; 12356 if (TInfo->getType()->isPromotableIntegerType()) { 12357 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12358 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12359 PromoteType = QualType(); 12360 } 12361 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12362 PromoteType = Context.DoubleTy; 12363 if (!PromoteType.isNull()) 12364 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12365 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12366 << TInfo->getType() 12367 << PromoteType 12368 << TInfo->getTypeLoc().getSourceRange()); 12369 } 12370 12371 QualType T = TInfo->getType().getNonLValueExprType(Context); 12372 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12373 } 12374 12375 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12376 // The type of __null will be int or long, depending on the size of 12377 // pointers on the target. 12378 QualType Ty; 12379 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12380 if (pw == Context.getTargetInfo().getIntWidth()) 12381 Ty = Context.IntTy; 12382 else if (pw == Context.getTargetInfo().getLongWidth()) 12383 Ty = Context.LongTy; 12384 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12385 Ty = Context.LongLongTy; 12386 else { 12387 llvm_unreachable("I don't know size of pointer!"); 12388 } 12389 12390 return new (Context) GNUNullExpr(Ty, TokenLoc); 12391 } 12392 12393 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12394 bool Diagnose) { 12395 if (!getLangOpts().ObjC1) 12396 return false; 12397 12398 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12399 if (!PT) 12400 return false; 12401 12402 if (!PT->isObjCIdType()) { 12403 // Check if the destination is the 'NSString' interface. 12404 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12405 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12406 return false; 12407 } 12408 12409 // Ignore any parens, implicit casts (should only be 12410 // array-to-pointer decays), and not-so-opaque values. The last is 12411 // important for making this trigger for property assignments. 12412 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12413 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12414 if (OV->getSourceExpr()) 12415 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12416 12417 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12418 if (!SL || !SL->isAscii()) 12419 return false; 12420 if (Diagnose) { 12421 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12422 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12423 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12424 } 12425 return true; 12426 } 12427 12428 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12429 const Expr *SrcExpr) { 12430 if (!DstType->isFunctionPointerType() || 12431 !SrcExpr->getType()->isFunctionType()) 12432 return false; 12433 12434 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12435 if (!DRE) 12436 return false; 12437 12438 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12439 if (!FD) 12440 return false; 12441 12442 return !S.checkAddressOfFunctionIsAvailable(FD, 12443 /*Complain=*/true, 12444 SrcExpr->getLocStart()); 12445 } 12446 12447 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12448 SourceLocation Loc, 12449 QualType DstType, QualType SrcType, 12450 Expr *SrcExpr, AssignmentAction Action, 12451 bool *Complained) { 12452 if (Complained) 12453 *Complained = false; 12454 12455 // Decode the result (notice that AST's are still created for extensions). 12456 bool CheckInferredResultType = false; 12457 bool isInvalid = false; 12458 unsigned DiagKind = 0; 12459 FixItHint Hint; 12460 ConversionFixItGenerator ConvHints; 12461 bool MayHaveConvFixit = false; 12462 bool MayHaveFunctionDiff = false; 12463 const ObjCInterfaceDecl *IFace = nullptr; 12464 const ObjCProtocolDecl *PDecl = nullptr; 12465 12466 switch (ConvTy) { 12467 case Compatible: 12468 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12469 return false; 12470 12471 case PointerToInt: 12472 DiagKind = diag::ext_typecheck_convert_pointer_int; 12473 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12474 MayHaveConvFixit = true; 12475 break; 12476 case IntToPointer: 12477 DiagKind = diag::ext_typecheck_convert_int_pointer; 12478 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12479 MayHaveConvFixit = true; 12480 break; 12481 case IncompatiblePointer: 12482 if (Action == AA_Passing_CFAudited) 12483 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12484 else if (SrcType->isFunctionPointerType() && 12485 DstType->isFunctionPointerType()) 12486 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12487 else 12488 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12489 12490 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12491 SrcType->isObjCObjectPointerType(); 12492 if (Hint.isNull() && !CheckInferredResultType) { 12493 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12494 } 12495 else if (CheckInferredResultType) { 12496 SrcType = SrcType.getUnqualifiedType(); 12497 DstType = DstType.getUnqualifiedType(); 12498 } 12499 MayHaveConvFixit = true; 12500 break; 12501 case IncompatiblePointerSign: 12502 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12503 break; 12504 case FunctionVoidPointer: 12505 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12506 break; 12507 case IncompatiblePointerDiscardsQualifiers: { 12508 // Perform array-to-pointer decay if necessary. 12509 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12510 12511 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12512 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12513 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12514 DiagKind = diag::err_typecheck_incompatible_address_space; 12515 break; 12516 12517 12518 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12519 DiagKind = diag::err_typecheck_incompatible_ownership; 12520 break; 12521 } 12522 12523 llvm_unreachable("unknown error case for discarding qualifiers!"); 12524 // fallthrough 12525 } 12526 case CompatiblePointerDiscardsQualifiers: 12527 // If the qualifiers lost were because we were applying the 12528 // (deprecated) C++ conversion from a string literal to a char* 12529 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12530 // Ideally, this check would be performed in 12531 // checkPointerTypesForAssignment. However, that would require a 12532 // bit of refactoring (so that the second argument is an 12533 // expression, rather than a type), which should be done as part 12534 // of a larger effort to fix checkPointerTypesForAssignment for 12535 // C++ semantics. 12536 if (getLangOpts().CPlusPlus && 12537 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12538 return false; 12539 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12540 break; 12541 case IncompatibleNestedPointerQualifiers: 12542 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12543 break; 12544 case IntToBlockPointer: 12545 DiagKind = diag::err_int_to_block_pointer; 12546 break; 12547 case IncompatibleBlockPointer: 12548 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12549 break; 12550 case IncompatibleObjCQualifiedId: { 12551 if (SrcType->isObjCQualifiedIdType()) { 12552 const ObjCObjectPointerType *srcOPT = 12553 SrcType->getAs<ObjCObjectPointerType>(); 12554 for (auto *srcProto : srcOPT->quals()) { 12555 PDecl = srcProto; 12556 break; 12557 } 12558 if (const ObjCInterfaceType *IFaceT = 12559 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12560 IFace = IFaceT->getDecl(); 12561 } 12562 else if (DstType->isObjCQualifiedIdType()) { 12563 const ObjCObjectPointerType *dstOPT = 12564 DstType->getAs<ObjCObjectPointerType>(); 12565 for (auto *dstProto : dstOPT->quals()) { 12566 PDecl = dstProto; 12567 break; 12568 } 12569 if (const ObjCInterfaceType *IFaceT = 12570 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12571 IFace = IFaceT->getDecl(); 12572 } 12573 DiagKind = diag::warn_incompatible_qualified_id; 12574 break; 12575 } 12576 case IncompatibleVectors: 12577 DiagKind = diag::warn_incompatible_vectors; 12578 break; 12579 case IncompatibleObjCWeakRef: 12580 DiagKind = diag::err_arc_weak_unavailable_assign; 12581 break; 12582 case Incompatible: 12583 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12584 if (Complained) 12585 *Complained = true; 12586 return true; 12587 } 12588 12589 DiagKind = diag::err_typecheck_convert_incompatible; 12590 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12591 MayHaveConvFixit = true; 12592 isInvalid = true; 12593 MayHaveFunctionDiff = true; 12594 break; 12595 } 12596 12597 QualType FirstType, SecondType; 12598 switch (Action) { 12599 case AA_Assigning: 12600 case AA_Initializing: 12601 // The destination type comes first. 12602 FirstType = DstType; 12603 SecondType = SrcType; 12604 break; 12605 12606 case AA_Returning: 12607 case AA_Passing: 12608 case AA_Passing_CFAudited: 12609 case AA_Converting: 12610 case AA_Sending: 12611 case AA_Casting: 12612 // The source type comes first. 12613 FirstType = SrcType; 12614 SecondType = DstType; 12615 break; 12616 } 12617 12618 PartialDiagnostic FDiag = PDiag(DiagKind); 12619 if (Action == AA_Passing_CFAudited) 12620 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12621 else 12622 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12623 12624 // If we can fix the conversion, suggest the FixIts. 12625 assert(ConvHints.isNull() || Hint.isNull()); 12626 if (!ConvHints.isNull()) { 12627 for (FixItHint &H : ConvHints.Hints) 12628 FDiag << H; 12629 } else { 12630 FDiag << Hint; 12631 } 12632 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12633 12634 if (MayHaveFunctionDiff) 12635 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12636 12637 Diag(Loc, FDiag); 12638 if (DiagKind == diag::warn_incompatible_qualified_id && 12639 PDecl && IFace && !IFace->hasDefinition()) 12640 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12641 << IFace->getName() << PDecl->getName(); 12642 12643 if (SecondType == Context.OverloadTy) 12644 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12645 FirstType, /*TakingAddress=*/true); 12646 12647 if (CheckInferredResultType) 12648 EmitRelatedResultTypeNote(SrcExpr); 12649 12650 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12651 EmitRelatedResultTypeNoteForReturn(DstType); 12652 12653 if (Complained) 12654 *Complained = true; 12655 return isInvalid; 12656 } 12657 12658 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12659 llvm::APSInt *Result) { 12660 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12661 public: 12662 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12663 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12664 } 12665 } Diagnoser; 12666 12667 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12668 } 12669 12670 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12671 llvm::APSInt *Result, 12672 unsigned DiagID, 12673 bool AllowFold) { 12674 class IDDiagnoser : public VerifyICEDiagnoser { 12675 unsigned DiagID; 12676 12677 public: 12678 IDDiagnoser(unsigned DiagID) 12679 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12680 12681 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12682 S.Diag(Loc, DiagID) << SR; 12683 } 12684 } Diagnoser(DiagID); 12685 12686 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12687 } 12688 12689 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12690 SourceRange SR) { 12691 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12692 } 12693 12694 ExprResult 12695 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12696 VerifyICEDiagnoser &Diagnoser, 12697 bool AllowFold) { 12698 SourceLocation DiagLoc = E->getLocStart(); 12699 12700 if (getLangOpts().CPlusPlus11) { 12701 // C++11 [expr.const]p5: 12702 // If an expression of literal class type is used in a context where an 12703 // integral constant expression is required, then that class type shall 12704 // have a single non-explicit conversion function to an integral or 12705 // unscoped enumeration type 12706 ExprResult Converted; 12707 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12708 public: 12709 CXX11ConvertDiagnoser(bool Silent) 12710 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12711 Silent, true) {} 12712 12713 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12714 QualType T) override { 12715 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12716 } 12717 12718 SemaDiagnosticBuilder diagnoseIncomplete( 12719 Sema &S, SourceLocation Loc, QualType T) override { 12720 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12721 } 12722 12723 SemaDiagnosticBuilder diagnoseExplicitConv( 12724 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12725 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12726 } 12727 12728 SemaDiagnosticBuilder noteExplicitConv( 12729 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12730 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12731 << ConvTy->isEnumeralType() << ConvTy; 12732 } 12733 12734 SemaDiagnosticBuilder diagnoseAmbiguous( 12735 Sema &S, SourceLocation Loc, QualType T) override { 12736 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12737 } 12738 12739 SemaDiagnosticBuilder noteAmbiguous( 12740 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12741 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12742 << ConvTy->isEnumeralType() << ConvTy; 12743 } 12744 12745 SemaDiagnosticBuilder diagnoseConversion( 12746 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12747 llvm_unreachable("conversion functions are permitted"); 12748 } 12749 } ConvertDiagnoser(Diagnoser.Suppress); 12750 12751 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12752 ConvertDiagnoser); 12753 if (Converted.isInvalid()) 12754 return Converted; 12755 E = Converted.get(); 12756 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12757 return ExprError(); 12758 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12759 // An ICE must be of integral or unscoped enumeration type. 12760 if (!Diagnoser.Suppress) 12761 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12762 return ExprError(); 12763 } 12764 12765 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12766 // in the non-ICE case. 12767 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12768 if (Result) 12769 *Result = E->EvaluateKnownConstInt(Context); 12770 return E; 12771 } 12772 12773 Expr::EvalResult EvalResult; 12774 SmallVector<PartialDiagnosticAt, 8> Notes; 12775 EvalResult.Diag = &Notes; 12776 12777 // Try to evaluate the expression, and produce diagnostics explaining why it's 12778 // not a constant expression as a side-effect. 12779 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12780 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12781 12782 // In C++11, we can rely on diagnostics being produced for any expression 12783 // which is not a constant expression. If no diagnostics were produced, then 12784 // this is a constant expression. 12785 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12786 if (Result) 12787 *Result = EvalResult.Val.getInt(); 12788 return E; 12789 } 12790 12791 // If our only note is the usual "invalid subexpression" note, just point 12792 // the caret at its location rather than producing an essentially 12793 // redundant note. 12794 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12795 diag::note_invalid_subexpr_in_const_expr) { 12796 DiagLoc = Notes[0].first; 12797 Notes.clear(); 12798 } 12799 12800 if (!Folded || !AllowFold) { 12801 if (!Diagnoser.Suppress) { 12802 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12803 for (const PartialDiagnosticAt &Note : Notes) 12804 Diag(Note.first, Note.second); 12805 } 12806 12807 return ExprError(); 12808 } 12809 12810 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12811 for (const PartialDiagnosticAt &Note : Notes) 12812 Diag(Note.first, Note.second); 12813 12814 if (Result) 12815 *Result = EvalResult.Val.getInt(); 12816 return E; 12817 } 12818 12819 namespace { 12820 // Handle the case where we conclude a expression which we speculatively 12821 // considered to be unevaluated is actually evaluated. 12822 class TransformToPE : public TreeTransform<TransformToPE> { 12823 typedef TreeTransform<TransformToPE> BaseTransform; 12824 12825 public: 12826 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12827 12828 // Make sure we redo semantic analysis 12829 bool AlwaysRebuild() { return true; } 12830 12831 // Make sure we handle LabelStmts correctly. 12832 // FIXME: This does the right thing, but maybe we need a more general 12833 // fix to TreeTransform? 12834 StmtResult TransformLabelStmt(LabelStmt *S) { 12835 S->getDecl()->setStmt(nullptr); 12836 return BaseTransform::TransformLabelStmt(S); 12837 } 12838 12839 // We need to special-case DeclRefExprs referring to FieldDecls which 12840 // are not part of a member pointer formation; normal TreeTransforming 12841 // doesn't catch this case because of the way we represent them in the AST. 12842 // FIXME: This is a bit ugly; is it really the best way to handle this 12843 // case? 12844 // 12845 // Error on DeclRefExprs referring to FieldDecls. 12846 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12847 if (isa<FieldDecl>(E->getDecl()) && 12848 !SemaRef.isUnevaluatedContext()) 12849 return SemaRef.Diag(E->getLocation(), 12850 diag::err_invalid_non_static_member_use) 12851 << E->getDecl() << E->getSourceRange(); 12852 12853 return BaseTransform::TransformDeclRefExpr(E); 12854 } 12855 12856 // Exception: filter out member pointer formation 12857 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12858 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12859 return E; 12860 12861 return BaseTransform::TransformUnaryOperator(E); 12862 } 12863 12864 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12865 // Lambdas never need to be transformed. 12866 return E; 12867 } 12868 }; 12869 } 12870 12871 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12872 assert(isUnevaluatedContext() && 12873 "Should only transform unevaluated expressions"); 12874 ExprEvalContexts.back().Context = 12875 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12876 if (isUnevaluatedContext()) 12877 return E; 12878 return TransformToPE(*this).TransformExpr(E); 12879 } 12880 12881 void 12882 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12883 Decl *LambdaContextDecl, 12884 bool IsDecltype) { 12885 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 12886 LambdaContextDecl, IsDecltype); 12887 Cleanup.reset(); 12888 if (!MaybeODRUseExprs.empty()) 12889 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12890 } 12891 12892 void 12893 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12894 ReuseLambdaContextDecl_t, 12895 bool IsDecltype) { 12896 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12897 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12898 } 12899 12900 void Sema::PopExpressionEvaluationContext() { 12901 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12902 unsigned NumTypos = Rec.NumTypos; 12903 12904 if (!Rec.Lambdas.empty()) { 12905 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12906 unsigned D; 12907 if (Rec.isUnevaluated()) { 12908 // C++11 [expr.prim.lambda]p2: 12909 // A lambda-expression shall not appear in an unevaluated operand 12910 // (Clause 5). 12911 D = diag::err_lambda_unevaluated_operand; 12912 } else { 12913 // C++1y [expr.const]p2: 12914 // A conditional-expression e is a core constant expression unless the 12915 // evaluation of e, following the rules of the abstract machine, would 12916 // evaluate [...] a lambda-expression. 12917 D = diag::err_lambda_in_constant_expression; 12918 } 12919 for (const auto *L : Rec.Lambdas) 12920 Diag(L->getLocStart(), D); 12921 } else { 12922 // Mark the capture expressions odr-used. This was deferred 12923 // during lambda expression creation. 12924 for (auto *Lambda : Rec.Lambdas) { 12925 for (auto *C : Lambda->capture_inits()) 12926 MarkDeclarationsReferencedInExpr(C); 12927 } 12928 } 12929 } 12930 12931 // When are coming out of an unevaluated context, clear out any 12932 // temporaries that we may have created as part of the evaluation of 12933 // the expression in that context: they aren't relevant because they 12934 // will never be constructed. 12935 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12936 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12937 ExprCleanupObjects.end()); 12938 Cleanup = Rec.ParentCleanup; 12939 CleanupVarDeclMarking(); 12940 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12941 // Otherwise, merge the contexts together. 12942 } else { 12943 Cleanup.mergeFrom(Rec.ParentCleanup); 12944 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12945 Rec.SavedMaybeODRUseExprs.end()); 12946 } 12947 12948 // Pop the current expression evaluation context off the stack. 12949 ExprEvalContexts.pop_back(); 12950 12951 if (!ExprEvalContexts.empty()) 12952 ExprEvalContexts.back().NumTypos += NumTypos; 12953 else 12954 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12955 "last ExpressionEvaluationContextRecord"); 12956 } 12957 12958 void Sema::DiscardCleanupsInEvaluationContext() { 12959 ExprCleanupObjects.erase( 12960 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12961 ExprCleanupObjects.end()); 12962 Cleanup.reset(); 12963 MaybeODRUseExprs.clear(); 12964 } 12965 12966 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12967 if (!E->getType()->isVariablyModifiedType()) 12968 return E; 12969 return TransformToPotentiallyEvaluated(E); 12970 } 12971 12972 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12973 // Do not mark anything as "used" within a dependent context; wait for 12974 // an instantiation. 12975 if (SemaRef.CurContext->isDependentContext()) 12976 return false; 12977 12978 switch (SemaRef.ExprEvalContexts.back().Context) { 12979 case Sema::Unevaluated: 12980 case Sema::UnevaluatedAbstract: 12981 // We are in an expression that is not potentially evaluated; do nothing. 12982 // (Depending on how you read the standard, we actually do need to do 12983 // something here for null pointer constants, but the standard's 12984 // definition of a null pointer constant is completely crazy.) 12985 return false; 12986 12987 case Sema::DiscardedStatement: 12988 // These are technically a potentially evaluated but they have the effect 12989 // of suppressing use marking. 12990 return false; 12991 12992 case Sema::ConstantEvaluated: 12993 case Sema::PotentiallyEvaluated: 12994 // We are in a potentially evaluated expression (or a constant-expression 12995 // in C++03); we need to do implicit template instantiation, implicitly 12996 // define class members, and mark most declarations as used. 12997 return true; 12998 12999 case Sema::PotentiallyEvaluatedIfUsed: 13000 // Referenced declarations will only be used if the construct in the 13001 // containing expression is used. 13002 return false; 13003 } 13004 llvm_unreachable("Invalid context"); 13005 } 13006 13007 /// \brief Mark a function referenced, and check whether it is odr-used 13008 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13009 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13010 bool MightBeOdrUse) { 13011 assert(Func && "No function?"); 13012 13013 Func->setReferenced(); 13014 13015 // C++11 [basic.def.odr]p3: 13016 // A function whose name appears as a potentially-evaluated expression is 13017 // odr-used if it is the unique lookup result or the selected member of a 13018 // set of overloaded functions [...]. 13019 // 13020 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13021 // can just check that here. 13022 bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this); 13023 13024 // Determine whether we require a function definition to exist, per 13025 // C++11 [temp.inst]p3: 13026 // Unless a function template specialization has been explicitly 13027 // instantiated or explicitly specialized, the function template 13028 // specialization is implicitly instantiated when the specialization is 13029 // referenced in a context that requires a function definition to exist. 13030 // 13031 // We consider constexpr function templates to be referenced in a context 13032 // that requires a definition to exist whenever they are referenced. 13033 // 13034 // FIXME: This instantiates constexpr functions too frequently. If this is 13035 // really an unevaluated context (and we're not just in the definition of a 13036 // function template or overload resolution or other cases which we 13037 // incorrectly consider to be unevaluated contexts), and we're not in a 13038 // subexpression which we actually need to evaluate (for instance, a 13039 // template argument, array bound or an expression in a braced-init-list), 13040 // we are not permitted to instantiate this constexpr function definition. 13041 // 13042 // FIXME: This also implicitly defines special members too frequently. They 13043 // are only supposed to be implicitly defined if they are odr-used, but they 13044 // are not odr-used from constant expressions in unevaluated contexts. 13045 // However, they cannot be referenced if they are deleted, and they are 13046 // deleted whenever the implicit definition of the special member would 13047 // fail (with very few exceptions). 13048 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13049 bool NeedDefinition = 13050 OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() || 13051 (MD && !MD->isUserProvided()))); 13052 13053 // C++14 [temp.expl.spec]p6: 13054 // If a template [...] is explicitly specialized then that specialization 13055 // shall be declared before the first use of that specialization that would 13056 // cause an implicit instantiation to take place, in every translation unit 13057 // in which such a use occurs 13058 if (NeedDefinition && 13059 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13060 Func->getMemberSpecializationInfo())) 13061 checkSpecializationVisibility(Loc, Func); 13062 13063 // If we don't need to mark the function as used, and we don't need to 13064 // try to provide a definition, there's nothing more to do. 13065 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13066 (!NeedDefinition || Func->getBody())) 13067 return; 13068 13069 // Note that this declaration has been used. 13070 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13071 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13072 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13073 if (Constructor->isDefaultConstructor()) { 13074 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13075 return; 13076 DefineImplicitDefaultConstructor(Loc, Constructor); 13077 } else if (Constructor->isCopyConstructor()) { 13078 DefineImplicitCopyConstructor(Loc, Constructor); 13079 } else if (Constructor->isMoveConstructor()) { 13080 DefineImplicitMoveConstructor(Loc, Constructor); 13081 } 13082 } else if (Constructor->getInheritedConstructor()) { 13083 DefineInheritingConstructor(Loc, Constructor); 13084 } 13085 } else if (CXXDestructorDecl *Destructor = 13086 dyn_cast<CXXDestructorDecl>(Func)) { 13087 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13088 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13089 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13090 return; 13091 DefineImplicitDestructor(Loc, Destructor); 13092 } 13093 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13094 MarkVTableUsed(Loc, Destructor->getParent()); 13095 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13096 if (MethodDecl->isOverloadedOperator() && 13097 MethodDecl->getOverloadedOperator() == OO_Equal) { 13098 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13099 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13100 if (MethodDecl->isCopyAssignmentOperator()) 13101 DefineImplicitCopyAssignment(Loc, MethodDecl); 13102 else if (MethodDecl->isMoveAssignmentOperator()) 13103 DefineImplicitMoveAssignment(Loc, MethodDecl); 13104 } 13105 } else if (isa<CXXConversionDecl>(MethodDecl) && 13106 MethodDecl->getParent()->isLambda()) { 13107 CXXConversionDecl *Conversion = 13108 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13109 if (Conversion->isLambdaToBlockPointerConversion()) 13110 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13111 else 13112 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13113 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13114 MarkVTableUsed(Loc, MethodDecl->getParent()); 13115 } 13116 13117 // Recursive functions should be marked when used from another function. 13118 // FIXME: Is this really right? 13119 if (CurContext == Func) return; 13120 13121 // Resolve the exception specification for any function which is 13122 // used: CodeGen will need it. 13123 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13124 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13125 ResolveExceptionSpec(Loc, FPT); 13126 13127 // Implicit instantiation of function templates and member functions of 13128 // class templates. 13129 if (Func->isImplicitlyInstantiable()) { 13130 bool AlreadyInstantiated = false; 13131 SourceLocation PointOfInstantiation = Loc; 13132 if (FunctionTemplateSpecializationInfo *SpecInfo 13133 = Func->getTemplateSpecializationInfo()) { 13134 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13135 SpecInfo->setPointOfInstantiation(Loc); 13136 else if (SpecInfo->getTemplateSpecializationKind() 13137 == TSK_ImplicitInstantiation) { 13138 AlreadyInstantiated = true; 13139 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13140 } 13141 } else if (MemberSpecializationInfo *MSInfo 13142 = Func->getMemberSpecializationInfo()) { 13143 if (MSInfo->getPointOfInstantiation().isInvalid()) 13144 MSInfo->setPointOfInstantiation(Loc); 13145 else if (MSInfo->getTemplateSpecializationKind() 13146 == TSK_ImplicitInstantiation) { 13147 AlreadyInstantiated = true; 13148 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13149 } 13150 } 13151 13152 if (!AlreadyInstantiated || Func->isConstexpr()) { 13153 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13154 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13155 ActiveTemplateInstantiations.size()) 13156 PendingLocalImplicitInstantiations.push_back( 13157 std::make_pair(Func, PointOfInstantiation)); 13158 else if (Func->isConstexpr()) 13159 // Do not defer instantiations of constexpr functions, to avoid the 13160 // expression evaluator needing to call back into Sema if it sees a 13161 // call to such a function. 13162 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13163 else { 13164 PendingInstantiations.push_back(std::make_pair(Func, 13165 PointOfInstantiation)); 13166 // Notify the consumer that a function was implicitly instantiated. 13167 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13168 } 13169 } 13170 } else { 13171 // Walk redefinitions, as some of them may be instantiable. 13172 for (auto i : Func->redecls()) { 13173 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13174 MarkFunctionReferenced(Loc, i, OdrUse); 13175 } 13176 } 13177 13178 if (!OdrUse) return; 13179 13180 // Keep track of used but undefined functions. 13181 if (!Func->isDefined()) { 13182 if (mightHaveNonExternalLinkage(Func)) 13183 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13184 else if (Func->getMostRecentDecl()->isInlined() && 13185 !LangOpts.GNUInline && 13186 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13187 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13188 } 13189 13190 Func->markUsed(Context); 13191 } 13192 13193 static void 13194 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13195 VarDecl *var, DeclContext *DC) { 13196 DeclContext *VarDC = var->getDeclContext(); 13197 13198 // If the parameter still belongs to the translation unit, then 13199 // we're actually just using one parameter in the declaration of 13200 // the next. 13201 if (isa<ParmVarDecl>(var) && 13202 isa<TranslationUnitDecl>(VarDC)) 13203 return; 13204 13205 // For C code, don't diagnose about capture if we're not actually in code 13206 // right now; it's impossible to write a non-constant expression outside of 13207 // function context, so we'll get other (more useful) diagnostics later. 13208 // 13209 // For C++, things get a bit more nasty... it would be nice to suppress this 13210 // diagnostic for certain cases like using a local variable in an array bound 13211 // for a member of a local class, but the correct predicate is not obvious. 13212 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13213 return; 13214 13215 if (isa<CXXMethodDecl>(VarDC) && 13216 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13217 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 13218 << var->getIdentifier(); 13219 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 13220 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 13221 << var->getIdentifier() << fn->getDeclName(); 13222 } else if (isa<BlockDecl>(VarDC)) { 13223 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 13224 << var->getIdentifier(); 13225 } else { 13226 // FIXME: Is there any other context where a local variable can be 13227 // declared? 13228 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 13229 << var->getIdentifier(); 13230 } 13231 13232 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13233 << var->getIdentifier(); 13234 13235 // FIXME: Add additional diagnostic info about class etc. which prevents 13236 // capture. 13237 } 13238 13239 13240 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13241 bool &SubCapturesAreNested, 13242 QualType &CaptureType, 13243 QualType &DeclRefType) { 13244 // Check whether we've already captured it. 13245 if (CSI->CaptureMap.count(Var)) { 13246 // If we found a capture, any subcaptures are nested. 13247 SubCapturesAreNested = true; 13248 13249 // Retrieve the capture type for this variable. 13250 CaptureType = CSI->getCapture(Var).getCaptureType(); 13251 13252 // Compute the type of an expression that refers to this variable. 13253 DeclRefType = CaptureType.getNonReferenceType(); 13254 13255 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13256 // are mutable in the sense that user can change their value - they are 13257 // private instances of the captured declarations. 13258 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13259 if (Cap.isCopyCapture() && 13260 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13261 !(isa<CapturedRegionScopeInfo>(CSI) && 13262 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13263 DeclRefType.addConst(); 13264 return true; 13265 } 13266 return false; 13267 } 13268 13269 // Only block literals, captured statements, and lambda expressions can 13270 // capture; other scopes don't work. 13271 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13272 SourceLocation Loc, 13273 const bool Diagnose, Sema &S) { 13274 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13275 return getLambdaAwareParentOfDeclContext(DC); 13276 else if (Var->hasLocalStorage()) { 13277 if (Diagnose) 13278 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13279 } 13280 return nullptr; 13281 } 13282 13283 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13284 // certain types of variables (unnamed, variably modified types etc.) 13285 // so check for eligibility. 13286 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13287 SourceLocation Loc, 13288 const bool Diagnose, Sema &S) { 13289 13290 bool IsBlock = isa<BlockScopeInfo>(CSI); 13291 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13292 13293 // Lambdas are not allowed to capture unnamed variables 13294 // (e.g. anonymous unions). 13295 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13296 // assuming that's the intent. 13297 if (IsLambda && !Var->getDeclName()) { 13298 if (Diagnose) { 13299 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13300 S.Diag(Var->getLocation(), diag::note_declared_at); 13301 } 13302 return false; 13303 } 13304 13305 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13306 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13307 if (Diagnose) { 13308 S.Diag(Loc, diag::err_ref_vm_type); 13309 S.Diag(Var->getLocation(), diag::note_previous_decl) 13310 << Var->getDeclName(); 13311 } 13312 return false; 13313 } 13314 // Prohibit structs with flexible array members too. 13315 // We cannot capture what is in the tail end of the struct. 13316 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13317 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13318 if (Diagnose) { 13319 if (IsBlock) 13320 S.Diag(Loc, diag::err_ref_flexarray_type); 13321 else 13322 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13323 << Var->getDeclName(); 13324 S.Diag(Var->getLocation(), diag::note_previous_decl) 13325 << Var->getDeclName(); 13326 } 13327 return false; 13328 } 13329 } 13330 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13331 // Lambdas and captured statements are not allowed to capture __block 13332 // variables; they don't support the expected semantics. 13333 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13334 if (Diagnose) { 13335 S.Diag(Loc, diag::err_capture_block_variable) 13336 << Var->getDeclName() << !IsLambda; 13337 S.Diag(Var->getLocation(), diag::note_previous_decl) 13338 << Var->getDeclName(); 13339 } 13340 return false; 13341 } 13342 13343 return true; 13344 } 13345 13346 // Returns true if the capture by block was successful. 13347 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13348 SourceLocation Loc, 13349 const bool BuildAndDiagnose, 13350 QualType &CaptureType, 13351 QualType &DeclRefType, 13352 const bool Nested, 13353 Sema &S) { 13354 Expr *CopyExpr = nullptr; 13355 bool ByRef = false; 13356 13357 // Blocks are not allowed to capture arrays. 13358 if (CaptureType->isArrayType()) { 13359 if (BuildAndDiagnose) { 13360 S.Diag(Loc, diag::err_ref_array_type); 13361 S.Diag(Var->getLocation(), diag::note_previous_decl) 13362 << Var->getDeclName(); 13363 } 13364 return false; 13365 } 13366 13367 // Forbid the block-capture of autoreleasing variables. 13368 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13369 if (BuildAndDiagnose) { 13370 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13371 << /*block*/ 0; 13372 S.Diag(Var->getLocation(), diag::note_previous_decl) 13373 << Var->getDeclName(); 13374 } 13375 return false; 13376 } 13377 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13378 if (HasBlocksAttr || CaptureType->isReferenceType() || 13379 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13380 // Block capture by reference does not change the capture or 13381 // declaration reference types. 13382 ByRef = true; 13383 } else { 13384 // Block capture by copy introduces 'const'. 13385 CaptureType = CaptureType.getNonReferenceType().withConst(); 13386 DeclRefType = CaptureType; 13387 13388 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13389 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13390 // The capture logic needs the destructor, so make sure we mark it. 13391 // Usually this is unnecessary because most local variables have 13392 // their destructors marked at declaration time, but parameters are 13393 // an exception because it's technically only the call site that 13394 // actually requires the destructor. 13395 if (isa<ParmVarDecl>(Var)) 13396 S.FinalizeVarWithDestructor(Var, Record); 13397 13398 // Enter a new evaluation context to insulate the copy 13399 // full-expression. 13400 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13401 13402 // According to the blocks spec, the capture of a variable from 13403 // the stack requires a const copy constructor. This is not true 13404 // of the copy/move done to move a __block variable to the heap. 13405 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13406 DeclRefType.withConst(), 13407 VK_LValue, Loc); 13408 13409 ExprResult Result 13410 = S.PerformCopyInitialization( 13411 InitializedEntity::InitializeBlock(Var->getLocation(), 13412 CaptureType, false), 13413 Loc, DeclRef); 13414 13415 // Build a full-expression copy expression if initialization 13416 // succeeded and used a non-trivial constructor. Recover from 13417 // errors by pretending that the copy isn't necessary. 13418 if (!Result.isInvalid() && 13419 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13420 ->isTrivial()) { 13421 Result = S.MaybeCreateExprWithCleanups(Result); 13422 CopyExpr = Result.get(); 13423 } 13424 } 13425 } 13426 } 13427 13428 // Actually capture the variable. 13429 if (BuildAndDiagnose) 13430 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13431 SourceLocation(), CaptureType, CopyExpr); 13432 13433 return true; 13434 13435 } 13436 13437 13438 /// \brief Capture the given variable in the captured region. 13439 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13440 VarDecl *Var, 13441 SourceLocation Loc, 13442 const bool BuildAndDiagnose, 13443 QualType &CaptureType, 13444 QualType &DeclRefType, 13445 const bool RefersToCapturedVariable, 13446 Sema &S) { 13447 // By default, capture variables by reference. 13448 bool ByRef = true; 13449 // Using an LValue reference type is consistent with Lambdas (see below). 13450 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13451 if (S.IsOpenMPCapturedDecl(Var)) 13452 DeclRefType = DeclRefType.getUnqualifiedType(); 13453 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13454 } 13455 13456 if (ByRef) 13457 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13458 else 13459 CaptureType = DeclRefType; 13460 13461 Expr *CopyExpr = nullptr; 13462 if (BuildAndDiagnose) { 13463 // The current implementation assumes that all variables are captured 13464 // by references. Since there is no capture by copy, no expression 13465 // evaluation will be needed. 13466 RecordDecl *RD = RSI->TheRecordDecl; 13467 13468 FieldDecl *Field 13469 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13470 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13471 nullptr, false, ICIS_NoInit); 13472 Field->setImplicit(true); 13473 Field->setAccess(AS_private); 13474 RD->addDecl(Field); 13475 13476 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13477 DeclRefType, VK_LValue, Loc); 13478 Var->setReferenced(true); 13479 Var->markUsed(S.Context); 13480 } 13481 13482 // Actually capture the variable. 13483 if (BuildAndDiagnose) 13484 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13485 SourceLocation(), CaptureType, CopyExpr); 13486 13487 13488 return true; 13489 } 13490 13491 /// \brief Create a field within the lambda class for the variable 13492 /// being captured. 13493 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13494 QualType FieldType, QualType DeclRefType, 13495 SourceLocation Loc, 13496 bool RefersToCapturedVariable) { 13497 CXXRecordDecl *Lambda = LSI->Lambda; 13498 13499 // Build the non-static data member. 13500 FieldDecl *Field 13501 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13502 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13503 nullptr, false, ICIS_NoInit); 13504 Field->setImplicit(true); 13505 Field->setAccess(AS_private); 13506 Lambda->addDecl(Field); 13507 } 13508 13509 /// \brief Capture the given variable in the lambda. 13510 static bool captureInLambda(LambdaScopeInfo *LSI, 13511 VarDecl *Var, 13512 SourceLocation Loc, 13513 const bool BuildAndDiagnose, 13514 QualType &CaptureType, 13515 QualType &DeclRefType, 13516 const bool RefersToCapturedVariable, 13517 const Sema::TryCaptureKind Kind, 13518 SourceLocation EllipsisLoc, 13519 const bool IsTopScope, 13520 Sema &S) { 13521 13522 // Determine whether we are capturing by reference or by value. 13523 bool ByRef = false; 13524 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13525 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13526 } else { 13527 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13528 } 13529 13530 // Compute the type of the field that will capture this variable. 13531 if (ByRef) { 13532 // C++11 [expr.prim.lambda]p15: 13533 // An entity is captured by reference if it is implicitly or 13534 // explicitly captured but not captured by copy. It is 13535 // unspecified whether additional unnamed non-static data 13536 // members are declared in the closure type for entities 13537 // captured by reference. 13538 // 13539 // FIXME: It is not clear whether we want to build an lvalue reference 13540 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13541 // to do the former, while EDG does the latter. Core issue 1249 will 13542 // clarify, but for now we follow GCC because it's a more permissive and 13543 // easily defensible position. 13544 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13545 } else { 13546 // C++11 [expr.prim.lambda]p14: 13547 // For each entity captured by copy, an unnamed non-static 13548 // data member is declared in the closure type. The 13549 // declaration order of these members is unspecified. The type 13550 // of such a data member is the type of the corresponding 13551 // captured entity if the entity is not a reference to an 13552 // object, or the referenced type otherwise. [Note: If the 13553 // captured entity is a reference to a function, the 13554 // corresponding data member is also a reference to a 13555 // function. - end note ] 13556 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13557 if (!RefType->getPointeeType()->isFunctionType()) 13558 CaptureType = RefType->getPointeeType(); 13559 } 13560 13561 // Forbid the lambda copy-capture of autoreleasing variables. 13562 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13563 if (BuildAndDiagnose) { 13564 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13565 S.Diag(Var->getLocation(), diag::note_previous_decl) 13566 << Var->getDeclName(); 13567 } 13568 return false; 13569 } 13570 13571 // Make sure that by-copy captures are of a complete and non-abstract type. 13572 if (BuildAndDiagnose) { 13573 if (!CaptureType->isDependentType() && 13574 S.RequireCompleteType(Loc, CaptureType, 13575 diag::err_capture_of_incomplete_type, 13576 Var->getDeclName())) 13577 return false; 13578 13579 if (S.RequireNonAbstractType(Loc, CaptureType, 13580 diag::err_capture_of_abstract_type)) 13581 return false; 13582 } 13583 } 13584 13585 // Capture this variable in the lambda. 13586 if (BuildAndDiagnose) 13587 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13588 RefersToCapturedVariable); 13589 13590 // Compute the type of a reference to this captured variable. 13591 if (ByRef) 13592 DeclRefType = CaptureType.getNonReferenceType(); 13593 else { 13594 // C++ [expr.prim.lambda]p5: 13595 // The closure type for a lambda-expression has a public inline 13596 // function call operator [...]. This function call operator is 13597 // declared const (9.3.1) if and only if the lambda-expression’s 13598 // parameter-declaration-clause is not followed by mutable. 13599 DeclRefType = CaptureType.getNonReferenceType(); 13600 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13601 DeclRefType.addConst(); 13602 } 13603 13604 // Add the capture. 13605 if (BuildAndDiagnose) 13606 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13607 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13608 13609 return true; 13610 } 13611 13612 bool Sema::tryCaptureVariable( 13613 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13614 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13615 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13616 // An init-capture is notionally from the context surrounding its 13617 // declaration, but its parent DC is the lambda class. 13618 DeclContext *VarDC = Var->getDeclContext(); 13619 if (Var->isInitCapture()) 13620 VarDC = VarDC->getParent(); 13621 13622 DeclContext *DC = CurContext; 13623 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13624 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13625 // We need to sync up the Declaration Context with the 13626 // FunctionScopeIndexToStopAt 13627 if (FunctionScopeIndexToStopAt) { 13628 unsigned FSIndex = FunctionScopes.size() - 1; 13629 while (FSIndex != MaxFunctionScopesIndex) { 13630 DC = getLambdaAwareParentOfDeclContext(DC); 13631 --FSIndex; 13632 } 13633 } 13634 13635 13636 // If the variable is declared in the current context, there is no need to 13637 // capture it. 13638 if (VarDC == DC) return true; 13639 13640 // Capture global variables if it is required to use private copy of this 13641 // variable. 13642 bool IsGlobal = !Var->hasLocalStorage(); 13643 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13644 return true; 13645 13646 // Walk up the stack to determine whether we can capture the variable, 13647 // performing the "simple" checks that don't depend on type. We stop when 13648 // we've either hit the declared scope of the variable or find an existing 13649 // capture of that variable. We start from the innermost capturing-entity 13650 // (the DC) and ensure that all intervening capturing-entities 13651 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13652 // declcontext can either capture the variable or have already captured 13653 // the variable. 13654 CaptureType = Var->getType(); 13655 DeclRefType = CaptureType.getNonReferenceType(); 13656 bool Nested = false; 13657 bool Explicit = (Kind != TryCapture_Implicit); 13658 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13659 do { 13660 // Only block literals, captured statements, and lambda expressions can 13661 // capture; other scopes don't work. 13662 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13663 ExprLoc, 13664 BuildAndDiagnose, 13665 *this); 13666 // We need to check for the parent *first* because, if we *have* 13667 // private-captured a global variable, we need to recursively capture it in 13668 // intermediate blocks, lambdas, etc. 13669 if (!ParentDC) { 13670 if (IsGlobal) { 13671 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13672 break; 13673 } 13674 return true; 13675 } 13676 13677 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13678 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13679 13680 13681 // Check whether we've already captured it. 13682 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13683 DeclRefType)) 13684 break; 13685 // If we are instantiating a generic lambda call operator body, 13686 // we do not want to capture new variables. What was captured 13687 // during either a lambdas transformation or initial parsing 13688 // should be used. 13689 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13690 if (BuildAndDiagnose) { 13691 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13692 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13693 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13694 Diag(Var->getLocation(), diag::note_previous_decl) 13695 << Var->getDeclName(); 13696 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13697 } else 13698 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13699 } 13700 return true; 13701 } 13702 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13703 // certain types of variables (unnamed, variably modified types etc.) 13704 // so check for eligibility. 13705 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13706 return true; 13707 13708 // Try to capture variable-length arrays types. 13709 if (Var->getType()->isVariablyModifiedType()) { 13710 // We're going to walk down into the type and look for VLA 13711 // expressions. 13712 QualType QTy = Var->getType(); 13713 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13714 QTy = PVD->getOriginalType(); 13715 captureVariablyModifiedType(Context, QTy, CSI); 13716 } 13717 13718 if (getLangOpts().OpenMP) { 13719 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13720 // OpenMP private variables should not be captured in outer scope, so 13721 // just break here. Similarly, global variables that are captured in a 13722 // target region should not be captured outside the scope of the region. 13723 if (RSI->CapRegionKind == CR_OpenMP) { 13724 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13725 // When we detect target captures we are looking from inside the 13726 // target region, therefore we need to propagate the capture from the 13727 // enclosing region. Therefore, the capture is not initially nested. 13728 if (IsTargetCap) 13729 FunctionScopesIndex--; 13730 13731 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13732 Nested = !IsTargetCap; 13733 DeclRefType = DeclRefType.getUnqualifiedType(); 13734 CaptureType = Context.getLValueReferenceType(DeclRefType); 13735 break; 13736 } 13737 } 13738 } 13739 } 13740 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13741 // No capture-default, and this is not an explicit capture 13742 // so cannot capture this variable. 13743 if (BuildAndDiagnose) { 13744 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13745 Diag(Var->getLocation(), diag::note_previous_decl) 13746 << Var->getDeclName(); 13747 if (cast<LambdaScopeInfo>(CSI)->Lambda) 13748 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13749 diag::note_lambda_decl); 13750 // FIXME: If we error out because an outer lambda can not implicitly 13751 // capture a variable that an inner lambda explicitly captures, we 13752 // should have the inner lambda do the explicit capture - because 13753 // it makes for cleaner diagnostics later. This would purely be done 13754 // so that the diagnostic does not misleadingly claim that a variable 13755 // can not be captured by a lambda implicitly even though it is captured 13756 // explicitly. Suggestion: 13757 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13758 // at the function head 13759 // - cache the StartingDeclContext - this must be a lambda 13760 // - captureInLambda in the innermost lambda the variable. 13761 } 13762 return true; 13763 } 13764 13765 FunctionScopesIndex--; 13766 DC = ParentDC; 13767 Explicit = false; 13768 } while (!VarDC->Equals(DC)); 13769 13770 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13771 // computing the type of the capture at each step, checking type-specific 13772 // requirements, and adding captures if requested. 13773 // If the variable had already been captured previously, we start capturing 13774 // at the lambda nested within that one. 13775 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13776 ++I) { 13777 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13778 13779 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13780 if (!captureInBlock(BSI, Var, ExprLoc, 13781 BuildAndDiagnose, CaptureType, 13782 DeclRefType, Nested, *this)) 13783 return true; 13784 Nested = true; 13785 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13786 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13787 BuildAndDiagnose, CaptureType, 13788 DeclRefType, Nested, *this)) 13789 return true; 13790 Nested = true; 13791 } else { 13792 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13793 if (!captureInLambda(LSI, Var, ExprLoc, 13794 BuildAndDiagnose, CaptureType, 13795 DeclRefType, Nested, Kind, EllipsisLoc, 13796 /*IsTopScope*/I == N - 1, *this)) 13797 return true; 13798 Nested = true; 13799 } 13800 } 13801 return false; 13802 } 13803 13804 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13805 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13806 QualType CaptureType; 13807 QualType DeclRefType; 13808 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13809 /*BuildAndDiagnose=*/true, CaptureType, 13810 DeclRefType, nullptr); 13811 } 13812 13813 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13814 QualType CaptureType; 13815 QualType DeclRefType; 13816 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13817 /*BuildAndDiagnose=*/false, CaptureType, 13818 DeclRefType, nullptr); 13819 } 13820 13821 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13822 QualType CaptureType; 13823 QualType DeclRefType; 13824 13825 // Determine whether we can capture this variable. 13826 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13827 /*BuildAndDiagnose=*/false, CaptureType, 13828 DeclRefType, nullptr)) 13829 return QualType(); 13830 13831 return DeclRefType; 13832 } 13833 13834 13835 13836 // If either the type of the variable or the initializer is dependent, 13837 // return false. Otherwise, determine whether the variable is a constant 13838 // expression. Use this if you need to know if a variable that might or 13839 // might not be dependent is truly a constant expression. 13840 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13841 ASTContext &Context) { 13842 13843 if (Var->getType()->isDependentType()) 13844 return false; 13845 const VarDecl *DefVD = nullptr; 13846 Var->getAnyInitializer(DefVD); 13847 if (!DefVD) 13848 return false; 13849 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13850 Expr *Init = cast<Expr>(Eval->Value); 13851 if (Init->isValueDependent()) 13852 return false; 13853 return IsVariableAConstantExpression(Var, Context); 13854 } 13855 13856 13857 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13858 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13859 // an object that satisfies the requirements for appearing in a 13860 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13861 // is immediately applied." This function handles the lvalue-to-rvalue 13862 // conversion part. 13863 MaybeODRUseExprs.erase(E->IgnoreParens()); 13864 13865 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13866 // to a variable that is a constant expression, and if so, identify it as 13867 // a reference to a variable that does not involve an odr-use of that 13868 // variable. 13869 if (LambdaScopeInfo *LSI = getCurLambda()) { 13870 Expr *SansParensExpr = E->IgnoreParens(); 13871 VarDecl *Var = nullptr; 13872 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13873 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13874 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13875 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13876 13877 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13878 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13879 } 13880 } 13881 13882 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13883 Res = CorrectDelayedTyposInExpr(Res); 13884 13885 if (!Res.isUsable()) 13886 return Res; 13887 13888 // If a constant-expression is a reference to a variable where we delay 13889 // deciding whether it is an odr-use, just assume we will apply the 13890 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13891 // (a non-type template argument), we have special handling anyway. 13892 UpdateMarkingForLValueToRValue(Res.get()); 13893 return Res; 13894 } 13895 13896 void Sema::CleanupVarDeclMarking() { 13897 for (Expr *E : MaybeODRUseExprs) { 13898 VarDecl *Var; 13899 SourceLocation Loc; 13900 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13901 Var = cast<VarDecl>(DRE->getDecl()); 13902 Loc = DRE->getLocation(); 13903 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13904 Var = cast<VarDecl>(ME->getMemberDecl()); 13905 Loc = ME->getMemberLoc(); 13906 } else { 13907 llvm_unreachable("Unexpected expression"); 13908 } 13909 13910 MarkVarDeclODRUsed(Var, Loc, *this, 13911 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13912 } 13913 13914 MaybeODRUseExprs.clear(); 13915 } 13916 13917 13918 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13919 VarDecl *Var, Expr *E) { 13920 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13921 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13922 Var->setReferenced(); 13923 13924 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13925 bool MarkODRUsed = true; 13926 13927 // If the context is not potentially evaluated, this is not an odr-use and 13928 // does not trigger instantiation. 13929 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13930 if (SemaRef.isUnevaluatedContext()) 13931 return; 13932 13933 // If we don't yet know whether this context is going to end up being an 13934 // evaluated context, and we're referencing a variable from an enclosing 13935 // scope, add a potential capture. 13936 // 13937 // FIXME: Is this necessary? These contexts are only used for default 13938 // arguments, where local variables can't be used. 13939 const bool RefersToEnclosingScope = 13940 (SemaRef.CurContext != Var->getDeclContext() && 13941 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13942 if (RefersToEnclosingScope) { 13943 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13944 // If a variable could potentially be odr-used, defer marking it so 13945 // until we finish analyzing the full expression for any 13946 // lvalue-to-rvalue 13947 // or discarded value conversions that would obviate odr-use. 13948 // Add it to the list of potential captures that will be analyzed 13949 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13950 // unless the variable is a reference that was initialized by a constant 13951 // expression (this will never need to be captured or odr-used). 13952 assert(E && "Capture variable should be used in an expression."); 13953 if (!Var->getType()->isReferenceType() || 13954 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13955 LSI->addPotentialCapture(E->IgnoreParens()); 13956 } 13957 } 13958 13959 if (!isTemplateInstantiation(TSK)) 13960 return; 13961 13962 // Instantiate, but do not mark as odr-used, variable templates. 13963 MarkODRUsed = false; 13964 } 13965 13966 VarTemplateSpecializationDecl *VarSpec = 13967 dyn_cast<VarTemplateSpecializationDecl>(Var); 13968 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13969 "Can't instantiate a partial template specialization."); 13970 13971 // If this might be a member specialization of a static data member, check 13972 // the specialization is visible. We already did the checks for variable 13973 // template specializations when we created them. 13974 if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var)) 13975 SemaRef.checkSpecializationVisibility(Loc, Var); 13976 13977 // Perform implicit instantiation of static data members, static data member 13978 // templates of class templates, and variable template specializations. Delay 13979 // instantiations of variable templates, except for those that could be used 13980 // in a constant expression. 13981 if (isTemplateInstantiation(TSK)) { 13982 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13983 13984 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13985 if (Var->getPointOfInstantiation().isInvalid()) { 13986 // This is a modification of an existing AST node. Notify listeners. 13987 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13988 L->StaticDataMemberInstantiated(Var); 13989 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13990 // Don't bother trying to instantiate it again, unless we might need 13991 // its initializer before we get to the end of the TU. 13992 TryInstantiating = false; 13993 } 13994 13995 if (Var->getPointOfInstantiation().isInvalid()) 13996 Var->setTemplateSpecializationKind(TSK, Loc); 13997 13998 if (TryInstantiating) { 13999 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14000 bool InstantiationDependent = false; 14001 bool IsNonDependent = 14002 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14003 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14004 : true; 14005 14006 // Do not instantiate specializations that are still type-dependent. 14007 if (IsNonDependent) { 14008 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14009 // Do not defer instantiations of variables which could be used in a 14010 // constant expression. 14011 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14012 } else { 14013 SemaRef.PendingInstantiations 14014 .push_back(std::make_pair(Var, PointOfInstantiation)); 14015 } 14016 } 14017 } 14018 } 14019 14020 if (!MarkODRUsed) 14021 return; 14022 14023 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14024 // the requirements for appearing in a constant expression (5.19) and, if 14025 // it is an object, the lvalue-to-rvalue conversion (4.1) 14026 // is immediately applied." We check the first part here, and 14027 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14028 // Note that we use the C++11 definition everywhere because nothing in 14029 // C++03 depends on whether we get the C++03 version correct. The second 14030 // part does not apply to references, since they are not objects. 14031 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 14032 // A reference initialized by a constant expression can never be 14033 // odr-used, so simply ignore it. 14034 if (!Var->getType()->isReferenceType()) 14035 SemaRef.MaybeODRUseExprs.insert(E); 14036 } else 14037 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14038 /*MaxFunctionScopeIndex ptr*/ nullptr); 14039 } 14040 14041 /// \brief Mark a variable referenced, and check whether it is odr-used 14042 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14043 /// used directly for normal expressions referring to VarDecl. 14044 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14045 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14046 } 14047 14048 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14049 Decl *D, Expr *E, bool MightBeOdrUse) { 14050 if (SemaRef.isInOpenMPDeclareTargetContext()) 14051 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14052 14053 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14054 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14055 return; 14056 } 14057 14058 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14059 14060 // If this is a call to a method via a cast, also mark the method in the 14061 // derived class used in case codegen can devirtualize the call. 14062 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14063 if (!ME) 14064 return; 14065 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14066 if (!MD) 14067 return; 14068 // Only attempt to devirtualize if this is truly a virtual call. 14069 bool IsVirtualCall = MD->isVirtual() && 14070 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14071 if (!IsVirtualCall) 14072 return; 14073 const Expr *Base = ME->getBase(); 14074 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14075 if (!MostDerivedClassDecl) 14076 return; 14077 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14078 if (!DM || DM->isPure()) 14079 return; 14080 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14081 } 14082 14083 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14084 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14085 // TODO: update this with DR# once a defect report is filed. 14086 // C++11 defect. The address of a pure member should not be an ODR use, even 14087 // if it's a qualified reference. 14088 bool OdrUse = true; 14089 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14090 if (Method->isVirtual()) 14091 OdrUse = false; 14092 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14093 } 14094 14095 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14096 void Sema::MarkMemberReferenced(MemberExpr *E) { 14097 // C++11 [basic.def.odr]p2: 14098 // A non-overloaded function whose name appears as a potentially-evaluated 14099 // expression or a member of a set of candidate functions, if selected by 14100 // overload resolution when referred to from a potentially-evaluated 14101 // expression, is odr-used, unless it is a pure virtual function and its 14102 // name is not explicitly qualified. 14103 bool MightBeOdrUse = true; 14104 if (E->performsVirtualDispatch(getLangOpts())) { 14105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14106 if (Method->isPure()) 14107 MightBeOdrUse = false; 14108 } 14109 SourceLocation Loc = E->getMemberLoc().isValid() ? 14110 E->getMemberLoc() : E->getLocStart(); 14111 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14112 } 14113 14114 /// \brief Perform marking for a reference to an arbitrary declaration. It 14115 /// marks the declaration referenced, and performs odr-use checking for 14116 /// functions and variables. This method should not be used when building a 14117 /// normal expression which refers to a variable. 14118 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14119 bool MightBeOdrUse) { 14120 if (MightBeOdrUse) { 14121 if (auto *VD = dyn_cast<VarDecl>(D)) { 14122 MarkVariableReferenced(Loc, VD); 14123 return; 14124 } 14125 } 14126 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14127 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14128 return; 14129 } 14130 D->setReferenced(); 14131 } 14132 14133 namespace { 14134 // Mark all of the declarations referenced 14135 // FIXME: Not fully implemented yet! We need to have a better understanding 14136 // of when we're entering 14137 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14138 Sema &S; 14139 SourceLocation Loc; 14140 14141 public: 14142 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14143 14144 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14145 14146 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14147 bool TraverseRecordType(RecordType *T); 14148 }; 14149 } 14150 14151 bool MarkReferencedDecls::TraverseTemplateArgument( 14152 const TemplateArgument &Arg) { 14153 if (Arg.getKind() == TemplateArgument::Declaration) { 14154 if (Decl *D = Arg.getAsDecl()) 14155 S.MarkAnyDeclReferenced(Loc, D, true); 14156 } 14157 14158 return Inherited::TraverseTemplateArgument(Arg); 14159 } 14160 14161 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 14162 if (ClassTemplateSpecializationDecl *Spec 14163 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 14164 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 14165 return TraverseTemplateArguments(Args.data(), Args.size()); 14166 } 14167 14168 return true; 14169 } 14170 14171 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14172 MarkReferencedDecls Marker(*this, Loc); 14173 Marker.TraverseType(Context.getCanonicalType(T)); 14174 } 14175 14176 namespace { 14177 /// \brief Helper class that marks all of the declarations referenced by 14178 /// potentially-evaluated subexpressions as "referenced". 14179 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14180 Sema &S; 14181 bool SkipLocalVariables; 14182 14183 public: 14184 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14185 14186 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14187 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14188 14189 void VisitDeclRefExpr(DeclRefExpr *E) { 14190 // If we were asked not to visit local variables, don't. 14191 if (SkipLocalVariables) { 14192 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14193 if (VD->hasLocalStorage()) 14194 return; 14195 } 14196 14197 S.MarkDeclRefReferenced(E); 14198 } 14199 14200 void VisitMemberExpr(MemberExpr *E) { 14201 S.MarkMemberReferenced(E); 14202 Inherited::VisitMemberExpr(E); 14203 } 14204 14205 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14206 S.MarkFunctionReferenced(E->getLocStart(), 14207 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14208 Visit(E->getSubExpr()); 14209 } 14210 14211 void VisitCXXNewExpr(CXXNewExpr *E) { 14212 if (E->getOperatorNew()) 14213 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14214 if (E->getOperatorDelete()) 14215 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14216 Inherited::VisitCXXNewExpr(E); 14217 } 14218 14219 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14220 if (E->getOperatorDelete()) 14221 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14222 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14223 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14224 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14225 S.MarkFunctionReferenced(E->getLocStart(), 14226 S.LookupDestructor(Record)); 14227 } 14228 14229 Inherited::VisitCXXDeleteExpr(E); 14230 } 14231 14232 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14233 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14234 Inherited::VisitCXXConstructExpr(E); 14235 } 14236 14237 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14238 Visit(E->getExpr()); 14239 } 14240 14241 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14242 Inherited::VisitImplicitCastExpr(E); 14243 14244 if (E->getCastKind() == CK_LValueToRValue) 14245 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14246 } 14247 }; 14248 } 14249 14250 /// \brief Mark any declarations that appear within this expression or any 14251 /// potentially-evaluated subexpressions as "referenced". 14252 /// 14253 /// \param SkipLocalVariables If true, don't mark local variables as 14254 /// 'referenced'. 14255 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14256 bool SkipLocalVariables) { 14257 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14258 } 14259 14260 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14261 /// of the program being compiled. 14262 /// 14263 /// This routine emits the given diagnostic when the code currently being 14264 /// type-checked is "potentially evaluated", meaning that there is a 14265 /// possibility that the code will actually be executable. Code in sizeof() 14266 /// expressions, code used only during overload resolution, etc., are not 14267 /// potentially evaluated. This routine will suppress such diagnostics or, 14268 /// in the absolutely nutty case of potentially potentially evaluated 14269 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14270 /// later. 14271 /// 14272 /// This routine should be used for all diagnostics that describe the run-time 14273 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14274 /// Failure to do so will likely result in spurious diagnostics or failures 14275 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14276 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14277 const PartialDiagnostic &PD) { 14278 switch (ExprEvalContexts.back().Context) { 14279 case Unevaluated: 14280 case UnevaluatedAbstract: 14281 case DiscardedStatement: 14282 // The argument will never be evaluated, so don't complain. 14283 break; 14284 14285 case ConstantEvaluated: 14286 // Relevant diagnostics should be produced by constant evaluation. 14287 break; 14288 14289 case PotentiallyEvaluated: 14290 case PotentiallyEvaluatedIfUsed: 14291 if (Statement && getCurFunctionOrMethodDecl()) { 14292 FunctionScopes.back()->PossiblyUnreachableDiags. 14293 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14294 } 14295 else 14296 Diag(Loc, PD); 14297 14298 return true; 14299 } 14300 14301 return false; 14302 } 14303 14304 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14305 CallExpr *CE, FunctionDecl *FD) { 14306 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14307 return false; 14308 14309 // If we're inside a decltype's expression, don't check for a valid return 14310 // type or construct temporaries until we know whether this is the last call. 14311 if (ExprEvalContexts.back().IsDecltype) { 14312 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14313 return false; 14314 } 14315 14316 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14317 FunctionDecl *FD; 14318 CallExpr *CE; 14319 14320 public: 14321 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14322 : FD(FD), CE(CE) { } 14323 14324 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14325 if (!FD) { 14326 S.Diag(Loc, diag::err_call_incomplete_return) 14327 << T << CE->getSourceRange(); 14328 return; 14329 } 14330 14331 S.Diag(Loc, diag::err_call_function_incomplete_return) 14332 << CE->getSourceRange() << FD->getDeclName() << T; 14333 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14334 << FD->getDeclName(); 14335 } 14336 } Diagnoser(FD, CE); 14337 14338 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14339 return true; 14340 14341 return false; 14342 } 14343 14344 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14345 // will prevent this condition from triggering, which is what we want. 14346 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14347 SourceLocation Loc; 14348 14349 unsigned diagnostic = diag::warn_condition_is_assignment; 14350 bool IsOrAssign = false; 14351 14352 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14353 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14354 return; 14355 14356 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14357 14358 // Greylist some idioms by putting them into a warning subcategory. 14359 if (ObjCMessageExpr *ME 14360 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14361 Selector Sel = ME->getSelector(); 14362 14363 // self = [<foo> init...] 14364 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14365 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14366 14367 // <foo> = [<bar> nextObject] 14368 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14369 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14370 } 14371 14372 Loc = Op->getOperatorLoc(); 14373 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14374 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14375 return; 14376 14377 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14378 Loc = Op->getOperatorLoc(); 14379 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14380 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14381 else { 14382 // Not an assignment. 14383 return; 14384 } 14385 14386 Diag(Loc, diagnostic) << E->getSourceRange(); 14387 14388 SourceLocation Open = E->getLocStart(); 14389 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14390 Diag(Loc, diag::note_condition_assign_silence) 14391 << FixItHint::CreateInsertion(Open, "(") 14392 << FixItHint::CreateInsertion(Close, ")"); 14393 14394 if (IsOrAssign) 14395 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14396 << FixItHint::CreateReplacement(Loc, "!="); 14397 else 14398 Diag(Loc, diag::note_condition_assign_to_comparison) 14399 << FixItHint::CreateReplacement(Loc, "=="); 14400 } 14401 14402 /// \brief Redundant parentheses over an equality comparison can indicate 14403 /// that the user intended an assignment used as condition. 14404 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14405 // Don't warn if the parens came from a macro. 14406 SourceLocation parenLoc = ParenE->getLocStart(); 14407 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14408 return; 14409 // Don't warn for dependent expressions. 14410 if (ParenE->isTypeDependent()) 14411 return; 14412 14413 Expr *E = ParenE->IgnoreParens(); 14414 14415 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14416 if (opE->getOpcode() == BO_EQ && 14417 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14418 == Expr::MLV_Valid) { 14419 SourceLocation Loc = opE->getOperatorLoc(); 14420 14421 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14422 SourceRange ParenERange = ParenE->getSourceRange(); 14423 Diag(Loc, diag::note_equality_comparison_silence) 14424 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14425 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14426 Diag(Loc, diag::note_equality_comparison_to_assign) 14427 << FixItHint::CreateReplacement(Loc, "="); 14428 } 14429 } 14430 14431 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14432 bool IsConstexpr) { 14433 DiagnoseAssignmentAsCondition(E); 14434 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14435 DiagnoseEqualityWithExtraParens(parenE); 14436 14437 ExprResult result = CheckPlaceholderExpr(E); 14438 if (result.isInvalid()) return ExprError(); 14439 E = result.get(); 14440 14441 if (!E->isTypeDependent()) { 14442 if (getLangOpts().CPlusPlus) 14443 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14444 14445 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14446 if (ERes.isInvalid()) 14447 return ExprError(); 14448 E = ERes.get(); 14449 14450 QualType T = E->getType(); 14451 if (!T->isScalarType()) { // C99 6.8.4.1p1 14452 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14453 << T << E->getSourceRange(); 14454 return ExprError(); 14455 } 14456 CheckBoolLikeConversion(E, Loc); 14457 } 14458 14459 return E; 14460 } 14461 14462 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14463 Expr *SubExpr, ConditionKind CK) { 14464 // Empty conditions are valid in for-statements. 14465 if (!SubExpr) 14466 return ConditionResult(); 14467 14468 ExprResult Cond; 14469 switch (CK) { 14470 case ConditionKind::Boolean: 14471 Cond = CheckBooleanCondition(Loc, SubExpr); 14472 break; 14473 14474 case ConditionKind::ConstexprIf: 14475 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14476 break; 14477 14478 case ConditionKind::Switch: 14479 Cond = CheckSwitchCondition(Loc, SubExpr); 14480 break; 14481 } 14482 if (Cond.isInvalid()) 14483 return ConditionError(); 14484 14485 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14486 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14487 if (!FullExpr.get()) 14488 return ConditionError(); 14489 14490 return ConditionResult(*this, nullptr, FullExpr, 14491 CK == ConditionKind::ConstexprIf); 14492 } 14493 14494 namespace { 14495 /// A visitor for rebuilding a call to an __unknown_any expression 14496 /// to have an appropriate type. 14497 struct RebuildUnknownAnyFunction 14498 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14499 14500 Sema &S; 14501 14502 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14503 14504 ExprResult VisitStmt(Stmt *S) { 14505 llvm_unreachable("unexpected statement!"); 14506 } 14507 14508 ExprResult VisitExpr(Expr *E) { 14509 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14510 << E->getSourceRange(); 14511 return ExprError(); 14512 } 14513 14514 /// Rebuild an expression which simply semantically wraps another 14515 /// expression which it shares the type and value kind of. 14516 template <class T> ExprResult rebuildSugarExpr(T *E) { 14517 ExprResult SubResult = Visit(E->getSubExpr()); 14518 if (SubResult.isInvalid()) return ExprError(); 14519 14520 Expr *SubExpr = SubResult.get(); 14521 E->setSubExpr(SubExpr); 14522 E->setType(SubExpr->getType()); 14523 E->setValueKind(SubExpr->getValueKind()); 14524 assert(E->getObjectKind() == OK_Ordinary); 14525 return E; 14526 } 14527 14528 ExprResult VisitParenExpr(ParenExpr *E) { 14529 return rebuildSugarExpr(E); 14530 } 14531 14532 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14533 return rebuildSugarExpr(E); 14534 } 14535 14536 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14537 ExprResult SubResult = Visit(E->getSubExpr()); 14538 if (SubResult.isInvalid()) return ExprError(); 14539 14540 Expr *SubExpr = SubResult.get(); 14541 E->setSubExpr(SubExpr); 14542 E->setType(S.Context.getPointerType(SubExpr->getType())); 14543 assert(E->getValueKind() == VK_RValue); 14544 assert(E->getObjectKind() == OK_Ordinary); 14545 return E; 14546 } 14547 14548 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14549 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14550 14551 E->setType(VD->getType()); 14552 14553 assert(E->getValueKind() == VK_RValue); 14554 if (S.getLangOpts().CPlusPlus && 14555 !(isa<CXXMethodDecl>(VD) && 14556 cast<CXXMethodDecl>(VD)->isInstance())) 14557 E->setValueKind(VK_LValue); 14558 14559 return E; 14560 } 14561 14562 ExprResult VisitMemberExpr(MemberExpr *E) { 14563 return resolveDecl(E, E->getMemberDecl()); 14564 } 14565 14566 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14567 return resolveDecl(E, E->getDecl()); 14568 } 14569 }; 14570 } 14571 14572 /// Given a function expression of unknown-any type, try to rebuild it 14573 /// to have a function type. 14574 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14575 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14576 if (Result.isInvalid()) return ExprError(); 14577 return S.DefaultFunctionArrayConversion(Result.get()); 14578 } 14579 14580 namespace { 14581 /// A visitor for rebuilding an expression of type __unknown_anytype 14582 /// into one which resolves the type directly on the referring 14583 /// expression. Strict preservation of the original source 14584 /// structure is not a goal. 14585 struct RebuildUnknownAnyExpr 14586 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14587 14588 Sema &S; 14589 14590 /// The current destination type. 14591 QualType DestType; 14592 14593 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14594 : S(S), DestType(CastType) {} 14595 14596 ExprResult VisitStmt(Stmt *S) { 14597 llvm_unreachable("unexpected statement!"); 14598 } 14599 14600 ExprResult VisitExpr(Expr *E) { 14601 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14602 << E->getSourceRange(); 14603 return ExprError(); 14604 } 14605 14606 ExprResult VisitCallExpr(CallExpr *E); 14607 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14608 14609 /// Rebuild an expression which simply semantically wraps another 14610 /// expression which it shares the type and value kind of. 14611 template <class T> ExprResult rebuildSugarExpr(T *E) { 14612 ExprResult SubResult = Visit(E->getSubExpr()); 14613 if (SubResult.isInvalid()) return ExprError(); 14614 Expr *SubExpr = SubResult.get(); 14615 E->setSubExpr(SubExpr); 14616 E->setType(SubExpr->getType()); 14617 E->setValueKind(SubExpr->getValueKind()); 14618 assert(E->getObjectKind() == OK_Ordinary); 14619 return E; 14620 } 14621 14622 ExprResult VisitParenExpr(ParenExpr *E) { 14623 return rebuildSugarExpr(E); 14624 } 14625 14626 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14627 return rebuildSugarExpr(E); 14628 } 14629 14630 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14631 const PointerType *Ptr = DestType->getAs<PointerType>(); 14632 if (!Ptr) { 14633 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14634 << E->getSourceRange(); 14635 return ExprError(); 14636 } 14637 assert(E->getValueKind() == VK_RValue); 14638 assert(E->getObjectKind() == OK_Ordinary); 14639 E->setType(DestType); 14640 14641 // Build the sub-expression as if it were an object of the pointee type. 14642 DestType = Ptr->getPointeeType(); 14643 ExprResult SubResult = Visit(E->getSubExpr()); 14644 if (SubResult.isInvalid()) return ExprError(); 14645 E->setSubExpr(SubResult.get()); 14646 return E; 14647 } 14648 14649 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14650 14651 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14652 14653 ExprResult VisitMemberExpr(MemberExpr *E) { 14654 return resolveDecl(E, E->getMemberDecl()); 14655 } 14656 14657 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14658 return resolveDecl(E, E->getDecl()); 14659 } 14660 }; 14661 } 14662 14663 /// Rebuilds a call expression which yielded __unknown_anytype. 14664 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14665 Expr *CalleeExpr = E->getCallee(); 14666 14667 enum FnKind { 14668 FK_MemberFunction, 14669 FK_FunctionPointer, 14670 FK_BlockPointer 14671 }; 14672 14673 FnKind Kind; 14674 QualType CalleeType = CalleeExpr->getType(); 14675 if (CalleeType == S.Context.BoundMemberTy) { 14676 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14677 Kind = FK_MemberFunction; 14678 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14679 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14680 CalleeType = Ptr->getPointeeType(); 14681 Kind = FK_FunctionPointer; 14682 } else { 14683 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14684 Kind = FK_BlockPointer; 14685 } 14686 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14687 14688 // Verify that this is a legal result type of a function. 14689 if (DestType->isArrayType() || DestType->isFunctionType()) { 14690 unsigned diagID = diag::err_func_returning_array_function; 14691 if (Kind == FK_BlockPointer) 14692 diagID = diag::err_block_returning_array_function; 14693 14694 S.Diag(E->getExprLoc(), diagID) 14695 << DestType->isFunctionType() << DestType; 14696 return ExprError(); 14697 } 14698 14699 // Otherwise, go ahead and set DestType as the call's result. 14700 E->setType(DestType.getNonLValueExprType(S.Context)); 14701 E->setValueKind(Expr::getValueKindForType(DestType)); 14702 assert(E->getObjectKind() == OK_Ordinary); 14703 14704 // Rebuild the function type, replacing the result type with DestType. 14705 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14706 if (Proto) { 14707 // __unknown_anytype(...) is a special case used by the debugger when 14708 // it has no idea what a function's signature is. 14709 // 14710 // We want to build this call essentially under the K&R 14711 // unprototyped rules, but making a FunctionNoProtoType in C++ 14712 // would foul up all sorts of assumptions. However, we cannot 14713 // simply pass all arguments as variadic arguments, nor can we 14714 // portably just call the function under a non-variadic type; see 14715 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14716 // However, it turns out that in practice it is generally safe to 14717 // call a function declared as "A foo(B,C,D);" under the prototype 14718 // "A foo(B,C,D,...);". The only known exception is with the 14719 // Windows ABI, where any variadic function is implicitly cdecl 14720 // regardless of its normal CC. Therefore we change the parameter 14721 // types to match the types of the arguments. 14722 // 14723 // This is a hack, but it is far superior to moving the 14724 // corresponding target-specific code from IR-gen to Sema/AST. 14725 14726 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14727 SmallVector<QualType, 8> ArgTypes; 14728 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14729 ArgTypes.reserve(E->getNumArgs()); 14730 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14731 Expr *Arg = E->getArg(i); 14732 QualType ArgType = Arg->getType(); 14733 if (E->isLValue()) { 14734 ArgType = S.Context.getLValueReferenceType(ArgType); 14735 } else if (E->isXValue()) { 14736 ArgType = S.Context.getRValueReferenceType(ArgType); 14737 } 14738 ArgTypes.push_back(ArgType); 14739 } 14740 ParamTypes = ArgTypes; 14741 } 14742 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14743 Proto->getExtProtoInfo()); 14744 } else { 14745 DestType = S.Context.getFunctionNoProtoType(DestType, 14746 FnType->getExtInfo()); 14747 } 14748 14749 // Rebuild the appropriate pointer-to-function type. 14750 switch (Kind) { 14751 case FK_MemberFunction: 14752 // Nothing to do. 14753 break; 14754 14755 case FK_FunctionPointer: 14756 DestType = S.Context.getPointerType(DestType); 14757 break; 14758 14759 case FK_BlockPointer: 14760 DestType = S.Context.getBlockPointerType(DestType); 14761 break; 14762 } 14763 14764 // Finally, we can recurse. 14765 ExprResult CalleeResult = Visit(CalleeExpr); 14766 if (!CalleeResult.isUsable()) return ExprError(); 14767 E->setCallee(CalleeResult.get()); 14768 14769 // Bind a temporary if necessary. 14770 return S.MaybeBindToTemporary(E); 14771 } 14772 14773 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14774 // Verify that this is a legal result type of a call. 14775 if (DestType->isArrayType() || DestType->isFunctionType()) { 14776 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14777 << DestType->isFunctionType() << DestType; 14778 return ExprError(); 14779 } 14780 14781 // Rewrite the method result type if available. 14782 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14783 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14784 Method->setReturnType(DestType); 14785 } 14786 14787 // Change the type of the message. 14788 E->setType(DestType.getNonReferenceType()); 14789 E->setValueKind(Expr::getValueKindForType(DestType)); 14790 14791 return S.MaybeBindToTemporary(E); 14792 } 14793 14794 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14795 // The only case we should ever see here is a function-to-pointer decay. 14796 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14797 assert(E->getValueKind() == VK_RValue); 14798 assert(E->getObjectKind() == OK_Ordinary); 14799 14800 E->setType(DestType); 14801 14802 // Rebuild the sub-expression as the pointee (function) type. 14803 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14804 14805 ExprResult Result = Visit(E->getSubExpr()); 14806 if (!Result.isUsable()) return ExprError(); 14807 14808 E->setSubExpr(Result.get()); 14809 return E; 14810 } else if (E->getCastKind() == CK_LValueToRValue) { 14811 assert(E->getValueKind() == VK_RValue); 14812 assert(E->getObjectKind() == OK_Ordinary); 14813 14814 assert(isa<BlockPointerType>(E->getType())); 14815 14816 E->setType(DestType); 14817 14818 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14819 DestType = S.Context.getLValueReferenceType(DestType); 14820 14821 ExprResult Result = Visit(E->getSubExpr()); 14822 if (!Result.isUsable()) return ExprError(); 14823 14824 E->setSubExpr(Result.get()); 14825 return E; 14826 } else { 14827 llvm_unreachable("Unhandled cast type!"); 14828 } 14829 } 14830 14831 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14832 ExprValueKind ValueKind = VK_LValue; 14833 QualType Type = DestType; 14834 14835 // We know how to make this work for certain kinds of decls: 14836 14837 // - functions 14838 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14839 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14840 DestType = Ptr->getPointeeType(); 14841 ExprResult Result = resolveDecl(E, VD); 14842 if (Result.isInvalid()) return ExprError(); 14843 return S.ImpCastExprToType(Result.get(), Type, 14844 CK_FunctionToPointerDecay, VK_RValue); 14845 } 14846 14847 if (!Type->isFunctionType()) { 14848 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14849 << VD << E->getSourceRange(); 14850 return ExprError(); 14851 } 14852 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14853 // We must match the FunctionDecl's type to the hack introduced in 14854 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14855 // type. See the lengthy commentary in that routine. 14856 QualType FDT = FD->getType(); 14857 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14858 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14859 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14860 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14861 SourceLocation Loc = FD->getLocation(); 14862 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14863 FD->getDeclContext(), 14864 Loc, Loc, FD->getNameInfo().getName(), 14865 DestType, FD->getTypeSourceInfo(), 14866 SC_None, false/*isInlineSpecified*/, 14867 FD->hasPrototype(), 14868 false/*isConstexprSpecified*/); 14869 14870 if (FD->getQualifier()) 14871 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14872 14873 SmallVector<ParmVarDecl*, 16> Params; 14874 for (const auto &AI : FT->param_types()) { 14875 ParmVarDecl *Param = 14876 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14877 Param->setScopeInfo(0, Params.size()); 14878 Params.push_back(Param); 14879 } 14880 NewFD->setParams(Params); 14881 DRE->setDecl(NewFD); 14882 VD = DRE->getDecl(); 14883 } 14884 } 14885 14886 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14887 if (MD->isInstance()) { 14888 ValueKind = VK_RValue; 14889 Type = S.Context.BoundMemberTy; 14890 } 14891 14892 // Function references aren't l-values in C. 14893 if (!S.getLangOpts().CPlusPlus) 14894 ValueKind = VK_RValue; 14895 14896 // - variables 14897 } else if (isa<VarDecl>(VD)) { 14898 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14899 Type = RefTy->getPointeeType(); 14900 } else if (Type->isFunctionType()) { 14901 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14902 << VD << E->getSourceRange(); 14903 return ExprError(); 14904 } 14905 14906 // - nothing else 14907 } else { 14908 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14909 << VD << E->getSourceRange(); 14910 return ExprError(); 14911 } 14912 14913 // Modifying the declaration like this is friendly to IR-gen but 14914 // also really dangerous. 14915 VD->setType(DestType); 14916 E->setType(Type); 14917 E->setValueKind(ValueKind); 14918 return E; 14919 } 14920 14921 /// Check a cast of an unknown-any type. We intentionally only 14922 /// trigger this for C-style casts. 14923 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14924 Expr *CastExpr, CastKind &CastKind, 14925 ExprValueKind &VK, CXXCastPath &Path) { 14926 // The type we're casting to must be either void or complete. 14927 if (!CastType->isVoidType() && 14928 RequireCompleteType(TypeRange.getBegin(), CastType, 14929 diag::err_typecheck_cast_to_incomplete)) 14930 return ExprError(); 14931 14932 // Rewrite the casted expression from scratch. 14933 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14934 if (!result.isUsable()) return ExprError(); 14935 14936 CastExpr = result.get(); 14937 VK = CastExpr->getValueKind(); 14938 CastKind = CK_NoOp; 14939 14940 return CastExpr; 14941 } 14942 14943 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14944 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14945 } 14946 14947 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14948 Expr *arg, QualType ¶mType) { 14949 // If the syntactic form of the argument is not an explicit cast of 14950 // any sort, just do default argument promotion. 14951 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14952 if (!castArg) { 14953 ExprResult result = DefaultArgumentPromotion(arg); 14954 if (result.isInvalid()) return ExprError(); 14955 paramType = result.get()->getType(); 14956 return result; 14957 } 14958 14959 // Otherwise, use the type that was written in the explicit cast. 14960 assert(!arg->hasPlaceholderType()); 14961 paramType = castArg->getTypeAsWritten(); 14962 14963 // Copy-initialize a parameter of that type. 14964 InitializedEntity entity = 14965 InitializedEntity::InitializeParameter(Context, paramType, 14966 /*consumed*/ false); 14967 return PerformCopyInitialization(entity, callLoc, arg); 14968 } 14969 14970 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14971 Expr *orig = E; 14972 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14973 while (true) { 14974 E = E->IgnoreParenImpCasts(); 14975 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14976 E = call->getCallee(); 14977 diagID = diag::err_uncasted_call_of_unknown_any; 14978 } else { 14979 break; 14980 } 14981 } 14982 14983 SourceLocation loc; 14984 NamedDecl *d; 14985 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14986 loc = ref->getLocation(); 14987 d = ref->getDecl(); 14988 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14989 loc = mem->getMemberLoc(); 14990 d = mem->getMemberDecl(); 14991 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14992 diagID = diag::err_uncasted_call_of_unknown_any; 14993 loc = msg->getSelectorStartLoc(); 14994 d = msg->getMethodDecl(); 14995 if (!d) { 14996 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14997 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14998 << orig->getSourceRange(); 14999 return ExprError(); 15000 } 15001 } else { 15002 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15003 << E->getSourceRange(); 15004 return ExprError(); 15005 } 15006 15007 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15008 15009 // Never recoverable. 15010 return ExprError(); 15011 } 15012 15013 /// Check for operands with placeholder types and complain if found. 15014 /// Returns true if there was an error and no recovery was possible. 15015 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15016 if (!getLangOpts().CPlusPlus) { 15017 // C cannot handle TypoExpr nodes on either side of a binop because it 15018 // doesn't handle dependent types properly, so make sure any TypoExprs have 15019 // been dealt with before checking the operands. 15020 ExprResult Result = CorrectDelayedTyposInExpr(E); 15021 if (!Result.isUsable()) return ExprError(); 15022 E = Result.get(); 15023 } 15024 15025 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15026 if (!placeholderType) return E; 15027 15028 switch (placeholderType->getKind()) { 15029 15030 // Overloaded expressions. 15031 case BuiltinType::Overload: { 15032 // Try to resolve a single function template specialization. 15033 // This is obligatory. 15034 ExprResult Result = E; 15035 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15036 return Result; 15037 15038 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15039 // leaves Result unchanged on failure. 15040 Result = E; 15041 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15042 return Result; 15043 15044 // If that failed, try to recover with a call. 15045 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15046 /*complain*/ true); 15047 return Result; 15048 } 15049 15050 // Bound member functions. 15051 case BuiltinType::BoundMember: { 15052 ExprResult result = E; 15053 const Expr *BME = E->IgnoreParens(); 15054 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15055 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15056 if (isa<CXXPseudoDestructorExpr>(BME)) { 15057 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15058 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15059 if (ME->getMemberNameInfo().getName().getNameKind() == 15060 DeclarationName::CXXDestructorName) 15061 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15062 } 15063 tryToRecoverWithCall(result, PD, 15064 /*complain*/ true); 15065 return result; 15066 } 15067 15068 // ARC unbridged casts. 15069 case BuiltinType::ARCUnbridgedCast: { 15070 Expr *realCast = stripARCUnbridgedCast(E); 15071 diagnoseARCUnbridgedCast(realCast); 15072 return realCast; 15073 } 15074 15075 // Expressions of unknown type. 15076 case BuiltinType::UnknownAny: 15077 return diagnoseUnknownAnyExpr(*this, E); 15078 15079 // Pseudo-objects. 15080 case BuiltinType::PseudoObject: 15081 return checkPseudoObjectRValue(E); 15082 15083 case BuiltinType::BuiltinFn: { 15084 // Accept __noop without parens by implicitly converting it to a call expr. 15085 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15086 if (DRE) { 15087 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15088 if (FD->getBuiltinID() == Builtin::BI__noop) { 15089 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15090 CK_BuiltinFnToFnPtr).get(); 15091 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15092 VK_RValue, SourceLocation()); 15093 } 15094 } 15095 15096 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15097 return ExprError(); 15098 } 15099 15100 // Expressions of unknown type. 15101 case BuiltinType::OMPArraySection: 15102 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15103 return ExprError(); 15104 15105 // Everything else should be impossible. 15106 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15107 case BuiltinType::Id: 15108 #include "clang/Basic/OpenCLImageTypes.def" 15109 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15110 #define PLACEHOLDER_TYPE(Id, SingletonId) 15111 #include "clang/AST/BuiltinTypes.def" 15112 break; 15113 } 15114 15115 llvm_unreachable("invalid placeholder type!"); 15116 } 15117 15118 bool Sema::CheckCaseExpression(Expr *E) { 15119 if (E->isTypeDependent()) 15120 return true; 15121 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15122 return E->getType()->isIntegralOrEnumerationType(); 15123 return false; 15124 } 15125 15126 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15127 ExprResult 15128 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15129 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15130 "Unknown Objective-C Boolean value!"); 15131 QualType BoolT = Context.ObjCBuiltinBoolTy; 15132 if (!Context.getBOOLDecl()) { 15133 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15134 Sema::LookupOrdinaryName); 15135 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15136 NamedDecl *ND = Result.getFoundDecl(); 15137 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15138 Context.setBOOLDecl(TD); 15139 } 15140 } 15141 if (Context.getBOOLDecl()) 15142 BoolT = Context.getBOOLType(); 15143 return new (Context) 15144 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15145 } 15146 15147 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15148 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15149 SourceLocation RParen) { 15150 15151 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15152 15153 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15154 [&](const AvailabilitySpec &Spec) { 15155 return Spec.getPlatform() == Platform; 15156 }); 15157 15158 VersionTuple Version; 15159 if (Spec != AvailSpecs.end()) 15160 Version = Spec->getVersion(); 15161 else 15162 // This is the '*' case in @available. We should diagnose this; the 15163 // programmer should explicitly account for this case if they target this 15164 // platform. 15165 Diag(AtLoc, diag::warn_available_using_star_case) << RParen << Platform; 15166 15167 return new (Context) 15168 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15169 } 15170