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 AvailabilityResult 107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) { 108 AvailabilityResult Result = D->getAvailability(Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(Message); 136 } 137 138 if (Result == AR_NotYetIntroduced) { 139 // Don't do this for enums, they can't be redeclared. 140 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 141 return AR_Available; 142 143 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 144 // Objective-C method declarations in categories are not modelled as 145 // redeclarations, so manually look for a redeclaration in a category 146 // if necessary. 147 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 148 Warn = false; 149 // In general, D will point to the most recent redeclaration. However, 150 // for `@class A;` decls, this isn't true -- manually go through the 151 // redecl chain in that case. 152 if (Warn && isa<ObjCInterfaceDecl>(D)) 153 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 154 Redecl = Redecl->getPreviousDecl()) 155 if (!Redecl->hasAttr<AvailabilityAttr>() || 156 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 157 Warn = false; 158 159 return Warn ? AR_NotYetIntroduced : AR_Available; 160 } 161 162 return Result; 163 } 164 165 static void 166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 167 const ObjCInterfaceDecl *UnknownObjCClass, 168 bool ObjCPropertyAccess) { 169 std::string Message; 170 // See if this declaration is unavailable, deprecated, or partial. 171 if (AvailabilityResult Result = 172 S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) { 173 174 if (Result == AR_NotYetIntroduced) { 175 if (S.getCurFunctionOrMethodDecl()) { 176 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 177 return; 178 } else if (S.getCurBlock() || S.getCurLambda()) { 179 S.getCurFunction()->HasPotentialAvailabilityViolations = true; 180 return; 181 } 182 } 183 184 const ObjCPropertyDecl *ObjCPDecl = nullptr; 185 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 186 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 187 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 188 if (PDeclResult == Result) 189 ObjCPDecl = PD; 190 } 191 } 192 193 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 194 ObjCPDecl, ObjCPropertyAccess); 195 } 196 } 197 198 /// \brief Emit a note explaining that this function is deleted. 199 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 200 assert(Decl->isDeleted()); 201 202 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 203 204 if (Method && Method->isDeleted() && Method->isDefaulted()) { 205 // If the method was explicitly defaulted, point at that declaration. 206 if (!Method->isImplicit()) 207 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 208 209 // Try to diagnose why this special member function was implicitly 210 // deleted. This might fail, if that reason no longer applies. 211 CXXSpecialMember CSM = getSpecialMember(Method); 212 if (CSM != CXXInvalid) 213 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 214 215 return; 216 } 217 218 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 219 if (Ctor && Ctor->isInheritingConstructor()) 220 return NoteDeletedInheritingConstructor(Ctor); 221 222 Diag(Decl->getLocation(), diag::note_availability_specified_here) 223 << Decl << true; 224 } 225 226 /// \brief Determine whether a FunctionDecl was ever declared with an 227 /// explicit storage class. 228 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 229 for (auto I : D->redecls()) { 230 if (I->getStorageClass() != SC_None) 231 return true; 232 } 233 return false; 234 } 235 236 /// \brief Check whether we're in an extern inline function and referring to a 237 /// variable or function with internal linkage (C11 6.7.4p3). 238 /// 239 /// This is only a warning because we used to silently accept this code, but 240 /// in many cases it will not behave correctly. This is not enabled in C++ mode 241 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 242 /// and so while there may still be user mistakes, most of the time we can't 243 /// prove that there are errors. 244 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 245 const NamedDecl *D, 246 SourceLocation Loc) { 247 // This is disabled under C++; there are too many ways for this to fire in 248 // contexts where the warning is a false positive, or where it is technically 249 // correct but benign. 250 if (S.getLangOpts().CPlusPlus) 251 return; 252 253 // Check if this is an inlined function or method. 254 FunctionDecl *Current = S.getCurFunctionDecl(); 255 if (!Current) 256 return; 257 if (!Current->isInlined()) 258 return; 259 if (!Current->isExternallyVisible()) 260 return; 261 262 // Check if the decl has internal linkage. 263 if (D->getFormalLinkage() != InternalLinkage) 264 return; 265 266 // Downgrade from ExtWarn to Extension if 267 // (1) the supposedly external inline function is in the main file, 268 // and probably won't be included anywhere else. 269 // (2) the thing we're referencing is a pure function. 270 // (3) the thing we're referencing is another inline function. 271 // This last can give us false negatives, but it's better than warning on 272 // wrappers for simple C library functions. 273 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 274 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 275 if (!DowngradeWarning && UsedFn) 276 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 277 278 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 279 : diag::ext_internal_in_extern_inline) 280 << /*IsVar=*/!UsedFn << D; 281 282 S.MaybeSuggestAddingStaticToDecl(Current); 283 284 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 285 << D; 286 } 287 288 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 289 const FunctionDecl *First = Cur->getFirstDecl(); 290 291 // Suggest "static" on the function, if possible. 292 if (!hasAnyExplicitStorageClass(First)) { 293 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 294 Diag(DeclBegin, diag::note_convert_inline_to_static) 295 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 296 } 297 } 298 299 /// \brief Determine whether the use of this declaration is valid, and 300 /// emit any corresponding diagnostics. 301 /// 302 /// This routine diagnoses various problems with referencing 303 /// declarations that can occur when using a declaration. For example, 304 /// it might warn if a deprecated or unavailable declaration is being 305 /// used, or produce an error (and return true) if a C++0x deleted 306 /// function is being used. 307 /// 308 /// \returns true if there was an error (this declaration cannot be 309 /// referenced), false otherwise. 310 /// 311 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 312 const ObjCInterfaceDecl *UnknownObjCClass, 313 bool ObjCPropertyAccess) { 314 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 315 // If there were any diagnostics suppressed by template argument deduction, 316 // emit them now. 317 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 318 if (Pos != SuppressedDiagnostics.end()) { 319 for (const PartialDiagnosticAt &Suppressed : Pos->second) 320 Diag(Suppressed.first, Suppressed.second); 321 322 // Clear out the list of suppressed diagnostics, so that we don't emit 323 // them again for this specialization. However, we don't obsolete this 324 // entry from the table, because we want to avoid ever emitting these 325 // diagnostics again. 326 Pos->second.clear(); 327 } 328 329 // C++ [basic.start.main]p3: 330 // The function 'main' shall not be used within a program. 331 if (cast<FunctionDecl>(D)->isMain()) 332 Diag(Loc, diag::ext_main_used); 333 } 334 335 // See if this is an auto-typed variable whose initializer we are parsing. 336 if (ParsingInitForAutoVars.count(D)) { 337 if (isa<BindingDecl>(D)) { 338 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 339 << D->getDeclName(); 340 } else { 341 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 342 << D->getDeclName() << cast<VarDecl>(D)->getType(); 343 } 344 return true; 345 } 346 347 // See if this is a deleted function. 348 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 349 if (FD->isDeleted()) { 350 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 351 if (Ctor && Ctor->isInheritingConstructor()) 352 Diag(Loc, diag::err_deleted_inherited_ctor_use) 353 << Ctor->getParent() 354 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 355 else 356 Diag(Loc, diag::err_deleted_function_use); 357 NoteDeletedFunction(FD); 358 return true; 359 } 360 361 // If the function has a deduced return type, and we can't deduce it, 362 // then we can't use it either. 363 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 364 DeduceReturnType(FD, Loc)) 365 return true; 366 367 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 368 return true; 369 370 if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc)) 371 return true; 372 } 373 374 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 375 // Only the variables omp_in and omp_out are allowed in the combiner. 376 // Only the variables omp_priv and omp_orig are allowed in the 377 // initializer-clause. 378 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 379 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 380 isa<VarDecl>(D)) { 381 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 382 << getCurFunction()->HasOMPDeclareReductionCombiner; 383 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 384 return true; 385 } 386 387 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 388 ObjCPropertyAccess); 389 390 DiagnoseUnusedOfDecl(*this, D, Loc); 391 392 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 393 394 return false; 395 } 396 397 /// \brief Retrieve the message suffix that should be added to a 398 /// diagnostic complaining about the given function being deleted or 399 /// unavailable. 400 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 401 std::string Message; 402 if (FD->getAvailability(&Message)) 403 return ": " + Message; 404 405 return std::string(); 406 } 407 408 /// DiagnoseSentinelCalls - This routine checks whether a call or 409 /// message-send is to a declaration with the sentinel attribute, and 410 /// if so, it checks that the requirements of the sentinel are 411 /// satisfied. 412 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 413 ArrayRef<Expr *> Args) { 414 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 415 if (!attr) 416 return; 417 418 // The number of formal parameters of the declaration. 419 unsigned numFormalParams; 420 421 // The kind of declaration. This is also an index into a %select in 422 // the diagnostic. 423 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 424 425 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 426 numFormalParams = MD->param_size(); 427 calleeType = CT_Method; 428 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 429 numFormalParams = FD->param_size(); 430 calleeType = CT_Function; 431 } else if (isa<VarDecl>(D)) { 432 QualType type = cast<ValueDecl>(D)->getType(); 433 const FunctionType *fn = nullptr; 434 if (const PointerType *ptr = type->getAs<PointerType>()) { 435 fn = ptr->getPointeeType()->getAs<FunctionType>(); 436 if (!fn) return; 437 calleeType = CT_Function; 438 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 439 fn = ptr->getPointeeType()->castAs<FunctionType>(); 440 calleeType = CT_Block; 441 } else { 442 return; 443 } 444 445 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 446 numFormalParams = proto->getNumParams(); 447 } else { 448 numFormalParams = 0; 449 } 450 } else { 451 return; 452 } 453 454 // "nullPos" is the number of formal parameters at the end which 455 // effectively count as part of the variadic arguments. This is 456 // useful if you would prefer to not have *any* formal parameters, 457 // but the language forces you to have at least one. 458 unsigned nullPos = attr->getNullPos(); 459 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 460 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 461 462 // The number of arguments which should follow the sentinel. 463 unsigned numArgsAfterSentinel = attr->getSentinel(); 464 465 // If there aren't enough arguments for all the formal parameters, 466 // the sentinel, and the args after the sentinel, complain. 467 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 468 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 469 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 470 return; 471 } 472 473 // Otherwise, find the sentinel expression. 474 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 475 if (!sentinelExpr) return; 476 if (sentinelExpr->isValueDependent()) return; 477 if (Context.isSentinelNullExpr(sentinelExpr)) return; 478 479 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 480 // or 'NULL' if those are actually defined in the context. Only use 481 // 'nil' for ObjC methods, where it's much more likely that the 482 // variadic arguments form a list of object pointers. 483 SourceLocation MissingNilLoc 484 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 485 std::string NullValue; 486 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 487 NullValue = "nil"; 488 else if (getLangOpts().CPlusPlus11) 489 NullValue = "nullptr"; 490 else if (PP.isMacroDefined("NULL")) 491 NullValue = "NULL"; 492 else 493 NullValue = "(void*) 0"; 494 495 if (MissingNilLoc.isInvalid()) 496 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 497 else 498 Diag(MissingNilLoc, diag::warn_missing_sentinel) 499 << int(calleeType) 500 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 501 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 502 } 503 504 SourceRange Sema::getExprRange(Expr *E) const { 505 return E ? E->getSourceRange() : SourceRange(); 506 } 507 508 //===----------------------------------------------------------------------===// 509 // Standard Promotions and Conversions 510 //===----------------------------------------------------------------------===// 511 512 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 513 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 514 // Handle any placeholder expressions which made it here. 515 if (E->getType()->isPlaceholderType()) { 516 ExprResult result = CheckPlaceholderExpr(E); 517 if (result.isInvalid()) return ExprError(); 518 E = result.get(); 519 } 520 521 QualType Ty = E->getType(); 522 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 523 524 if (Ty->isFunctionType()) { 525 // If we are here, we are not calling a function but taking 526 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 527 if (getLangOpts().OpenCL) { 528 if (Diagnose) 529 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 530 return ExprError(); 531 } 532 533 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 534 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 535 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 536 return ExprError(); 537 538 E = ImpCastExprToType(E, Context.getPointerType(Ty), 539 CK_FunctionToPointerDecay).get(); 540 } else if (Ty->isArrayType()) { 541 // In C90 mode, arrays only promote to pointers if the array expression is 542 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 543 // type 'array of type' is converted to an expression that has type 'pointer 544 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 545 // that has type 'array of type' ...". The relevant change is "an lvalue" 546 // (C90) to "an expression" (C99). 547 // 548 // C++ 4.2p1: 549 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 550 // T" can be converted to an rvalue of type "pointer to T". 551 // 552 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 553 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 554 CK_ArrayToPointerDecay).get(); 555 } 556 return E; 557 } 558 559 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 560 // Check to see if we are dereferencing a null pointer. If so, 561 // and if not volatile-qualified, this is undefined behavior that the 562 // optimizer will delete, so warn about it. People sometimes try to use this 563 // to get a deterministic trap and are surprised by clang's behavior. This 564 // only handles the pattern "*null", which is a very syntactic check. 565 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 566 if (UO->getOpcode() == UO_Deref && 567 UO->getSubExpr()->IgnoreParenCasts()-> 568 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 569 !UO->getType().isVolatileQualified()) { 570 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 571 S.PDiag(diag::warn_indirection_through_null) 572 << UO->getSubExpr()->getSourceRange()); 573 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 574 S.PDiag(diag::note_indirection_through_null)); 575 } 576 } 577 578 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 579 SourceLocation AssignLoc, 580 const Expr* RHS) { 581 const ObjCIvarDecl *IV = OIRE->getDecl(); 582 if (!IV) 583 return; 584 585 DeclarationName MemberName = IV->getDeclName(); 586 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 587 if (!Member || !Member->isStr("isa")) 588 return; 589 590 const Expr *Base = OIRE->getBase(); 591 QualType BaseType = Base->getType(); 592 if (OIRE->isArrow()) 593 BaseType = BaseType->getPointeeType(); 594 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 595 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 596 ObjCInterfaceDecl *ClassDeclared = nullptr; 597 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 598 if (!ClassDeclared->getSuperClass() 599 && (*ClassDeclared->ivar_begin()) == IV) { 600 if (RHS) { 601 NamedDecl *ObjectSetClass = 602 S.LookupSingleName(S.TUScope, 603 &S.Context.Idents.get("object_setClass"), 604 SourceLocation(), S.LookupOrdinaryName); 605 if (ObjectSetClass) { 606 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 607 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 608 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 609 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 610 AssignLoc), ",") << 611 FixItHint::CreateInsertion(RHSLocEnd, ")"); 612 } 613 else 614 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 615 } else { 616 NamedDecl *ObjectGetClass = 617 S.LookupSingleName(S.TUScope, 618 &S.Context.Idents.get("object_getClass"), 619 SourceLocation(), S.LookupOrdinaryName); 620 if (ObjectGetClass) 621 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 622 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 623 FixItHint::CreateReplacement( 624 SourceRange(OIRE->getOpLoc(), 625 OIRE->getLocEnd()), ")"); 626 else 627 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 628 } 629 S.Diag(IV->getLocation(), diag::note_ivar_decl); 630 } 631 } 632 } 633 634 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 635 // Handle any placeholder expressions which made it here. 636 if (E->getType()->isPlaceholderType()) { 637 ExprResult result = CheckPlaceholderExpr(E); 638 if (result.isInvalid()) return ExprError(); 639 E = result.get(); 640 } 641 642 // C++ [conv.lval]p1: 643 // A glvalue of a non-function, non-array type T can be 644 // converted to a prvalue. 645 if (!E->isGLValue()) return E; 646 647 QualType T = E->getType(); 648 assert(!T.isNull() && "r-value conversion on typeless expression?"); 649 650 // We don't want to throw lvalue-to-rvalue casts on top of 651 // expressions of certain types in C++. 652 if (getLangOpts().CPlusPlus && 653 (E->getType() == Context.OverloadTy || 654 T->isDependentType() || 655 T->isRecordType())) 656 return E; 657 658 // The C standard is actually really unclear on this point, and 659 // DR106 tells us what the result should be but not why. It's 660 // generally best to say that void types just doesn't undergo 661 // lvalue-to-rvalue at all. Note that expressions of unqualified 662 // 'void' type are never l-values, but qualified void can be. 663 if (T->isVoidType()) 664 return E; 665 666 // OpenCL usually rejects direct accesses to values of 'half' type. 667 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 668 T->isHalfType()) { 669 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 670 << 0 << T; 671 return ExprError(); 672 } 673 674 CheckForNullPointerDereference(*this, E); 675 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 676 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 677 &Context.Idents.get("object_getClass"), 678 SourceLocation(), LookupOrdinaryName); 679 if (ObjectGetClass) 680 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 681 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 682 FixItHint::CreateReplacement( 683 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 684 else 685 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 686 } 687 else if (const ObjCIvarRefExpr *OIRE = 688 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 689 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 690 691 // C++ [conv.lval]p1: 692 // [...] If T is a non-class type, the type of the prvalue is the 693 // cv-unqualified version of T. Otherwise, the type of the 694 // rvalue is T. 695 // 696 // C99 6.3.2.1p2: 697 // If the lvalue has qualified type, the value has the unqualified 698 // version of the type of the lvalue; otherwise, the value has the 699 // type of the lvalue. 700 if (T.hasQualifiers()) 701 T = T.getUnqualifiedType(); 702 703 // Under the MS ABI, lock down the inheritance model now. 704 if (T->isMemberPointerType() && 705 Context.getTargetInfo().getCXXABI().isMicrosoft()) 706 (void)isCompleteType(E->getExprLoc(), T); 707 708 UpdateMarkingForLValueToRValue(E); 709 710 // Loading a __weak object implicitly retains the value, so we need a cleanup to 711 // balance that. 712 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 713 Cleanup.setExprNeedsCleanups(true); 714 715 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 716 nullptr, VK_RValue); 717 718 // C11 6.3.2.1p2: 719 // ... if the lvalue has atomic type, the value has the non-atomic version 720 // of the type of the lvalue ... 721 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 722 T = Atomic->getValueType().getUnqualifiedType(); 723 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 724 nullptr, VK_RValue); 725 } 726 727 return Res; 728 } 729 730 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 731 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 732 if (Res.isInvalid()) 733 return ExprError(); 734 Res = DefaultLvalueConversion(Res.get()); 735 if (Res.isInvalid()) 736 return ExprError(); 737 return Res; 738 } 739 740 /// CallExprUnaryConversions - a special case of an unary conversion 741 /// performed on a function designator of a call expression. 742 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 743 QualType Ty = E->getType(); 744 ExprResult Res = E; 745 // Only do implicit cast for a function type, but not for a pointer 746 // to function type. 747 if (Ty->isFunctionType()) { 748 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 749 CK_FunctionToPointerDecay).get(); 750 if (Res.isInvalid()) 751 return ExprError(); 752 } 753 Res = DefaultLvalueConversion(Res.get()); 754 if (Res.isInvalid()) 755 return ExprError(); 756 return Res.get(); 757 } 758 759 /// UsualUnaryConversions - Performs various conversions that are common to most 760 /// operators (C99 6.3). The conversions of array and function types are 761 /// sometimes suppressed. For example, the array->pointer conversion doesn't 762 /// apply if the array is an argument to the sizeof or address (&) operators. 763 /// In these instances, this routine should *not* be called. 764 ExprResult Sema::UsualUnaryConversions(Expr *E) { 765 // First, convert to an r-value. 766 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 767 if (Res.isInvalid()) 768 return ExprError(); 769 E = Res.get(); 770 771 QualType Ty = E->getType(); 772 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 773 774 // Half FP have to be promoted to float unless it is natively supported 775 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 776 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 777 778 // Try to perform integral promotions if the object has a theoretically 779 // promotable type. 780 if (Ty->isIntegralOrUnscopedEnumerationType()) { 781 // C99 6.3.1.1p2: 782 // 783 // The following may be used in an expression wherever an int or 784 // unsigned int may be used: 785 // - an object or expression with an integer type whose integer 786 // conversion rank is less than or equal to the rank of int 787 // and unsigned int. 788 // - A bit-field of type _Bool, int, signed int, or unsigned int. 789 // 790 // If an int can represent all values of the original type, the 791 // value is converted to an int; otherwise, it is converted to an 792 // unsigned int. These are called the integer promotions. All 793 // other types are unchanged by the integer promotions. 794 795 QualType PTy = Context.isPromotableBitField(E); 796 if (!PTy.isNull()) { 797 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 798 return E; 799 } 800 if (Ty->isPromotableIntegerType()) { 801 QualType PT = Context.getPromotedIntegerType(Ty); 802 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 803 return E; 804 } 805 } 806 return E; 807 } 808 809 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 810 /// do not have a prototype. Arguments that have type float or __fp16 811 /// are promoted to double. All other argument types are converted by 812 /// UsualUnaryConversions(). 813 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 814 QualType Ty = E->getType(); 815 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 816 817 ExprResult Res = UsualUnaryConversions(E); 818 if (Res.isInvalid()) 819 return ExprError(); 820 E = Res.get(); 821 822 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 823 // double. 824 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 825 if (BTy && (BTy->getKind() == BuiltinType::Half || 826 BTy->getKind() == BuiltinType::Float)) { 827 if (getLangOpts().OpenCL && 828 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 829 if (BTy->getKind() == BuiltinType::Half) { 830 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 831 } 832 } else { 833 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 834 } 835 } 836 837 // C++ performs lvalue-to-rvalue conversion as a default argument 838 // promotion, even on class types, but note: 839 // C++11 [conv.lval]p2: 840 // When an lvalue-to-rvalue conversion occurs in an unevaluated 841 // operand or a subexpression thereof the value contained in the 842 // referenced object is not accessed. Otherwise, if the glvalue 843 // has a class type, the conversion copy-initializes a temporary 844 // of type T from the glvalue and the result of the conversion 845 // is a prvalue for the temporary. 846 // FIXME: add some way to gate this entire thing for correctness in 847 // potentially potentially evaluated contexts. 848 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 849 ExprResult Temp = PerformCopyInitialization( 850 InitializedEntity::InitializeTemporary(E->getType()), 851 E->getExprLoc(), E); 852 if (Temp.isInvalid()) 853 return ExprError(); 854 E = Temp.get(); 855 } 856 857 return E; 858 } 859 860 /// Determine the degree of POD-ness for an expression. 861 /// Incomplete types are considered POD, since this check can be performed 862 /// when we're in an unevaluated context. 863 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 864 if (Ty->isIncompleteType()) { 865 // C++11 [expr.call]p7: 866 // After these conversions, if the argument does not have arithmetic, 867 // enumeration, pointer, pointer to member, or class type, the program 868 // is ill-formed. 869 // 870 // Since we've already performed array-to-pointer and function-to-pointer 871 // decay, the only such type in C++ is cv void. This also handles 872 // initializer lists as variadic arguments. 873 if (Ty->isVoidType()) 874 return VAK_Invalid; 875 876 if (Ty->isObjCObjectType()) 877 return VAK_Invalid; 878 return VAK_Valid; 879 } 880 881 if (Ty.isCXX98PODType(Context)) 882 return VAK_Valid; 883 884 // C++11 [expr.call]p7: 885 // Passing a potentially-evaluated argument of class type (Clause 9) 886 // having a non-trivial copy constructor, a non-trivial move constructor, 887 // or a non-trivial destructor, with no corresponding parameter, 888 // is conditionally-supported with implementation-defined semantics. 889 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 890 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 891 if (!Record->hasNonTrivialCopyConstructor() && 892 !Record->hasNonTrivialMoveConstructor() && 893 !Record->hasNonTrivialDestructor()) 894 return VAK_ValidInCXX11; 895 896 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 897 return VAK_Valid; 898 899 if (Ty->isObjCObjectType()) 900 return VAK_Invalid; 901 902 if (getLangOpts().MSVCCompat) 903 return VAK_MSVCUndefined; 904 905 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 906 // permitted to reject them. We should consider doing so. 907 return VAK_Undefined; 908 } 909 910 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 911 // Don't allow one to pass an Objective-C interface to a vararg. 912 const QualType &Ty = E->getType(); 913 VarArgKind VAK = isValidVarArgType(Ty); 914 915 // Complain about passing non-POD types through varargs. 916 switch (VAK) { 917 case VAK_ValidInCXX11: 918 DiagRuntimeBehavior( 919 E->getLocStart(), nullptr, 920 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 921 << Ty << CT); 922 // Fall through. 923 case VAK_Valid: 924 if (Ty->isRecordType()) { 925 // This is unlikely to be what the user intended. If the class has a 926 // 'c_str' member function, the user probably meant to call that. 927 DiagRuntimeBehavior(E->getLocStart(), nullptr, 928 PDiag(diag::warn_pass_class_arg_to_vararg) 929 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 930 } 931 break; 932 933 case VAK_Undefined: 934 case VAK_MSVCUndefined: 935 DiagRuntimeBehavior( 936 E->getLocStart(), nullptr, 937 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 938 << getLangOpts().CPlusPlus11 << Ty << CT); 939 break; 940 941 case VAK_Invalid: 942 if (Ty->isObjCObjectType()) 943 DiagRuntimeBehavior( 944 E->getLocStart(), nullptr, 945 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 946 << Ty << CT); 947 else 948 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 949 << isa<InitListExpr>(E) << Ty << CT; 950 break; 951 } 952 } 953 954 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 955 /// will create a trap if the resulting type is not a POD type. 956 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 957 FunctionDecl *FDecl) { 958 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 959 // Strip the unbridged-cast placeholder expression off, if applicable. 960 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 961 (CT == VariadicMethod || 962 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 963 E = stripARCUnbridgedCast(E); 964 965 // Otherwise, do normal placeholder checking. 966 } else { 967 ExprResult ExprRes = CheckPlaceholderExpr(E); 968 if (ExprRes.isInvalid()) 969 return ExprError(); 970 E = ExprRes.get(); 971 } 972 } 973 974 ExprResult ExprRes = DefaultArgumentPromotion(E); 975 if (ExprRes.isInvalid()) 976 return ExprError(); 977 E = ExprRes.get(); 978 979 // Diagnostics regarding non-POD argument types are 980 // emitted along with format string checking in Sema::CheckFunctionCall(). 981 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 982 // Turn this into a trap. 983 CXXScopeSpec SS; 984 SourceLocation TemplateKWLoc; 985 UnqualifiedId Name; 986 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 987 E->getLocStart()); 988 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 989 Name, true, false); 990 if (TrapFn.isInvalid()) 991 return ExprError(); 992 993 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 994 E->getLocStart(), None, 995 E->getLocEnd()); 996 if (Call.isInvalid()) 997 return ExprError(); 998 999 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 1000 Call.get(), E); 1001 if (Comma.isInvalid()) 1002 return ExprError(); 1003 return Comma.get(); 1004 } 1005 1006 if (!getLangOpts().CPlusPlus && 1007 RequireCompleteType(E->getExprLoc(), E->getType(), 1008 diag::err_call_incomplete_argument)) 1009 return ExprError(); 1010 1011 return E; 1012 } 1013 1014 /// \brief Converts an integer to complex float type. Helper function of 1015 /// UsualArithmeticConversions() 1016 /// 1017 /// \return false if the integer expression is an integer type and is 1018 /// successfully converted to the complex type. 1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1020 ExprResult &ComplexExpr, 1021 QualType IntTy, 1022 QualType ComplexTy, 1023 bool SkipCast) { 1024 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1025 if (SkipCast) return false; 1026 if (IntTy->isIntegerType()) { 1027 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1029 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1030 CK_FloatingRealToComplex); 1031 } else { 1032 assert(IntTy->isComplexIntegerType()); 1033 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1034 CK_IntegralComplexToFloatingComplex); 1035 } 1036 return false; 1037 } 1038 1039 /// \brief Handle arithmetic conversion with complex types. Helper function of 1040 /// UsualArithmeticConversions() 1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1042 ExprResult &RHS, QualType LHSType, 1043 QualType RHSType, 1044 bool IsCompAssign) { 1045 // if we have an integer operand, the result is the complex type. 1046 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1047 /*skipCast*/false)) 1048 return LHSType; 1049 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1050 /*skipCast*/IsCompAssign)) 1051 return RHSType; 1052 1053 // This handles complex/complex, complex/float, or float/complex. 1054 // When both operands are complex, the shorter operand is converted to the 1055 // type of the longer, and that is the type of the result. This corresponds 1056 // to what is done when combining two real floating-point operands. 1057 // The fun begins when size promotion occur across type domains. 1058 // From H&S 6.3.4: When one operand is complex and the other is a real 1059 // floating-point type, the less precise type is converted, within it's 1060 // real or complex domain, to the precision of the other type. For example, 1061 // when combining a "long double" with a "double _Complex", the 1062 // "double _Complex" is promoted to "long double _Complex". 1063 1064 // Compute the rank of the two types, regardless of whether they are complex. 1065 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1066 1067 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1068 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1069 QualType LHSElementType = 1070 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1071 QualType RHSElementType = 1072 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1073 1074 QualType ResultType = S.Context.getComplexType(LHSElementType); 1075 if (Order < 0) { 1076 // Promote the precision of the LHS if not an assignment. 1077 ResultType = S.Context.getComplexType(RHSElementType); 1078 if (!IsCompAssign) { 1079 if (LHSComplexType) 1080 LHS = 1081 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1082 else 1083 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1084 } 1085 } else if (Order > 0) { 1086 // Promote the precision of the RHS. 1087 if (RHSComplexType) 1088 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1089 else 1090 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1091 } 1092 return ResultType; 1093 } 1094 1095 /// \brief Hande arithmetic conversion from integer to float. Helper function 1096 /// of UsualArithmeticConversions() 1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1098 ExprResult &IntExpr, 1099 QualType FloatTy, QualType IntTy, 1100 bool ConvertFloat, bool ConvertInt) { 1101 if (IntTy->isIntegerType()) { 1102 if (ConvertInt) 1103 // Convert intExpr to the lhs floating point type. 1104 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1105 CK_IntegralToFloating); 1106 return FloatTy; 1107 } 1108 1109 // Convert both sides to the appropriate complex float. 1110 assert(IntTy->isComplexIntegerType()); 1111 QualType result = S.Context.getComplexType(FloatTy); 1112 1113 // _Complex int -> _Complex float 1114 if (ConvertInt) 1115 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1116 CK_IntegralComplexToFloatingComplex); 1117 1118 // float -> _Complex float 1119 if (ConvertFloat) 1120 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1121 CK_FloatingRealToComplex); 1122 1123 return result; 1124 } 1125 1126 /// \brief Handle arithmethic conversion with floating point types. Helper 1127 /// function of UsualArithmeticConversions() 1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1129 ExprResult &RHS, QualType LHSType, 1130 QualType RHSType, bool IsCompAssign) { 1131 bool LHSFloat = LHSType->isRealFloatingType(); 1132 bool RHSFloat = RHSType->isRealFloatingType(); 1133 1134 // If we have two real floating types, convert the smaller operand 1135 // to the bigger result. 1136 if (LHSFloat && RHSFloat) { 1137 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1138 if (order > 0) { 1139 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1140 return LHSType; 1141 } 1142 1143 assert(order < 0 && "illegal float comparison"); 1144 if (!IsCompAssign) 1145 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1146 return RHSType; 1147 } 1148 1149 if (LHSFloat) { 1150 // Half FP has to be promoted to float unless it is natively supported 1151 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1152 LHSType = S.Context.FloatTy; 1153 1154 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1155 /*convertFloat=*/!IsCompAssign, 1156 /*convertInt=*/ true); 1157 } 1158 assert(RHSFloat); 1159 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1160 /*convertInt=*/ true, 1161 /*convertFloat=*/!IsCompAssign); 1162 } 1163 1164 /// \brief Diagnose attempts to convert between __float128 and long double if 1165 /// there is no support for such conversion. Helper function of 1166 /// UsualArithmeticConversions(). 1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1168 QualType RHSType) { 1169 /* No issue converting if at least one of the types is not a floating point 1170 type or the two types have the same rank. 1171 */ 1172 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1173 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1174 return false; 1175 1176 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1177 "The remaining types must be floating point types."); 1178 1179 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1180 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1181 1182 QualType LHSElemType = LHSComplex ? 1183 LHSComplex->getElementType() : LHSType; 1184 QualType RHSElemType = RHSComplex ? 1185 RHSComplex->getElementType() : RHSType; 1186 1187 // No issue if the two types have the same representation 1188 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1189 &S.Context.getFloatTypeSemantics(RHSElemType)) 1190 return false; 1191 1192 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1193 RHSElemType == S.Context.LongDoubleTy); 1194 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1195 RHSElemType == S.Context.Float128Ty); 1196 1197 /* We've handled the situation where __float128 and long double have the same 1198 representation. The only other allowable conversion is if long double is 1199 really just double. 1200 */ 1201 return Float128AndLongDouble && 1202 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1203 &llvm::APFloat::IEEEdouble()); 1204 } 1205 1206 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1207 1208 namespace { 1209 /// These helper callbacks are placed in an anonymous namespace to 1210 /// permit their use as function template parameters. 1211 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1212 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1213 } 1214 1215 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1216 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1217 CK_IntegralComplexCast); 1218 } 1219 } 1220 1221 /// \brief Handle integer arithmetic conversions. Helper function of 1222 /// UsualArithmeticConversions() 1223 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1224 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1225 ExprResult &RHS, QualType LHSType, 1226 QualType RHSType, bool IsCompAssign) { 1227 // The rules for this case are in C99 6.3.1.8 1228 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1229 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1230 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1231 if (LHSSigned == RHSSigned) { 1232 // Same signedness; use the higher-ranked type 1233 if (order >= 0) { 1234 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1235 return LHSType; 1236 } else if (!IsCompAssign) 1237 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1238 return RHSType; 1239 } else if (order != (LHSSigned ? 1 : -1)) { 1240 // The unsigned type has greater than or equal rank to the 1241 // signed type, so use the unsigned type 1242 if (RHSSigned) { 1243 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1244 return LHSType; 1245 } else if (!IsCompAssign) 1246 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1247 return RHSType; 1248 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1249 // The two types are different widths; if we are here, that 1250 // means the signed type is larger than the unsigned type, so 1251 // use the signed type. 1252 if (LHSSigned) { 1253 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1254 return LHSType; 1255 } else if (!IsCompAssign) 1256 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1257 return RHSType; 1258 } else { 1259 // The signed type is higher-ranked than the unsigned type, 1260 // but isn't actually any bigger (like unsigned int and long 1261 // on most 32-bit systems). Use the unsigned type corresponding 1262 // to the signed type. 1263 QualType result = 1264 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1265 RHS = (*doRHSCast)(S, RHS.get(), result); 1266 if (!IsCompAssign) 1267 LHS = (*doLHSCast)(S, LHS.get(), result); 1268 return result; 1269 } 1270 } 1271 1272 /// \brief Handle conversions with GCC complex int extension. Helper function 1273 /// of UsualArithmeticConversions() 1274 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1275 ExprResult &RHS, QualType LHSType, 1276 QualType RHSType, 1277 bool IsCompAssign) { 1278 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1279 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1280 1281 if (LHSComplexInt && RHSComplexInt) { 1282 QualType LHSEltType = LHSComplexInt->getElementType(); 1283 QualType RHSEltType = RHSComplexInt->getElementType(); 1284 QualType ScalarType = 1285 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1286 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1287 1288 return S.Context.getComplexType(ScalarType); 1289 } 1290 1291 if (LHSComplexInt) { 1292 QualType LHSEltType = LHSComplexInt->getElementType(); 1293 QualType ScalarType = 1294 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1295 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1296 QualType ComplexType = S.Context.getComplexType(ScalarType); 1297 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1298 CK_IntegralRealToComplex); 1299 1300 return ComplexType; 1301 } 1302 1303 assert(RHSComplexInt); 1304 1305 QualType RHSEltType = RHSComplexInt->getElementType(); 1306 QualType ScalarType = 1307 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1308 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1309 QualType ComplexType = S.Context.getComplexType(ScalarType); 1310 1311 if (!IsCompAssign) 1312 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1313 CK_IntegralRealToComplex); 1314 return ComplexType; 1315 } 1316 1317 /// UsualArithmeticConversions - Performs various conversions that are common to 1318 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1319 /// routine returns the first non-arithmetic type found. The client is 1320 /// responsible for emitting appropriate error diagnostics. 1321 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1322 bool IsCompAssign) { 1323 if (!IsCompAssign) { 1324 LHS = UsualUnaryConversions(LHS.get()); 1325 if (LHS.isInvalid()) 1326 return QualType(); 1327 } 1328 1329 RHS = UsualUnaryConversions(RHS.get()); 1330 if (RHS.isInvalid()) 1331 return QualType(); 1332 1333 // For conversion purposes, we ignore any qualifiers. 1334 // For example, "const float" and "float" are equivalent. 1335 QualType LHSType = 1336 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1337 QualType RHSType = 1338 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1339 1340 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1341 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1342 LHSType = AtomicLHS->getValueType(); 1343 1344 // If both types are identical, no conversion is needed. 1345 if (LHSType == RHSType) 1346 return LHSType; 1347 1348 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1349 // The caller can deal with this (e.g. pointer + int). 1350 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1351 return QualType(); 1352 1353 // Apply unary and bitfield promotions to the LHS's type. 1354 QualType LHSUnpromotedType = LHSType; 1355 if (LHSType->isPromotableIntegerType()) 1356 LHSType = Context.getPromotedIntegerType(LHSType); 1357 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1358 if (!LHSBitfieldPromoteTy.isNull()) 1359 LHSType = LHSBitfieldPromoteTy; 1360 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1361 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1362 1363 // If both types are identical, no conversion is needed. 1364 if (LHSType == RHSType) 1365 return LHSType; 1366 1367 // At this point, we have two different arithmetic types. 1368 1369 // Diagnose attempts to convert between __float128 and long double where 1370 // such conversions currently can't be handled. 1371 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1372 return QualType(); 1373 1374 // Handle complex types first (C99 6.3.1.8p1). 1375 if (LHSType->isComplexType() || RHSType->isComplexType()) 1376 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1377 IsCompAssign); 1378 1379 // Now handle "real" floating types (i.e. float, double, long double). 1380 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1381 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1382 IsCompAssign); 1383 1384 // Handle GCC complex int extension. 1385 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1386 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1387 IsCompAssign); 1388 1389 // Finally, we have two differing integer types. 1390 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1391 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1392 } 1393 1394 1395 //===----------------------------------------------------------------------===// 1396 // Semantic Analysis for various Expression Types 1397 //===----------------------------------------------------------------------===// 1398 1399 1400 ExprResult 1401 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1402 SourceLocation DefaultLoc, 1403 SourceLocation RParenLoc, 1404 Expr *ControllingExpr, 1405 ArrayRef<ParsedType> ArgTypes, 1406 ArrayRef<Expr *> ArgExprs) { 1407 unsigned NumAssocs = ArgTypes.size(); 1408 assert(NumAssocs == ArgExprs.size()); 1409 1410 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1411 for (unsigned i = 0; i < NumAssocs; ++i) { 1412 if (ArgTypes[i]) 1413 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1414 else 1415 Types[i] = nullptr; 1416 } 1417 1418 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1419 ControllingExpr, 1420 llvm::makeArrayRef(Types, NumAssocs), 1421 ArgExprs); 1422 delete [] Types; 1423 return ER; 1424 } 1425 1426 ExprResult 1427 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1428 SourceLocation DefaultLoc, 1429 SourceLocation RParenLoc, 1430 Expr *ControllingExpr, 1431 ArrayRef<TypeSourceInfo *> Types, 1432 ArrayRef<Expr *> Exprs) { 1433 unsigned NumAssocs = Types.size(); 1434 assert(NumAssocs == Exprs.size()); 1435 1436 // Decay and strip qualifiers for the controlling expression type, and handle 1437 // placeholder type replacement. See committee discussion from WG14 DR423. 1438 { 1439 EnterExpressionEvaluationContext Unevaluated( 1440 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1441 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1442 if (R.isInvalid()) 1443 return ExprError(); 1444 ControllingExpr = R.get(); 1445 } 1446 1447 // The controlling expression is an unevaluated operand, so side effects are 1448 // likely unintended. 1449 if (!inTemplateInstantiation() && 1450 ControllingExpr->HasSideEffects(Context, false)) 1451 Diag(ControllingExpr->getExprLoc(), 1452 diag::warn_side_effects_unevaluated_context); 1453 1454 bool TypeErrorFound = false, 1455 IsResultDependent = ControllingExpr->isTypeDependent(), 1456 ContainsUnexpandedParameterPack 1457 = ControllingExpr->containsUnexpandedParameterPack(); 1458 1459 for (unsigned i = 0; i < NumAssocs; ++i) { 1460 if (Exprs[i]->containsUnexpandedParameterPack()) 1461 ContainsUnexpandedParameterPack = true; 1462 1463 if (Types[i]) { 1464 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1465 ContainsUnexpandedParameterPack = true; 1466 1467 if (Types[i]->getType()->isDependentType()) { 1468 IsResultDependent = true; 1469 } else { 1470 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1471 // complete object type other than a variably modified type." 1472 unsigned D = 0; 1473 if (Types[i]->getType()->isIncompleteType()) 1474 D = diag::err_assoc_type_incomplete; 1475 else if (!Types[i]->getType()->isObjectType()) 1476 D = diag::err_assoc_type_nonobject; 1477 else if (Types[i]->getType()->isVariablyModifiedType()) 1478 D = diag::err_assoc_type_variably_modified; 1479 1480 if (D != 0) { 1481 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1482 << Types[i]->getTypeLoc().getSourceRange() 1483 << Types[i]->getType(); 1484 TypeErrorFound = true; 1485 } 1486 1487 // C11 6.5.1.1p2 "No two generic associations in the same generic 1488 // selection shall specify compatible types." 1489 for (unsigned j = i+1; j < NumAssocs; ++j) 1490 if (Types[j] && !Types[j]->getType()->isDependentType() && 1491 Context.typesAreCompatible(Types[i]->getType(), 1492 Types[j]->getType())) { 1493 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1494 diag::err_assoc_compatible_types) 1495 << Types[j]->getTypeLoc().getSourceRange() 1496 << Types[j]->getType() 1497 << Types[i]->getType(); 1498 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1499 diag::note_compat_assoc) 1500 << Types[i]->getTypeLoc().getSourceRange() 1501 << Types[i]->getType(); 1502 TypeErrorFound = true; 1503 } 1504 } 1505 } 1506 } 1507 if (TypeErrorFound) 1508 return ExprError(); 1509 1510 // If we determined that the generic selection is result-dependent, don't 1511 // try to compute the result expression. 1512 if (IsResultDependent) 1513 return new (Context) GenericSelectionExpr( 1514 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1515 ContainsUnexpandedParameterPack); 1516 1517 SmallVector<unsigned, 1> CompatIndices; 1518 unsigned DefaultIndex = -1U; 1519 for (unsigned i = 0; i < NumAssocs; ++i) { 1520 if (!Types[i]) 1521 DefaultIndex = i; 1522 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1523 Types[i]->getType())) 1524 CompatIndices.push_back(i); 1525 } 1526 1527 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1528 // type compatible with at most one of the types named in its generic 1529 // association list." 1530 if (CompatIndices.size() > 1) { 1531 // We strip parens here because the controlling expression is typically 1532 // parenthesized in macro definitions. 1533 ControllingExpr = ControllingExpr->IgnoreParens(); 1534 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1535 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1536 << (unsigned) CompatIndices.size(); 1537 for (unsigned I : CompatIndices) { 1538 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1539 diag::note_compat_assoc) 1540 << Types[I]->getTypeLoc().getSourceRange() 1541 << Types[I]->getType(); 1542 } 1543 return ExprError(); 1544 } 1545 1546 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1547 // its controlling expression shall have type compatible with exactly one of 1548 // the types named in its generic association list." 1549 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1550 // We strip parens here because the controlling expression is typically 1551 // parenthesized in macro definitions. 1552 ControllingExpr = ControllingExpr->IgnoreParens(); 1553 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1554 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1555 return ExprError(); 1556 } 1557 1558 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1559 // type name that is compatible with the type of the controlling expression, 1560 // then the result expression of the generic selection is the expression 1561 // in that generic association. Otherwise, the result expression of the 1562 // generic selection is the expression in the default generic association." 1563 unsigned ResultIndex = 1564 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1565 1566 return new (Context) GenericSelectionExpr( 1567 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1568 ContainsUnexpandedParameterPack, ResultIndex); 1569 } 1570 1571 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1572 /// location of the token and the offset of the ud-suffix within it. 1573 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1574 unsigned Offset) { 1575 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1576 S.getLangOpts()); 1577 } 1578 1579 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1580 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1581 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1582 IdentifierInfo *UDSuffix, 1583 SourceLocation UDSuffixLoc, 1584 ArrayRef<Expr*> Args, 1585 SourceLocation LitEndLoc) { 1586 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1587 1588 QualType ArgTy[2]; 1589 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1590 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1591 if (ArgTy[ArgIdx]->isArrayType()) 1592 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1593 } 1594 1595 DeclarationName OpName = 1596 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1597 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1598 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1599 1600 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1601 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1602 /*AllowRaw*/false, /*AllowTemplate*/false, 1603 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1604 return ExprError(); 1605 1606 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1607 } 1608 1609 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1610 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1611 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1612 /// multiple tokens. However, the common case is that StringToks points to one 1613 /// string. 1614 /// 1615 ExprResult 1616 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1617 assert(!StringToks.empty() && "Must have at least one string!"); 1618 1619 StringLiteralParser Literal(StringToks, PP); 1620 if (Literal.hadError) 1621 return ExprError(); 1622 1623 SmallVector<SourceLocation, 4> StringTokLocs; 1624 for (const Token &Tok : StringToks) 1625 StringTokLocs.push_back(Tok.getLocation()); 1626 1627 QualType CharTy = Context.CharTy; 1628 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1629 if (Literal.isWide()) { 1630 CharTy = Context.getWideCharType(); 1631 Kind = StringLiteral::Wide; 1632 } else if (Literal.isUTF8()) { 1633 Kind = StringLiteral::UTF8; 1634 } else if (Literal.isUTF16()) { 1635 CharTy = Context.Char16Ty; 1636 Kind = StringLiteral::UTF16; 1637 } else if (Literal.isUTF32()) { 1638 CharTy = Context.Char32Ty; 1639 Kind = StringLiteral::UTF32; 1640 } else if (Literal.isPascal()) { 1641 CharTy = Context.UnsignedCharTy; 1642 } 1643 1644 QualType CharTyConst = CharTy; 1645 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1646 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1647 CharTyConst.addConst(); 1648 1649 // Get an array type for the string, according to C99 6.4.5. This includes 1650 // the nul terminator character as well as the string length for pascal 1651 // strings. 1652 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1653 llvm::APInt(32, Literal.GetNumStringChars()+1), 1654 ArrayType::Normal, 0); 1655 1656 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1657 if (getLangOpts().OpenCL) { 1658 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1659 } 1660 1661 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1662 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1663 Kind, Literal.Pascal, StrTy, 1664 &StringTokLocs[0], 1665 StringTokLocs.size()); 1666 if (Literal.getUDSuffix().empty()) 1667 return Lit; 1668 1669 // We're building a user-defined literal. 1670 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1671 SourceLocation UDSuffixLoc = 1672 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1673 Literal.getUDSuffixOffset()); 1674 1675 // Make sure we're allowed user-defined literals here. 1676 if (!UDLScope) 1677 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1678 1679 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1680 // operator "" X (str, len) 1681 QualType SizeType = Context.getSizeType(); 1682 1683 DeclarationName OpName = 1684 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1685 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1686 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1687 1688 QualType ArgTy[] = { 1689 Context.getArrayDecayedType(StrTy), SizeType 1690 }; 1691 1692 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1693 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1694 /*AllowRaw*/false, /*AllowTemplate*/false, 1695 /*AllowStringTemplate*/true)) { 1696 1697 case LOLR_Cooked: { 1698 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1699 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1700 StringTokLocs[0]); 1701 Expr *Args[] = { Lit, LenArg }; 1702 1703 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1704 } 1705 1706 case LOLR_StringTemplate: { 1707 TemplateArgumentListInfo ExplicitArgs; 1708 1709 unsigned CharBits = Context.getIntWidth(CharTy); 1710 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1711 llvm::APSInt Value(CharBits, CharIsUnsigned); 1712 1713 TemplateArgument TypeArg(CharTy); 1714 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1715 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1716 1717 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1718 Value = Lit->getCodeUnit(I); 1719 TemplateArgument Arg(Context, Value, CharTy); 1720 TemplateArgumentLocInfo ArgInfo; 1721 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1722 } 1723 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1724 &ExplicitArgs); 1725 } 1726 case LOLR_Raw: 1727 case LOLR_Template: 1728 llvm_unreachable("unexpected literal operator lookup result"); 1729 case LOLR_Error: 1730 return ExprError(); 1731 } 1732 llvm_unreachable("unexpected literal operator lookup result"); 1733 } 1734 1735 ExprResult 1736 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1737 SourceLocation Loc, 1738 const CXXScopeSpec *SS) { 1739 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1740 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1741 } 1742 1743 /// BuildDeclRefExpr - Build an expression that references a 1744 /// declaration that does not require a closure capture. 1745 ExprResult 1746 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1747 const DeclarationNameInfo &NameInfo, 1748 const CXXScopeSpec *SS, NamedDecl *FoundD, 1749 const TemplateArgumentListInfo *TemplateArgs) { 1750 bool RefersToCapturedVariable = 1751 isa<VarDecl>(D) && 1752 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1753 1754 DeclRefExpr *E; 1755 if (isa<VarTemplateSpecializationDecl>(D)) { 1756 VarTemplateSpecializationDecl *VarSpec = 1757 cast<VarTemplateSpecializationDecl>(D); 1758 1759 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1760 : NestedNameSpecifierLoc(), 1761 VarSpec->getTemplateKeywordLoc(), D, 1762 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1763 FoundD, TemplateArgs); 1764 } else { 1765 assert(!TemplateArgs && "No template arguments for non-variable" 1766 " template specialization references"); 1767 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1768 : NestedNameSpecifierLoc(), 1769 SourceLocation(), D, RefersToCapturedVariable, 1770 NameInfo, Ty, VK, FoundD); 1771 } 1772 1773 MarkDeclRefReferenced(E); 1774 1775 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1776 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1777 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1778 recordUseOfEvaluatedWeak(E); 1779 1780 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1781 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1782 FD = IFD->getAnonField(); 1783 if (FD) { 1784 UnusedPrivateFields.remove(FD); 1785 // Just in case we're building an illegal pointer-to-member. 1786 if (FD->isBitField()) 1787 E->setObjectKind(OK_BitField); 1788 } 1789 1790 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1791 // designates a bit-field. 1792 if (auto *BD = dyn_cast<BindingDecl>(D)) 1793 if (auto *BE = BD->getBinding()) 1794 E->setObjectKind(BE->getObjectKind()); 1795 1796 return E; 1797 } 1798 1799 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1800 /// possibly a list of template arguments. 1801 /// 1802 /// If this produces template arguments, it is permitted to call 1803 /// DecomposeTemplateName. 1804 /// 1805 /// This actually loses a lot of source location information for 1806 /// non-standard name kinds; we should consider preserving that in 1807 /// some way. 1808 void 1809 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1810 TemplateArgumentListInfo &Buffer, 1811 DeclarationNameInfo &NameInfo, 1812 const TemplateArgumentListInfo *&TemplateArgs) { 1813 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1814 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1815 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1816 1817 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1818 Id.TemplateId->NumArgs); 1819 translateTemplateArguments(TemplateArgsPtr, Buffer); 1820 1821 TemplateName TName = Id.TemplateId->Template.get(); 1822 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1823 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1824 TemplateArgs = &Buffer; 1825 } else { 1826 NameInfo = GetNameFromUnqualifiedId(Id); 1827 TemplateArgs = nullptr; 1828 } 1829 } 1830 1831 static void emitEmptyLookupTypoDiagnostic( 1832 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1833 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1834 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1835 DeclContext *Ctx = 1836 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1837 if (!TC) { 1838 // Emit a special diagnostic for failed member lookups. 1839 // FIXME: computing the declaration context might fail here (?) 1840 if (Ctx) 1841 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1842 << SS.getRange(); 1843 else 1844 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1845 return; 1846 } 1847 1848 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1849 bool DroppedSpecifier = 1850 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1851 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1852 ? diag::note_implicit_param_decl 1853 : diag::note_previous_decl; 1854 if (!Ctx) 1855 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1856 SemaRef.PDiag(NoteID)); 1857 else 1858 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1859 << Typo << Ctx << DroppedSpecifier 1860 << SS.getRange(), 1861 SemaRef.PDiag(NoteID)); 1862 } 1863 1864 /// Diagnose an empty lookup. 1865 /// 1866 /// \return false if new lookup candidates were found 1867 bool 1868 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1869 std::unique_ptr<CorrectionCandidateCallback> CCC, 1870 TemplateArgumentListInfo *ExplicitTemplateArgs, 1871 ArrayRef<Expr *> Args, TypoExpr **Out) { 1872 DeclarationName Name = R.getLookupName(); 1873 1874 unsigned diagnostic = diag::err_undeclared_var_use; 1875 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1876 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1877 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1878 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1879 diagnostic = diag::err_undeclared_use; 1880 diagnostic_suggest = diag::err_undeclared_use_suggest; 1881 } 1882 1883 // If the original lookup was an unqualified lookup, fake an 1884 // unqualified lookup. This is useful when (for example) the 1885 // original lookup would not have found something because it was a 1886 // dependent name. 1887 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1888 while (DC) { 1889 if (isa<CXXRecordDecl>(DC)) { 1890 LookupQualifiedName(R, DC); 1891 1892 if (!R.empty()) { 1893 // Don't give errors about ambiguities in this lookup. 1894 R.suppressDiagnostics(); 1895 1896 // During a default argument instantiation the CurContext points 1897 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1898 // function parameter list, hence add an explicit check. 1899 bool isDefaultArgument = 1900 !CodeSynthesisContexts.empty() && 1901 CodeSynthesisContexts.back().Kind == 1902 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1903 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1904 bool isInstance = CurMethod && 1905 CurMethod->isInstance() && 1906 DC == CurMethod->getParent() && !isDefaultArgument; 1907 1908 // Give a code modification hint to insert 'this->'. 1909 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1910 // Actually quite difficult! 1911 if (getLangOpts().MSVCCompat) 1912 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1913 if (isInstance) { 1914 Diag(R.getNameLoc(), diagnostic) << Name 1915 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1916 CheckCXXThisCapture(R.getNameLoc()); 1917 } else { 1918 Diag(R.getNameLoc(), diagnostic) << Name; 1919 } 1920 1921 // Do we really want to note all of these? 1922 for (NamedDecl *D : R) 1923 Diag(D->getLocation(), diag::note_dependent_var_use); 1924 1925 // Return true if we are inside a default argument instantiation 1926 // and the found name refers to an instance member function, otherwise 1927 // the function calling DiagnoseEmptyLookup will try to create an 1928 // implicit member call and this is wrong for default argument. 1929 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1930 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1931 return true; 1932 } 1933 1934 // Tell the callee to try to recover. 1935 return false; 1936 } 1937 1938 R.clear(); 1939 } 1940 1941 // In Microsoft mode, if we are performing lookup from within a friend 1942 // function definition declared at class scope then we must set 1943 // DC to the lexical parent to be able to search into the parent 1944 // class. 1945 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1946 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1947 DC->getLexicalParent()->isRecord()) 1948 DC = DC->getLexicalParent(); 1949 else 1950 DC = DC->getParent(); 1951 } 1952 1953 // We didn't find anything, so try to correct for a typo. 1954 TypoCorrection Corrected; 1955 if (S && Out) { 1956 SourceLocation TypoLoc = R.getNameLoc(); 1957 assert(!ExplicitTemplateArgs && 1958 "Diagnosing an empty lookup with explicit template args!"); 1959 *Out = CorrectTypoDelayed( 1960 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1961 [=](const TypoCorrection &TC) { 1962 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1963 diagnostic, diagnostic_suggest); 1964 }, 1965 nullptr, CTK_ErrorRecovery); 1966 if (*Out) 1967 return true; 1968 } else if (S && (Corrected = 1969 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1970 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1971 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1972 bool DroppedSpecifier = 1973 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1974 R.setLookupName(Corrected.getCorrection()); 1975 1976 bool AcceptableWithRecovery = false; 1977 bool AcceptableWithoutRecovery = false; 1978 NamedDecl *ND = Corrected.getFoundDecl(); 1979 if (ND) { 1980 if (Corrected.isOverloaded()) { 1981 OverloadCandidateSet OCS(R.getNameLoc(), 1982 OverloadCandidateSet::CSK_Normal); 1983 OverloadCandidateSet::iterator Best; 1984 for (NamedDecl *CD : Corrected) { 1985 if (FunctionTemplateDecl *FTD = 1986 dyn_cast<FunctionTemplateDecl>(CD)) 1987 AddTemplateOverloadCandidate( 1988 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1989 Args, OCS); 1990 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1991 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1992 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1993 Args, OCS); 1994 } 1995 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1996 case OR_Success: 1997 ND = Best->FoundDecl; 1998 Corrected.setCorrectionDecl(ND); 1999 break; 2000 default: 2001 // FIXME: Arbitrarily pick the first declaration for the note. 2002 Corrected.setCorrectionDecl(ND); 2003 break; 2004 } 2005 } 2006 R.addDecl(ND); 2007 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2008 CXXRecordDecl *Record = nullptr; 2009 if (Corrected.getCorrectionSpecifier()) { 2010 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2011 Record = Ty->getAsCXXRecordDecl(); 2012 } 2013 if (!Record) 2014 Record = cast<CXXRecordDecl>( 2015 ND->getDeclContext()->getRedeclContext()); 2016 R.setNamingClass(Record); 2017 } 2018 2019 auto *UnderlyingND = ND->getUnderlyingDecl(); 2020 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2021 isa<FunctionTemplateDecl>(UnderlyingND); 2022 // FIXME: If we ended up with a typo for a type name or 2023 // Objective-C class name, we're in trouble because the parser 2024 // is in the wrong place to recover. Suggest the typo 2025 // correction, but don't make it a fix-it since we're not going 2026 // to recover well anyway. 2027 AcceptableWithoutRecovery = 2028 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2029 } else { 2030 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2031 // because we aren't able to recover. 2032 AcceptableWithoutRecovery = true; 2033 } 2034 2035 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2036 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2037 ? diag::note_implicit_param_decl 2038 : diag::note_previous_decl; 2039 if (SS.isEmpty()) 2040 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2041 PDiag(NoteID), AcceptableWithRecovery); 2042 else 2043 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2044 << Name << computeDeclContext(SS, false) 2045 << DroppedSpecifier << SS.getRange(), 2046 PDiag(NoteID), AcceptableWithRecovery); 2047 2048 // Tell the callee whether to try to recover. 2049 return !AcceptableWithRecovery; 2050 } 2051 } 2052 R.clear(); 2053 2054 // Emit a special diagnostic for failed member lookups. 2055 // FIXME: computing the declaration context might fail here (?) 2056 if (!SS.isEmpty()) { 2057 Diag(R.getNameLoc(), diag::err_no_member) 2058 << Name << computeDeclContext(SS, false) 2059 << SS.getRange(); 2060 return true; 2061 } 2062 2063 // Give up, we can't recover. 2064 Diag(R.getNameLoc(), diagnostic) << Name; 2065 return true; 2066 } 2067 2068 /// In Microsoft mode, if we are inside a template class whose parent class has 2069 /// dependent base classes, and we can't resolve an unqualified identifier, then 2070 /// assume the identifier is a member of a dependent base class. We can only 2071 /// recover successfully in static methods, instance methods, and other contexts 2072 /// where 'this' is available. This doesn't precisely match MSVC's 2073 /// instantiation model, but it's close enough. 2074 static Expr * 2075 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2076 DeclarationNameInfo &NameInfo, 2077 SourceLocation TemplateKWLoc, 2078 const TemplateArgumentListInfo *TemplateArgs) { 2079 // Only try to recover from lookup into dependent bases in static methods or 2080 // contexts where 'this' is available. 2081 QualType ThisType = S.getCurrentThisType(); 2082 const CXXRecordDecl *RD = nullptr; 2083 if (!ThisType.isNull()) 2084 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2085 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2086 RD = MD->getParent(); 2087 if (!RD || !RD->hasAnyDependentBases()) 2088 return nullptr; 2089 2090 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2091 // is available, suggest inserting 'this->' as a fixit. 2092 SourceLocation Loc = NameInfo.getLoc(); 2093 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2094 DB << NameInfo.getName() << RD; 2095 2096 if (!ThisType.isNull()) { 2097 DB << FixItHint::CreateInsertion(Loc, "this->"); 2098 return CXXDependentScopeMemberExpr::Create( 2099 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2100 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2101 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2102 } 2103 2104 // Synthesize a fake NNS that points to the derived class. This will 2105 // perform name lookup during template instantiation. 2106 CXXScopeSpec SS; 2107 auto *NNS = 2108 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2109 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2110 return DependentScopeDeclRefExpr::Create( 2111 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2112 TemplateArgs); 2113 } 2114 2115 ExprResult 2116 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2117 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2118 bool HasTrailingLParen, bool IsAddressOfOperand, 2119 std::unique_ptr<CorrectionCandidateCallback> CCC, 2120 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2121 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2122 "cannot be direct & operand and have a trailing lparen"); 2123 if (SS.isInvalid()) 2124 return ExprError(); 2125 2126 TemplateArgumentListInfo TemplateArgsBuffer; 2127 2128 // Decompose the UnqualifiedId into the following data. 2129 DeclarationNameInfo NameInfo; 2130 const TemplateArgumentListInfo *TemplateArgs; 2131 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2132 2133 DeclarationName Name = NameInfo.getName(); 2134 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2135 SourceLocation NameLoc = NameInfo.getLoc(); 2136 2137 if (II && II->isEditorPlaceholder()) { 2138 // FIXME: When typed placeholders are supported we can create a typed 2139 // placeholder expression node. 2140 return ExprError(); 2141 } 2142 2143 // C++ [temp.dep.expr]p3: 2144 // An id-expression is type-dependent if it contains: 2145 // -- an identifier that was declared with a dependent type, 2146 // (note: handled after lookup) 2147 // -- a template-id that is dependent, 2148 // (note: handled in BuildTemplateIdExpr) 2149 // -- a conversion-function-id that specifies a dependent type, 2150 // -- a nested-name-specifier that contains a class-name that 2151 // names a dependent type. 2152 // Determine whether this is a member of an unknown specialization; 2153 // we need to handle these differently. 2154 bool DependentID = false; 2155 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2156 Name.getCXXNameType()->isDependentType()) { 2157 DependentID = true; 2158 } else if (SS.isSet()) { 2159 if (DeclContext *DC = computeDeclContext(SS, false)) { 2160 if (RequireCompleteDeclContext(SS, DC)) 2161 return ExprError(); 2162 } else { 2163 DependentID = true; 2164 } 2165 } 2166 2167 if (DependentID) 2168 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2169 IsAddressOfOperand, TemplateArgs); 2170 2171 // Perform the required lookup. 2172 LookupResult R(*this, NameInfo, 2173 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2174 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2175 if (TemplateArgs) { 2176 // Lookup the template name again to correctly establish the context in 2177 // which it was found. This is really unfortunate as we already did the 2178 // lookup to determine that it was a template name in the first place. If 2179 // this becomes a performance hit, we can work harder to preserve those 2180 // results until we get here but it's likely not worth it. 2181 bool MemberOfUnknownSpecialization; 2182 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2183 MemberOfUnknownSpecialization); 2184 2185 if (MemberOfUnknownSpecialization || 2186 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2187 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2188 IsAddressOfOperand, TemplateArgs); 2189 } else { 2190 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2191 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2192 2193 // If the result might be in a dependent base class, this is a dependent 2194 // id-expression. 2195 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2196 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2197 IsAddressOfOperand, TemplateArgs); 2198 2199 // If this reference is in an Objective-C method, then we need to do 2200 // some special Objective-C lookup, too. 2201 if (IvarLookupFollowUp) { 2202 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2203 if (E.isInvalid()) 2204 return ExprError(); 2205 2206 if (Expr *Ex = E.getAs<Expr>()) 2207 return Ex; 2208 } 2209 } 2210 2211 if (R.isAmbiguous()) 2212 return ExprError(); 2213 2214 // This could be an implicitly declared function reference (legal in C90, 2215 // extension in C99, forbidden in C++). 2216 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2217 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2218 if (D) R.addDecl(D); 2219 } 2220 2221 // Determine whether this name might be a candidate for 2222 // argument-dependent lookup. 2223 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2224 2225 if (R.empty() && !ADL) { 2226 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2227 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2228 TemplateKWLoc, TemplateArgs)) 2229 return E; 2230 } 2231 2232 // Don't diagnose an empty lookup for inline assembly. 2233 if (IsInlineAsmIdentifier) 2234 return ExprError(); 2235 2236 // If this name wasn't predeclared and if this is not a function 2237 // call, diagnose the problem. 2238 TypoExpr *TE = nullptr; 2239 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2240 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2241 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2242 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2243 "Typo correction callback misconfigured"); 2244 if (CCC) { 2245 // Make sure the callback knows what the typo being diagnosed is. 2246 CCC->setTypoName(II); 2247 if (SS.isValid()) 2248 CCC->setTypoNNS(SS.getScopeRep()); 2249 } 2250 if (DiagnoseEmptyLookup(S, SS, R, 2251 CCC ? std::move(CCC) : std::move(DefaultValidator), 2252 nullptr, None, &TE)) { 2253 if (TE && KeywordReplacement) { 2254 auto &State = getTypoExprState(TE); 2255 auto BestTC = State.Consumer->getNextCorrection(); 2256 if (BestTC.isKeyword()) { 2257 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2258 if (State.DiagHandler) 2259 State.DiagHandler(BestTC); 2260 KeywordReplacement->startToken(); 2261 KeywordReplacement->setKind(II->getTokenID()); 2262 KeywordReplacement->setIdentifierInfo(II); 2263 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2264 // Clean up the state associated with the TypoExpr, since it has 2265 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2266 clearDelayedTypo(TE); 2267 // Signal that a correction to a keyword was performed by returning a 2268 // valid-but-null ExprResult. 2269 return (Expr*)nullptr; 2270 } 2271 State.Consumer->resetCorrectionStream(); 2272 } 2273 return TE ? TE : ExprError(); 2274 } 2275 2276 assert(!R.empty() && 2277 "DiagnoseEmptyLookup returned false but added no results"); 2278 2279 // If we found an Objective-C instance variable, let 2280 // LookupInObjCMethod build the appropriate expression to 2281 // reference the ivar. 2282 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2283 R.clear(); 2284 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2285 // In a hopelessly buggy code, Objective-C instance variable 2286 // lookup fails and no expression will be built to reference it. 2287 if (!E.isInvalid() && !E.get()) 2288 return ExprError(); 2289 return E; 2290 } 2291 } 2292 2293 // This is guaranteed from this point on. 2294 assert(!R.empty() || ADL); 2295 2296 // Check whether this might be a C++ implicit instance member access. 2297 // C++ [class.mfct.non-static]p3: 2298 // When an id-expression that is not part of a class member access 2299 // syntax and not used to form a pointer to member is used in the 2300 // body of a non-static member function of class X, if name lookup 2301 // resolves the name in the id-expression to a non-static non-type 2302 // member of some class C, the id-expression is transformed into a 2303 // class member access expression using (*this) as the 2304 // postfix-expression to the left of the . operator. 2305 // 2306 // But we don't actually need to do this for '&' operands if R 2307 // resolved to a function or overloaded function set, because the 2308 // expression is ill-formed if it actually works out to be a 2309 // non-static member function: 2310 // 2311 // C++ [expr.ref]p4: 2312 // Otherwise, if E1.E2 refers to a non-static member function. . . 2313 // [t]he expression can be used only as the left-hand operand of a 2314 // member function call. 2315 // 2316 // There are other safeguards against such uses, but it's important 2317 // to get this right here so that we don't end up making a 2318 // spuriously dependent expression if we're inside a dependent 2319 // instance method. 2320 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2321 bool MightBeImplicitMember; 2322 if (!IsAddressOfOperand) 2323 MightBeImplicitMember = true; 2324 else if (!SS.isEmpty()) 2325 MightBeImplicitMember = false; 2326 else if (R.isOverloadedResult()) 2327 MightBeImplicitMember = false; 2328 else if (R.isUnresolvableResult()) 2329 MightBeImplicitMember = true; 2330 else 2331 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2332 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2333 isa<MSPropertyDecl>(R.getFoundDecl()); 2334 2335 if (MightBeImplicitMember) 2336 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2337 R, TemplateArgs, S); 2338 } 2339 2340 if (TemplateArgs || TemplateKWLoc.isValid()) { 2341 2342 // In C++1y, if this is a variable template id, then check it 2343 // in BuildTemplateIdExpr(). 2344 // The single lookup result must be a variable template declaration. 2345 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2346 Id.TemplateId->Kind == TNK_Var_template) { 2347 assert(R.getAsSingle<VarTemplateDecl>() && 2348 "There should only be one declaration found."); 2349 } 2350 2351 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2352 } 2353 2354 return BuildDeclarationNameExpr(SS, R, ADL); 2355 } 2356 2357 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2358 /// declaration name, generally during template instantiation. 2359 /// There's a large number of things which don't need to be done along 2360 /// this path. 2361 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2362 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2363 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2364 DeclContext *DC = computeDeclContext(SS, false); 2365 if (!DC) 2366 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2367 NameInfo, /*TemplateArgs=*/nullptr); 2368 2369 if (RequireCompleteDeclContext(SS, DC)) 2370 return ExprError(); 2371 2372 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2373 LookupQualifiedName(R, DC); 2374 2375 if (R.isAmbiguous()) 2376 return ExprError(); 2377 2378 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2379 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2380 NameInfo, /*TemplateArgs=*/nullptr); 2381 2382 if (R.empty()) { 2383 Diag(NameInfo.getLoc(), diag::err_no_member) 2384 << NameInfo.getName() << DC << SS.getRange(); 2385 return ExprError(); 2386 } 2387 2388 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2389 // Diagnose a missing typename if this resolved unambiguously to a type in 2390 // a dependent context. If we can recover with a type, downgrade this to 2391 // a warning in Microsoft compatibility mode. 2392 unsigned DiagID = diag::err_typename_missing; 2393 if (RecoveryTSI && getLangOpts().MSVCCompat) 2394 DiagID = diag::ext_typename_missing; 2395 SourceLocation Loc = SS.getBeginLoc(); 2396 auto D = Diag(Loc, DiagID); 2397 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2398 << SourceRange(Loc, NameInfo.getEndLoc()); 2399 2400 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2401 // context. 2402 if (!RecoveryTSI) 2403 return ExprError(); 2404 2405 // Only issue the fixit if we're prepared to recover. 2406 D << FixItHint::CreateInsertion(Loc, "typename "); 2407 2408 // Recover by pretending this was an elaborated type. 2409 QualType Ty = Context.getTypeDeclType(TD); 2410 TypeLocBuilder TLB; 2411 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2412 2413 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2414 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2415 QTL.setElaboratedKeywordLoc(SourceLocation()); 2416 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2417 2418 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2419 2420 return ExprEmpty(); 2421 } 2422 2423 // Defend against this resolving to an implicit member access. We usually 2424 // won't get here if this might be a legitimate a class member (we end up in 2425 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2426 // a pointer-to-member or in an unevaluated context in C++11. 2427 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2428 return BuildPossibleImplicitMemberExpr(SS, 2429 /*TemplateKWLoc=*/SourceLocation(), 2430 R, /*TemplateArgs=*/nullptr, S); 2431 2432 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2433 } 2434 2435 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2436 /// detected that we're currently inside an ObjC method. Perform some 2437 /// additional lookup. 2438 /// 2439 /// Ideally, most of this would be done by lookup, but there's 2440 /// actually quite a lot of extra work involved. 2441 /// 2442 /// Returns a null sentinel to indicate trivial success. 2443 ExprResult 2444 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2445 IdentifierInfo *II, bool AllowBuiltinCreation) { 2446 SourceLocation Loc = Lookup.getNameLoc(); 2447 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2448 2449 // Check for error condition which is already reported. 2450 if (!CurMethod) 2451 return ExprError(); 2452 2453 // There are two cases to handle here. 1) scoped lookup could have failed, 2454 // in which case we should look for an ivar. 2) scoped lookup could have 2455 // found a decl, but that decl is outside the current instance method (i.e. 2456 // a global variable). In these two cases, we do a lookup for an ivar with 2457 // this name, if the lookup sucedes, we replace it our current decl. 2458 2459 // If we're in a class method, we don't normally want to look for 2460 // ivars. But if we don't find anything else, and there's an 2461 // ivar, that's an error. 2462 bool IsClassMethod = CurMethod->isClassMethod(); 2463 2464 bool LookForIvars; 2465 if (Lookup.empty()) 2466 LookForIvars = true; 2467 else if (IsClassMethod) 2468 LookForIvars = false; 2469 else 2470 LookForIvars = (Lookup.isSingleResult() && 2471 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2472 ObjCInterfaceDecl *IFace = nullptr; 2473 if (LookForIvars) { 2474 IFace = CurMethod->getClassInterface(); 2475 ObjCInterfaceDecl *ClassDeclared; 2476 ObjCIvarDecl *IV = nullptr; 2477 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2478 // Diagnose using an ivar in a class method. 2479 if (IsClassMethod) 2480 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2481 << IV->getDeclName()); 2482 2483 // If we're referencing an invalid decl, just return this as a silent 2484 // error node. The error diagnostic was already emitted on the decl. 2485 if (IV->isInvalidDecl()) 2486 return ExprError(); 2487 2488 // Check if referencing a field with __attribute__((deprecated)). 2489 if (DiagnoseUseOfDecl(IV, Loc)) 2490 return ExprError(); 2491 2492 // Diagnose the use of an ivar outside of the declaring class. 2493 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2494 !declaresSameEntity(ClassDeclared, IFace) && 2495 !getLangOpts().DebuggerSupport) 2496 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2497 2498 // FIXME: This should use a new expr for a direct reference, don't 2499 // turn this into Self->ivar, just return a BareIVarExpr or something. 2500 IdentifierInfo &II = Context.Idents.get("self"); 2501 UnqualifiedId SelfName; 2502 SelfName.setIdentifier(&II, SourceLocation()); 2503 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2504 CXXScopeSpec SelfScopeSpec; 2505 SourceLocation TemplateKWLoc; 2506 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2507 SelfName, false, false); 2508 if (SelfExpr.isInvalid()) 2509 return ExprError(); 2510 2511 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2512 if (SelfExpr.isInvalid()) 2513 return ExprError(); 2514 2515 MarkAnyDeclReferenced(Loc, IV, true); 2516 2517 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2518 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2519 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2520 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2521 2522 ObjCIvarRefExpr *Result = new (Context) 2523 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2524 IV->getLocation(), SelfExpr.get(), true, true); 2525 2526 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2527 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2528 recordUseOfEvaluatedWeak(Result); 2529 } 2530 if (getLangOpts().ObjCAutoRefCount) { 2531 if (CurContext->isClosure()) 2532 Diag(Loc, diag::warn_implicitly_retains_self) 2533 << FixItHint::CreateInsertion(Loc, "self->"); 2534 } 2535 2536 return Result; 2537 } 2538 } else if (CurMethod->isInstanceMethod()) { 2539 // We should warn if a local variable hides an ivar. 2540 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2541 ObjCInterfaceDecl *ClassDeclared; 2542 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2543 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2544 declaresSameEntity(IFace, ClassDeclared)) 2545 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2546 } 2547 } 2548 } else if (Lookup.isSingleResult() && 2549 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2550 // If accessing a stand-alone ivar in a class method, this is an error. 2551 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2552 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2553 << IV->getDeclName()); 2554 } 2555 2556 if (Lookup.empty() && II && AllowBuiltinCreation) { 2557 // FIXME. Consolidate this with similar code in LookupName. 2558 if (unsigned BuiltinID = II->getBuiltinID()) { 2559 if (!(getLangOpts().CPlusPlus && 2560 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2561 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2562 S, Lookup.isForRedeclaration(), 2563 Lookup.getNameLoc()); 2564 if (D) Lookup.addDecl(D); 2565 } 2566 } 2567 } 2568 // Sentinel value saying that we didn't do anything special. 2569 return ExprResult((Expr *)nullptr); 2570 } 2571 2572 /// \brief Cast a base object to a member's actual type. 2573 /// 2574 /// Logically this happens in three phases: 2575 /// 2576 /// * First we cast from the base type to the naming class. 2577 /// The naming class is the class into which we were looking 2578 /// when we found the member; it's the qualifier type if a 2579 /// qualifier was provided, and otherwise it's the base type. 2580 /// 2581 /// * Next we cast from the naming class to the declaring class. 2582 /// If the member we found was brought into a class's scope by 2583 /// a using declaration, this is that class; otherwise it's 2584 /// the class declaring the member. 2585 /// 2586 /// * Finally we cast from the declaring class to the "true" 2587 /// declaring class of the member. This conversion does not 2588 /// obey access control. 2589 ExprResult 2590 Sema::PerformObjectMemberConversion(Expr *From, 2591 NestedNameSpecifier *Qualifier, 2592 NamedDecl *FoundDecl, 2593 NamedDecl *Member) { 2594 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2595 if (!RD) 2596 return From; 2597 2598 QualType DestRecordType; 2599 QualType DestType; 2600 QualType FromRecordType; 2601 QualType FromType = From->getType(); 2602 bool PointerConversions = false; 2603 if (isa<FieldDecl>(Member)) { 2604 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2605 2606 if (FromType->getAs<PointerType>()) { 2607 DestType = Context.getPointerType(DestRecordType); 2608 FromRecordType = FromType->getPointeeType(); 2609 PointerConversions = true; 2610 } else { 2611 DestType = DestRecordType; 2612 FromRecordType = FromType; 2613 } 2614 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2615 if (Method->isStatic()) 2616 return From; 2617 2618 DestType = Method->getThisType(Context); 2619 DestRecordType = DestType->getPointeeType(); 2620 2621 if (FromType->getAs<PointerType>()) { 2622 FromRecordType = FromType->getPointeeType(); 2623 PointerConversions = true; 2624 } else { 2625 FromRecordType = FromType; 2626 DestType = DestRecordType; 2627 } 2628 } else { 2629 // No conversion necessary. 2630 return From; 2631 } 2632 2633 if (DestType->isDependentType() || FromType->isDependentType()) 2634 return From; 2635 2636 // If the unqualified types are the same, no conversion is necessary. 2637 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2638 return From; 2639 2640 SourceRange FromRange = From->getSourceRange(); 2641 SourceLocation FromLoc = FromRange.getBegin(); 2642 2643 ExprValueKind VK = From->getValueKind(); 2644 2645 // C++ [class.member.lookup]p8: 2646 // [...] Ambiguities can often be resolved by qualifying a name with its 2647 // class name. 2648 // 2649 // If the member was a qualified name and the qualified referred to a 2650 // specific base subobject type, we'll cast to that intermediate type 2651 // first and then to the object in which the member is declared. That allows 2652 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2653 // 2654 // class Base { public: int x; }; 2655 // class Derived1 : public Base { }; 2656 // class Derived2 : public Base { }; 2657 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2658 // 2659 // void VeryDerived::f() { 2660 // x = 17; // error: ambiguous base subobjects 2661 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2662 // } 2663 if (Qualifier && Qualifier->getAsType()) { 2664 QualType QType = QualType(Qualifier->getAsType(), 0); 2665 assert(QType->isRecordType() && "lookup done with non-record type"); 2666 2667 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2668 2669 // In C++98, the qualifier type doesn't actually have to be a base 2670 // type of the object type, in which case we just ignore it. 2671 // Otherwise build the appropriate casts. 2672 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2673 CXXCastPath BasePath; 2674 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2675 FromLoc, FromRange, &BasePath)) 2676 return ExprError(); 2677 2678 if (PointerConversions) 2679 QType = Context.getPointerType(QType); 2680 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2681 VK, &BasePath).get(); 2682 2683 FromType = QType; 2684 FromRecordType = QRecordType; 2685 2686 // If the qualifier type was the same as the destination type, 2687 // we're done. 2688 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2689 return From; 2690 } 2691 } 2692 2693 bool IgnoreAccess = false; 2694 2695 // If we actually found the member through a using declaration, cast 2696 // down to the using declaration's type. 2697 // 2698 // Pointer equality is fine here because only one declaration of a 2699 // class ever has member declarations. 2700 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2701 assert(isa<UsingShadowDecl>(FoundDecl)); 2702 QualType URecordType = Context.getTypeDeclType( 2703 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2704 2705 // We only need to do this if the naming-class to declaring-class 2706 // conversion is non-trivial. 2707 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2708 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2709 CXXCastPath BasePath; 2710 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2711 FromLoc, FromRange, &BasePath)) 2712 return ExprError(); 2713 2714 QualType UType = URecordType; 2715 if (PointerConversions) 2716 UType = Context.getPointerType(UType); 2717 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2718 VK, &BasePath).get(); 2719 FromType = UType; 2720 FromRecordType = URecordType; 2721 } 2722 2723 // We don't do access control for the conversion from the 2724 // declaring class to the true declaring class. 2725 IgnoreAccess = true; 2726 } 2727 2728 CXXCastPath BasePath; 2729 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2730 FromLoc, FromRange, &BasePath, 2731 IgnoreAccess)) 2732 return ExprError(); 2733 2734 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2735 VK, &BasePath); 2736 } 2737 2738 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2739 const LookupResult &R, 2740 bool HasTrailingLParen) { 2741 // Only when used directly as the postfix-expression of a call. 2742 if (!HasTrailingLParen) 2743 return false; 2744 2745 // Never if a scope specifier was provided. 2746 if (SS.isSet()) 2747 return false; 2748 2749 // Only in C++ or ObjC++. 2750 if (!getLangOpts().CPlusPlus) 2751 return false; 2752 2753 // Turn off ADL when we find certain kinds of declarations during 2754 // normal lookup: 2755 for (NamedDecl *D : R) { 2756 // C++0x [basic.lookup.argdep]p3: 2757 // -- a declaration of a class member 2758 // Since using decls preserve this property, we check this on the 2759 // original decl. 2760 if (D->isCXXClassMember()) 2761 return false; 2762 2763 // C++0x [basic.lookup.argdep]p3: 2764 // -- a block-scope function declaration that is not a 2765 // using-declaration 2766 // NOTE: we also trigger this for function templates (in fact, we 2767 // don't check the decl type at all, since all other decl types 2768 // turn off ADL anyway). 2769 if (isa<UsingShadowDecl>(D)) 2770 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2771 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2772 return false; 2773 2774 // C++0x [basic.lookup.argdep]p3: 2775 // -- a declaration that is neither a function or a function 2776 // template 2777 // And also for builtin functions. 2778 if (isa<FunctionDecl>(D)) { 2779 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2780 2781 // But also builtin functions. 2782 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2783 return false; 2784 } else if (!isa<FunctionTemplateDecl>(D)) 2785 return false; 2786 } 2787 2788 return true; 2789 } 2790 2791 2792 /// Diagnoses obvious problems with the use of the given declaration 2793 /// as an expression. This is only actually called for lookups that 2794 /// were not overloaded, and it doesn't promise that the declaration 2795 /// will in fact be used. 2796 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2797 if (D->isInvalidDecl()) 2798 return true; 2799 2800 if (isa<TypedefNameDecl>(D)) { 2801 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2802 return true; 2803 } 2804 2805 if (isa<ObjCInterfaceDecl>(D)) { 2806 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2807 return true; 2808 } 2809 2810 if (isa<NamespaceDecl>(D)) { 2811 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2812 return true; 2813 } 2814 2815 return false; 2816 } 2817 2818 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2819 LookupResult &R, bool NeedsADL, 2820 bool AcceptInvalidDecl) { 2821 // If this is a single, fully-resolved result and we don't need ADL, 2822 // just build an ordinary singleton decl ref. 2823 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2824 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2825 R.getRepresentativeDecl(), nullptr, 2826 AcceptInvalidDecl); 2827 2828 // We only need to check the declaration if there's exactly one 2829 // result, because in the overloaded case the results can only be 2830 // functions and function templates. 2831 if (R.isSingleResult() && 2832 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2833 return ExprError(); 2834 2835 // Otherwise, just build an unresolved lookup expression. Suppress 2836 // any lookup-related diagnostics; we'll hash these out later, when 2837 // we've picked a target. 2838 R.suppressDiagnostics(); 2839 2840 UnresolvedLookupExpr *ULE 2841 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2842 SS.getWithLocInContext(Context), 2843 R.getLookupNameInfo(), 2844 NeedsADL, R.isOverloadedResult(), 2845 R.begin(), R.end()); 2846 2847 return ULE; 2848 } 2849 2850 static void 2851 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2852 ValueDecl *var, DeclContext *DC); 2853 2854 /// \brief Complete semantic analysis for a reference to the given declaration. 2855 ExprResult Sema::BuildDeclarationNameExpr( 2856 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2857 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2858 bool AcceptInvalidDecl) { 2859 assert(D && "Cannot refer to a NULL declaration"); 2860 assert(!isa<FunctionTemplateDecl>(D) && 2861 "Cannot refer unambiguously to a function template"); 2862 2863 SourceLocation Loc = NameInfo.getLoc(); 2864 if (CheckDeclInExpr(*this, Loc, D)) 2865 return ExprError(); 2866 2867 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2868 // Specifically diagnose references to class templates that are missing 2869 // a template argument list. 2870 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2871 << Template << SS.getRange(); 2872 Diag(Template->getLocation(), diag::note_template_decl_here); 2873 return ExprError(); 2874 } 2875 2876 // Make sure that we're referring to a value. 2877 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2878 if (!VD) { 2879 Diag(Loc, diag::err_ref_non_value) 2880 << D << SS.getRange(); 2881 Diag(D->getLocation(), diag::note_declared_at); 2882 return ExprError(); 2883 } 2884 2885 // Check whether this declaration can be used. Note that we suppress 2886 // this check when we're going to perform argument-dependent lookup 2887 // on this function name, because this might not be the function 2888 // that overload resolution actually selects. 2889 if (DiagnoseUseOfDecl(VD, Loc)) 2890 return ExprError(); 2891 2892 // Only create DeclRefExpr's for valid Decl's. 2893 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2894 return ExprError(); 2895 2896 // Handle members of anonymous structs and unions. If we got here, 2897 // and the reference is to a class member indirect field, then this 2898 // must be the subject of a pointer-to-member expression. 2899 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2900 if (!indirectField->isCXXClassMember()) 2901 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2902 indirectField); 2903 2904 { 2905 QualType type = VD->getType(); 2906 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2907 // C++ [except.spec]p17: 2908 // An exception-specification is considered to be needed when: 2909 // - in an expression, the function is the unique lookup result or 2910 // the selected member of a set of overloaded functions. 2911 ResolveExceptionSpec(Loc, FPT); 2912 type = VD->getType(); 2913 } 2914 ExprValueKind valueKind = VK_RValue; 2915 2916 switch (D->getKind()) { 2917 // Ignore all the non-ValueDecl kinds. 2918 #define ABSTRACT_DECL(kind) 2919 #define VALUE(type, base) 2920 #define DECL(type, base) \ 2921 case Decl::type: 2922 #include "clang/AST/DeclNodes.inc" 2923 llvm_unreachable("invalid value decl kind"); 2924 2925 // These shouldn't make it here. 2926 case Decl::ObjCAtDefsField: 2927 case Decl::ObjCIvar: 2928 llvm_unreachable("forming non-member reference to ivar?"); 2929 2930 // Enum constants are always r-values and never references. 2931 // Unresolved using declarations are dependent. 2932 case Decl::EnumConstant: 2933 case Decl::UnresolvedUsingValue: 2934 case Decl::OMPDeclareReduction: 2935 valueKind = VK_RValue; 2936 break; 2937 2938 // Fields and indirect fields that got here must be for 2939 // pointer-to-member expressions; we just call them l-values for 2940 // internal consistency, because this subexpression doesn't really 2941 // exist in the high-level semantics. 2942 case Decl::Field: 2943 case Decl::IndirectField: 2944 assert(getLangOpts().CPlusPlus && 2945 "building reference to field in C?"); 2946 2947 // These can't have reference type in well-formed programs, but 2948 // for internal consistency we do this anyway. 2949 type = type.getNonReferenceType(); 2950 valueKind = VK_LValue; 2951 break; 2952 2953 // Non-type template parameters are either l-values or r-values 2954 // depending on the type. 2955 case Decl::NonTypeTemplateParm: { 2956 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2957 type = reftype->getPointeeType(); 2958 valueKind = VK_LValue; // even if the parameter is an r-value reference 2959 break; 2960 } 2961 2962 // For non-references, we need to strip qualifiers just in case 2963 // the template parameter was declared as 'const int' or whatever. 2964 valueKind = VK_RValue; 2965 type = type.getUnqualifiedType(); 2966 break; 2967 } 2968 2969 case Decl::Var: 2970 case Decl::VarTemplateSpecialization: 2971 case Decl::VarTemplatePartialSpecialization: 2972 case Decl::Decomposition: 2973 case Decl::OMPCapturedExpr: 2974 // In C, "extern void blah;" is valid and is an r-value. 2975 if (!getLangOpts().CPlusPlus && 2976 !type.hasQualifiers() && 2977 type->isVoidType()) { 2978 valueKind = VK_RValue; 2979 break; 2980 } 2981 // fallthrough 2982 2983 case Decl::ImplicitParam: 2984 case Decl::ParmVar: { 2985 // These are always l-values. 2986 valueKind = VK_LValue; 2987 type = type.getNonReferenceType(); 2988 2989 // FIXME: Does the addition of const really only apply in 2990 // potentially-evaluated contexts? Since the variable isn't actually 2991 // captured in an unevaluated context, it seems that the answer is no. 2992 if (!isUnevaluatedContext()) { 2993 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2994 if (!CapturedType.isNull()) 2995 type = CapturedType; 2996 } 2997 2998 break; 2999 } 3000 3001 case Decl::Binding: { 3002 // These are always lvalues. 3003 valueKind = VK_LValue; 3004 type = type.getNonReferenceType(); 3005 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3006 // decides how that's supposed to work. 3007 auto *BD = cast<BindingDecl>(VD); 3008 if (BD->getDeclContext()->isFunctionOrMethod() && 3009 BD->getDeclContext() != CurContext) 3010 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3011 break; 3012 } 3013 3014 case Decl::Function: { 3015 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3016 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3017 type = Context.BuiltinFnTy; 3018 valueKind = VK_RValue; 3019 break; 3020 } 3021 } 3022 3023 const FunctionType *fty = type->castAs<FunctionType>(); 3024 3025 // If we're referring to a function with an __unknown_anytype 3026 // result type, make the entire expression __unknown_anytype. 3027 if (fty->getReturnType() == Context.UnknownAnyTy) { 3028 type = Context.UnknownAnyTy; 3029 valueKind = VK_RValue; 3030 break; 3031 } 3032 3033 // Functions are l-values in C++. 3034 if (getLangOpts().CPlusPlus) { 3035 valueKind = VK_LValue; 3036 break; 3037 } 3038 3039 // C99 DR 316 says that, if a function type comes from a 3040 // function definition (without a prototype), that type is only 3041 // used for checking compatibility. Therefore, when referencing 3042 // the function, we pretend that we don't have the full function 3043 // type. 3044 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3045 isa<FunctionProtoType>(fty)) 3046 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3047 fty->getExtInfo()); 3048 3049 // Functions are r-values in C. 3050 valueKind = VK_RValue; 3051 break; 3052 } 3053 3054 case Decl::CXXDeductionGuide: 3055 llvm_unreachable("building reference to deduction guide"); 3056 3057 case Decl::MSProperty: 3058 valueKind = VK_LValue; 3059 break; 3060 3061 case Decl::CXXMethod: 3062 // If we're referring to a method with an __unknown_anytype 3063 // result type, make the entire expression __unknown_anytype. 3064 // This should only be possible with a type written directly. 3065 if (const FunctionProtoType *proto 3066 = dyn_cast<FunctionProtoType>(VD->getType())) 3067 if (proto->getReturnType() == Context.UnknownAnyTy) { 3068 type = Context.UnknownAnyTy; 3069 valueKind = VK_RValue; 3070 break; 3071 } 3072 3073 // C++ methods are l-values if static, r-values if non-static. 3074 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3075 valueKind = VK_LValue; 3076 break; 3077 } 3078 // fallthrough 3079 3080 case Decl::CXXConversion: 3081 case Decl::CXXDestructor: 3082 case Decl::CXXConstructor: 3083 valueKind = VK_RValue; 3084 break; 3085 } 3086 3087 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3088 TemplateArgs); 3089 } 3090 } 3091 3092 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3093 SmallString<32> &Target) { 3094 Target.resize(CharByteWidth * (Source.size() + 1)); 3095 char *ResultPtr = &Target[0]; 3096 const llvm::UTF8 *ErrorPtr; 3097 bool success = 3098 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3099 (void)success; 3100 assert(success); 3101 Target.resize(ResultPtr - &Target[0]); 3102 } 3103 3104 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3105 PredefinedExpr::IdentType IT) { 3106 // Pick the current block, lambda, captured statement or function. 3107 Decl *currentDecl = nullptr; 3108 if (const BlockScopeInfo *BSI = getCurBlock()) 3109 currentDecl = BSI->TheDecl; 3110 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3111 currentDecl = LSI->CallOperator; 3112 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3113 currentDecl = CSI->TheCapturedDecl; 3114 else 3115 currentDecl = getCurFunctionOrMethodDecl(); 3116 3117 if (!currentDecl) { 3118 Diag(Loc, diag::ext_predef_outside_function); 3119 currentDecl = Context.getTranslationUnitDecl(); 3120 } 3121 3122 QualType ResTy; 3123 StringLiteral *SL = nullptr; 3124 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3125 ResTy = Context.DependentTy; 3126 else { 3127 // Pre-defined identifiers are of type char[x], where x is the length of 3128 // the string. 3129 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3130 unsigned Length = Str.length(); 3131 3132 llvm::APInt LengthI(32, Length + 1); 3133 if (IT == PredefinedExpr::LFunction) { 3134 ResTy = Context.WideCharTy.withConst(); 3135 SmallString<32> RawChars; 3136 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3137 Str, RawChars); 3138 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3139 /*IndexTypeQuals*/ 0); 3140 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3141 /*Pascal*/ false, ResTy, Loc); 3142 } else { 3143 ResTy = Context.CharTy.withConst(); 3144 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3145 /*IndexTypeQuals*/ 0); 3146 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3147 /*Pascal*/ false, ResTy, Loc); 3148 } 3149 } 3150 3151 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3152 } 3153 3154 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3155 PredefinedExpr::IdentType IT; 3156 3157 switch (Kind) { 3158 default: llvm_unreachable("Unknown simple primary expr!"); 3159 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3160 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3161 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3162 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3163 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3164 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3165 } 3166 3167 return BuildPredefinedExpr(Loc, IT); 3168 } 3169 3170 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3171 SmallString<16> CharBuffer; 3172 bool Invalid = false; 3173 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3174 if (Invalid) 3175 return ExprError(); 3176 3177 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3178 PP, Tok.getKind()); 3179 if (Literal.hadError()) 3180 return ExprError(); 3181 3182 QualType Ty; 3183 if (Literal.isWide()) 3184 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3185 else if (Literal.isUTF16()) 3186 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3187 else if (Literal.isUTF32()) 3188 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3189 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3190 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3191 else 3192 Ty = Context.CharTy; // 'x' -> char in C++ 3193 3194 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3195 if (Literal.isWide()) 3196 Kind = CharacterLiteral::Wide; 3197 else if (Literal.isUTF16()) 3198 Kind = CharacterLiteral::UTF16; 3199 else if (Literal.isUTF32()) 3200 Kind = CharacterLiteral::UTF32; 3201 else if (Literal.isUTF8()) 3202 Kind = CharacterLiteral::UTF8; 3203 3204 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3205 Tok.getLocation()); 3206 3207 if (Literal.getUDSuffix().empty()) 3208 return Lit; 3209 3210 // We're building a user-defined literal. 3211 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3212 SourceLocation UDSuffixLoc = 3213 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3214 3215 // Make sure we're allowed user-defined literals here. 3216 if (!UDLScope) 3217 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3218 3219 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3220 // operator "" X (ch) 3221 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3222 Lit, Tok.getLocation()); 3223 } 3224 3225 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3226 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3227 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3228 Context.IntTy, Loc); 3229 } 3230 3231 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3232 QualType Ty, SourceLocation Loc) { 3233 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3234 3235 using llvm::APFloat; 3236 APFloat Val(Format); 3237 3238 APFloat::opStatus result = Literal.GetFloatValue(Val); 3239 3240 // Overflow is always an error, but underflow is only an error if 3241 // we underflowed to zero (APFloat reports denormals as underflow). 3242 if ((result & APFloat::opOverflow) || 3243 ((result & APFloat::opUnderflow) && Val.isZero())) { 3244 unsigned diagnostic; 3245 SmallString<20> buffer; 3246 if (result & APFloat::opOverflow) { 3247 diagnostic = diag::warn_float_overflow; 3248 APFloat::getLargest(Format).toString(buffer); 3249 } else { 3250 diagnostic = diag::warn_float_underflow; 3251 APFloat::getSmallest(Format).toString(buffer); 3252 } 3253 3254 S.Diag(Loc, diagnostic) 3255 << Ty 3256 << StringRef(buffer.data(), buffer.size()); 3257 } 3258 3259 bool isExact = (result == APFloat::opOK); 3260 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3261 } 3262 3263 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3264 assert(E && "Invalid expression"); 3265 3266 if (E->isValueDependent()) 3267 return false; 3268 3269 QualType QT = E->getType(); 3270 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3271 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3272 return true; 3273 } 3274 3275 llvm::APSInt ValueAPS; 3276 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3277 3278 if (R.isInvalid()) 3279 return true; 3280 3281 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3282 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3283 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3284 << ValueAPS.toString(10) << ValueIsPositive; 3285 return true; 3286 } 3287 3288 return false; 3289 } 3290 3291 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3292 // Fast path for a single digit (which is quite common). A single digit 3293 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3294 if (Tok.getLength() == 1) { 3295 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3296 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3297 } 3298 3299 SmallString<128> SpellingBuffer; 3300 // NumericLiteralParser wants to overread by one character. Add padding to 3301 // the buffer in case the token is copied to the buffer. If getSpelling() 3302 // returns a StringRef to the memory buffer, it should have a null char at 3303 // the EOF, so it is also safe. 3304 SpellingBuffer.resize(Tok.getLength() + 1); 3305 3306 // Get the spelling of the token, which eliminates trigraphs, etc. 3307 bool Invalid = false; 3308 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3309 if (Invalid) 3310 return ExprError(); 3311 3312 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3313 if (Literal.hadError) 3314 return ExprError(); 3315 3316 if (Literal.hasUDSuffix()) { 3317 // We're building a user-defined literal. 3318 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3319 SourceLocation UDSuffixLoc = 3320 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3321 3322 // Make sure we're allowed user-defined literals here. 3323 if (!UDLScope) 3324 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3325 3326 QualType CookedTy; 3327 if (Literal.isFloatingLiteral()) { 3328 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3329 // long double, the literal is treated as a call of the form 3330 // operator "" X (f L) 3331 CookedTy = Context.LongDoubleTy; 3332 } else { 3333 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3334 // unsigned long long, the literal is treated as a call of the form 3335 // operator "" X (n ULL) 3336 CookedTy = Context.UnsignedLongLongTy; 3337 } 3338 3339 DeclarationName OpName = 3340 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3341 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3342 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3343 3344 SourceLocation TokLoc = Tok.getLocation(); 3345 3346 // Perform literal operator lookup to determine if we're building a raw 3347 // literal or a cooked one. 3348 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3349 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3350 /*AllowRaw*/true, /*AllowTemplate*/true, 3351 /*AllowStringTemplate*/false)) { 3352 case LOLR_Error: 3353 return ExprError(); 3354 3355 case LOLR_Cooked: { 3356 Expr *Lit; 3357 if (Literal.isFloatingLiteral()) { 3358 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3359 } else { 3360 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3361 if (Literal.GetIntegerValue(ResultVal)) 3362 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3363 << /* Unsigned */ 1; 3364 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3365 Tok.getLocation()); 3366 } 3367 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3368 } 3369 3370 case LOLR_Raw: { 3371 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3372 // literal is treated as a call of the form 3373 // operator "" X ("n") 3374 unsigned Length = Literal.getUDSuffixOffset(); 3375 QualType StrTy = Context.getConstantArrayType( 3376 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3377 ArrayType::Normal, 0); 3378 Expr *Lit = StringLiteral::Create( 3379 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3380 /*Pascal*/false, StrTy, &TokLoc, 1); 3381 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3382 } 3383 3384 case LOLR_Template: { 3385 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3386 // template), L is treated as a call fo the form 3387 // operator "" X <'c1', 'c2', ... 'ck'>() 3388 // where n is the source character sequence c1 c2 ... ck. 3389 TemplateArgumentListInfo ExplicitArgs; 3390 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3391 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3392 llvm::APSInt Value(CharBits, CharIsUnsigned); 3393 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3394 Value = TokSpelling[I]; 3395 TemplateArgument Arg(Context, Value, Context.CharTy); 3396 TemplateArgumentLocInfo ArgInfo; 3397 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3398 } 3399 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3400 &ExplicitArgs); 3401 } 3402 case LOLR_StringTemplate: 3403 llvm_unreachable("unexpected literal operator lookup result"); 3404 } 3405 } 3406 3407 Expr *Res; 3408 3409 if (Literal.isFloatingLiteral()) { 3410 QualType Ty; 3411 if (Literal.isHalf){ 3412 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3413 Ty = Context.HalfTy; 3414 else { 3415 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3416 return ExprError(); 3417 } 3418 } else if (Literal.isFloat) 3419 Ty = Context.FloatTy; 3420 else if (Literal.isLong) 3421 Ty = Context.LongDoubleTy; 3422 else if (Literal.isFloat128) 3423 Ty = Context.Float128Ty; 3424 else 3425 Ty = Context.DoubleTy; 3426 3427 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3428 3429 if (Ty == Context.DoubleTy) { 3430 if (getLangOpts().SinglePrecisionConstants) { 3431 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3432 if (BTy->getKind() != BuiltinType::Float) { 3433 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3434 } 3435 } else if (getLangOpts().OpenCL && 3436 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3437 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3438 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3439 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3440 } 3441 } 3442 } else if (!Literal.isIntegerLiteral()) { 3443 return ExprError(); 3444 } else { 3445 QualType Ty; 3446 3447 // 'long long' is a C99 or C++11 feature. 3448 if (!getLangOpts().C99 && Literal.isLongLong) { 3449 if (getLangOpts().CPlusPlus) 3450 Diag(Tok.getLocation(), 3451 getLangOpts().CPlusPlus11 ? 3452 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3453 else 3454 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3455 } 3456 3457 // Get the value in the widest-possible width. 3458 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3459 llvm::APInt ResultVal(MaxWidth, 0); 3460 3461 if (Literal.GetIntegerValue(ResultVal)) { 3462 // If this value didn't fit into uintmax_t, error and force to ull. 3463 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3464 << /* Unsigned */ 1; 3465 Ty = Context.UnsignedLongLongTy; 3466 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3467 "long long is not intmax_t?"); 3468 } else { 3469 // If this value fits into a ULL, try to figure out what else it fits into 3470 // according to the rules of C99 6.4.4.1p5. 3471 3472 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3473 // be an unsigned int. 3474 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3475 3476 // Check from smallest to largest, picking the smallest type we can. 3477 unsigned Width = 0; 3478 3479 // Microsoft specific integer suffixes are explicitly sized. 3480 if (Literal.MicrosoftInteger) { 3481 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3482 Width = 8; 3483 Ty = Context.CharTy; 3484 } else { 3485 Width = Literal.MicrosoftInteger; 3486 Ty = Context.getIntTypeForBitwidth(Width, 3487 /*Signed=*/!Literal.isUnsigned); 3488 } 3489 } 3490 3491 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3492 // Are int/unsigned possibilities? 3493 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3494 3495 // Does it fit in a unsigned int? 3496 if (ResultVal.isIntN(IntSize)) { 3497 // Does it fit in a signed int? 3498 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3499 Ty = Context.IntTy; 3500 else if (AllowUnsigned) 3501 Ty = Context.UnsignedIntTy; 3502 Width = IntSize; 3503 } 3504 } 3505 3506 // Are long/unsigned long possibilities? 3507 if (Ty.isNull() && !Literal.isLongLong) { 3508 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3509 3510 // Does it fit in a unsigned long? 3511 if (ResultVal.isIntN(LongSize)) { 3512 // Does it fit in a signed long? 3513 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3514 Ty = Context.LongTy; 3515 else if (AllowUnsigned) 3516 Ty = Context.UnsignedLongTy; 3517 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3518 // is compatible. 3519 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3520 const unsigned LongLongSize = 3521 Context.getTargetInfo().getLongLongWidth(); 3522 Diag(Tok.getLocation(), 3523 getLangOpts().CPlusPlus 3524 ? Literal.isLong 3525 ? diag::warn_old_implicitly_unsigned_long_cxx 3526 : /*C++98 UB*/ diag:: 3527 ext_old_implicitly_unsigned_long_cxx 3528 : diag::warn_old_implicitly_unsigned_long) 3529 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3530 : /*will be ill-formed*/ 1); 3531 Ty = Context.UnsignedLongTy; 3532 } 3533 Width = LongSize; 3534 } 3535 } 3536 3537 // Check long long if needed. 3538 if (Ty.isNull()) { 3539 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3540 3541 // Does it fit in a unsigned long long? 3542 if (ResultVal.isIntN(LongLongSize)) { 3543 // Does it fit in a signed long long? 3544 // To be compatible with MSVC, hex integer literals ending with the 3545 // LL or i64 suffix are always signed in Microsoft mode. 3546 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3547 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3548 Ty = Context.LongLongTy; 3549 else if (AllowUnsigned) 3550 Ty = Context.UnsignedLongLongTy; 3551 Width = LongLongSize; 3552 } 3553 } 3554 3555 // If we still couldn't decide a type, we probably have something that 3556 // does not fit in a signed long long, but has no U suffix. 3557 if (Ty.isNull()) { 3558 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3559 Ty = Context.UnsignedLongLongTy; 3560 Width = Context.getTargetInfo().getLongLongWidth(); 3561 } 3562 3563 if (ResultVal.getBitWidth() != Width) 3564 ResultVal = ResultVal.trunc(Width); 3565 } 3566 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3567 } 3568 3569 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3570 if (Literal.isImaginary) 3571 Res = new (Context) ImaginaryLiteral(Res, 3572 Context.getComplexType(Res->getType())); 3573 3574 return Res; 3575 } 3576 3577 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3578 assert(E && "ActOnParenExpr() missing expr"); 3579 return new (Context) ParenExpr(L, R, E); 3580 } 3581 3582 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3583 SourceLocation Loc, 3584 SourceRange ArgRange) { 3585 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3586 // scalar or vector data type argument..." 3587 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3588 // type (C99 6.2.5p18) or void. 3589 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3590 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3591 << T << ArgRange; 3592 return true; 3593 } 3594 3595 assert((T->isVoidType() || !T->isIncompleteType()) && 3596 "Scalar types should always be complete"); 3597 return false; 3598 } 3599 3600 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3601 SourceLocation Loc, 3602 SourceRange ArgRange, 3603 UnaryExprOrTypeTrait TraitKind) { 3604 // Invalid types must be hard errors for SFINAE in C++. 3605 if (S.LangOpts.CPlusPlus) 3606 return true; 3607 3608 // C99 6.5.3.4p1: 3609 if (T->isFunctionType() && 3610 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3611 // sizeof(function)/alignof(function) is allowed as an extension. 3612 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3613 << TraitKind << ArgRange; 3614 return false; 3615 } 3616 3617 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3618 // this is an error (OpenCL v1.1 s6.3.k) 3619 if (T->isVoidType()) { 3620 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3621 : diag::ext_sizeof_alignof_void_type; 3622 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3623 return false; 3624 } 3625 3626 return true; 3627 } 3628 3629 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3630 SourceLocation Loc, 3631 SourceRange ArgRange, 3632 UnaryExprOrTypeTrait TraitKind) { 3633 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3634 // runtime doesn't allow it. 3635 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3636 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3637 << T << (TraitKind == UETT_SizeOf) 3638 << ArgRange; 3639 return true; 3640 } 3641 3642 return false; 3643 } 3644 3645 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3646 /// pointer type is equal to T) and emit a warning if it is. 3647 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3648 Expr *E) { 3649 // Don't warn if the operation changed the type. 3650 if (T != E->getType()) 3651 return; 3652 3653 // Now look for array decays. 3654 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3655 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3656 return; 3657 3658 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3659 << ICE->getType() 3660 << ICE->getSubExpr()->getType(); 3661 } 3662 3663 /// \brief Check the constraints on expression operands to unary type expression 3664 /// and type traits. 3665 /// 3666 /// Completes any types necessary and validates the constraints on the operand 3667 /// expression. The logic mostly mirrors the type-based overload, but may modify 3668 /// the expression as it completes the type for that expression through template 3669 /// instantiation, etc. 3670 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3671 UnaryExprOrTypeTrait ExprKind) { 3672 QualType ExprTy = E->getType(); 3673 assert(!ExprTy->isReferenceType()); 3674 3675 if (ExprKind == UETT_VecStep) 3676 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3677 E->getSourceRange()); 3678 3679 // Whitelist some types as extensions 3680 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3681 E->getSourceRange(), ExprKind)) 3682 return false; 3683 3684 // 'alignof' applied to an expression only requires the base element type of 3685 // the expression to be complete. 'sizeof' requires the expression's type to 3686 // be complete (and will attempt to complete it if it's an array of unknown 3687 // bound). 3688 if (ExprKind == UETT_AlignOf) { 3689 if (RequireCompleteType(E->getExprLoc(), 3690 Context.getBaseElementType(E->getType()), 3691 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3692 E->getSourceRange())) 3693 return true; 3694 } else { 3695 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3696 ExprKind, E->getSourceRange())) 3697 return true; 3698 } 3699 3700 // Completing the expression's type may have changed it. 3701 ExprTy = E->getType(); 3702 assert(!ExprTy->isReferenceType()); 3703 3704 if (ExprTy->isFunctionType()) { 3705 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3706 << ExprKind << E->getSourceRange(); 3707 return true; 3708 } 3709 3710 // The operand for sizeof and alignof is in an unevaluated expression context, 3711 // so side effects could result in unintended consequences. 3712 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3713 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3714 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3715 3716 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3717 E->getSourceRange(), ExprKind)) 3718 return true; 3719 3720 if (ExprKind == UETT_SizeOf) { 3721 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3722 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3723 QualType OType = PVD->getOriginalType(); 3724 QualType Type = PVD->getType(); 3725 if (Type->isPointerType() && OType->isArrayType()) { 3726 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3727 << Type << OType; 3728 Diag(PVD->getLocation(), diag::note_declared_at); 3729 } 3730 } 3731 } 3732 3733 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3734 // decays into a pointer and returns an unintended result. This is most 3735 // likely a typo for "sizeof(array) op x". 3736 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3737 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3738 BO->getLHS()); 3739 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3740 BO->getRHS()); 3741 } 3742 } 3743 3744 return false; 3745 } 3746 3747 /// \brief Check the constraints on operands to unary expression and type 3748 /// traits. 3749 /// 3750 /// This will complete any types necessary, and validate the various constraints 3751 /// on those operands. 3752 /// 3753 /// The UsualUnaryConversions() function is *not* called by this routine. 3754 /// C99 6.3.2.1p[2-4] all state: 3755 /// Except when it is the operand of the sizeof operator ... 3756 /// 3757 /// C++ [expr.sizeof]p4 3758 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3759 /// standard conversions are not applied to the operand of sizeof. 3760 /// 3761 /// This policy is followed for all of the unary trait expressions. 3762 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3763 SourceLocation OpLoc, 3764 SourceRange ExprRange, 3765 UnaryExprOrTypeTrait ExprKind) { 3766 if (ExprType->isDependentType()) 3767 return false; 3768 3769 // C++ [expr.sizeof]p2: 3770 // When applied to a reference or a reference type, the result 3771 // is the size of the referenced type. 3772 // C++11 [expr.alignof]p3: 3773 // When alignof is applied to a reference type, the result 3774 // shall be the alignment of the referenced type. 3775 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3776 ExprType = Ref->getPointeeType(); 3777 3778 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3779 // When alignof or _Alignof is applied to an array type, the result 3780 // is the alignment of the element type. 3781 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3782 ExprType = Context.getBaseElementType(ExprType); 3783 3784 if (ExprKind == UETT_VecStep) 3785 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3786 3787 // Whitelist some types as extensions 3788 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3789 ExprKind)) 3790 return false; 3791 3792 if (RequireCompleteType(OpLoc, ExprType, 3793 diag::err_sizeof_alignof_incomplete_type, 3794 ExprKind, ExprRange)) 3795 return true; 3796 3797 if (ExprType->isFunctionType()) { 3798 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3799 << ExprKind << ExprRange; 3800 return true; 3801 } 3802 3803 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3804 ExprKind)) 3805 return true; 3806 3807 return false; 3808 } 3809 3810 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3811 E = E->IgnoreParens(); 3812 3813 // Cannot know anything else if the expression is dependent. 3814 if (E->isTypeDependent()) 3815 return false; 3816 3817 if (E->getObjectKind() == OK_BitField) { 3818 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3819 << 1 << E->getSourceRange(); 3820 return true; 3821 } 3822 3823 ValueDecl *D = nullptr; 3824 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3825 D = DRE->getDecl(); 3826 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3827 D = ME->getMemberDecl(); 3828 } 3829 3830 // If it's a field, require the containing struct to have a 3831 // complete definition so that we can compute the layout. 3832 // 3833 // This can happen in C++11 onwards, either by naming the member 3834 // in a way that is not transformed into a member access expression 3835 // (in an unevaluated operand, for instance), or by naming the member 3836 // in a trailing-return-type. 3837 // 3838 // For the record, since __alignof__ on expressions is a GCC 3839 // extension, GCC seems to permit this but always gives the 3840 // nonsensical answer 0. 3841 // 3842 // We don't really need the layout here --- we could instead just 3843 // directly check for all the appropriate alignment-lowing 3844 // attributes --- but that would require duplicating a lot of 3845 // logic that just isn't worth duplicating for such a marginal 3846 // use-case. 3847 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3848 // Fast path this check, since we at least know the record has a 3849 // definition if we can find a member of it. 3850 if (!FD->getParent()->isCompleteDefinition()) { 3851 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3852 << E->getSourceRange(); 3853 return true; 3854 } 3855 3856 // Otherwise, if it's a field, and the field doesn't have 3857 // reference type, then it must have a complete type (or be a 3858 // flexible array member, which we explicitly want to 3859 // white-list anyway), which makes the following checks trivial. 3860 if (!FD->getType()->isReferenceType()) 3861 return false; 3862 } 3863 3864 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3865 } 3866 3867 bool Sema::CheckVecStepExpr(Expr *E) { 3868 E = E->IgnoreParens(); 3869 3870 // Cannot know anything else if the expression is dependent. 3871 if (E->isTypeDependent()) 3872 return false; 3873 3874 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3875 } 3876 3877 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3878 CapturingScopeInfo *CSI) { 3879 assert(T->isVariablyModifiedType()); 3880 assert(CSI != nullptr); 3881 3882 // We're going to walk down into the type and look for VLA expressions. 3883 do { 3884 const Type *Ty = T.getTypePtr(); 3885 switch (Ty->getTypeClass()) { 3886 #define TYPE(Class, Base) 3887 #define ABSTRACT_TYPE(Class, Base) 3888 #define NON_CANONICAL_TYPE(Class, Base) 3889 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3890 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3891 #include "clang/AST/TypeNodes.def" 3892 T = QualType(); 3893 break; 3894 // These types are never variably-modified. 3895 case Type::Builtin: 3896 case Type::Complex: 3897 case Type::Vector: 3898 case Type::ExtVector: 3899 case Type::Record: 3900 case Type::Enum: 3901 case Type::Elaborated: 3902 case Type::TemplateSpecialization: 3903 case Type::ObjCObject: 3904 case Type::ObjCInterface: 3905 case Type::ObjCObjectPointer: 3906 case Type::ObjCTypeParam: 3907 case Type::Pipe: 3908 llvm_unreachable("type class is never variably-modified!"); 3909 case Type::Adjusted: 3910 T = cast<AdjustedType>(Ty)->getOriginalType(); 3911 break; 3912 case Type::Decayed: 3913 T = cast<DecayedType>(Ty)->getPointeeType(); 3914 break; 3915 case Type::Pointer: 3916 T = cast<PointerType>(Ty)->getPointeeType(); 3917 break; 3918 case Type::BlockPointer: 3919 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3920 break; 3921 case Type::LValueReference: 3922 case Type::RValueReference: 3923 T = cast<ReferenceType>(Ty)->getPointeeType(); 3924 break; 3925 case Type::MemberPointer: 3926 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3927 break; 3928 case Type::ConstantArray: 3929 case Type::IncompleteArray: 3930 // Losing element qualification here is fine. 3931 T = cast<ArrayType>(Ty)->getElementType(); 3932 break; 3933 case Type::VariableArray: { 3934 // Losing element qualification here is fine. 3935 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3936 3937 // Unknown size indication requires no size computation. 3938 // Otherwise, evaluate and record it. 3939 if (auto Size = VAT->getSizeExpr()) { 3940 if (!CSI->isVLATypeCaptured(VAT)) { 3941 RecordDecl *CapRecord = nullptr; 3942 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3943 CapRecord = LSI->Lambda; 3944 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3945 CapRecord = CRSI->TheRecordDecl; 3946 } 3947 if (CapRecord) { 3948 auto ExprLoc = Size->getExprLoc(); 3949 auto SizeType = Context.getSizeType(); 3950 // Build the non-static data member. 3951 auto Field = 3952 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3953 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3954 /*BW*/ nullptr, /*Mutable*/ false, 3955 /*InitStyle*/ ICIS_NoInit); 3956 Field->setImplicit(true); 3957 Field->setAccess(AS_private); 3958 Field->setCapturedVLAType(VAT); 3959 CapRecord->addDecl(Field); 3960 3961 CSI->addVLATypeCapture(ExprLoc, SizeType); 3962 } 3963 } 3964 } 3965 T = VAT->getElementType(); 3966 break; 3967 } 3968 case Type::FunctionProto: 3969 case Type::FunctionNoProto: 3970 T = cast<FunctionType>(Ty)->getReturnType(); 3971 break; 3972 case Type::Paren: 3973 case Type::TypeOf: 3974 case Type::UnaryTransform: 3975 case Type::Attributed: 3976 case Type::SubstTemplateTypeParm: 3977 case Type::PackExpansion: 3978 // Keep walking after single level desugaring. 3979 T = T.getSingleStepDesugaredType(Context); 3980 break; 3981 case Type::Typedef: 3982 T = cast<TypedefType>(Ty)->desugar(); 3983 break; 3984 case Type::Decltype: 3985 T = cast<DecltypeType>(Ty)->desugar(); 3986 break; 3987 case Type::Auto: 3988 case Type::DeducedTemplateSpecialization: 3989 T = cast<DeducedType>(Ty)->getDeducedType(); 3990 break; 3991 case Type::TypeOfExpr: 3992 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3993 break; 3994 case Type::Atomic: 3995 T = cast<AtomicType>(Ty)->getValueType(); 3996 break; 3997 } 3998 } while (!T.isNull() && T->isVariablyModifiedType()); 3999 } 4000 4001 /// \brief Build a sizeof or alignof expression given a type operand. 4002 ExprResult 4003 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4004 SourceLocation OpLoc, 4005 UnaryExprOrTypeTrait ExprKind, 4006 SourceRange R) { 4007 if (!TInfo) 4008 return ExprError(); 4009 4010 QualType T = TInfo->getType(); 4011 4012 if (!T->isDependentType() && 4013 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4014 return ExprError(); 4015 4016 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4017 if (auto *TT = T->getAs<TypedefType>()) { 4018 for (auto I = FunctionScopes.rbegin(), 4019 E = std::prev(FunctionScopes.rend()); 4020 I != E; ++I) { 4021 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4022 if (CSI == nullptr) 4023 break; 4024 DeclContext *DC = nullptr; 4025 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4026 DC = LSI->CallOperator; 4027 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4028 DC = CRSI->TheCapturedDecl; 4029 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4030 DC = BSI->TheDecl; 4031 if (DC) { 4032 if (DC->containsDecl(TT->getDecl())) 4033 break; 4034 captureVariablyModifiedType(Context, T, CSI); 4035 } 4036 } 4037 } 4038 } 4039 4040 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4041 return new (Context) UnaryExprOrTypeTraitExpr( 4042 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4043 } 4044 4045 /// \brief Build a sizeof or alignof expression given an expression 4046 /// operand. 4047 ExprResult 4048 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4049 UnaryExprOrTypeTrait ExprKind) { 4050 ExprResult PE = CheckPlaceholderExpr(E); 4051 if (PE.isInvalid()) 4052 return ExprError(); 4053 4054 E = PE.get(); 4055 4056 // Verify that the operand is valid. 4057 bool isInvalid = false; 4058 if (E->isTypeDependent()) { 4059 // Delay type-checking for type-dependent expressions. 4060 } else if (ExprKind == UETT_AlignOf) { 4061 isInvalid = CheckAlignOfExpr(*this, E); 4062 } else if (ExprKind == UETT_VecStep) { 4063 isInvalid = CheckVecStepExpr(E); 4064 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4065 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4066 isInvalid = true; 4067 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4068 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4069 isInvalid = true; 4070 } else { 4071 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4072 } 4073 4074 if (isInvalid) 4075 return ExprError(); 4076 4077 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4078 PE = TransformToPotentiallyEvaluated(E); 4079 if (PE.isInvalid()) return ExprError(); 4080 E = PE.get(); 4081 } 4082 4083 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4084 return new (Context) UnaryExprOrTypeTraitExpr( 4085 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4086 } 4087 4088 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4089 /// expr and the same for @c alignof and @c __alignof 4090 /// Note that the ArgRange is invalid if isType is false. 4091 ExprResult 4092 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4093 UnaryExprOrTypeTrait ExprKind, bool IsType, 4094 void *TyOrEx, SourceRange ArgRange) { 4095 // If error parsing type, ignore. 4096 if (!TyOrEx) return ExprError(); 4097 4098 if (IsType) { 4099 TypeSourceInfo *TInfo; 4100 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4101 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4102 } 4103 4104 Expr *ArgEx = (Expr *)TyOrEx; 4105 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4106 return Result; 4107 } 4108 4109 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4110 bool IsReal) { 4111 if (V.get()->isTypeDependent()) 4112 return S.Context.DependentTy; 4113 4114 // _Real and _Imag are only l-values for normal l-values. 4115 if (V.get()->getObjectKind() != OK_Ordinary) { 4116 V = S.DefaultLvalueConversion(V.get()); 4117 if (V.isInvalid()) 4118 return QualType(); 4119 } 4120 4121 // These operators return the element type of a complex type. 4122 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4123 return CT->getElementType(); 4124 4125 // Otherwise they pass through real integer and floating point types here. 4126 if (V.get()->getType()->isArithmeticType()) 4127 return V.get()->getType(); 4128 4129 // Test for placeholders. 4130 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4131 if (PR.isInvalid()) return QualType(); 4132 if (PR.get() != V.get()) { 4133 V = PR; 4134 return CheckRealImagOperand(S, V, Loc, IsReal); 4135 } 4136 4137 // Reject anything else. 4138 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4139 << (IsReal ? "__real" : "__imag"); 4140 return QualType(); 4141 } 4142 4143 4144 4145 ExprResult 4146 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4147 tok::TokenKind Kind, Expr *Input) { 4148 UnaryOperatorKind Opc; 4149 switch (Kind) { 4150 default: llvm_unreachable("Unknown unary op!"); 4151 case tok::plusplus: Opc = UO_PostInc; break; 4152 case tok::minusminus: Opc = UO_PostDec; break; 4153 } 4154 4155 // Since this might is a postfix expression, get rid of ParenListExprs. 4156 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4157 if (Result.isInvalid()) return ExprError(); 4158 Input = Result.get(); 4159 4160 return BuildUnaryOp(S, OpLoc, Opc, Input); 4161 } 4162 4163 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4164 /// 4165 /// \return true on error 4166 static bool checkArithmeticOnObjCPointer(Sema &S, 4167 SourceLocation opLoc, 4168 Expr *op) { 4169 assert(op->getType()->isObjCObjectPointerType()); 4170 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4171 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4172 return false; 4173 4174 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4175 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4176 << op->getSourceRange(); 4177 return true; 4178 } 4179 4180 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4181 auto *BaseNoParens = Base->IgnoreParens(); 4182 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4183 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4184 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4185 } 4186 4187 ExprResult 4188 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4189 Expr *idx, SourceLocation rbLoc) { 4190 if (base && !base->getType().isNull() && 4191 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4192 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4193 /*Length=*/nullptr, rbLoc); 4194 4195 // Since this might be a postfix expression, get rid of ParenListExprs. 4196 if (isa<ParenListExpr>(base)) { 4197 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4198 if (result.isInvalid()) return ExprError(); 4199 base = result.get(); 4200 } 4201 4202 // Handle any non-overload placeholder types in the base and index 4203 // expressions. We can't handle overloads here because the other 4204 // operand might be an overloadable type, in which case the overload 4205 // resolution for the operator overload should get the first crack 4206 // at the overload. 4207 bool IsMSPropertySubscript = false; 4208 if (base->getType()->isNonOverloadPlaceholderType()) { 4209 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4210 if (!IsMSPropertySubscript) { 4211 ExprResult result = CheckPlaceholderExpr(base); 4212 if (result.isInvalid()) 4213 return ExprError(); 4214 base = result.get(); 4215 } 4216 } 4217 if (idx->getType()->isNonOverloadPlaceholderType()) { 4218 ExprResult result = CheckPlaceholderExpr(idx); 4219 if (result.isInvalid()) return ExprError(); 4220 idx = result.get(); 4221 } 4222 4223 // Build an unanalyzed expression if either operand is type-dependent. 4224 if (getLangOpts().CPlusPlus && 4225 (base->isTypeDependent() || idx->isTypeDependent())) { 4226 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4227 VK_LValue, OK_Ordinary, rbLoc); 4228 } 4229 4230 // MSDN, property (C++) 4231 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4232 // This attribute can also be used in the declaration of an empty array in a 4233 // class or structure definition. For example: 4234 // __declspec(property(get=GetX, put=PutX)) int x[]; 4235 // The above statement indicates that x[] can be used with one or more array 4236 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4237 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4238 if (IsMSPropertySubscript) { 4239 // Build MS property subscript expression if base is MS property reference 4240 // or MS property subscript. 4241 return new (Context) MSPropertySubscriptExpr( 4242 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4243 } 4244 4245 // Use C++ overloaded-operator rules if either operand has record 4246 // type. The spec says to do this if either type is *overloadable*, 4247 // but enum types can't declare subscript operators or conversion 4248 // operators, so there's nothing interesting for overload resolution 4249 // to do if there aren't any record types involved. 4250 // 4251 // ObjC pointers have their own subscripting logic that is not tied 4252 // to overload resolution and so should not take this path. 4253 if (getLangOpts().CPlusPlus && 4254 (base->getType()->isRecordType() || 4255 (!base->getType()->isObjCObjectPointerType() && 4256 idx->getType()->isRecordType()))) { 4257 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4258 } 4259 4260 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4261 } 4262 4263 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4264 Expr *LowerBound, 4265 SourceLocation ColonLoc, Expr *Length, 4266 SourceLocation RBLoc) { 4267 if (Base->getType()->isPlaceholderType() && 4268 !Base->getType()->isSpecificPlaceholderType( 4269 BuiltinType::OMPArraySection)) { 4270 ExprResult Result = CheckPlaceholderExpr(Base); 4271 if (Result.isInvalid()) 4272 return ExprError(); 4273 Base = Result.get(); 4274 } 4275 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4276 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4277 if (Result.isInvalid()) 4278 return ExprError(); 4279 Result = DefaultLvalueConversion(Result.get()); 4280 if (Result.isInvalid()) 4281 return ExprError(); 4282 LowerBound = Result.get(); 4283 } 4284 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4285 ExprResult Result = CheckPlaceholderExpr(Length); 4286 if (Result.isInvalid()) 4287 return ExprError(); 4288 Result = DefaultLvalueConversion(Result.get()); 4289 if (Result.isInvalid()) 4290 return ExprError(); 4291 Length = Result.get(); 4292 } 4293 4294 // Build an unanalyzed expression if either operand is type-dependent. 4295 if (Base->isTypeDependent() || 4296 (LowerBound && 4297 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4298 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4299 return new (Context) 4300 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4301 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4302 } 4303 4304 // Perform default conversions. 4305 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4306 QualType ResultTy; 4307 if (OriginalTy->isAnyPointerType()) { 4308 ResultTy = OriginalTy->getPointeeType(); 4309 } else if (OriginalTy->isArrayType()) { 4310 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4311 } else { 4312 return ExprError( 4313 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4314 << Base->getSourceRange()); 4315 } 4316 // C99 6.5.2.1p1 4317 if (LowerBound) { 4318 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4319 LowerBound); 4320 if (Res.isInvalid()) 4321 return ExprError(Diag(LowerBound->getExprLoc(), 4322 diag::err_omp_typecheck_section_not_integer) 4323 << 0 << LowerBound->getSourceRange()); 4324 LowerBound = Res.get(); 4325 4326 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4327 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4328 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4329 << 0 << LowerBound->getSourceRange(); 4330 } 4331 if (Length) { 4332 auto Res = 4333 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4334 if (Res.isInvalid()) 4335 return ExprError(Diag(Length->getExprLoc(), 4336 diag::err_omp_typecheck_section_not_integer) 4337 << 1 << Length->getSourceRange()); 4338 Length = Res.get(); 4339 4340 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4341 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4342 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4343 << 1 << Length->getSourceRange(); 4344 } 4345 4346 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4347 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4348 // type. Note that functions are not objects, and that (in C99 parlance) 4349 // incomplete types are not object types. 4350 if (ResultTy->isFunctionType()) { 4351 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4352 << ResultTy << Base->getSourceRange(); 4353 return ExprError(); 4354 } 4355 4356 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4357 diag::err_omp_section_incomplete_type, Base)) 4358 return ExprError(); 4359 4360 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4361 llvm::APSInt LowerBoundValue; 4362 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4363 // OpenMP 4.5, [2.4 Array Sections] 4364 // The array section must be a subset of the original array. 4365 if (LowerBoundValue.isNegative()) { 4366 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4367 << LowerBound->getSourceRange(); 4368 return ExprError(); 4369 } 4370 } 4371 } 4372 4373 if (Length) { 4374 llvm::APSInt LengthValue; 4375 if (Length->EvaluateAsInt(LengthValue, Context)) { 4376 // OpenMP 4.5, [2.4 Array Sections] 4377 // The length must evaluate to non-negative integers. 4378 if (LengthValue.isNegative()) { 4379 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4380 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4381 << Length->getSourceRange(); 4382 return ExprError(); 4383 } 4384 } 4385 } else if (ColonLoc.isValid() && 4386 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4387 !OriginalTy->isVariableArrayType()))) { 4388 // OpenMP 4.5, [2.4 Array Sections] 4389 // When the size of the array dimension is not known, the length must be 4390 // specified explicitly. 4391 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4392 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4393 return ExprError(); 4394 } 4395 4396 if (!Base->getType()->isSpecificPlaceholderType( 4397 BuiltinType::OMPArraySection)) { 4398 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4399 if (Result.isInvalid()) 4400 return ExprError(); 4401 Base = Result.get(); 4402 } 4403 return new (Context) 4404 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4405 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4406 } 4407 4408 ExprResult 4409 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4410 Expr *Idx, SourceLocation RLoc) { 4411 Expr *LHSExp = Base; 4412 Expr *RHSExp = Idx; 4413 4414 ExprValueKind VK = VK_LValue; 4415 ExprObjectKind OK = OK_Ordinary; 4416 4417 // Per C++ core issue 1213, the result is an xvalue if either operand is 4418 // a non-lvalue array, and an lvalue otherwise. 4419 if (getLangOpts().CPlusPlus11 && 4420 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4421 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4422 VK = VK_XValue; 4423 4424 // Perform default conversions. 4425 if (!LHSExp->getType()->getAs<VectorType>()) { 4426 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4427 if (Result.isInvalid()) 4428 return ExprError(); 4429 LHSExp = Result.get(); 4430 } 4431 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4432 if (Result.isInvalid()) 4433 return ExprError(); 4434 RHSExp = Result.get(); 4435 4436 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4437 4438 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4439 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4440 // in the subscript position. As a result, we need to derive the array base 4441 // and index from the expression types. 4442 Expr *BaseExpr, *IndexExpr; 4443 QualType ResultType; 4444 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4445 BaseExpr = LHSExp; 4446 IndexExpr = RHSExp; 4447 ResultType = Context.DependentTy; 4448 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4449 BaseExpr = LHSExp; 4450 IndexExpr = RHSExp; 4451 ResultType = PTy->getPointeeType(); 4452 } else if (const ObjCObjectPointerType *PTy = 4453 LHSTy->getAs<ObjCObjectPointerType>()) { 4454 BaseExpr = LHSExp; 4455 IndexExpr = RHSExp; 4456 4457 // Use custom logic if this should be the pseudo-object subscript 4458 // expression. 4459 if (!LangOpts.isSubscriptPointerArithmetic()) 4460 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4461 nullptr); 4462 4463 ResultType = PTy->getPointeeType(); 4464 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4465 // Handle the uncommon case of "123[Ptr]". 4466 BaseExpr = RHSExp; 4467 IndexExpr = LHSExp; 4468 ResultType = PTy->getPointeeType(); 4469 } else if (const ObjCObjectPointerType *PTy = 4470 RHSTy->getAs<ObjCObjectPointerType>()) { 4471 // Handle the uncommon case of "123[Ptr]". 4472 BaseExpr = RHSExp; 4473 IndexExpr = LHSExp; 4474 ResultType = PTy->getPointeeType(); 4475 if (!LangOpts.isSubscriptPointerArithmetic()) { 4476 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4477 << ResultType << BaseExpr->getSourceRange(); 4478 return ExprError(); 4479 } 4480 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4481 BaseExpr = LHSExp; // vectors: V[123] 4482 IndexExpr = RHSExp; 4483 VK = LHSExp->getValueKind(); 4484 if (VK != VK_RValue) 4485 OK = OK_VectorComponent; 4486 4487 // FIXME: need to deal with const... 4488 ResultType = VTy->getElementType(); 4489 } else if (LHSTy->isArrayType()) { 4490 // If we see an array that wasn't promoted by 4491 // DefaultFunctionArrayLvalueConversion, it must be an array that 4492 // wasn't promoted because of the C90 rule that doesn't 4493 // allow promoting non-lvalue arrays. Warn, then 4494 // force the promotion here. 4495 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4496 LHSExp->getSourceRange(); 4497 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4498 CK_ArrayToPointerDecay).get(); 4499 LHSTy = LHSExp->getType(); 4500 4501 BaseExpr = LHSExp; 4502 IndexExpr = RHSExp; 4503 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4504 } else if (RHSTy->isArrayType()) { 4505 // Same as previous, except for 123[f().a] case 4506 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4507 RHSExp->getSourceRange(); 4508 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4509 CK_ArrayToPointerDecay).get(); 4510 RHSTy = RHSExp->getType(); 4511 4512 BaseExpr = RHSExp; 4513 IndexExpr = LHSExp; 4514 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4515 } else { 4516 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4517 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4518 } 4519 // C99 6.5.2.1p1 4520 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4521 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4522 << IndexExpr->getSourceRange()); 4523 4524 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4525 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4526 && !IndexExpr->isTypeDependent()) 4527 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4528 4529 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4530 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4531 // type. Note that Functions are not objects, and that (in C99 parlance) 4532 // incomplete types are not object types. 4533 if (ResultType->isFunctionType()) { 4534 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4535 << ResultType << BaseExpr->getSourceRange(); 4536 return ExprError(); 4537 } 4538 4539 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4540 // GNU extension: subscripting on pointer to void 4541 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4542 << BaseExpr->getSourceRange(); 4543 4544 // C forbids expressions of unqualified void type from being l-values. 4545 // See IsCForbiddenLValueType. 4546 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4547 } else if (!ResultType->isDependentType() && 4548 RequireCompleteType(LLoc, ResultType, 4549 diag::err_subscript_incomplete_type, BaseExpr)) 4550 return ExprError(); 4551 4552 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4553 !ResultType.isCForbiddenLValueType()); 4554 4555 return new (Context) 4556 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4557 } 4558 4559 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4560 ParmVarDecl *Param) { 4561 if (Param->hasUnparsedDefaultArg()) { 4562 Diag(CallLoc, 4563 diag::err_use_of_default_argument_to_function_declared_later) << 4564 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4565 Diag(UnparsedDefaultArgLocs[Param], 4566 diag::note_default_argument_declared_here); 4567 return true; 4568 } 4569 4570 if (Param->hasUninstantiatedDefaultArg()) { 4571 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4572 4573 EnterExpressionEvaluationContext EvalContext( 4574 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4575 4576 // Instantiate the expression. 4577 MultiLevelTemplateArgumentList MutiLevelArgList 4578 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4579 4580 InstantiatingTemplate Inst(*this, CallLoc, Param, 4581 MutiLevelArgList.getInnermost()); 4582 if (Inst.isInvalid()) 4583 return true; 4584 if (Inst.isAlreadyInstantiating()) { 4585 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4586 Param->setInvalidDecl(); 4587 return true; 4588 } 4589 4590 ExprResult Result; 4591 { 4592 // C++ [dcl.fct.default]p5: 4593 // The names in the [default argument] expression are bound, and 4594 // the semantic constraints are checked, at the point where the 4595 // default argument expression appears. 4596 ContextRAII SavedContext(*this, FD); 4597 LocalInstantiationScope Local(*this); 4598 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4599 /*DirectInit*/false); 4600 } 4601 if (Result.isInvalid()) 4602 return true; 4603 4604 // Check the expression as an initializer for the parameter. 4605 InitializedEntity Entity 4606 = InitializedEntity::InitializeParameter(Context, Param); 4607 InitializationKind Kind 4608 = InitializationKind::CreateCopy(Param->getLocation(), 4609 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4610 Expr *ResultE = Result.getAs<Expr>(); 4611 4612 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4613 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4614 if (Result.isInvalid()) 4615 return true; 4616 4617 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4618 Param->getOuterLocStart()); 4619 if (Result.isInvalid()) 4620 return true; 4621 4622 // Remember the instantiated default argument. 4623 Param->setDefaultArg(Result.getAs<Expr>()); 4624 if (ASTMutationListener *L = getASTMutationListener()) { 4625 L->DefaultArgumentInstantiated(Param); 4626 } 4627 } 4628 4629 // If the default argument expression is not set yet, we are building it now. 4630 if (!Param->hasInit()) { 4631 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4632 Param->setInvalidDecl(); 4633 return true; 4634 } 4635 4636 // If the default expression creates temporaries, we need to 4637 // push them to the current stack of expression temporaries so they'll 4638 // be properly destroyed. 4639 // FIXME: We should really be rebuilding the default argument with new 4640 // bound temporaries; see the comment in PR5810. 4641 // We don't need to do that with block decls, though, because 4642 // blocks in default argument expression can never capture anything. 4643 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4644 // Set the "needs cleanups" bit regardless of whether there are 4645 // any explicit objects. 4646 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4647 4648 // Append all the objects to the cleanup list. Right now, this 4649 // should always be a no-op, because blocks in default argument 4650 // expressions should never be able to capture anything. 4651 assert(!Init->getNumObjects() && 4652 "default argument expression has capturing blocks?"); 4653 } 4654 4655 // We already type-checked the argument, so we know it works. 4656 // Just mark all of the declarations in this potentially-evaluated expression 4657 // as being "referenced". 4658 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4659 /*SkipLocalVariables=*/true); 4660 return false; 4661 } 4662 4663 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4664 FunctionDecl *FD, ParmVarDecl *Param) { 4665 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4666 return ExprError(); 4667 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4668 } 4669 4670 Sema::VariadicCallType 4671 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4672 Expr *Fn) { 4673 if (Proto && Proto->isVariadic()) { 4674 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4675 return VariadicConstructor; 4676 else if (Fn && Fn->getType()->isBlockPointerType()) 4677 return VariadicBlock; 4678 else if (FDecl) { 4679 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4680 if (Method->isInstance()) 4681 return VariadicMethod; 4682 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4683 return VariadicMethod; 4684 return VariadicFunction; 4685 } 4686 return VariadicDoesNotApply; 4687 } 4688 4689 namespace { 4690 class FunctionCallCCC : public FunctionCallFilterCCC { 4691 public: 4692 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4693 unsigned NumArgs, MemberExpr *ME) 4694 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4695 FunctionName(FuncName) {} 4696 4697 bool ValidateCandidate(const TypoCorrection &candidate) override { 4698 if (!candidate.getCorrectionSpecifier() || 4699 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4700 return false; 4701 } 4702 4703 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4704 } 4705 4706 private: 4707 const IdentifierInfo *const FunctionName; 4708 }; 4709 } 4710 4711 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4712 FunctionDecl *FDecl, 4713 ArrayRef<Expr *> Args) { 4714 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4715 DeclarationName FuncName = FDecl->getDeclName(); 4716 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4717 4718 if (TypoCorrection Corrected = S.CorrectTypo( 4719 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4720 S.getScopeForContext(S.CurContext), nullptr, 4721 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4722 Args.size(), ME), 4723 Sema::CTK_ErrorRecovery)) { 4724 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4725 if (Corrected.isOverloaded()) { 4726 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4727 OverloadCandidateSet::iterator Best; 4728 for (NamedDecl *CD : Corrected) { 4729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4730 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4731 OCS); 4732 } 4733 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4734 case OR_Success: 4735 ND = Best->FoundDecl; 4736 Corrected.setCorrectionDecl(ND); 4737 break; 4738 default: 4739 break; 4740 } 4741 } 4742 ND = ND->getUnderlyingDecl(); 4743 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4744 return Corrected; 4745 } 4746 } 4747 return TypoCorrection(); 4748 } 4749 4750 /// ConvertArgumentsForCall - Converts the arguments specified in 4751 /// Args/NumArgs to the parameter types of the function FDecl with 4752 /// function prototype Proto. Call is the call expression itself, and 4753 /// Fn is the function expression. For a C++ member function, this 4754 /// routine does not attempt to convert the object argument. Returns 4755 /// true if the call is ill-formed. 4756 bool 4757 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4758 FunctionDecl *FDecl, 4759 const FunctionProtoType *Proto, 4760 ArrayRef<Expr *> Args, 4761 SourceLocation RParenLoc, 4762 bool IsExecConfig) { 4763 // Bail out early if calling a builtin with custom typechecking. 4764 if (FDecl) 4765 if (unsigned ID = FDecl->getBuiltinID()) 4766 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4767 return false; 4768 4769 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4770 // assignment, to the types of the corresponding parameter, ... 4771 unsigned NumParams = Proto->getNumParams(); 4772 bool Invalid = false; 4773 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4774 unsigned FnKind = Fn->getType()->isBlockPointerType() 4775 ? 1 /* block */ 4776 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4777 : 0 /* function */); 4778 4779 // If too few arguments are available (and we don't have default 4780 // arguments for the remaining parameters), don't make the call. 4781 if (Args.size() < NumParams) { 4782 if (Args.size() < MinArgs) { 4783 TypoCorrection TC; 4784 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4785 unsigned diag_id = 4786 MinArgs == NumParams && !Proto->isVariadic() 4787 ? diag::err_typecheck_call_too_few_args_suggest 4788 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4789 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4790 << static_cast<unsigned>(Args.size()) 4791 << TC.getCorrectionRange()); 4792 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4793 Diag(RParenLoc, 4794 MinArgs == NumParams && !Proto->isVariadic() 4795 ? diag::err_typecheck_call_too_few_args_one 4796 : diag::err_typecheck_call_too_few_args_at_least_one) 4797 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4798 else 4799 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4800 ? diag::err_typecheck_call_too_few_args 4801 : diag::err_typecheck_call_too_few_args_at_least) 4802 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4803 << Fn->getSourceRange(); 4804 4805 // Emit the location of the prototype. 4806 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4807 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4808 << FDecl; 4809 4810 return true; 4811 } 4812 Call->setNumArgs(Context, NumParams); 4813 } 4814 4815 // If too many are passed and not variadic, error on the extras and drop 4816 // them. 4817 if (Args.size() > NumParams) { 4818 if (!Proto->isVariadic()) { 4819 TypoCorrection TC; 4820 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4821 unsigned diag_id = 4822 MinArgs == NumParams && !Proto->isVariadic() 4823 ? diag::err_typecheck_call_too_many_args_suggest 4824 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4825 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4826 << static_cast<unsigned>(Args.size()) 4827 << TC.getCorrectionRange()); 4828 } else if (NumParams == 1 && FDecl && 4829 FDecl->getParamDecl(0)->getDeclName()) 4830 Diag(Args[NumParams]->getLocStart(), 4831 MinArgs == NumParams 4832 ? diag::err_typecheck_call_too_many_args_one 4833 : diag::err_typecheck_call_too_many_args_at_most_one) 4834 << FnKind << FDecl->getParamDecl(0) 4835 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4836 << SourceRange(Args[NumParams]->getLocStart(), 4837 Args.back()->getLocEnd()); 4838 else 4839 Diag(Args[NumParams]->getLocStart(), 4840 MinArgs == NumParams 4841 ? diag::err_typecheck_call_too_many_args 4842 : diag::err_typecheck_call_too_many_args_at_most) 4843 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4844 << Fn->getSourceRange() 4845 << SourceRange(Args[NumParams]->getLocStart(), 4846 Args.back()->getLocEnd()); 4847 4848 // Emit the location of the prototype. 4849 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4850 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4851 << FDecl; 4852 4853 // This deletes the extra arguments. 4854 Call->setNumArgs(Context, NumParams); 4855 return true; 4856 } 4857 } 4858 SmallVector<Expr *, 8> AllArgs; 4859 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4860 4861 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4862 Proto, 0, Args, AllArgs, CallType); 4863 if (Invalid) 4864 return true; 4865 unsigned TotalNumArgs = AllArgs.size(); 4866 for (unsigned i = 0; i < TotalNumArgs; ++i) 4867 Call->setArg(i, AllArgs[i]); 4868 4869 return false; 4870 } 4871 4872 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4873 const FunctionProtoType *Proto, 4874 unsigned FirstParam, ArrayRef<Expr *> Args, 4875 SmallVectorImpl<Expr *> &AllArgs, 4876 VariadicCallType CallType, bool AllowExplicit, 4877 bool IsListInitialization) { 4878 unsigned NumParams = Proto->getNumParams(); 4879 bool Invalid = false; 4880 size_t ArgIx = 0; 4881 // Continue to check argument types (even if we have too few/many args). 4882 for (unsigned i = FirstParam; i < NumParams; i++) { 4883 QualType ProtoArgType = Proto->getParamType(i); 4884 4885 Expr *Arg; 4886 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4887 if (ArgIx < Args.size()) { 4888 Arg = Args[ArgIx++]; 4889 4890 if (RequireCompleteType(Arg->getLocStart(), 4891 ProtoArgType, 4892 diag::err_call_incomplete_argument, Arg)) 4893 return true; 4894 4895 // Strip the unbridged-cast placeholder expression off, if applicable. 4896 bool CFAudited = false; 4897 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4898 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4899 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4900 Arg = stripARCUnbridgedCast(Arg); 4901 else if (getLangOpts().ObjCAutoRefCount && 4902 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4903 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4904 CFAudited = true; 4905 4906 InitializedEntity Entity = 4907 Param ? InitializedEntity::InitializeParameter(Context, Param, 4908 ProtoArgType) 4909 : InitializedEntity::InitializeParameter( 4910 Context, ProtoArgType, Proto->isParamConsumed(i)); 4911 4912 // Remember that parameter belongs to a CF audited API. 4913 if (CFAudited) 4914 Entity.setParameterCFAudited(); 4915 4916 ExprResult ArgE = PerformCopyInitialization( 4917 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4918 if (ArgE.isInvalid()) 4919 return true; 4920 4921 Arg = ArgE.getAs<Expr>(); 4922 } else { 4923 assert(Param && "can't use default arguments without a known callee"); 4924 4925 ExprResult ArgExpr = 4926 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4927 if (ArgExpr.isInvalid()) 4928 return true; 4929 4930 Arg = ArgExpr.getAs<Expr>(); 4931 } 4932 4933 // Check for array bounds violations for each argument to the call. This 4934 // check only triggers warnings when the argument isn't a more complex Expr 4935 // with its own checking, such as a BinaryOperator. 4936 CheckArrayAccess(Arg); 4937 4938 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4939 CheckStaticArrayArgument(CallLoc, Param, Arg); 4940 4941 AllArgs.push_back(Arg); 4942 } 4943 4944 // If this is a variadic call, handle args passed through "...". 4945 if (CallType != VariadicDoesNotApply) { 4946 // Assume that extern "C" functions with variadic arguments that 4947 // return __unknown_anytype aren't *really* variadic. 4948 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4949 FDecl->isExternC()) { 4950 for (Expr *A : Args.slice(ArgIx)) { 4951 QualType paramType; // ignored 4952 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4953 Invalid |= arg.isInvalid(); 4954 AllArgs.push_back(arg.get()); 4955 } 4956 4957 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4958 } else { 4959 for (Expr *A : Args.slice(ArgIx)) { 4960 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4961 Invalid |= Arg.isInvalid(); 4962 AllArgs.push_back(Arg.get()); 4963 } 4964 } 4965 4966 // Check for array bounds violations. 4967 for (Expr *A : Args.slice(ArgIx)) 4968 CheckArrayAccess(A); 4969 } 4970 return Invalid; 4971 } 4972 4973 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4974 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4975 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4976 TL = DTL.getOriginalLoc(); 4977 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4978 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4979 << ATL.getLocalSourceRange(); 4980 } 4981 4982 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4983 /// array parameter, check that it is non-null, and that if it is formed by 4984 /// array-to-pointer decay, the underlying array is sufficiently large. 4985 /// 4986 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4987 /// array type derivation, then for each call to the function, the value of the 4988 /// corresponding actual argument shall provide access to the first element of 4989 /// an array with at least as many elements as specified by the size expression. 4990 void 4991 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4992 ParmVarDecl *Param, 4993 const Expr *ArgExpr) { 4994 // Static array parameters are not supported in C++. 4995 if (!Param || getLangOpts().CPlusPlus) 4996 return; 4997 4998 QualType OrigTy = Param->getOriginalType(); 4999 5000 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5001 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5002 return; 5003 5004 if (ArgExpr->isNullPointerConstant(Context, 5005 Expr::NPC_NeverValueDependent)) { 5006 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5007 DiagnoseCalleeStaticArrayParam(*this, Param); 5008 return; 5009 } 5010 5011 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5012 if (!CAT) 5013 return; 5014 5015 const ConstantArrayType *ArgCAT = 5016 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5017 if (!ArgCAT) 5018 return; 5019 5020 if (ArgCAT->getSize().ult(CAT->getSize())) { 5021 Diag(CallLoc, diag::warn_static_array_too_small) 5022 << ArgExpr->getSourceRange() 5023 << (unsigned) ArgCAT->getSize().getZExtValue() 5024 << (unsigned) CAT->getSize().getZExtValue(); 5025 DiagnoseCalleeStaticArrayParam(*this, Param); 5026 } 5027 } 5028 5029 /// Given a function expression of unknown-any type, try to rebuild it 5030 /// to have a function type. 5031 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5032 5033 /// Is the given type a placeholder that we need to lower out 5034 /// immediately during argument processing? 5035 static bool isPlaceholderToRemoveAsArg(QualType type) { 5036 // Placeholders are never sugared. 5037 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5038 if (!placeholder) return false; 5039 5040 switch (placeholder->getKind()) { 5041 // Ignore all the non-placeholder types. 5042 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5043 case BuiltinType::Id: 5044 #include "clang/Basic/OpenCLImageTypes.def" 5045 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5046 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5047 #include "clang/AST/BuiltinTypes.def" 5048 return false; 5049 5050 // We cannot lower out overload sets; they might validly be resolved 5051 // by the call machinery. 5052 case BuiltinType::Overload: 5053 return false; 5054 5055 // Unbridged casts in ARC can be handled in some call positions and 5056 // should be left in place. 5057 case BuiltinType::ARCUnbridgedCast: 5058 return false; 5059 5060 // Pseudo-objects should be converted as soon as possible. 5061 case BuiltinType::PseudoObject: 5062 return true; 5063 5064 // The debugger mode could theoretically but currently does not try 5065 // to resolve unknown-typed arguments based on known parameter types. 5066 case BuiltinType::UnknownAny: 5067 return true; 5068 5069 // These are always invalid as call arguments and should be reported. 5070 case BuiltinType::BoundMember: 5071 case BuiltinType::BuiltinFn: 5072 case BuiltinType::OMPArraySection: 5073 return true; 5074 5075 } 5076 llvm_unreachable("bad builtin type kind"); 5077 } 5078 5079 /// Check an argument list for placeholders that we won't try to 5080 /// handle later. 5081 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5082 // Apply this processing to all the arguments at once instead of 5083 // dying at the first failure. 5084 bool hasInvalid = false; 5085 for (size_t i = 0, e = args.size(); i != e; i++) { 5086 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5087 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5088 if (result.isInvalid()) hasInvalid = true; 5089 else args[i] = result.get(); 5090 } else if (hasInvalid) { 5091 (void)S.CorrectDelayedTyposInExpr(args[i]); 5092 } 5093 } 5094 return hasInvalid; 5095 } 5096 5097 /// If a builtin function has a pointer argument with no explicit address 5098 /// space, then it should be able to accept a pointer to any address 5099 /// space as input. In order to do this, we need to replace the 5100 /// standard builtin declaration with one that uses the same address space 5101 /// as the call. 5102 /// 5103 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5104 /// it does not contain any pointer arguments without 5105 /// an address space qualifer. Otherwise the rewritten 5106 /// FunctionDecl is returned. 5107 /// TODO: Handle pointer return types. 5108 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5109 const FunctionDecl *FDecl, 5110 MultiExprArg ArgExprs) { 5111 5112 QualType DeclType = FDecl->getType(); 5113 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5114 5115 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5116 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5117 return nullptr; 5118 5119 bool NeedsNewDecl = false; 5120 unsigned i = 0; 5121 SmallVector<QualType, 8> OverloadParams; 5122 5123 for (QualType ParamType : FT->param_types()) { 5124 5125 // Convert array arguments to pointer to simplify type lookup. 5126 ExprResult ArgRes = 5127 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5128 if (ArgRes.isInvalid()) 5129 return nullptr; 5130 Expr *Arg = ArgRes.get(); 5131 QualType ArgType = Arg->getType(); 5132 if (!ParamType->isPointerType() || 5133 ParamType.getQualifiers().hasAddressSpace() || 5134 !ArgType->isPointerType() || 5135 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5136 OverloadParams.push_back(ParamType); 5137 continue; 5138 } 5139 5140 NeedsNewDecl = true; 5141 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5142 5143 QualType PointeeType = ParamType->getPointeeType(); 5144 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5145 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5146 } 5147 5148 if (!NeedsNewDecl) 5149 return nullptr; 5150 5151 FunctionProtoType::ExtProtoInfo EPI; 5152 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5153 OverloadParams, EPI); 5154 DeclContext *Parent = Context.getTranslationUnitDecl(); 5155 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5156 FDecl->getLocation(), 5157 FDecl->getLocation(), 5158 FDecl->getIdentifier(), 5159 OverloadTy, 5160 /*TInfo=*/nullptr, 5161 SC_Extern, false, 5162 /*hasPrototype=*/true); 5163 SmallVector<ParmVarDecl*, 16> Params; 5164 FT = cast<FunctionProtoType>(OverloadTy); 5165 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5166 QualType ParamType = FT->getParamType(i); 5167 ParmVarDecl *Parm = 5168 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5169 SourceLocation(), nullptr, ParamType, 5170 /*TInfo=*/nullptr, SC_None, nullptr); 5171 Parm->setScopeInfo(0, i); 5172 Params.push_back(Parm); 5173 } 5174 OverloadDecl->setParams(Params); 5175 return OverloadDecl; 5176 } 5177 5178 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5179 FunctionDecl *Callee, 5180 MultiExprArg ArgExprs) { 5181 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5182 // similar attributes) really don't like it when functions are called with an 5183 // invalid number of args. 5184 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5185 /*PartialOverloading=*/false) && 5186 !Callee->isVariadic()) 5187 return; 5188 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5189 return; 5190 5191 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5192 S.Diag(Fn->getLocStart(), 5193 isa<CXXMethodDecl>(Callee) 5194 ? diag::err_ovl_no_viable_member_function_in_call 5195 : diag::err_ovl_no_viable_function_in_call) 5196 << Callee << Callee->getSourceRange(); 5197 S.Diag(Callee->getLocation(), 5198 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5199 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5200 return; 5201 } 5202 } 5203 5204 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5205 /// This provides the location of the left/right parens and a list of comma 5206 /// locations. 5207 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5208 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5209 Expr *ExecConfig, bool IsExecConfig) { 5210 // Since this might be a postfix expression, get rid of ParenListExprs. 5211 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5212 if (Result.isInvalid()) return ExprError(); 5213 Fn = Result.get(); 5214 5215 if (checkArgsForPlaceholders(*this, ArgExprs)) 5216 return ExprError(); 5217 5218 if (getLangOpts().CPlusPlus) { 5219 // If this is a pseudo-destructor expression, build the call immediately. 5220 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5221 if (!ArgExprs.empty()) { 5222 // Pseudo-destructor calls should not have any arguments. 5223 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5224 << FixItHint::CreateRemoval( 5225 SourceRange(ArgExprs.front()->getLocStart(), 5226 ArgExprs.back()->getLocEnd())); 5227 } 5228 5229 return new (Context) 5230 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5231 } 5232 if (Fn->getType() == Context.PseudoObjectTy) { 5233 ExprResult result = CheckPlaceholderExpr(Fn); 5234 if (result.isInvalid()) return ExprError(); 5235 Fn = result.get(); 5236 } 5237 5238 // Determine whether this is a dependent call inside a C++ template, 5239 // in which case we won't do any semantic analysis now. 5240 bool Dependent = false; 5241 if (Fn->isTypeDependent()) 5242 Dependent = true; 5243 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5244 Dependent = true; 5245 5246 if (Dependent) { 5247 if (ExecConfig) { 5248 return new (Context) CUDAKernelCallExpr( 5249 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5250 Context.DependentTy, VK_RValue, RParenLoc); 5251 } else { 5252 return new (Context) CallExpr( 5253 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5254 } 5255 } 5256 5257 // Determine whether this is a call to an object (C++ [over.call.object]). 5258 if (Fn->getType()->isRecordType()) 5259 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5260 RParenLoc); 5261 5262 if (Fn->getType() == Context.UnknownAnyTy) { 5263 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5264 if (result.isInvalid()) return ExprError(); 5265 Fn = result.get(); 5266 } 5267 5268 if (Fn->getType() == Context.BoundMemberTy) { 5269 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5270 RParenLoc); 5271 } 5272 } 5273 5274 // Check for overloaded calls. This can happen even in C due to extensions. 5275 if (Fn->getType() == Context.OverloadTy) { 5276 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5277 5278 // We aren't supposed to apply this logic if there's an '&' involved. 5279 if (!find.HasFormOfMemberPointer) { 5280 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5281 return new (Context) CallExpr( 5282 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5283 OverloadExpr *ovl = find.Expression; 5284 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5285 return BuildOverloadedCallExpr( 5286 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5287 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5288 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5289 RParenLoc); 5290 } 5291 } 5292 5293 // If we're directly calling a function, get the appropriate declaration. 5294 if (Fn->getType() == Context.UnknownAnyTy) { 5295 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5296 if (result.isInvalid()) return ExprError(); 5297 Fn = result.get(); 5298 } 5299 5300 Expr *NakedFn = Fn->IgnoreParens(); 5301 5302 bool CallingNDeclIndirectly = false; 5303 NamedDecl *NDecl = nullptr; 5304 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5305 if (UnOp->getOpcode() == UO_AddrOf) { 5306 CallingNDeclIndirectly = true; 5307 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5308 } 5309 } 5310 5311 if (isa<DeclRefExpr>(NakedFn)) { 5312 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5313 5314 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5315 if (FDecl && FDecl->getBuiltinID()) { 5316 // Rewrite the function decl for this builtin by replacing parameters 5317 // with no explicit address space with the address space of the arguments 5318 // in ArgExprs. 5319 if ((FDecl = 5320 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5321 NDecl = FDecl; 5322 Fn = DeclRefExpr::Create( 5323 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5324 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5325 } 5326 } 5327 } else if (isa<MemberExpr>(NakedFn)) 5328 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5329 5330 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5331 if (CallingNDeclIndirectly && 5332 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5333 Fn->getLocStart())) 5334 return ExprError(); 5335 5336 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5337 return ExprError(); 5338 5339 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5340 } 5341 5342 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5343 ExecConfig, IsExecConfig); 5344 } 5345 5346 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5347 /// 5348 /// __builtin_astype( value, dst type ) 5349 /// 5350 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5351 SourceLocation BuiltinLoc, 5352 SourceLocation RParenLoc) { 5353 ExprValueKind VK = VK_RValue; 5354 ExprObjectKind OK = OK_Ordinary; 5355 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5356 QualType SrcTy = E->getType(); 5357 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5358 return ExprError(Diag(BuiltinLoc, 5359 diag::err_invalid_astype_of_different_size) 5360 << DstTy 5361 << SrcTy 5362 << E->getSourceRange()); 5363 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5364 } 5365 5366 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5367 /// provided arguments. 5368 /// 5369 /// __builtin_convertvector( value, dst type ) 5370 /// 5371 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5372 SourceLocation BuiltinLoc, 5373 SourceLocation RParenLoc) { 5374 TypeSourceInfo *TInfo; 5375 GetTypeFromParser(ParsedDestTy, &TInfo); 5376 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5377 } 5378 5379 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5380 /// i.e. an expression not of \p OverloadTy. The expression should 5381 /// unary-convert to an expression of function-pointer or 5382 /// block-pointer type. 5383 /// 5384 /// \param NDecl the declaration being called, if available 5385 ExprResult 5386 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5387 SourceLocation LParenLoc, 5388 ArrayRef<Expr *> Args, 5389 SourceLocation RParenLoc, 5390 Expr *Config, bool IsExecConfig) { 5391 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5392 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5393 5394 // Functions with 'interrupt' attribute cannot be called directly. 5395 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5396 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5397 return ExprError(); 5398 } 5399 5400 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5401 // so there's some risk when calling out to non-interrupt handler functions 5402 // that the callee might not preserve them. This is easy to diagnose here, 5403 // but can be very challenging to debug. 5404 if (auto *Caller = getCurFunctionDecl()) 5405 if (Caller->hasAttr<ARMInterruptAttr>()) { 5406 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5407 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5408 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5409 } 5410 5411 // Promote the function operand. 5412 // We special-case function promotion here because we only allow promoting 5413 // builtin functions to function pointers in the callee of a call. 5414 ExprResult Result; 5415 if (BuiltinID && 5416 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5417 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5418 CK_BuiltinFnToFnPtr).get(); 5419 } else { 5420 Result = CallExprUnaryConversions(Fn); 5421 } 5422 if (Result.isInvalid()) 5423 return ExprError(); 5424 Fn = Result.get(); 5425 5426 // Make the call expr early, before semantic checks. This guarantees cleanup 5427 // of arguments and function on error. 5428 CallExpr *TheCall; 5429 if (Config) 5430 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5431 cast<CallExpr>(Config), Args, 5432 Context.BoolTy, VK_RValue, 5433 RParenLoc); 5434 else 5435 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5436 VK_RValue, RParenLoc); 5437 5438 if (!getLangOpts().CPlusPlus) { 5439 // C cannot always handle TypoExpr nodes in builtin calls and direct 5440 // function calls as their argument checking don't necessarily handle 5441 // dependent types properly, so make sure any TypoExprs have been 5442 // dealt with. 5443 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5444 if (!Result.isUsable()) return ExprError(); 5445 TheCall = dyn_cast<CallExpr>(Result.get()); 5446 if (!TheCall) return Result; 5447 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5448 } 5449 5450 // Bail out early if calling a builtin with custom typechecking. 5451 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5452 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5453 5454 retry: 5455 const FunctionType *FuncT; 5456 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5457 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5458 // have type pointer to function". 5459 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5460 if (!FuncT) 5461 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5462 << Fn->getType() << Fn->getSourceRange()); 5463 } else if (const BlockPointerType *BPT = 5464 Fn->getType()->getAs<BlockPointerType>()) { 5465 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5466 } else { 5467 // Handle calls to expressions of unknown-any type. 5468 if (Fn->getType() == Context.UnknownAnyTy) { 5469 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5470 if (rewrite.isInvalid()) return ExprError(); 5471 Fn = rewrite.get(); 5472 TheCall->setCallee(Fn); 5473 goto retry; 5474 } 5475 5476 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5477 << Fn->getType() << Fn->getSourceRange()); 5478 } 5479 5480 if (getLangOpts().CUDA) { 5481 if (Config) { 5482 // CUDA: Kernel calls must be to global functions 5483 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5484 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5485 << FDecl->getName() << Fn->getSourceRange()); 5486 5487 // CUDA: Kernel function must have 'void' return type 5488 if (!FuncT->getReturnType()->isVoidType()) 5489 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5490 << Fn->getType() << Fn->getSourceRange()); 5491 } else { 5492 // CUDA: Calls to global functions must be configured 5493 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5494 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5495 << FDecl->getName() << Fn->getSourceRange()); 5496 } 5497 } 5498 5499 // Check for a valid return type 5500 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5501 FDecl)) 5502 return ExprError(); 5503 5504 // We know the result type of the call, set it. 5505 TheCall->setType(FuncT->getCallResultType(Context)); 5506 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5507 5508 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5509 if (Proto) { 5510 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5511 IsExecConfig)) 5512 return ExprError(); 5513 } else { 5514 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5515 5516 if (FDecl) { 5517 // Check if we have too few/too many template arguments, based 5518 // on our knowledge of the function definition. 5519 const FunctionDecl *Def = nullptr; 5520 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5521 Proto = Def->getType()->getAs<FunctionProtoType>(); 5522 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5523 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5524 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5525 } 5526 5527 // If the function we're calling isn't a function prototype, but we have 5528 // a function prototype from a prior declaratiom, use that prototype. 5529 if (!FDecl->hasPrototype()) 5530 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5531 } 5532 5533 // Promote the arguments (C99 6.5.2.2p6). 5534 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5535 Expr *Arg = Args[i]; 5536 5537 if (Proto && i < Proto->getNumParams()) { 5538 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5539 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5540 ExprResult ArgE = 5541 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5542 if (ArgE.isInvalid()) 5543 return true; 5544 5545 Arg = ArgE.getAs<Expr>(); 5546 5547 } else { 5548 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5549 5550 if (ArgE.isInvalid()) 5551 return true; 5552 5553 Arg = ArgE.getAs<Expr>(); 5554 } 5555 5556 if (RequireCompleteType(Arg->getLocStart(), 5557 Arg->getType(), 5558 diag::err_call_incomplete_argument, Arg)) 5559 return ExprError(); 5560 5561 TheCall->setArg(i, Arg); 5562 } 5563 } 5564 5565 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5566 if (!Method->isStatic()) 5567 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5568 << Fn->getSourceRange()); 5569 5570 // Check for sentinels 5571 if (NDecl) 5572 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5573 5574 // Do special checking on direct calls to functions. 5575 if (FDecl) { 5576 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5577 return ExprError(); 5578 5579 if (BuiltinID) 5580 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5581 } else if (NDecl) { 5582 if (CheckPointerCall(NDecl, TheCall, Proto)) 5583 return ExprError(); 5584 } else { 5585 if (CheckOtherCall(TheCall, Proto)) 5586 return ExprError(); 5587 } 5588 5589 return MaybeBindToTemporary(TheCall); 5590 } 5591 5592 ExprResult 5593 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5594 SourceLocation RParenLoc, Expr *InitExpr) { 5595 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5596 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5597 5598 TypeSourceInfo *TInfo; 5599 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5600 if (!TInfo) 5601 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5602 5603 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5604 } 5605 5606 ExprResult 5607 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5608 SourceLocation RParenLoc, Expr *LiteralExpr) { 5609 QualType literalType = TInfo->getType(); 5610 5611 if (literalType->isArrayType()) { 5612 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5613 diag::err_illegal_decl_array_incomplete_type, 5614 SourceRange(LParenLoc, 5615 LiteralExpr->getSourceRange().getEnd()))) 5616 return ExprError(); 5617 if (literalType->isVariableArrayType()) 5618 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5619 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5620 } else if (!literalType->isDependentType() && 5621 RequireCompleteType(LParenLoc, literalType, 5622 diag::err_typecheck_decl_incomplete_type, 5623 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5624 return ExprError(); 5625 5626 InitializedEntity Entity 5627 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5628 InitializationKind Kind 5629 = InitializationKind::CreateCStyleCast(LParenLoc, 5630 SourceRange(LParenLoc, RParenLoc), 5631 /*InitList=*/true); 5632 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5633 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5634 &literalType); 5635 if (Result.isInvalid()) 5636 return ExprError(); 5637 LiteralExpr = Result.get(); 5638 5639 bool isFileScope = !CurContext->isFunctionOrMethod(); 5640 if (isFileScope && 5641 !LiteralExpr->isTypeDependent() && 5642 !LiteralExpr->isValueDependent() && 5643 !literalType->isDependentType()) { // 6.5.2.5p3 5644 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5645 return ExprError(); 5646 } 5647 5648 // In C, compound literals are l-values for some reason. 5649 // For GCC compatibility, in C++, file-scope array compound literals with 5650 // constant initializers are also l-values, and compound literals are 5651 // otherwise prvalues. 5652 // 5653 // (GCC also treats C++ list-initialized file-scope array prvalues with 5654 // constant initializers as l-values, but that's non-conforming, so we don't 5655 // follow it there.) 5656 // 5657 // FIXME: It would be better to handle the lvalue cases as materializing and 5658 // lifetime-extending a temporary object, but our materialized temporaries 5659 // representation only supports lifetime extension from a variable, not "out 5660 // of thin air". 5661 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5662 // is bound to the result of applying array-to-pointer decay to the compound 5663 // literal. 5664 // FIXME: GCC supports compound literals of reference type, which should 5665 // obviously have a value kind derived from the kind of reference involved. 5666 ExprValueKind VK = 5667 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5668 ? VK_RValue 5669 : VK_LValue; 5670 5671 return MaybeBindToTemporary( 5672 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5673 VK, LiteralExpr, isFileScope)); 5674 } 5675 5676 ExprResult 5677 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5678 SourceLocation RBraceLoc) { 5679 // Immediately handle non-overload placeholders. Overloads can be 5680 // resolved contextually, but everything else here can't. 5681 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5682 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5683 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5684 5685 // Ignore failures; dropping the entire initializer list because 5686 // of one failure would be terrible for indexing/etc. 5687 if (result.isInvalid()) continue; 5688 5689 InitArgList[I] = result.get(); 5690 } 5691 } 5692 5693 // Semantic analysis for initializers is done by ActOnDeclarator() and 5694 // CheckInitializer() - it requires knowledge of the object being intialized. 5695 5696 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5697 RBraceLoc); 5698 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5699 return E; 5700 } 5701 5702 /// Do an explicit extend of the given block pointer if we're in ARC. 5703 void Sema::maybeExtendBlockObject(ExprResult &E) { 5704 assert(E.get()->getType()->isBlockPointerType()); 5705 assert(E.get()->isRValue()); 5706 5707 // Only do this in an r-value context. 5708 if (!getLangOpts().ObjCAutoRefCount) return; 5709 5710 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5711 CK_ARCExtendBlockObject, E.get(), 5712 /*base path*/ nullptr, VK_RValue); 5713 Cleanup.setExprNeedsCleanups(true); 5714 } 5715 5716 /// Prepare a conversion of the given expression to an ObjC object 5717 /// pointer type. 5718 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5719 QualType type = E.get()->getType(); 5720 if (type->isObjCObjectPointerType()) { 5721 return CK_BitCast; 5722 } else if (type->isBlockPointerType()) { 5723 maybeExtendBlockObject(E); 5724 return CK_BlockPointerToObjCPointerCast; 5725 } else { 5726 assert(type->isPointerType()); 5727 return CK_CPointerToObjCPointerCast; 5728 } 5729 } 5730 5731 /// Prepares for a scalar cast, performing all the necessary stages 5732 /// except the final cast and returning the kind required. 5733 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5734 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5735 // Also, callers should have filtered out the invalid cases with 5736 // pointers. Everything else should be possible. 5737 5738 QualType SrcTy = Src.get()->getType(); 5739 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5740 return CK_NoOp; 5741 5742 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5743 case Type::STK_MemberPointer: 5744 llvm_unreachable("member pointer type in C"); 5745 5746 case Type::STK_CPointer: 5747 case Type::STK_BlockPointer: 5748 case Type::STK_ObjCObjectPointer: 5749 switch (DestTy->getScalarTypeKind()) { 5750 case Type::STK_CPointer: { 5751 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5752 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5753 if (SrcAS != DestAS) 5754 return CK_AddressSpaceConversion; 5755 return CK_BitCast; 5756 } 5757 case Type::STK_BlockPointer: 5758 return (SrcKind == Type::STK_BlockPointer 5759 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5760 case Type::STK_ObjCObjectPointer: 5761 if (SrcKind == Type::STK_ObjCObjectPointer) 5762 return CK_BitCast; 5763 if (SrcKind == Type::STK_CPointer) 5764 return CK_CPointerToObjCPointerCast; 5765 maybeExtendBlockObject(Src); 5766 return CK_BlockPointerToObjCPointerCast; 5767 case Type::STK_Bool: 5768 return CK_PointerToBoolean; 5769 case Type::STK_Integral: 5770 return CK_PointerToIntegral; 5771 case Type::STK_Floating: 5772 case Type::STK_FloatingComplex: 5773 case Type::STK_IntegralComplex: 5774 case Type::STK_MemberPointer: 5775 llvm_unreachable("illegal cast from pointer"); 5776 } 5777 llvm_unreachable("Should have returned before this"); 5778 5779 case Type::STK_Bool: // casting from bool is like casting from an integer 5780 case Type::STK_Integral: 5781 switch (DestTy->getScalarTypeKind()) { 5782 case Type::STK_CPointer: 5783 case Type::STK_ObjCObjectPointer: 5784 case Type::STK_BlockPointer: 5785 if (Src.get()->isNullPointerConstant(Context, 5786 Expr::NPC_ValueDependentIsNull)) 5787 return CK_NullToPointer; 5788 return CK_IntegralToPointer; 5789 case Type::STK_Bool: 5790 return CK_IntegralToBoolean; 5791 case Type::STK_Integral: 5792 return CK_IntegralCast; 5793 case Type::STK_Floating: 5794 return CK_IntegralToFloating; 5795 case Type::STK_IntegralComplex: 5796 Src = ImpCastExprToType(Src.get(), 5797 DestTy->castAs<ComplexType>()->getElementType(), 5798 CK_IntegralCast); 5799 return CK_IntegralRealToComplex; 5800 case Type::STK_FloatingComplex: 5801 Src = ImpCastExprToType(Src.get(), 5802 DestTy->castAs<ComplexType>()->getElementType(), 5803 CK_IntegralToFloating); 5804 return CK_FloatingRealToComplex; 5805 case Type::STK_MemberPointer: 5806 llvm_unreachable("member pointer type in C"); 5807 } 5808 llvm_unreachable("Should have returned before this"); 5809 5810 case Type::STK_Floating: 5811 switch (DestTy->getScalarTypeKind()) { 5812 case Type::STK_Floating: 5813 return CK_FloatingCast; 5814 case Type::STK_Bool: 5815 return CK_FloatingToBoolean; 5816 case Type::STK_Integral: 5817 return CK_FloatingToIntegral; 5818 case Type::STK_FloatingComplex: 5819 Src = ImpCastExprToType(Src.get(), 5820 DestTy->castAs<ComplexType>()->getElementType(), 5821 CK_FloatingCast); 5822 return CK_FloatingRealToComplex; 5823 case Type::STK_IntegralComplex: 5824 Src = ImpCastExprToType(Src.get(), 5825 DestTy->castAs<ComplexType>()->getElementType(), 5826 CK_FloatingToIntegral); 5827 return CK_IntegralRealToComplex; 5828 case Type::STK_CPointer: 5829 case Type::STK_ObjCObjectPointer: 5830 case Type::STK_BlockPointer: 5831 llvm_unreachable("valid float->pointer cast?"); 5832 case Type::STK_MemberPointer: 5833 llvm_unreachable("member pointer type in C"); 5834 } 5835 llvm_unreachable("Should have returned before this"); 5836 5837 case Type::STK_FloatingComplex: 5838 switch (DestTy->getScalarTypeKind()) { 5839 case Type::STK_FloatingComplex: 5840 return CK_FloatingComplexCast; 5841 case Type::STK_IntegralComplex: 5842 return CK_FloatingComplexToIntegralComplex; 5843 case Type::STK_Floating: { 5844 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5845 if (Context.hasSameType(ET, DestTy)) 5846 return CK_FloatingComplexToReal; 5847 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5848 return CK_FloatingCast; 5849 } 5850 case Type::STK_Bool: 5851 return CK_FloatingComplexToBoolean; 5852 case Type::STK_Integral: 5853 Src = ImpCastExprToType(Src.get(), 5854 SrcTy->castAs<ComplexType>()->getElementType(), 5855 CK_FloatingComplexToReal); 5856 return CK_FloatingToIntegral; 5857 case Type::STK_CPointer: 5858 case Type::STK_ObjCObjectPointer: 5859 case Type::STK_BlockPointer: 5860 llvm_unreachable("valid complex float->pointer cast?"); 5861 case Type::STK_MemberPointer: 5862 llvm_unreachable("member pointer type in C"); 5863 } 5864 llvm_unreachable("Should have returned before this"); 5865 5866 case Type::STK_IntegralComplex: 5867 switch (DestTy->getScalarTypeKind()) { 5868 case Type::STK_FloatingComplex: 5869 return CK_IntegralComplexToFloatingComplex; 5870 case Type::STK_IntegralComplex: 5871 return CK_IntegralComplexCast; 5872 case Type::STK_Integral: { 5873 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5874 if (Context.hasSameType(ET, DestTy)) 5875 return CK_IntegralComplexToReal; 5876 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5877 return CK_IntegralCast; 5878 } 5879 case Type::STK_Bool: 5880 return CK_IntegralComplexToBoolean; 5881 case Type::STK_Floating: 5882 Src = ImpCastExprToType(Src.get(), 5883 SrcTy->castAs<ComplexType>()->getElementType(), 5884 CK_IntegralComplexToReal); 5885 return CK_IntegralToFloating; 5886 case Type::STK_CPointer: 5887 case Type::STK_ObjCObjectPointer: 5888 case Type::STK_BlockPointer: 5889 llvm_unreachable("valid complex int->pointer cast?"); 5890 case Type::STK_MemberPointer: 5891 llvm_unreachable("member pointer type in C"); 5892 } 5893 llvm_unreachable("Should have returned before this"); 5894 } 5895 5896 llvm_unreachable("Unhandled scalar cast"); 5897 } 5898 5899 static bool breakDownVectorType(QualType type, uint64_t &len, 5900 QualType &eltType) { 5901 // Vectors are simple. 5902 if (const VectorType *vecType = type->getAs<VectorType>()) { 5903 len = vecType->getNumElements(); 5904 eltType = vecType->getElementType(); 5905 assert(eltType->isScalarType()); 5906 return true; 5907 } 5908 5909 // We allow lax conversion to and from non-vector types, but only if 5910 // they're real types (i.e. non-complex, non-pointer scalar types). 5911 if (!type->isRealType()) return false; 5912 5913 len = 1; 5914 eltType = type; 5915 return true; 5916 } 5917 5918 /// Are the two types lax-compatible vector types? That is, given 5919 /// that one of them is a vector, do they have equal storage sizes, 5920 /// where the storage size is the number of elements times the element 5921 /// size? 5922 /// 5923 /// This will also return false if either of the types is neither a 5924 /// vector nor a real type. 5925 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5926 assert(destTy->isVectorType() || srcTy->isVectorType()); 5927 5928 // Disallow lax conversions between scalars and ExtVectors (these 5929 // conversions are allowed for other vector types because common headers 5930 // depend on them). Most scalar OP ExtVector cases are handled by the 5931 // splat path anyway, which does what we want (convert, not bitcast). 5932 // What this rules out for ExtVectors is crazy things like char4*float. 5933 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5934 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5935 5936 uint64_t srcLen, destLen; 5937 QualType srcEltTy, destEltTy; 5938 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5939 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5940 5941 // ASTContext::getTypeSize will return the size rounded up to a 5942 // power of 2, so instead of using that, we need to use the raw 5943 // element size multiplied by the element count. 5944 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5945 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5946 5947 return (srcLen * srcEltSize == destLen * destEltSize); 5948 } 5949 5950 /// Is this a legal conversion between two types, one of which is 5951 /// known to be a vector type? 5952 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5953 assert(destTy->isVectorType() || srcTy->isVectorType()); 5954 5955 if (!Context.getLangOpts().LaxVectorConversions) 5956 return false; 5957 return areLaxCompatibleVectorTypes(srcTy, destTy); 5958 } 5959 5960 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5961 CastKind &Kind) { 5962 assert(VectorTy->isVectorType() && "Not a vector type!"); 5963 5964 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5965 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5966 return Diag(R.getBegin(), 5967 Ty->isVectorType() ? 5968 diag::err_invalid_conversion_between_vectors : 5969 diag::err_invalid_conversion_between_vector_and_integer) 5970 << VectorTy << Ty << R; 5971 } else 5972 return Diag(R.getBegin(), 5973 diag::err_invalid_conversion_between_vector_and_scalar) 5974 << VectorTy << Ty << R; 5975 5976 Kind = CK_BitCast; 5977 return false; 5978 } 5979 5980 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5981 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5982 5983 if (DestElemTy == SplattedExpr->getType()) 5984 return SplattedExpr; 5985 5986 assert(DestElemTy->isFloatingType() || 5987 DestElemTy->isIntegralOrEnumerationType()); 5988 5989 CastKind CK; 5990 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5991 // OpenCL requires that we convert `true` boolean expressions to -1, but 5992 // only when splatting vectors. 5993 if (DestElemTy->isFloatingType()) { 5994 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5995 // in two steps: boolean to signed integral, then to floating. 5996 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5997 CK_BooleanToSignedIntegral); 5998 SplattedExpr = CastExprRes.get(); 5999 CK = CK_IntegralToFloating; 6000 } else { 6001 CK = CK_BooleanToSignedIntegral; 6002 } 6003 } else { 6004 ExprResult CastExprRes = SplattedExpr; 6005 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6006 if (CastExprRes.isInvalid()) 6007 return ExprError(); 6008 SplattedExpr = CastExprRes.get(); 6009 } 6010 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6011 } 6012 6013 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6014 Expr *CastExpr, CastKind &Kind) { 6015 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6016 6017 QualType SrcTy = CastExpr->getType(); 6018 6019 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6020 // an ExtVectorType. 6021 // In OpenCL, casts between vectors of different types are not allowed. 6022 // (See OpenCL 6.2). 6023 if (SrcTy->isVectorType()) { 6024 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 6025 || (getLangOpts().OpenCL && 6026 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 6027 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6028 << DestTy << SrcTy << R; 6029 return ExprError(); 6030 } 6031 Kind = CK_BitCast; 6032 return CastExpr; 6033 } 6034 6035 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6036 // conversion will take place first from scalar to elt type, and then 6037 // splat from elt type to vector. 6038 if (SrcTy->isPointerType()) 6039 return Diag(R.getBegin(), 6040 diag::err_invalid_conversion_between_vector_and_scalar) 6041 << DestTy << SrcTy << R; 6042 6043 Kind = CK_VectorSplat; 6044 return prepareVectorSplat(DestTy, CastExpr); 6045 } 6046 6047 ExprResult 6048 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6049 Declarator &D, ParsedType &Ty, 6050 SourceLocation RParenLoc, Expr *CastExpr) { 6051 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6052 "ActOnCastExpr(): missing type or expr"); 6053 6054 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6055 if (D.isInvalidType()) 6056 return ExprError(); 6057 6058 if (getLangOpts().CPlusPlus) { 6059 // Check that there are no default arguments (C++ only). 6060 CheckExtraCXXDefaultArguments(D); 6061 } else { 6062 // Make sure any TypoExprs have been dealt with. 6063 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6064 if (!Res.isUsable()) 6065 return ExprError(); 6066 CastExpr = Res.get(); 6067 } 6068 6069 checkUnusedDeclAttributes(D); 6070 6071 QualType castType = castTInfo->getType(); 6072 Ty = CreateParsedType(castType, castTInfo); 6073 6074 bool isVectorLiteral = false; 6075 6076 // Check for an altivec or OpenCL literal, 6077 // i.e. all the elements are integer constants. 6078 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6079 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6080 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6081 && castType->isVectorType() && (PE || PLE)) { 6082 if (PLE && PLE->getNumExprs() == 0) { 6083 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6084 return ExprError(); 6085 } 6086 if (PE || PLE->getNumExprs() == 1) { 6087 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6088 if (!E->getType()->isVectorType()) 6089 isVectorLiteral = true; 6090 } 6091 else 6092 isVectorLiteral = true; 6093 } 6094 6095 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6096 // then handle it as such. 6097 if (isVectorLiteral) 6098 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6099 6100 // If the Expr being casted is a ParenListExpr, handle it specially. 6101 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6102 // sequence of BinOp comma operators. 6103 if (isa<ParenListExpr>(CastExpr)) { 6104 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6105 if (Result.isInvalid()) return ExprError(); 6106 CastExpr = Result.get(); 6107 } 6108 6109 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6110 !getSourceManager().isInSystemMacro(LParenLoc)) 6111 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6112 6113 CheckTollFreeBridgeCast(castType, CastExpr); 6114 6115 CheckObjCBridgeRelatedCast(castType, CastExpr); 6116 6117 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6118 6119 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6120 } 6121 6122 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6123 SourceLocation RParenLoc, Expr *E, 6124 TypeSourceInfo *TInfo) { 6125 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6126 "Expected paren or paren list expression"); 6127 6128 Expr **exprs; 6129 unsigned numExprs; 6130 Expr *subExpr; 6131 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6132 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6133 LiteralLParenLoc = PE->getLParenLoc(); 6134 LiteralRParenLoc = PE->getRParenLoc(); 6135 exprs = PE->getExprs(); 6136 numExprs = PE->getNumExprs(); 6137 } else { // isa<ParenExpr> by assertion at function entrance 6138 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6139 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6140 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6141 exprs = &subExpr; 6142 numExprs = 1; 6143 } 6144 6145 QualType Ty = TInfo->getType(); 6146 assert(Ty->isVectorType() && "Expected vector type"); 6147 6148 SmallVector<Expr *, 8> initExprs; 6149 const VectorType *VTy = Ty->getAs<VectorType>(); 6150 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6151 6152 // '(...)' form of vector initialization in AltiVec: the number of 6153 // initializers must be one or must match the size of the vector. 6154 // If a single value is specified in the initializer then it will be 6155 // replicated to all the components of the vector 6156 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6157 // The number of initializers must be one or must match the size of the 6158 // vector. If a single value is specified in the initializer then it will 6159 // be replicated to all the components of the vector 6160 if (numExprs == 1) { 6161 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6162 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6163 if (Literal.isInvalid()) 6164 return ExprError(); 6165 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6166 PrepareScalarCast(Literal, ElemTy)); 6167 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6168 } 6169 else if (numExprs < numElems) { 6170 Diag(E->getExprLoc(), 6171 diag::err_incorrect_number_of_vector_initializers); 6172 return ExprError(); 6173 } 6174 else 6175 initExprs.append(exprs, exprs + numExprs); 6176 } 6177 else { 6178 // For OpenCL, when the number of initializers is a single value, 6179 // it will be replicated to all components of the vector. 6180 if (getLangOpts().OpenCL && 6181 VTy->getVectorKind() == VectorType::GenericVector && 6182 numExprs == 1) { 6183 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6184 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6185 if (Literal.isInvalid()) 6186 return ExprError(); 6187 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6188 PrepareScalarCast(Literal, ElemTy)); 6189 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6190 } 6191 6192 initExprs.append(exprs, exprs + numExprs); 6193 } 6194 // FIXME: This means that pretty-printing the final AST will produce curly 6195 // braces instead of the original commas. 6196 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6197 initExprs, LiteralRParenLoc); 6198 initE->setType(Ty); 6199 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6200 } 6201 6202 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6203 /// the ParenListExpr into a sequence of comma binary operators. 6204 ExprResult 6205 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6206 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6207 if (!E) 6208 return OrigExpr; 6209 6210 ExprResult Result(E->getExpr(0)); 6211 6212 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6213 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6214 E->getExpr(i)); 6215 6216 if (Result.isInvalid()) return ExprError(); 6217 6218 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6219 } 6220 6221 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6222 SourceLocation R, 6223 MultiExprArg Val) { 6224 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6225 return expr; 6226 } 6227 6228 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6229 /// constant and the other is not a pointer. Returns true if a diagnostic is 6230 /// emitted. 6231 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6232 SourceLocation QuestionLoc) { 6233 Expr *NullExpr = LHSExpr; 6234 Expr *NonPointerExpr = RHSExpr; 6235 Expr::NullPointerConstantKind NullKind = 6236 NullExpr->isNullPointerConstant(Context, 6237 Expr::NPC_ValueDependentIsNotNull); 6238 6239 if (NullKind == Expr::NPCK_NotNull) { 6240 NullExpr = RHSExpr; 6241 NonPointerExpr = LHSExpr; 6242 NullKind = 6243 NullExpr->isNullPointerConstant(Context, 6244 Expr::NPC_ValueDependentIsNotNull); 6245 } 6246 6247 if (NullKind == Expr::NPCK_NotNull) 6248 return false; 6249 6250 if (NullKind == Expr::NPCK_ZeroExpression) 6251 return false; 6252 6253 if (NullKind == Expr::NPCK_ZeroLiteral) { 6254 // In this case, check to make sure that we got here from a "NULL" 6255 // string in the source code. 6256 NullExpr = NullExpr->IgnoreParenImpCasts(); 6257 SourceLocation loc = NullExpr->getExprLoc(); 6258 if (!findMacroSpelling(loc, "NULL")) 6259 return false; 6260 } 6261 6262 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6263 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6264 << NonPointerExpr->getType() << DiagType 6265 << NonPointerExpr->getSourceRange(); 6266 return true; 6267 } 6268 6269 /// \brief Return false if the condition expression is valid, true otherwise. 6270 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6271 QualType CondTy = Cond->getType(); 6272 6273 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6274 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6275 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6276 << CondTy << Cond->getSourceRange(); 6277 return true; 6278 } 6279 6280 // C99 6.5.15p2 6281 if (CondTy->isScalarType()) return false; 6282 6283 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6284 << CondTy << Cond->getSourceRange(); 6285 return true; 6286 } 6287 6288 /// \brief Handle when one or both operands are void type. 6289 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6290 ExprResult &RHS) { 6291 Expr *LHSExpr = LHS.get(); 6292 Expr *RHSExpr = RHS.get(); 6293 6294 if (!LHSExpr->getType()->isVoidType()) 6295 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6296 << RHSExpr->getSourceRange(); 6297 if (!RHSExpr->getType()->isVoidType()) 6298 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6299 << LHSExpr->getSourceRange(); 6300 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6301 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6302 return S.Context.VoidTy; 6303 } 6304 6305 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6306 /// true otherwise. 6307 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6308 QualType PointerTy) { 6309 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6310 !NullExpr.get()->isNullPointerConstant(S.Context, 6311 Expr::NPC_ValueDependentIsNull)) 6312 return true; 6313 6314 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6315 return false; 6316 } 6317 6318 /// \brief Checks compatibility between two pointers and return the resulting 6319 /// type. 6320 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6321 ExprResult &RHS, 6322 SourceLocation Loc) { 6323 QualType LHSTy = LHS.get()->getType(); 6324 QualType RHSTy = RHS.get()->getType(); 6325 6326 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6327 // Two identical pointers types are always compatible. 6328 return LHSTy; 6329 } 6330 6331 QualType lhptee, rhptee; 6332 6333 // Get the pointee types. 6334 bool IsBlockPointer = false; 6335 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6336 lhptee = LHSBTy->getPointeeType(); 6337 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6338 IsBlockPointer = true; 6339 } else { 6340 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6341 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6342 } 6343 6344 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6345 // differently qualified versions of compatible types, the result type is 6346 // a pointer to an appropriately qualified version of the composite 6347 // type. 6348 6349 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6350 // clause doesn't make sense for our extensions. E.g. address space 2 should 6351 // be incompatible with address space 3: they may live on different devices or 6352 // anything. 6353 Qualifiers lhQual = lhptee.getQualifiers(); 6354 Qualifiers rhQual = rhptee.getQualifiers(); 6355 6356 unsigned ResultAddrSpace = 0; 6357 unsigned LAddrSpace = lhQual.getAddressSpace(); 6358 unsigned RAddrSpace = rhQual.getAddressSpace(); 6359 if (S.getLangOpts().OpenCL) { 6360 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6361 // spaces is disallowed. 6362 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6363 ResultAddrSpace = LAddrSpace; 6364 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6365 ResultAddrSpace = RAddrSpace; 6366 else { 6367 S.Diag(Loc, 6368 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6369 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6370 << RHS.get()->getSourceRange(); 6371 return QualType(); 6372 } 6373 } 6374 6375 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6376 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6377 lhQual.removeCVRQualifiers(); 6378 rhQual.removeCVRQualifiers(); 6379 6380 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6381 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6382 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6383 // qual types are compatible iff 6384 // * corresponded types are compatible 6385 // * CVR qualifiers are equal 6386 // * address spaces are equal 6387 // Thus for conditional operator we merge CVR and address space unqualified 6388 // pointees and if there is a composite type we return a pointer to it with 6389 // merged qualifiers. 6390 if (S.getLangOpts().OpenCL) { 6391 LHSCastKind = LAddrSpace == ResultAddrSpace 6392 ? CK_BitCast 6393 : CK_AddressSpaceConversion; 6394 RHSCastKind = RAddrSpace == ResultAddrSpace 6395 ? CK_BitCast 6396 : CK_AddressSpaceConversion; 6397 lhQual.removeAddressSpace(); 6398 rhQual.removeAddressSpace(); 6399 } 6400 6401 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6402 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6403 6404 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6405 6406 if (CompositeTy.isNull()) { 6407 // In this situation, we assume void* type. No especially good 6408 // reason, but this is what gcc does, and we do have to pick 6409 // to get a consistent AST. 6410 QualType incompatTy; 6411 incompatTy = S.Context.getPointerType( 6412 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6413 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6414 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6415 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6416 // for casts between types with incompatible address space qualifiers. 6417 // For the following code the compiler produces casts between global and 6418 // local address spaces of the corresponded innermost pointees: 6419 // local int *global *a; 6420 // global int *global *b; 6421 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6422 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6423 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6424 << RHS.get()->getSourceRange(); 6425 return incompatTy; 6426 } 6427 6428 // The pointer types are compatible. 6429 // In case of OpenCL ResultTy should have the address space qualifier 6430 // which is a superset of address spaces of both the 2nd and the 3rd 6431 // operands of the conditional operator. 6432 QualType ResultTy = [&, ResultAddrSpace]() { 6433 if (S.getLangOpts().OpenCL) { 6434 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6435 CompositeQuals.setAddressSpace(ResultAddrSpace); 6436 return S.Context 6437 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6438 .withCVRQualifiers(MergedCVRQual); 6439 } 6440 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6441 }(); 6442 if (IsBlockPointer) 6443 ResultTy = S.Context.getBlockPointerType(ResultTy); 6444 else 6445 ResultTy = S.Context.getPointerType(ResultTy); 6446 6447 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6448 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6449 return ResultTy; 6450 } 6451 6452 /// \brief Return the resulting type when the operands are both block pointers. 6453 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6454 ExprResult &LHS, 6455 ExprResult &RHS, 6456 SourceLocation Loc) { 6457 QualType LHSTy = LHS.get()->getType(); 6458 QualType RHSTy = RHS.get()->getType(); 6459 6460 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6461 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6462 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6463 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6464 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6465 return destType; 6466 } 6467 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6468 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6469 << RHS.get()->getSourceRange(); 6470 return QualType(); 6471 } 6472 6473 // We have 2 block pointer types. 6474 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6475 } 6476 6477 /// \brief Return the resulting type when the operands are both pointers. 6478 static QualType 6479 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6480 ExprResult &RHS, 6481 SourceLocation Loc) { 6482 // get the pointer types 6483 QualType LHSTy = LHS.get()->getType(); 6484 QualType RHSTy = RHS.get()->getType(); 6485 6486 // get the "pointed to" types 6487 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6488 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6489 6490 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6491 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6492 // Figure out necessary qualifiers (C99 6.5.15p6) 6493 QualType destPointee 6494 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6495 QualType destType = S.Context.getPointerType(destPointee); 6496 // Add qualifiers if necessary. 6497 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6498 // Promote to void*. 6499 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6500 return destType; 6501 } 6502 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6503 QualType destPointee 6504 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6505 QualType destType = S.Context.getPointerType(destPointee); 6506 // Add qualifiers if necessary. 6507 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6508 // Promote to void*. 6509 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6510 return destType; 6511 } 6512 6513 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6514 } 6515 6516 /// \brief Return false if the first expression is not an integer and the second 6517 /// expression is not a pointer, true otherwise. 6518 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6519 Expr* PointerExpr, SourceLocation Loc, 6520 bool IsIntFirstExpr) { 6521 if (!PointerExpr->getType()->isPointerType() || 6522 !Int.get()->getType()->isIntegerType()) 6523 return false; 6524 6525 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6526 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6527 6528 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6529 << Expr1->getType() << Expr2->getType() 6530 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6531 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6532 CK_IntegralToPointer); 6533 return true; 6534 } 6535 6536 /// \brief Simple conversion between integer and floating point types. 6537 /// 6538 /// Used when handling the OpenCL conditional operator where the 6539 /// condition is a vector while the other operands are scalar. 6540 /// 6541 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6542 /// types are either integer or floating type. Between the two 6543 /// operands, the type with the higher rank is defined as the "result 6544 /// type". The other operand needs to be promoted to the same type. No 6545 /// other type promotion is allowed. We cannot use 6546 /// UsualArithmeticConversions() for this purpose, since it always 6547 /// promotes promotable types. 6548 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6549 ExprResult &RHS, 6550 SourceLocation QuestionLoc) { 6551 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6552 if (LHS.isInvalid()) 6553 return QualType(); 6554 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6555 if (RHS.isInvalid()) 6556 return QualType(); 6557 6558 // For conversion purposes, we ignore any qualifiers. 6559 // For example, "const float" and "float" are equivalent. 6560 QualType LHSType = 6561 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6562 QualType RHSType = 6563 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6564 6565 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6566 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6567 << LHSType << LHS.get()->getSourceRange(); 6568 return QualType(); 6569 } 6570 6571 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6572 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6573 << RHSType << RHS.get()->getSourceRange(); 6574 return QualType(); 6575 } 6576 6577 // If both types are identical, no conversion is needed. 6578 if (LHSType == RHSType) 6579 return LHSType; 6580 6581 // Now handle "real" floating types (i.e. float, double, long double). 6582 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6583 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6584 /*IsCompAssign = */ false); 6585 6586 // Finally, we have two differing integer types. 6587 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6588 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6589 } 6590 6591 /// \brief Convert scalar operands to a vector that matches the 6592 /// condition in length. 6593 /// 6594 /// Used when handling the OpenCL conditional operator where the 6595 /// condition is a vector while the other operands are scalar. 6596 /// 6597 /// We first compute the "result type" for the scalar operands 6598 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6599 /// into a vector of that type where the length matches the condition 6600 /// vector type. s6.11.6 requires that the element types of the result 6601 /// and the condition must have the same number of bits. 6602 static QualType 6603 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6604 QualType CondTy, SourceLocation QuestionLoc) { 6605 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6606 if (ResTy.isNull()) return QualType(); 6607 6608 const VectorType *CV = CondTy->getAs<VectorType>(); 6609 assert(CV); 6610 6611 // Determine the vector result type 6612 unsigned NumElements = CV->getNumElements(); 6613 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6614 6615 // Ensure that all types have the same number of bits 6616 if (S.Context.getTypeSize(CV->getElementType()) 6617 != S.Context.getTypeSize(ResTy)) { 6618 // Since VectorTy is created internally, it does not pretty print 6619 // with an OpenCL name. Instead, we just print a description. 6620 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6621 SmallString<64> Str; 6622 llvm::raw_svector_ostream OS(Str); 6623 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6624 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6625 << CondTy << OS.str(); 6626 return QualType(); 6627 } 6628 6629 // Convert operands to the vector result type 6630 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6631 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6632 6633 return VectorTy; 6634 } 6635 6636 /// \brief Return false if this is a valid OpenCL condition vector 6637 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6638 SourceLocation QuestionLoc) { 6639 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6640 // integral type. 6641 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6642 assert(CondTy); 6643 QualType EleTy = CondTy->getElementType(); 6644 if (EleTy->isIntegerType()) return false; 6645 6646 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6647 << Cond->getType() << Cond->getSourceRange(); 6648 return true; 6649 } 6650 6651 /// \brief Return false if the vector condition type and the vector 6652 /// result type are compatible. 6653 /// 6654 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6655 /// number of elements, and their element types have the same number 6656 /// of bits. 6657 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6658 SourceLocation QuestionLoc) { 6659 const VectorType *CV = CondTy->getAs<VectorType>(); 6660 const VectorType *RV = VecResTy->getAs<VectorType>(); 6661 assert(CV && RV); 6662 6663 if (CV->getNumElements() != RV->getNumElements()) { 6664 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6665 << CondTy << VecResTy; 6666 return true; 6667 } 6668 6669 QualType CVE = CV->getElementType(); 6670 QualType RVE = RV->getElementType(); 6671 6672 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6673 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6674 << CondTy << VecResTy; 6675 return true; 6676 } 6677 6678 return false; 6679 } 6680 6681 /// \brief Return the resulting type for the conditional operator in 6682 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6683 /// s6.3.i) when the condition is a vector type. 6684 static QualType 6685 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6686 ExprResult &LHS, ExprResult &RHS, 6687 SourceLocation QuestionLoc) { 6688 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6689 if (Cond.isInvalid()) 6690 return QualType(); 6691 QualType CondTy = Cond.get()->getType(); 6692 6693 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6694 return QualType(); 6695 6696 // If either operand is a vector then find the vector type of the 6697 // result as specified in OpenCL v1.1 s6.3.i. 6698 if (LHS.get()->getType()->isVectorType() || 6699 RHS.get()->getType()->isVectorType()) { 6700 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6701 /*isCompAssign*/false, 6702 /*AllowBothBool*/true, 6703 /*AllowBoolConversions*/false); 6704 if (VecResTy.isNull()) return QualType(); 6705 // The result type must match the condition type as specified in 6706 // OpenCL v1.1 s6.11.6. 6707 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6708 return QualType(); 6709 return VecResTy; 6710 } 6711 6712 // Both operands are scalar. 6713 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6714 } 6715 6716 /// \brief Return true if the Expr is block type 6717 static bool checkBlockType(Sema &S, const Expr *E) { 6718 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6719 QualType Ty = CE->getCallee()->getType(); 6720 if (Ty->isBlockPointerType()) { 6721 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6722 return true; 6723 } 6724 } 6725 return false; 6726 } 6727 6728 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6729 /// In that case, LHS = cond. 6730 /// C99 6.5.15 6731 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6732 ExprResult &RHS, ExprValueKind &VK, 6733 ExprObjectKind &OK, 6734 SourceLocation QuestionLoc) { 6735 6736 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6737 if (!LHSResult.isUsable()) return QualType(); 6738 LHS = LHSResult; 6739 6740 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6741 if (!RHSResult.isUsable()) return QualType(); 6742 RHS = RHSResult; 6743 6744 // C++ is sufficiently different to merit its own checker. 6745 if (getLangOpts().CPlusPlus) 6746 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6747 6748 VK = VK_RValue; 6749 OK = OK_Ordinary; 6750 6751 // The OpenCL operator with a vector condition is sufficiently 6752 // different to merit its own checker. 6753 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6754 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6755 6756 // First, check the condition. 6757 Cond = UsualUnaryConversions(Cond.get()); 6758 if (Cond.isInvalid()) 6759 return QualType(); 6760 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6761 return QualType(); 6762 6763 // Now check the two expressions. 6764 if (LHS.get()->getType()->isVectorType() || 6765 RHS.get()->getType()->isVectorType()) 6766 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6767 /*AllowBothBool*/true, 6768 /*AllowBoolConversions*/false); 6769 6770 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6771 if (LHS.isInvalid() || RHS.isInvalid()) 6772 return QualType(); 6773 6774 QualType LHSTy = LHS.get()->getType(); 6775 QualType RHSTy = RHS.get()->getType(); 6776 6777 // Diagnose attempts to convert between __float128 and long double where 6778 // such conversions currently can't be handled. 6779 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6780 Diag(QuestionLoc, 6781 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6782 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6783 return QualType(); 6784 } 6785 6786 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6787 // selection operator (?:). 6788 if (getLangOpts().OpenCL && 6789 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6790 return QualType(); 6791 } 6792 6793 // If both operands have arithmetic type, do the usual arithmetic conversions 6794 // to find a common type: C99 6.5.15p3,5. 6795 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6796 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6797 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6798 6799 return ResTy; 6800 } 6801 6802 // If both operands are the same structure or union type, the result is that 6803 // type. 6804 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6805 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6806 if (LHSRT->getDecl() == RHSRT->getDecl()) 6807 // "If both the operands have structure or union type, the result has 6808 // that type." This implies that CV qualifiers are dropped. 6809 return LHSTy.getUnqualifiedType(); 6810 // FIXME: Type of conditional expression must be complete in C mode. 6811 } 6812 6813 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6814 // The following || allows only one side to be void (a GCC-ism). 6815 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6816 return checkConditionalVoidType(*this, LHS, RHS); 6817 } 6818 6819 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6820 // the type of the other operand." 6821 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6822 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6823 6824 // All objective-c pointer type analysis is done here. 6825 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6826 QuestionLoc); 6827 if (LHS.isInvalid() || RHS.isInvalid()) 6828 return QualType(); 6829 if (!compositeType.isNull()) 6830 return compositeType; 6831 6832 6833 // Handle block pointer types. 6834 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6835 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6836 QuestionLoc); 6837 6838 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6839 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6840 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6841 QuestionLoc); 6842 6843 // GCC compatibility: soften pointer/integer mismatch. Note that 6844 // null pointers have been filtered out by this point. 6845 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6846 /*isIntFirstExpr=*/true)) 6847 return RHSTy; 6848 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6849 /*isIntFirstExpr=*/false)) 6850 return LHSTy; 6851 6852 // Emit a better diagnostic if one of the expressions is a null pointer 6853 // constant and the other is not a pointer type. In this case, the user most 6854 // likely forgot to take the address of the other expression. 6855 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6856 return QualType(); 6857 6858 // Otherwise, the operands are not compatible. 6859 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6860 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6861 << RHS.get()->getSourceRange(); 6862 return QualType(); 6863 } 6864 6865 /// FindCompositeObjCPointerType - Helper method to find composite type of 6866 /// two objective-c pointer types of the two input expressions. 6867 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6868 SourceLocation QuestionLoc) { 6869 QualType LHSTy = LHS.get()->getType(); 6870 QualType RHSTy = RHS.get()->getType(); 6871 6872 // Handle things like Class and struct objc_class*. Here we case the result 6873 // to the pseudo-builtin, because that will be implicitly cast back to the 6874 // redefinition type if an attempt is made to access its fields. 6875 if (LHSTy->isObjCClassType() && 6876 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6877 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6878 return LHSTy; 6879 } 6880 if (RHSTy->isObjCClassType() && 6881 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6882 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6883 return RHSTy; 6884 } 6885 // And the same for struct objc_object* / id 6886 if (LHSTy->isObjCIdType() && 6887 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6888 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6889 return LHSTy; 6890 } 6891 if (RHSTy->isObjCIdType() && 6892 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6893 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6894 return RHSTy; 6895 } 6896 // And the same for struct objc_selector* / SEL 6897 if (Context.isObjCSelType(LHSTy) && 6898 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6899 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6900 return LHSTy; 6901 } 6902 if (Context.isObjCSelType(RHSTy) && 6903 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6904 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6905 return RHSTy; 6906 } 6907 // Check constraints for Objective-C object pointers types. 6908 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6909 6910 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6911 // Two identical object pointer types are always compatible. 6912 return LHSTy; 6913 } 6914 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6915 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6916 QualType compositeType = LHSTy; 6917 6918 // If both operands are interfaces and either operand can be 6919 // assigned to the other, use that type as the composite 6920 // type. This allows 6921 // xxx ? (A*) a : (B*) b 6922 // where B is a subclass of A. 6923 // 6924 // Additionally, as for assignment, if either type is 'id' 6925 // allow silent coercion. Finally, if the types are 6926 // incompatible then make sure to use 'id' as the composite 6927 // type so the result is acceptable for sending messages to. 6928 6929 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6930 // It could return the composite type. 6931 if (!(compositeType = 6932 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6933 // Nothing more to do. 6934 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6935 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6936 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6937 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6938 } else if ((LHSTy->isObjCQualifiedIdType() || 6939 RHSTy->isObjCQualifiedIdType()) && 6940 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6941 // Need to handle "id<xx>" explicitly. 6942 // GCC allows qualified id and any Objective-C type to devolve to 6943 // id. Currently localizing to here until clear this should be 6944 // part of ObjCQualifiedIdTypesAreCompatible. 6945 compositeType = Context.getObjCIdType(); 6946 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6947 compositeType = Context.getObjCIdType(); 6948 } else { 6949 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6950 << LHSTy << RHSTy 6951 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6952 QualType incompatTy = Context.getObjCIdType(); 6953 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6954 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6955 return incompatTy; 6956 } 6957 // The object pointer types are compatible. 6958 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6959 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6960 return compositeType; 6961 } 6962 // Check Objective-C object pointer types and 'void *' 6963 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6964 if (getLangOpts().ObjCAutoRefCount) { 6965 // ARC forbids the implicit conversion of object pointers to 'void *', 6966 // so these types are not compatible. 6967 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6968 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6969 LHS = RHS = true; 6970 return QualType(); 6971 } 6972 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6973 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6974 QualType destPointee 6975 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6976 QualType destType = Context.getPointerType(destPointee); 6977 // Add qualifiers if necessary. 6978 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6979 // Promote to void*. 6980 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6981 return destType; 6982 } 6983 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6984 if (getLangOpts().ObjCAutoRefCount) { 6985 // ARC forbids the implicit conversion of object pointers to 'void *', 6986 // so these types are not compatible. 6987 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6988 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6989 LHS = RHS = true; 6990 return QualType(); 6991 } 6992 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6993 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6994 QualType destPointee 6995 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6996 QualType destType = Context.getPointerType(destPointee); 6997 // Add qualifiers if necessary. 6998 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6999 // Promote to void*. 7000 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7001 return destType; 7002 } 7003 return QualType(); 7004 } 7005 7006 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7007 /// ParenRange in parentheses. 7008 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7009 const PartialDiagnostic &Note, 7010 SourceRange ParenRange) { 7011 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7012 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7013 EndLoc.isValid()) { 7014 Self.Diag(Loc, Note) 7015 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7016 << FixItHint::CreateInsertion(EndLoc, ")"); 7017 } else { 7018 // We can't display the parentheses, so just show the bare note. 7019 Self.Diag(Loc, Note) << ParenRange; 7020 } 7021 } 7022 7023 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7024 return BinaryOperator::isAdditiveOp(Opc) || 7025 BinaryOperator::isMultiplicativeOp(Opc) || 7026 BinaryOperator::isShiftOp(Opc); 7027 } 7028 7029 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7030 /// expression, either using a built-in or overloaded operator, 7031 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7032 /// expression. 7033 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7034 Expr **RHSExprs) { 7035 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7036 E = E->IgnoreImpCasts(); 7037 E = E->IgnoreConversionOperator(); 7038 E = E->IgnoreImpCasts(); 7039 7040 // Built-in binary operator. 7041 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7042 if (IsArithmeticOp(OP->getOpcode())) { 7043 *Opcode = OP->getOpcode(); 7044 *RHSExprs = OP->getRHS(); 7045 return true; 7046 } 7047 } 7048 7049 // Overloaded operator. 7050 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7051 if (Call->getNumArgs() != 2) 7052 return false; 7053 7054 // Make sure this is really a binary operator that is safe to pass into 7055 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7056 OverloadedOperatorKind OO = Call->getOperator(); 7057 if (OO < OO_Plus || OO > OO_Arrow || 7058 OO == OO_PlusPlus || OO == OO_MinusMinus) 7059 return false; 7060 7061 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7062 if (IsArithmeticOp(OpKind)) { 7063 *Opcode = OpKind; 7064 *RHSExprs = Call->getArg(1); 7065 return true; 7066 } 7067 } 7068 7069 return false; 7070 } 7071 7072 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7073 /// or is a logical expression such as (x==y) which has int type, but is 7074 /// commonly interpreted as boolean. 7075 static bool ExprLooksBoolean(Expr *E) { 7076 E = E->IgnoreParenImpCasts(); 7077 7078 if (E->getType()->isBooleanType()) 7079 return true; 7080 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7081 return OP->isComparisonOp() || OP->isLogicalOp(); 7082 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7083 return OP->getOpcode() == UO_LNot; 7084 if (E->getType()->isPointerType()) 7085 return true; 7086 7087 return false; 7088 } 7089 7090 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7091 /// and binary operator are mixed in a way that suggests the programmer assumed 7092 /// the conditional operator has higher precedence, for example: 7093 /// "int x = a + someBinaryCondition ? 1 : 2". 7094 static void DiagnoseConditionalPrecedence(Sema &Self, 7095 SourceLocation OpLoc, 7096 Expr *Condition, 7097 Expr *LHSExpr, 7098 Expr *RHSExpr) { 7099 BinaryOperatorKind CondOpcode; 7100 Expr *CondRHS; 7101 7102 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7103 return; 7104 if (!ExprLooksBoolean(CondRHS)) 7105 return; 7106 7107 // The condition is an arithmetic binary expression, with a right- 7108 // hand side that looks boolean, so warn. 7109 7110 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7111 << Condition->getSourceRange() 7112 << BinaryOperator::getOpcodeStr(CondOpcode); 7113 7114 SuggestParentheses(Self, OpLoc, 7115 Self.PDiag(diag::note_precedence_silence) 7116 << BinaryOperator::getOpcodeStr(CondOpcode), 7117 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7118 7119 SuggestParentheses(Self, OpLoc, 7120 Self.PDiag(diag::note_precedence_conditional_first), 7121 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7122 } 7123 7124 /// Compute the nullability of a conditional expression. 7125 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7126 QualType LHSTy, QualType RHSTy, 7127 ASTContext &Ctx) { 7128 if (!ResTy->isAnyPointerType()) 7129 return ResTy; 7130 7131 auto GetNullability = [&Ctx](QualType Ty) { 7132 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7133 if (Kind) 7134 return *Kind; 7135 return NullabilityKind::Unspecified; 7136 }; 7137 7138 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7139 NullabilityKind MergedKind; 7140 7141 // Compute nullability of a binary conditional expression. 7142 if (IsBin) { 7143 if (LHSKind == NullabilityKind::NonNull) 7144 MergedKind = NullabilityKind::NonNull; 7145 else 7146 MergedKind = RHSKind; 7147 // Compute nullability of a normal conditional expression. 7148 } else { 7149 if (LHSKind == NullabilityKind::Nullable || 7150 RHSKind == NullabilityKind::Nullable) 7151 MergedKind = NullabilityKind::Nullable; 7152 else if (LHSKind == NullabilityKind::NonNull) 7153 MergedKind = RHSKind; 7154 else if (RHSKind == NullabilityKind::NonNull) 7155 MergedKind = LHSKind; 7156 else 7157 MergedKind = NullabilityKind::Unspecified; 7158 } 7159 7160 // Return if ResTy already has the correct nullability. 7161 if (GetNullability(ResTy) == MergedKind) 7162 return ResTy; 7163 7164 // Strip all nullability from ResTy. 7165 while (ResTy->getNullability(Ctx)) 7166 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7167 7168 // Create a new AttributedType with the new nullability kind. 7169 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7170 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7171 } 7172 7173 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7174 /// in the case of a the GNU conditional expr extension. 7175 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7176 SourceLocation ColonLoc, 7177 Expr *CondExpr, Expr *LHSExpr, 7178 Expr *RHSExpr) { 7179 if (!getLangOpts().CPlusPlus) { 7180 // C cannot handle TypoExpr nodes in the condition because it 7181 // doesn't handle dependent types properly, so make sure any TypoExprs have 7182 // been dealt with before checking the operands. 7183 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7184 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7185 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7186 7187 if (!CondResult.isUsable()) 7188 return ExprError(); 7189 7190 if (LHSExpr) { 7191 if (!LHSResult.isUsable()) 7192 return ExprError(); 7193 } 7194 7195 if (!RHSResult.isUsable()) 7196 return ExprError(); 7197 7198 CondExpr = CondResult.get(); 7199 LHSExpr = LHSResult.get(); 7200 RHSExpr = RHSResult.get(); 7201 } 7202 7203 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7204 // was the condition. 7205 OpaqueValueExpr *opaqueValue = nullptr; 7206 Expr *commonExpr = nullptr; 7207 if (!LHSExpr) { 7208 commonExpr = CondExpr; 7209 // Lower out placeholder types first. This is important so that we don't 7210 // try to capture a placeholder. This happens in few cases in C++; such 7211 // as Objective-C++'s dictionary subscripting syntax. 7212 if (commonExpr->hasPlaceholderType()) { 7213 ExprResult result = CheckPlaceholderExpr(commonExpr); 7214 if (!result.isUsable()) return ExprError(); 7215 commonExpr = result.get(); 7216 } 7217 // We usually want to apply unary conversions *before* saving, except 7218 // in the special case of a C++ l-value conditional. 7219 if (!(getLangOpts().CPlusPlus 7220 && !commonExpr->isTypeDependent() 7221 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7222 && commonExpr->isGLValue() 7223 && commonExpr->isOrdinaryOrBitFieldObject() 7224 && RHSExpr->isOrdinaryOrBitFieldObject() 7225 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7226 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7227 if (commonRes.isInvalid()) 7228 return ExprError(); 7229 commonExpr = commonRes.get(); 7230 } 7231 7232 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7233 commonExpr->getType(), 7234 commonExpr->getValueKind(), 7235 commonExpr->getObjectKind(), 7236 commonExpr); 7237 LHSExpr = CondExpr = opaqueValue; 7238 } 7239 7240 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7241 ExprValueKind VK = VK_RValue; 7242 ExprObjectKind OK = OK_Ordinary; 7243 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7244 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7245 VK, OK, QuestionLoc); 7246 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7247 RHS.isInvalid()) 7248 return ExprError(); 7249 7250 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7251 RHS.get()); 7252 7253 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7254 7255 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7256 Context); 7257 7258 if (!commonExpr) 7259 return new (Context) 7260 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7261 RHS.get(), result, VK, OK); 7262 7263 return new (Context) BinaryConditionalOperator( 7264 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7265 ColonLoc, result, VK, OK); 7266 } 7267 7268 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7269 // being closely modeled after the C99 spec:-). The odd characteristic of this 7270 // routine is it effectively iqnores the qualifiers on the top level pointee. 7271 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7272 // FIXME: add a couple examples in this comment. 7273 static Sema::AssignConvertType 7274 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7275 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7276 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7277 7278 // get the "pointed to" type (ignoring qualifiers at the top level) 7279 const Type *lhptee, *rhptee; 7280 Qualifiers lhq, rhq; 7281 std::tie(lhptee, lhq) = 7282 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7283 std::tie(rhptee, rhq) = 7284 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7285 7286 Sema::AssignConvertType ConvTy = Sema::Compatible; 7287 7288 // C99 6.5.16.1p1: This following citation is common to constraints 7289 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7290 // qualifiers of the type *pointed to* by the right; 7291 7292 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7293 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7294 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7295 // Ignore lifetime for further calculation. 7296 lhq.removeObjCLifetime(); 7297 rhq.removeObjCLifetime(); 7298 } 7299 7300 if (!lhq.compatiblyIncludes(rhq)) { 7301 // Treat address-space mismatches as fatal. TODO: address subspaces 7302 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7303 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7304 7305 // It's okay to add or remove GC or lifetime qualifiers when converting to 7306 // and from void*. 7307 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7308 .compatiblyIncludes( 7309 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7310 && (lhptee->isVoidType() || rhptee->isVoidType())) 7311 ; // keep old 7312 7313 // Treat lifetime mismatches as fatal. 7314 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7315 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7316 7317 // For GCC/MS compatibility, other qualifier mismatches are treated 7318 // as still compatible in C. 7319 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7320 } 7321 7322 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7323 // incomplete type and the other is a pointer to a qualified or unqualified 7324 // version of void... 7325 if (lhptee->isVoidType()) { 7326 if (rhptee->isIncompleteOrObjectType()) 7327 return ConvTy; 7328 7329 // As an extension, we allow cast to/from void* to function pointer. 7330 assert(rhptee->isFunctionType()); 7331 return Sema::FunctionVoidPointer; 7332 } 7333 7334 if (rhptee->isVoidType()) { 7335 if (lhptee->isIncompleteOrObjectType()) 7336 return ConvTy; 7337 7338 // As an extension, we allow cast to/from void* to function pointer. 7339 assert(lhptee->isFunctionType()); 7340 return Sema::FunctionVoidPointer; 7341 } 7342 7343 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7344 // unqualified versions of compatible types, ... 7345 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7346 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7347 // Check if the pointee types are compatible ignoring the sign. 7348 // We explicitly check for char so that we catch "char" vs 7349 // "unsigned char" on systems where "char" is unsigned. 7350 if (lhptee->isCharType()) 7351 ltrans = S.Context.UnsignedCharTy; 7352 else if (lhptee->hasSignedIntegerRepresentation()) 7353 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7354 7355 if (rhptee->isCharType()) 7356 rtrans = S.Context.UnsignedCharTy; 7357 else if (rhptee->hasSignedIntegerRepresentation()) 7358 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7359 7360 if (ltrans == rtrans) { 7361 // Types are compatible ignoring the sign. Qualifier incompatibility 7362 // takes priority over sign incompatibility because the sign 7363 // warning can be disabled. 7364 if (ConvTy != Sema::Compatible) 7365 return ConvTy; 7366 7367 return Sema::IncompatiblePointerSign; 7368 } 7369 7370 // If we are a multi-level pointer, it's possible that our issue is simply 7371 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7372 // the eventual target type is the same and the pointers have the same 7373 // level of indirection, this must be the issue. 7374 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7375 do { 7376 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7377 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7378 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7379 7380 if (lhptee == rhptee) 7381 return Sema::IncompatibleNestedPointerQualifiers; 7382 } 7383 7384 // General pointer incompatibility takes priority over qualifiers. 7385 return Sema::IncompatiblePointer; 7386 } 7387 if (!S.getLangOpts().CPlusPlus && 7388 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7389 return Sema::IncompatiblePointer; 7390 return ConvTy; 7391 } 7392 7393 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7394 /// block pointer types are compatible or whether a block and normal pointer 7395 /// are compatible. It is more restrict than comparing two function pointer 7396 // types. 7397 static Sema::AssignConvertType 7398 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7399 QualType RHSType) { 7400 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7401 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7402 7403 QualType lhptee, rhptee; 7404 7405 // get the "pointed to" type (ignoring qualifiers at the top level) 7406 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7407 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7408 7409 // In C++, the types have to match exactly. 7410 if (S.getLangOpts().CPlusPlus) 7411 return Sema::IncompatibleBlockPointer; 7412 7413 Sema::AssignConvertType ConvTy = Sema::Compatible; 7414 7415 // For blocks we enforce that qualifiers are identical. 7416 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7417 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7418 if (S.getLangOpts().OpenCL) { 7419 LQuals.removeAddressSpace(); 7420 RQuals.removeAddressSpace(); 7421 } 7422 if (LQuals != RQuals) 7423 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7424 7425 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7426 // assignment. 7427 // The current behavior is similar to C++ lambdas. A block might be 7428 // assigned to a variable iff its return type and parameters are compatible 7429 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7430 // an assignment. Presumably it should behave in way that a function pointer 7431 // assignment does in C, so for each parameter and return type: 7432 // * CVR and address space of LHS should be a superset of CVR and address 7433 // space of RHS. 7434 // * unqualified types should be compatible. 7435 if (S.getLangOpts().OpenCL) { 7436 if (!S.Context.typesAreBlockPointerCompatible( 7437 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7438 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7439 return Sema::IncompatibleBlockPointer; 7440 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7441 return Sema::IncompatibleBlockPointer; 7442 7443 return ConvTy; 7444 } 7445 7446 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7447 /// for assignment compatibility. 7448 static Sema::AssignConvertType 7449 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7450 QualType RHSType) { 7451 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7452 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7453 7454 if (LHSType->isObjCBuiltinType()) { 7455 // Class is not compatible with ObjC object pointers. 7456 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7457 !RHSType->isObjCQualifiedClassType()) 7458 return Sema::IncompatiblePointer; 7459 return Sema::Compatible; 7460 } 7461 if (RHSType->isObjCBuiltinType()) { 7462 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7463 !LHSType->isObjCQualifiedClassType()) 7464 return Sema::IncompatiblePointer; 7465 return Sema::Compatible; 7466 } 7467 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7468 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7469 7470 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7471 // make an exception for id<P> 7472 !LHSType->isObjCQualifiedIdType()) 7473 return Sema::CompatiblePointerDiscardsQualifiers; 7474 7475 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7476 return Sema::Compatible; 7477 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7478 return Sema::IncompatibleObjCQualifiedId; 7479 return Sema::IncompatiblePointer; 7480 } 7481 7482 Sema::AssignConvertType 7483 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7484 QualType LHSType, QualType RHSType) { 7485 // Fake up an opaque expression. We don't actually care about what 7486 // cast operations are required, so if CheckAssignmentConstraints 7487 // adds casts to this they'll be wasted, but fortunately that doesn't 7488 // usually happen on valid code. 7489 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7490 ExprResult RHSPtr = &RHSExpr; 7491 CastKind K = CK_Invalid; 7492 7493 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7494 } 7495 7496 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7497 /// has code to accommodate several GCC extensions when type checking 7498 /// pointers. Here are some objectionable examples that GCC considers warnings: 7499 /// 7500 /// int a, *pint; 7501 /// short *pshort; 7502 /// struct foo *pfoo; 7503 /// 7504 /// pint = pshort; // warning: assignment from incompatible pointer type 7505 /// a = pint; // warning: assignment makes integer from pointer without a cast 7506 /// pint = a; // warning: assignment makes pointer from integer without a cast 7507 /// pint = pfoo; // warning: assignment from incompatible pointer type 7508 /// 7509 /// As a result, the code for dealing with pointers is more complex than the 7510 /// C99 spec dictates. 7511 /// 7512 /// Sets 'Kind' for any result kind except Incompatible. 7513 Sema::AssignConvertType 7514 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7515 CastKind &Kind, bool ConvertRHS) { 7516 QualType RHSType = RHS.get()->getType(); 7517 QualType OrigLHSType = LHSType; 7518 7519 // Get canonical types. We're not formatting these types, just comparing 7520 // them. 7521 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7522 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7523 7524 // Common case: no conversion required. 7525 if (LHSType == RHSType) { 7526 Kind = CK_NoOp; 7527 return Compatible; 7528 } 7529 7530 // If we have an atomic type, try a non-atomic assignment, then just add an 7531 // atomic qualification step. 7532 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7533 Sema::AssignConvertType result = 7534 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7535 if (result != Compatible) 7536 return result; 7537 if (Kind != CK_NoOp && ConvertRHS) 7538 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7539 Kind = CK_NonAtomicToAtomic; 7540 return Compatible; 7541 } 7542 7543 // If the left-hand side is a reference type, then we are in a 7544 // (rare!) case where we've allowed the use of references in C, 7545 // e.g., as a parameter type in a built-in function. In this case, 7546 // just make sure that the type referenced is compatible with the 7547 // right-hand side type. The caller is responsible for adjusting 7548 // LHSType so that the resulting expression does not have reference 7549 // type. 7550 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7551 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7552 Kind = CK_LValueBitCast; 7553 return Compatible; 7554 } 7555 return Incompatible; 7556 } 7557 7558 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7559 // to the same ExtVector type. 7560 if (LHSType->isExtVectorType()) { 7561 if (RHSType->isExtVectorType()) 7562 return Incompatible; 7563 if (RHSType->isArithmeticType()) { 7564 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7565 if (ConvertRHS) 7566 RHS = prepareVectorSplat(LHSType, RHS.get()); 7567 Kind = CK_VectorSplat; 7568 return Compatible; 7569 } 7570 } 7571 7572 // Conversions to or from vector type. 7573 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7574 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7575 // Allow assignments of an AltiVec vector type to an equivalent GCC 7576 // vector type and vice versa 7577 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7578 Kind = CK_BitCast; 7579 return Compatible; 7580 } 7581 7582 // If we are allowing lax vector conversions, and LHS and RHS are both 7583 // vectors, the total size only needs to be the same. This is a bitcast; 7584 // no bits are changed but the result type is different. 7585 if (isLaxVectorConversion(RHSType, LHSType)) { 7586 Kind = CK_BitCast; 7587 return IncompatibleVectors; 7588 } 7589 } 7590 7591 // When the RHS comes from another lax conversion (e.g. binops between 7592 // scalars and vectors) the result is canonicalized as a vector. When the 7593 // LHS is also a vector, the lax is allowed by the condition above. Handle 7594 // the case where LHS is a scalar. 7595 if (LHSType->isScalarType()) { 7596 const VectorType *VecType = RHSType->getAs<VectorType>(); 7597 if (VecType && VecType->getNumElements() == 1 && 7598 isLaxVectorConversion(RHSType, LHSType)) { 7599 ExprResult *VecExpr = &RHS; 7600 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7601 Kind = CK_BitCast; 7602 return Compatible; 7603 } 7604 } 7605 7606 return Incompatible; 7607 } 7608 7609 // Diagnose attempts to convert between __float128 and long double where 7610 // such conversions currently can't be handled. 7611 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7612 return Incompatible; 7613 7614 // Arithmetic conversions. 7615 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7616 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7617 if (ConvertRHS) 7618 Kind = PrepareScalarCast(RHS, LHSType); 7619 return Compatible; 7620 } 7621 7622 // Conversions to normal pointers. 7623 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7624 // U* -> T* 7625 if (isa<PointerType>(RHSType)) { 7626 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7627 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7628 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7629 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7630 } 7631 7632 // int -> T* 7633 if (RHSType->isIntegerType()) { 7634 Kind = CK_IntegralToPointer; // FIXME: null? 7635 return IntToPointer; 7636 } 7637 7638 // C pointers are not compatible with ObjC object pointers, 7639 // with two exceptions: 7640 if (isa<ObjCObjectPointerType>(RHSType)) { 7641 // - conversions to void* 7642 if (LHSPointer->getPointeeType()->isVoidType()) { 7643 Kind = CK_BitCast; 7644 return Compatible; 7645 } 7646 7647 // - conversions from 'Class' to the redefinition type 7648 if (RHSType->isObjCClassType() && 7649 Context.hasSameType(LHSType, 7650 Context.getObjCClassRedefinitionType())) { 7651 Kind = CK_BitCast; 7652 return Compatible; 7653 } 7654 7655 Kind = CK_BitCast; 7656 return IncompatiblePointer; 7657 } 7658 7659 // U^ -> void* 7660 if (RHSType->getAs<BlockPointerType>()) { 7661 if (LHSPointer->getPointeeType()->isVoidType()) { 7662 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7663 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7664 ->getPointeeType() 7665 .getAddressSpace(); 7666 Kind = 7667 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7668 return Compatible; 7669 } 7670 } 7671 7672 return Incompatible; 7673 } 7674 7675 // Conversions to block pointers. 7676 if (isa<BlockPointerType>(LHSType)) { 7677 // U^ -> T^ 7678 if (RHSType->isBlockPointerType()) { 7679 unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>() 7680 ->getPointeeType() 7681 .getAddressSpace(); 7682 unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>() 7683 ->getPointeeType() 7684 .getAddressSpace(); 7685 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7686 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7687 } 7688 7689 // int or null -> T^ 7690 if (RHSType->isIntegerType()) { 7691 Kind = CK_IntegralToPointer; // FIXME: null 7692 return IntToBlockPointer; 7693 } 7694 7695 // id -> T^ 7696 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7697 Kind = CK_AnyPointerToBlockPointerCast; 7698 return Compatible; 7699 } 7700 7701 // void* -> T^ 7702 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7703 if (RHSPT->getPointeeType()->isVoidType()) { 7704 Kind = CK_AnyPointerToBlockPointerCast; 7705 return Compatible; 7706 } 7707 7708 return Incompatible; 7709 } 7710 7711 // Conversions to Objective-C pointers. 7712 if (isa<ObjCObjectPointerType>(LHSType)) { 7713 // A* -> B* 7714 if (RHSType->isObjCObjectPointerType()) { 7715 Kind = CK_BitCast; 7716 Sema::AssignConvertType result = 7717 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7718 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7719 result == Compatible && 7720 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7721 result = IncompatibleObjCWeakRef; 7722 return result; 7723 } 7724 7725 // int or null -> A* 7726 if (RHSType->isIntegerType()) { 7727 Kind = CK_IntegralToPointer; // FIXME: null 7728 return IntToPointer; 7729 } 7730 7731 // In general, C pointers are not compatible with ObjC object pointers, 7732 // with two exceptions: 7733 if (isa<PointerType>(RHSType)) { 7734 Kind = CK_CPointerToObjCPointerCast; 7735 7736 // - conversions from 'void*' 7737 if (RHSType->isVoidPointerType()) { 7738 return Compatible; 7739 } 7740 7741 // - conversions to 'Class' from its redefinition type 7742 if (LHSType->isObjCClassType() && 7743 Context.hasSameType(RHSType, 7744 Context.getObjCClassRedefinitionType())) { 7745 return Compatible; 7746 } 7747 7748 return IncompatiblePointer; 7749 } 7750 7751 // Only under strict condition T^ is compatible with an Objective-C pointer. 7752 if (RHSType->isBlockPointerType() && 7753 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7754 if (ConvertRHS) 7755 maybeExtendBlockObject(RHS); 7756 Kind = CK_BlockPointerToObjCPointerCast; 7757 return Compatible; 7758 } 7759 7760 return Incompatible; 7761 } 7762 7763 // Conversions from pointers that are not covered by the above. 7764 if (isa<PointerType>(RHSType)) { 7765 // T* -> _Bool 7766 if (LHSType == Context.BoolTy) { 7767 Kind = CK_PointerToBoolean; 7768 return Compatible; 7769 } 7770 7771 // T* -> int 7772 if (LHSType->isIntegerType()) { 7773 Kind = CK_PointerToIntegral; 7774 return PointerToInt; 7775 } 7776 7777 return Incompatible; 7778 } 7779 7780 // Conversions from Objective-C pointers that are not covered by the above. 7781 if (isa<ObjCObjectPointerType>(RHSType)) { 7782 // T* -> _Bool 7783 if (LHSType == Context.BoolTy) { 7784 Kind = CK_PointerToBoolean; 7785 return Compatible; 7786 } 7787 7788 // T* -> int 7789 if (LHSType->isIntegerType()) { 7790 Kind = CK_PointerToIntegral; 7791 return PointerToInt; 7792 } 7793 7794 return Incompatible; 7795 } 7796 7797 // struct A -> struct B 7798 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7799 if (Context.typesAreCompatible(LHSType, RHSType)) { 7800 Kind = CK_NoOp; 7801 return Compatible; 7802 } 7803 } 7804 7805 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7806 Kind = CK_IntToOCLSampler; 7807 return Compatible; 7808 } 7809 7810 return Incompatible; 7811 } 7812 7813 /// \brief Constructs a transparent union from an expression that is 7814 /// used to initialize the transparent union. 7815 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7816 ExprResult &EResult, QualType UnionType, 7817 FieldDecl *Field) { 7818 // Build an initializer list that designates the appropriate member 7819 // of the transparent union. 7820 Expr *E = EResult.get(); 7821 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7822 E, SourceLocation()); 7823 Initializer->setType(UnionType); 7824 Initializer->setInitializedFieldInUnion(Field); 7825 7826 // Build a compound literal constructing a value of the transparent 7827 // union type from this initializer list. 7828 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7829 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7830 VK_RValue, Initializer, false); 7831 } 7832 7833 Sema::AssignConvertType 7834 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7835 ExprResult &RHS) { 7836 QualType RHSType = RHS.get()->getType(); 7837 7838 // If the ArgType is a Union type, we want to handle a potential 7839 // transparent_union GCC extension. 7840 const RecordType *UT = ArgType->getAsUnionType(); 7841 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7842 return Incompatible; 7843 7844 // The field to initialize within the transparent union. 7845 RecordDecl *UD = UT->getDecl(); 7846 FieldDecl *InitField = nullptr; 7847 // It's compatible if the expression matches any of the fields. 7848 for (auto *it : UD->fields()) { 7849 if (it->getType()->isPointerType()) { 7850 // If the transparent union contains a pointer type, we allow: 7851 // 1) void pointer 7852 // 2) null pointer constant 7853 if (RHSType->isPointerType()) 7854 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7855 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7856 InitField = it; 7857 break; 7858 } 7859 7860 if (RHS.get()->isNullPointerConstant(Context, 7861 Expr::NPC_ValueDependentIsNull)) { 7862 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7863 CK_NullToPointer); 7864 InitField = it; 7865 break; 7866 } 7867 } 7868 7869 CastKind Kind = CK_Invalid; 7870 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7871 == Compatible) { 7872 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7873 InitField = it; 7874 break; 7875 } 7876 } 7877 7878 if (!InitField) 7879 return Incompatible; 7880 7881 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7882 return Compatible; 7883 } 7884 7885 Sema::AssignConvertType 7886 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7887 bool Diagnose, 7888 bool DiagnoseCFAudited, 7889 bool ConvertRHS) { 7890 // We need to be able to tell the caller whether we diagnosed a problem, if 7891 // they ask us to issue diagnostics. 7892 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7893 7894 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7895 // we can't avoid *all* modifications at the moment, so we need some somewhere 7896 // to put the updated value. 7897 ExprResult LocalRHS = CallerRHS; 7898 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7899 7900 if (getLangOpts().CPlusPlus) { 7901 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7902 // C++ 5.17p3: If the left operand is not of class type, the 7903 // expression is implicitly converted (C++ 4) to the 7904 // cv-unqualified type of the left operand. 7905 QualType RHSType = RHS.get()->getType(); 7906 if (Diagnose) { 7907 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7908 AA_Assigning); 7909 } else { 7910 ImplicitConversionSequence ICS = 7911 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7912 /*SuppressUserConversions=*/false, 7913 /*AllowExplicit=*/false, 7914 /*InOverloadResolution=*/false, 7915 /*CStyle=*/false, 7916 /*AllowObjCWritebackConversion=*/false); 7917 if (ICS.isFailure()) 7918 return Incompatible; 7919 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7920 ICS, AA_Assigning); 7921 } 7922 if (RHS.isInvalid()) 7923 return Incompatible; 7924 Sema::AssignConvertType result = Compatible; 7925 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7926 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7927 result = IncompatibleObjCWeakRef; 7928 return result; 7929 } 7930 7931 // FIXME: Currently, we fall through and treat C++ classes like C 7932 // structures. 7933 // FIXME: We also fall through for atomics; not sure what should 7934 // happen there, though. 7935 } else if (RHS.get()->getType() == Context.OverloadTy) { 7936 // As a set of extensions to C, we support overloading on functions. These 7937 // functions need to be resolved here. 7938 DeclAccessPair DAP; 7939 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7940 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7941 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7942 else 7943 return Incompatible; 7944 } 7945 7946 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7947 // a null pointer constant. 7948 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7949 LHSType->isBlockPointerType()) && 7950 RHS.get()->isNullPointerConstant(Context, 7951 Expr::NPC_ValueDependentIsNull)) { 7952 if (Diagnose || ConvertRHS) { 7953 CastKind Kind; 7954 CXXCastPath Path; 7955 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7956 /*IgnoreBaseAccess=*/false, Diagnose); 7957 if (ConvertRHS) 7958 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7959 } 7960 return Compatible; 7961 } 7962 7963 // This check seems unnatural, however it is necessary to ensure the proper 7964 // conversion of functions/arrays. If the conversion were done for all 7965 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7966 // expressions that suppress this implicit conversion (&, sizeof). 7967 // 7968 // Suppress this for references: C++ 8.5.3p5. 7969 if (!LHSType->isReferenceType()) { 7970 // FIXME: We potentially allocate here even if ConvertRHS is false. 7971 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7972 if (RHS.isInvalid()) 7973 return Incompatible; 7974 } 7975 7976 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7977 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7978 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7979 if (PDecl && !PDecl->hasDefinition()) { 7980 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7981 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7982 } 7983 } 7984 7985 CastKind Kind = CK_Invalid; 7986 Sema::AssignConvertType result = 7987 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7988 7989 // C99 6.5.16.1p2: The value of the right operand is converted to the 7990 // type of the assignment expression. 7991 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7992 // so that we can use references in built-in functions even in C. 7993 // The getNonReferenceType() call makes sure that the resulting expression 7994 // does not have reference type. 7995 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7996 QualType Ty = LHSType.getNonLValueExprType(Context); 7997 Expr *E = RHS.get(); 7998 7999 // Check for various Objective-C errors. If we are not reporting 8000 // diagnostics and just checking for errors, e.g., during overload 8001 // resolution, return Incompatible to indicate the failure. 8002 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8003 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8004 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8005 if (!Diagnose) 8006 return Incompatible; 8007 } 8008 if (getLangOpts().ObjC1 && 8009 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8010 E->getType(), E, Diagnose) || 8011 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8012 if (!Diagnose) 8013 return Incompatible; 8014 // Replace the expression with a corrected version and continue so we 8015 // can find further errors. 8016 RHS = E; 8017 return Compatible; 8018 } 8019 8020 if (ConvertRHS) 8021 RHS = ImpCastExprToType(E, Ty, Kind); 8022 } 8023 return result; 8024 } 8025 8026 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8027 ExprResult &RHS) { 8028 Diag(Loc, diag::err_typecheck_invalid_operands) 8029 << LHS.get()->getType() << RHS.get()->getType() 8030 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8031 return QualType(); 8032 } 8033 8034 // Diagnose cases where a scalar was implicitly converted to a vector and 8035 // diagnose the underlying types. Otherwise, diagnose the error 8036 // as invalid vector logical operands for non-C++ cases. 8037 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8038 ExprResult &RHS) { 8039 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8040 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8041 8042 bool LHSNatVec = LHSType->isVectorType(); 8043 bool RHSNatVec = RHSType->isVectorType(); 8044 8045 if (!(LHSNatVec && RHSNatVec)) { 8046 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8047 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8048 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8049 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8050 << Vector->getSourceRange(); 8051 return QualType(); 8052 } 8053 8054 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8055 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8056 << RHS.get()->getSourceRange(); 8057 8058 return QualType(); 8059 } 8060 8061 /// Try to convert a value of non-vector type to a vector type by converting 8062 /// the type to the element type of the vector and then performing a splat. 8063 /// If the language is OpenCL, we only use conversions that promote scalar 8064 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8065 /// for float->int. 8066 /// 8067 /// \param scalar - if non-null, actually perform the conversions 8068 /// \return true if the operation fails (but without diagnosing the failure) 8069 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8070 QualType scalarTy, 8071 QualType vectorEltTy, 8072 QualType vectorTy) { 8073 // The conversion to apply to the scalar before splatting it, 8074 // if necessary. 8075 CastKind scalarCast = CK_Invalid; 8076 8077 if (vectorEltTy->isIntegralType(S.Context)) { 8078 if (!scalarTy->isIntegralType(S.Context)) 8079 return true; 8080 if (S.getLangOpts().OpenCL && 8081 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 8082 return true; 8083 scalarCast = CK_IntegralCast; 8084 } else if (vectorEltTy->isRealFloatingType()) { 8085 if (scalarTy->isRealFloatingType()) { 8086 if (S.getLangOpts().OpenCL && 8087 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 8088 return true; 8089 scalarCast = CK_FloatingCast; 8090 } 8091 else if (scalarTy->isIntegralType(S.Context)) 8092 scalarCast = CK_IntegralToFloating; 8093 else 8094 return true; 8095 } else { 8096 return true; 8097 } 8098 8099 // Adjust scalar if desired. 8100 if (scalar) { 8101 if (scalarCast != CK_Invalid) 8102 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8103 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8104 } 8105 return false; 8106 } 8107 8108 /// Test if a (constant) integer Int can be casted to another integer type 8109 /// IntTy without losing precision. 8110 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8111 QualType OtherIntTy) { 8112 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8113 8114 // Reject cases where the value of the Int is unknown as that would 8115 // possibly cause truncation, but accept cases where the scalar can be 8116 // demoted without loss of precision. 8117 llvm::APSInt Result; 8118 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8119 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8120 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8121 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8122 8123 if (CstInt) { 8124 // If the scalar is constant and is of a higher order and has more active 8125 // bits that the vector element type, reject it. 8126 unsigned NumBits = IntSigned 8127 ? (Result.isNegative() ? Result.getMinSignedBits() 8128 : Result.getActiveBits()) 8129 : Result.getActiveBits(); 8130 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8131 return true; 8132 8133 // If the signedness of the scalar type and the vector element type 8134 // differs and the number of bits is greater than that of the vector 8135 // element reject it. 8136 return (IntSigned != OtherIntSigned && 8137 NumBits > S.Context.getIntWidth(OtherIntTy)); 8138 } 8139 8140 // Reject cases where the value of the scalar is not constant and it's 8141 // order is greater than that of the vector element type. 8142 return (Order < 0); 8143 } 8144 8145 /// Test if a (constant) integer Int can be casted to floating point type 8146 /// FloatTy without losing precision. 8147 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8148 QualType FloatTy) { 8149 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8150 8151 // Determine if the integer constant can be expressed as a floating point 8152 // number of the appropiate type. 8153 llvm::APSInt Result; 8154 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8155 uint64_t Bits = 0; 8156 if (CstInt) { 8157 // Reject constants that would be truncated if they were converted to 8158 // the floating point type. Test by simple to/from conversion. 8159 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8160 // could be avoided if there was a convertFromAPInt method 8161 // which could signal back if implicit truncation occurred. 8162 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8163 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8164 llvm::APFloat::rmTowardZero); 8165 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8166 !IntTy->hasSignedIntegerRepresentation()); 8167 bool Ignored = false; 8168 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8169 &Ignored); 8170 if (Result != ConvertBack) 8171 return true; 8172 } else { 8173 // Reject types that cannot be fully encoded into the mantissa of 8174 // the float. 8175 Bits = S.Context.getTypeSize(IntTy); 8176 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8177 S.Context.getFloatTypeSemantics(FloatTy)); 8178 if (Bits > FloatPrec) 8179 return true; 8180 } 8181 8182 return false; 8183 } 8184 8185 /// Attempt to convert and splat Scalar into a vector whose types matches 8186 /// Vector following GCC conversion rules. The rule is that implicit 8187 /// conversion can occur when Scalar can be casted to match Vector's element 8188 /// type without causing truncation of Scalar. 8189 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8190 ExprResult *Vector) { 8191 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8192 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8193 const VectorType *VT = VectorTy->getAs<VectorType>(); 8194 8195 assert(!isa<ExtVectorType>(VT) && 8196 "ExtVectorTypes should not be handled here!"); 8197 8198 QualType VectorEltTy = VT->getElementType(); 8199 8200 // Reject cases where the vector element type or the scalar element type are 8201 // not integral or floating point types. 8202 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8203 return true; 8204 8205 // The conversion to apply to the scalar before splatting it, 8206 // if necessary. 8207 CastKind ScalarCast = CK_NoOp; 8208 8209 // Accept cases where the vector elements are integers and the scalar is 8210 // an integer. 8211 // FIXME: Notionally if the scalar was a floating point value with a precise 8212 // integral representation, we could cast it to an appropriate integer 8213 // type and then perform the rest of the checks here. GCC will perform 8214 // this conversion in some cases as determined by the input language. 8215 // We should accept it on a language independent basis. 8216 if (VectorEltTy->isIntegralType(S.Context) && 8217 ScalarTy->isIntegralType(S.Context) && 8218 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8219 8220 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8221 return true; 8222 8223 ScalarCast = CK_IntegralCast; 8224 } else if (VectorEltTy->isRealFloatingType()) { 8225 if (ScalarTy->isRealFloatingType()) { 8226 8227 // Reject cases where the scalar type is not a constant and has a higher 8228 // Order than the vector element type. 8229 llvm::APFloat Result(0.0); 8230 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8231 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8232 if (!CstScalar && Order < 0) 8233 return true; 8234 8235 // If the scalar cannot be safely casted to the vector element type, 8236 // reject it. 8237 if (CstScalar) { 8238 bool Truncated = false; 8239 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8240 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8241 if (Truncated) 8242 return true; 8243 } 8244 8245 ScalarCast = CK_FloatingCast; 8246 } else if (ScalarTy->isIntegralType(S.Context)) { 8247 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8248 return true; 8249 8250 ScalarCast = CK_IntegralToFloating; 8251 } else 8252 return true; 8253 } 8254 8255 // Adjust scalar if desired. 8256 if (Scalar) { 8257 if (ScalarCast != CK_NoOp) 8258 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8259 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8260 } 8261 return false; 8262 } 8263 8264 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8265 SourceLocation Loc, bool IsCompAssign, 8266 bool AllowBothBool, 8267 bool AllowBoolConversions) { 8268 if (!IsCompAssign) { 8269 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8270 if (LHS.isInvalid()) 8271 return QualType(); 8272 } 8273 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8274 if (RHS.isInvalid()) 8275 return QualType(); 8276 8277 // For conversion purposes, we ignore any qualifiers. 8278 // For example, "const float" and "float" are equivalent. 8279 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8280 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8281 8282 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8283 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8284 assert(LHSVecType || RHSVecType); 8285 8286 // AltiVec-style "vector bool op vector bool" combinations are allowed 8287 // for some operators but not others. 8288 if (!AllowBothBool && 8289 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8290 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8291 return InvalidOperands(Loc, LHS, RHS); 8292 8293 // If the vector types are identical, return. 8294 if (Context.hasSameType(LHSType, RHSType)) 8295 return LHSType; 8296 8297 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8298 if (LHSVecType && RHSVecType && 8299 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8300 if (isa<ExtVectorType>(LHSVecType)) { 8301 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8302 return LHSType; 8303 } 8304 8305 if (!IsCompAssign) 8306 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8307 return RHSType; 8308 } 8309 8310 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8311 // can be mixed, with the result being the non-bool type. The non-bool 8312 // operand must have integer element type. 8313 if (AllowBoolConversions && LHSVecType && RHSVecType && 8314 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8315 (Context.getTypeSize(LHSVecType->getElementType()) == 8316 Context.getTypeSize(RHSVecType->getElementType()))) { 8317 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8318 LHSVecType->getElementType()->isIntegerType() && 8319 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8320 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8321 return LHSType; 8322 } 8323 if (!IsCompAssign && 8324 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8325 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8326 RHSVecType->getElementType()->isIntegerType()) { 8327 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8328 return RHSType; 8329 } 8330 } 8331 8332 // If there's a vector type and a scalar, try to convert the scalar to 8333 // the vector element type and splat. 8334 if (!RHSVecType) { 8335 if (isa<ExtVectorType>(LHSVecType)) { 8336 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8337 LHSVecType->getElementType(), LHSType)) 8338 return LHSType; 8339 } else { 8340 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8341 return LHSType; 8342 } 8343 } 8344 if (!LHSVecType) { 8345 if (isa<ExtVectorType>(RHSVecType)) { 8346 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8347 LHSType, RHSVecType->getElementType(), 8348 RHSType)) 8349 return RHSType; 8350 } else { 8351 if (LHS.get()->getValueKind() == VK_LValue || 8352 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8353 return RHSType; 8354 } 8355 } 8356 8357 // FIXME: The code below also handles conversion between vectors and 8358 // non-scalars, we should break this down into fine grained specific checks 8359 // and emit proper diagnostics. 8360 QualType VecType = LHSVecType ? LHSType : RHSType; 8361 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8362 QualType OtherType = LHSVecType ? RHSType : LHSType; 8363 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8364 if (isLaxVectorConversion(OtherType, VecType)) { 8365 // If we're allowing lax vector conversions, only the total (data) size 8366 // needs to be the same. For non compound assignment, if one of the types is 8367 // scalar, the result is always the vector type. 8368 if (!IsCompAssign) { 8369 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8370 return VecType; 8371 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8372 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8373 // type. Note that this is already done by non-compound assignments in 8374 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8375 // <1 x T> -> T. The result is also a vector type. 8376 } else if (OtherType->isExtVectorType() || 8377 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8378 ExprResult *RHSExpr = &RHS; 8379 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8380 return VecType; 8381 } 8382 } 8383 8384 // Okay, the expression is invalid. 8385 8386 // If there's a non-vector, non-real operand, diagnose that. 8387 if ((!RHSVecType && !RHSType->isRealType()) || 8388 (!LHSVecType && !LHSType->isRealType())) { 8389 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8390 << LHSType << RHSType 8391 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8392 return QualType(); 8393 } 8394 8395 // OpenCL V1.1 6.2.6.p1: 8396 // If the operands are of more than one vector type, then an error shall 8397 // occur. Implicit conversions between vector types are not permitted, per 8398 // section 6.2.1. 8399 if (getLangOpts().OpenCL && 8400 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8401 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8402 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8403 << RHSType; 8404 return QualType(); 8405 } 8406 8407 8408 // If there is a vector type that is not a ExtVector and a scalar, we reach 8409 // this point if scalar could not be converted to the vector's element type 8410 // without truncation. 8411 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8412 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8413 QualType Scalar = LHSVecType ? RHSType : LHSType; 8414 QualType Vector = LHSVecType ? LHSType : RHSType; 8415 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8416 Diag(Loc, 8417 diag::err_typecheck_vector_not_convertable_implict_truncation) 8418 << ScalarOrVector << Scalar << Vector; 8419 8420 return QualType(); 8421 } 8422 8423 // Otherwise, use the generic diagnostic. 8424 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8425 << LHSType << RHSType 8426 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8427 return QualType(); 8428 } 8429 8430 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8431 // expression. These are mainly cases where the null pointer is used as an 8432 // integer instead of a pointer. 8433 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8434 SourceLocation Loc, bool IsCompare) { 8435 // The canonical way to check for a GNU null is with isNullPointerConstant, 8436 // but we use a bit of a hack here for speed; this is a relatively 8437 // hot path, and isNullPointerConstant is slow. 8438 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8439 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8440 8441 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8442 8443 // Avoid analyzing cases where the result will either be invalid (and 8444 // diagnosed as such) or entirely valid and not something to warn about. 8445 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8446 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8447 return; 8448 8449 // Comparison operations would not make sense with a null pointer no matter 8450 // what the other expression is. 8451 if (!IsCompare) { 8452 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8453 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8454 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8455 return; 8456 } 8457 8458 // The rest of the operations only make sense with a null pointer 8459 // if the other expression is a pointer. 8460 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8461 NonNullType->canDecayToPointerType()) 8462 return; 8463 8464 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8465 << LHSNull /* LHS is NULL */ << NonNullType 8466 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8467 } 8468 8469 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8470 ExprResult &RHS, 8471 SourceLocation Loc, bool IsDiv) { 8472 // Check for division/remainder by zero. 8473 llvm::APSInt RHSValue; 8474 if (!RHS.get()->isValueDependent() && 8475 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8476 S.DiagRuntimeBehavior(Loc, RHS.get(), 8477 S.PDiag(diag::warn_remainder_division_by_zero) 8478 << IsDiv << RHS.get()->getSourceRange()); 8479 } 8480 8481 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8482 SourceLocation Loc, 8483 bool IsCompAssign, bool IsDiv) { 8484 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8485 8486 if (LHS.get()->getType()->isVectorType() || 8487 RHS.get()->getType()->isVectorType()) 8488 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8489 /*AllowBothBool*/getLangOpts().AltiVec, 8490 /*AllowBoolConversions*/false); 8491 8492 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8493 if (LHS.isInvalid() || RHS.isInvalid()) 8494 return QualType(); 8495 8496 8497 if (compType.isNull() || !compType->isArithmeticType()) 8498 return InvalidOperands(Loc, LHS, RHS); 8499 if (IsDiv) 8500 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8501 return compType; 8502 } 8503 8504 QualType Sema::CheckRemainderOperands( 8505 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8506 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8507 8508 if (LHS.get()->getType()->isVectorType() || 8509 RHS.get()->getType()->isVectorType()) { 8510 if (LHS.get()->getType()->hasIntegerRepresentation() && 8511 RHS.get()->getType()->hasIntegerRepresentation()) 8512 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8513 /*AllowBothBool*/getLangOpts().AltiVec, 8514 /*AllowBoolConversions*/false); 8515 return InvalidOperands(Loc, LHS, RHS); 8516 } 8517 8518 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8519 if (LHS.isInvalid() || RHS.isInvalid()) 8520 return QualType(); 8521 8522 if (compType.isNull() || !compType->isIntegerType()) 8523 return InvalidOperands(Loc, LHS, RHS); 8524 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8525 return compType; 8526 } 8527 8528 /// \brief Diagnose invalid arithmetic on two void pointers. 8529 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8530 Expr *LHSExpr, Expr *RHSExpr) { 8531 S.Diag(Loc, S.getLangOpts().CPlusPlus 8532 ? diag::err_typecheck_pointer_arith_void_type 8533 : diag::ext_gnu_void_ptr) 8534 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8535 << RHSExpr->getSourceRange(); 8536 } 8537 8538 /// \brief Diagnose invalid arithmetic on a void pointer. 8539 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8540 Expr *Pointer) { 8541 S.Diag(Loc, S.getLangOpts().CPlusPlus 8542 ? diag::err_typecheck_pointer_arith_void_type 8543 : diag::ext_gnu_void_ptr) 8544 << 0 /* one pointer */ << Pointer->getSourceRange(); 8545 } 8546 8547 /// \brief Diagnose invalid arithmetic on two function pointers. 8548 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8549 Expr *LHS, Expr *RHS) { 8550 assert(LHS->getType()->isAnyPointerType()); 8551 assert(RHS->getType()->isAnyPointerType()); 8552 S.Diag(Loc, S.getLangOpts().CPlusPlus 8553 ? diag::err_typecheck_pointer_arith_function_type 8554 : diag::ext_gnu_ptr_func_arith) 8555 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8556 // We only show the second type if it differs from the first. 8557 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8558 RHS->getType()) 8559 << RHS->getType()->getPointeeType() 8560 << LHS->getSourceRange() << RHS->getSourceRange(); 8561 } 8562 8563 /// \brief Diagnose invalid arithmetic on a function pointer. 8564 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8565 Expr *Pointer) { 8566 assert(Pointer->getType()->isAnyPointerType()); 8567 S.Diag(Loc, S.getLangOpts().CPlusPlus 8568 ? diag::err_typecheck_pointer_arith_function_type 8569 : diag::ext_gnu_ptr_func_arith) 8570 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8571 << 0 /* one pointer, so only one type */ 8572 << Pointer->getSourceRange(); 8573 } 8574 8575 /// \brief Emit error if Operand is incomplete pointer type 8576 /// 8577 /// \returns True if pointer has incomplete type 8578 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8579 Expr *Operand) { 8580 QualType ResType = Operand->getType(); 8581 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8582 ResType = ResAtomicType->getValueType(); 8583 8584 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8585 QualType PointeeTy = ResType->getPointeeType(); 8586 return S.RequireCompleteType(Loc, PointeeTy, 8587 diag::err_typecheck_arithmetic_incomplete_type, 8588 PointeeTy, Operand->getSourceRange()); 8589 } 8590 8591 /// \brief Check the validity of an arithmetic pointer operand. 8592 /// 8593 /// If the operand has pointer type, this code will check for pointer types 8594 /// which are invalid in arithmetic operations. These will be diagnosed 8595 /// appropriately, including whether or not the use is supported as an 8596 /// extension. 8597 /// 8598 /// \returns True when the operand is valid to use (even if as an extension). 8599 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8600 Expr *Operand) { 8601 QualType ResType = Operand->getType(); 8602 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8603 ResType = ResAtomicType->getValueType(); 8604 8605 if (!ResType->isAnyPointerType()) return true; 8606 8607 QualType PointeeTy = ResType->getPointeeType(); 8608 if (PointeeTy->isVoidType()) { 8609 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8610 return !S.getLangOpts().CPlusPlus; 8611 } 8612 if (PointeeTy->isFunctionType()) { 8613 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8614 return !S.getLangOpts().CPlusPlus; 8615 } 8616 8617 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8618 8619 return true; 8620 } 8621 8622 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8623 /// operands. 8624 /// 8625 /// This routine will diagnose any invalid arithmetic on pointer operands much 8626 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8627 /// for emitting a single diagnostic even for operations where both LHS and RHS 8628 /// are (potentially problematic) pointers. 8629 /// 8630 /// \returns True when the operand is valid to use (even if as an extension). 8631 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8632 Expr *LHSExpr, Expr *RHSExpr) { 8633 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8634 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8635 if (!isLHSPointer && !isRHSPointer) return true; 8636 8637 QualType LHSPointeeTy, RHSPointeeTy; 8638 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8639 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8640 8641 // if both are pointers check if operation is valid wrt address spaces 8642 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8643 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8644 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8645 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8646 S.Diag(Loc, 8647 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8648 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8649 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8650 return false; 8651 } 8652 } 8653 8654 // Check for arithmetic on pointers to incomplete types. 8655 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8656 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8657 if (isLHSVoidPtr || isRHSVoidPtr) { 8658 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8659 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8660 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8661 8662 return !S.getLangOpts().CPlusPlus; 8663 } 8664 8665 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8666 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8667 if (isLHSFuncPtr || isRHSFuncPtr) { 8668 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8669 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8670 RHSExpr); 8671 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8672 8673 return !S.getLangOpts().CPlusPlus; 8674 } 8675 8676 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8677 return false; 8678 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8679 return false; 8680 8681 return true; 8682 } 8683 8684 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8685 /// literal. 8686 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8687 Expr *LHSExpr, Expr *RHSExpr) { 8688 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8689 Expr* IndexExpr = RHSExpr; 8690 if (!StrExpr) { 8691 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8692 IndexExpr = LHSExpr; 8693 } 8694 8695 bool IsStringPlusInt = StrExpr && 8696 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8697 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8698 return; 8699 8700 llvm::APSInt index; 8701 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8702 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8703 if (index.isNonNegative() && 8704 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8705 index.isUnsigned())) 8706 return; 8707 } 8708 8709 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8710 Self.Diag(OpLoc, diag::warn_string_plus_int) 8711 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8712 8713 // Only print a fixit for "str" + int, not for int + "str". 8714 if (IndexExpr == RHSExpr) { 8715 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8716 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8717 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8718 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8719 << FixItHint::CreateInsertion(EndLoc, "]"); 8720 } else 8721 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8722 } 8723 8724 /// \brief Emit a warning when adding a char literal to a string. 8725 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8726 Expr *LHSExpr, Expr *RHSExpr) { 8727 const Expr *StringRefExpr = LHSExpr; 8728 const CharacterLiteral *CharExpr = 8729 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8730 8731 if (!CharExpr) { 8732 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8733 StringRefExpr = RHSExpr; 8734 } 8735 8736 if (!CharExpr || !StringRefExpr) 8737 return; 8738 8739 const QualType StringType = StringRefExpr->getType(); 8740 8741 // Return if not a PointerType. 8742 if (!StringType->isAnyPointerType()) 8743 return; 8744 8745 // Return if not a CharacterType. 8746 if (!StringType->getPointeeType()->isAnyCharacterType()) 8747 return; 8748 8749 ASTContext &Ctx = Self.getASTContext(); 8750 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8751 8752 const QualType CharType = CharExpr->getType(); 8753 if (!CharType->isAnyCharacterType() && 8754 CharType->isIntegerType() && 8755 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8756 Self.Diag(OpLoc, diag::warn_string_plus_char) 8757 << DiagRange << Ctx.CharTy; 8758 } else { 8759 Self.Diag(OpLoc, diag::warn_string_plus_char) 8760 << DiagRange << CharExpr->getType(); 8761 } 8762 8763 // Only print a fixit for str + char, not for char + str. 8764 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8765 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8766 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8767 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8768 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8769 << FixItHint::CreateInsertion(EndLoc, "]"); 8770 } else { 8771 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8772 } 8773 } 8774 8775 /// \brief Emit error when two pointers are incompatible. 8776 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8777 Expr *LHSExpr, Expr *RHSExpr) { 8778 assert(LHSExpr->getType()->isAnyPointerType()); 8779 assert(RHSExpr->getType()->isAnyPointerType()); 8780 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8781 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8782 << RHSExpr->getSourceRange(); 8783 } 8784 8785 // C99 6.5.6 8786 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8787 SourceLocation Loc, BinaryOperatorKind Opc, 8788 QualType* CompLHSTy) { 8789 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8790 8791 if (LHS.get()->getType()->isVectorType() || 8792 RHS.get()->getType()->isVectorType()) { 8793 QualType compType = CheckVectorOperands( 8794 LHS, RHS, Loc, CompLHSTy, 8795 /*AllowBothBool*/getLangOpts().AltiVec, 8796 /*AllowBoolConversions*/getLangOpts().ZVector); 8797 if (CompLHSTy) *CompLHSTy = compType; 8798 return compType; 8799 } 8800 8801 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8802 if (LHS.isInvalid() || RHS.isInvalid()) 8803 return QualType(); 8804 8805 // Diagnose "string literal" '+' int and string '+' "char literal". 8806 if (Opc == BO_Add) { 8807 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8808 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8809 } 8810 8811 // handle the common case first (both operands are arithmetic). 8812 if (!compType.isNull() && compType->isArithmeticType()) { 8813 if (CompLHSTy) *CompLHSTy = compType; 8814 return compType; 8815 } 8816 8817 // Type-checking. Ultimately the pointer's going to be in PExp; 8818 // note that we bias towards the LHS being the pointer. 8819 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8820 8821 bool isObjCPointer; 8822 if (PExp->getType()->isPointerType()) { 8823 isObjCPointer = false; 8824 } else if (PExp->getType()->isObjCObjectPointerType()) { 8825 isObjCPointer = true; 8826 } else { 8827 std::swap(PExp, IExp); 8828 if (PExp->getType()->isPointerType()) { 8829 isObjCPointer = false; 8830 } else if (PExp->getType()->isObjCObjectPointerType()) { 8831 isObjCPointer = true; 8832 } else { 8833 return InvalidOperands(Loc, LHS, RHS); 8834 } 8835 } 8836 assert(PExp->getType()->isAnyPointerType()); 8837 8838 if (!IExp->getType()->isIntegerType()) 8839 return InvalidOperands(Loc, LHS, RHS); 8840 8841 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8842 return QualType(); 8843 8844 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8845 return QualType(); 8846 8847 // Check array bounds for pointer arithemtic 8848 CheckArrayAccess(PExp, IExp); 8849 8850 if (CompLHSTy) { 8851 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8852 if (LHSTy.isNull()) { 8853 LHSTy = LHS.get()->getType(); 8854 if (LHSTy->isPromotableIntegerType()) 8855 LHSTy = Context.getPromotedIntegerType(LHSTy); 8856 } 8857 *CompLHSTy = LHSTy; 8858 } 8859 8860 return PExp->getType(); 8861 } 8862 8863 // C99 6.5.6 8864 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8865 SourceLocation Loc, 8866 QualType* CompLHSTy) { 8867 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8868 8869 if (LHS.get()->getType()->isVectorType() || 8870 RHS.get()->getType()->isVectorType()) { 8871 QualType compType = CheckVectorOperands( 8872 LHS, RHS, Loc, CompLHSTy, 8873 /*AllowBothBool*/getLangOpts().AltiVec, 8874 /*AllowBoolConversions*/getLangOpts().ZVector); 8875 if (CompLHSTy) *CompLHSTy = compType; 8876 return compType; 8877 } 8878 8879 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8880 if (LHS.isInvalid() || RHS.isInvalid()) 8881 return QualType(); 8882 8883 // Enforce type constraints: C99 6.5.6p3. 8884 8885 // Handle the common case first (both operands are arithmetic). 8886 if (!compType.isNull() && compType->isArithmeticType()) { 8887 if (CompLHSTy) *CompLHSTy = compType; 8888 return compType; 8889 } 8890 8891 // Either ptr - int or ptr - ptr. 8892 if (LHS.get()->getType()->isAnyPointerType()) { 8893 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8894 8895 // Diagnose bad cases where we step over interface counts. 8896 if (LHS.get()->getType()->isObjCObjectPointerType() && 8897 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8898 return QualType(); 8899 8900 // The result type of a pointer-int computation is the pointer type. 8901 if (RHS.get()->getType()->isIntegerType()) { 8902 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8903 return QualType(); 8904 8905 // Check array bounds for pointer arithemtic 8906 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8907 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8908 8909 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8910 return LHS.get()->getType(); 8911 } 8912 8913 // Handle pointer-pointer subtractions. 8914 if (const PointerType *RHSPTy 8915 = RHS.get()->getType()->getAs<PointerType>()) { 8916 QualType rpointee = RHSPTy->getPointeeType(); 8917 8918 if (getLangOpts().CPlusPlus) { 8919 // Pointee types must be the same: C++ [expr.add] 8920 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8921 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8922 } 8923 } else { 8924 // Pointee types must be compatible C99 6.5.6p3 8925 if (!Context.typesAreCompatible( 8926 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8927 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8928 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8929 return QualType(); 8930 } 8931 } 8932 8933 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8934 LHS.get(), RHS.get())) 8935 return QualType(); 8936 8937 // The pointee type may have zero size. As an extension, a structure or 8938 // union may have zero size or an array may have zero length. In this 8939 // case subtraction does not make sense. 8940 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8941 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8942 if (ElementSize.isZero()) { 8943 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8944 << rpointee.getUnqualifiedType() 8945 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8946 } 8947 } 8948 8949 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8950 return Context.getPointerDiffType(); 8951 } 8952 } 8953 8954 return InvalidOperands(Loc, LHS, RHS); 8955 } 8956 8957 static bool isScopedEnumerationType(QualType T) { 8958 if (const EnumType *ET = T->getAs<EnumType>()) 8959 return ET->getDecl()->isScoped(); 8960 return false; 8961 } 8962 8963 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8964 SourceLocation Loc, BinaryOperatorKind Opc, 8965 QualType LHSType) { 8966 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8967 // so skip remaining warnings as we don't want to modify values within Sema. 8968 if (S.getLangOpts().OpenCL) 8969 return; 8970 8971 llvm::APSInt Right; 8972 // Check right/shifter operand 8973 if (RHS.get()->isValueDependent() || 8974 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8975 return; 8976 8977 if (Right.isNegative()) { 8978 S.DiagRuntimeBehavior(Loc, RHS.get(), 8979 S.PDiag(diag::warn_shift_negative) 8980 << RHS.get()->getSourceRange()); 8981 return; 8982 } 8983 llvm::APInt LeftBits(Right.getBitWidth(), 8984 S.Context.getTypeSize(LHS.get()->getType())); 8985 if (Right.uge(LeftBits)) { 8986 S.DiagRuntimeBehavior(Loc, RHS.get(), 8987 S.PDiag(diag::warn_shift_gt_typewidth) 8988 << RHS.get()->getSourceRange()); 8989 return; 8990 } 8991 if (Opc != BO_Shl) 8992 return; 8993 8994 // When left shifting an ICE which is signed, we can check for overflow which 8995 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8996 // integers have defined behavior modulo one more than the maximum value 8997 // representable in the result type, so never warn for those. 8998 llvm::APSInt Left; 8999 if (LHS.get()->isValueDependent() || 9000 LHSType->hasUnsignedIntegerRepresentation() || 9001 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9002 return; 9003 9004 // If LHS does not have a signed type and non-negative value 9005 // then, the behavior is undefined. Warn about it. 9006 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9007 S.DiagRuntimeBehavior(Loc, LHS.get(), 9008 S.PDiag(diag::warn_shift_lhs_negative) 9009 << LHS.get()->getSourceRange()); 9010 return; 9011 } 9012 9013 llvm::APInt ResultBits = 9014 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9015 if (LeftBits.uge(ResultBits)) 9016 return; 9017 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9018 Result = Result.shl(Right); 9019 9020 // Print the bit representation of the signed integer as an unsigned 9021 // hexadecimal number. 9022 SmallString<40> HexResult; 9023 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9024 9025 // If we are only missing a sign bit, this is less likely to result in actual 9026 // bugs -- if the result is cast back to an unsigned type, it will have the 9027 // expected value. Thus we place this behind a different warning that can be 9028 // turned off separately if needed. 9029 if (LeftBits == ResultBits - 1) { 9030 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9031 << HexResult << LHSType 9032 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9033 return; 9034 } 9035 9036 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9037 << HexResult.str() << Result.getMinSignedBits() << LHSType 9038 << Left.getBitWidth() << LHS.get()->getSourceRange() 9039 << RHS.get()->getSourceRange(); 9040 } 9041 9042 /// \brief Return the resulting type when a vector is shifted 9043 /// by a scalar or vector shift amount. 9044 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9045 SourceLocation Loc, bool IsCompAssign) { 9046 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9047 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9048 !LHS.get()->getType()->isVectorType()) { 9049 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9050 << RHS.get()->getType() << LHS.get()->getType() 9051 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9052 return QualType(); 9053 } 9054 9055 if (!IsCompAssign) { 9056 LHS = S.UsualUnaryConversions(LHS.get()); 9057 if (LHS.isInvalid()) return QualType(); 9058 } 9059 9060 RHS = S.UsualUnaryConversions(RHS.get()); 9061 if (RHS.isInvalid()) return QualType(); 9062 9063 QualType LHSType = LHS.get()->getType(); 9064 // Note that LHS might be a scalar because the routine calls not only in 9065 // OpenCL case. 9066 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9067 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9068 9069 // Note that RHS might not be a vector. 9070 QualType RHSType = RHS.get()->getType(); 9071 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9072 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9073 9074 // The operands need to be integers. 9075 if (!LHSEleType->isIntegerType()) { 9076 S.Diag(Loc, diag::err_typecheck_expect_int) 9077 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9078 return QualType(); 9079 } 9080 9081 if (!RHSEleType->isIntegerType()) { 9082 S.Diag(Loc, diag::err_typecheck_expect_int) 9083 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9084 return QualType(); 9085 } 9086 9087 if (!LHSVecTy) { 9088 assert(RHSVecTy); 9089 if (IsCompAssign) 9090 return RHSType; 9091 if (LHSEleType != RHSEleType) { 9092 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9093 LHSEleType = RHSEleType; 9094 } 9095 QualType VecTy = 9096 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9097 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9098 LHSType = VecTy; 9099 } else if (RHSVecTy) { 9100 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9101 // are applied component-wise. So if RHS is a vector, then ensure 9102 // that the number of elements is the same as LHS... 9103 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9104 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9105 << LHS.get()->getType() << RHS.get()->getType() 9106 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9107 return QualType(); 9108 } 9109 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9110 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9111 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9112 if (LHSBT != RHSBT && 9113 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9114 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9115 << LHS.get()->getType() << RHS.get()->getType() 9116 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9117 } 9118 } 9119 } else { 9120 // ...else expand RHS to match the number of elements in LHS. 9121 QualType VecTy = 9122 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9123 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9124 } 9125 9126 return LHSType; 9127 } 9128 9129 // C99 6.5.7 9130 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9131 SourceLocation Loc, BinaryOperatorKind Opc, 9132 bool IsCompAssign) { 9133 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9134 9135 // Vector shifts promote their scalar inputs to vector type. 9136 if (LHS.get()->getType()->isVectorType() || 9137 RHS.get()->getType()->isVectorType()) { 9138 if (LangOpts.ZVector) { 9139 // The shift operators for the z vector extensions work basically 9140 // like general shifts, except that neither the LHS nor the RHS is 9141 // allowed to be a "vector bool". 9142 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9143 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9144 return InvalidOperands(Loc, LHS, RHS); 9145 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9146 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9147 return InvalidOperands(Loc, LHS, RHS); 9148 } 9149 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9150 } 9151 9152 // Shifts don't perform usual arithmetic conversions, they just do integer 9153 // promotions on each operand. C99 6.5.7p3 9154 9155 // For the LHS, do usual unary conversions, but then reset them away 9156 // if this is a compound assignment. 9157 ExprResult OldLHS = LHS; 9158 LHS = UsualUnaryConversions(LHS.get()); 9159 if (LHS.isInvalid()) 9160 return QualType(); 9161 QualType LHSType = LHS.get()->getType(); 9162 if (IsCompAssign) LHS = OldLHS; 9163 9164 // The RHS is simpler. 9165 RHS = UsualUnaryConversions(RHS.get()); 9166 if (RHS.isInvalid()) 9167 return QualType(); 9168 QualType RHSType = RHS.get()->getType(); 9169 9170 // C99 6.5.7p2: Each of the operands shall have integer type. 9171 if (!LHSType->hasIntegerRepresentation() || 9172 !RHSType->hasIntegerRepresentation()) 9173 return InvalidOperands(Loc, LHS, RHS); 9174 9175 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9176 // hasIntegerRepresentation() above instead of this. 9177 if (isScopedEnumerationType(LHSType) || 9178 isScopedEnumerationType(RHSType)) { 9179 return InvalidOperands(Loc, LHS, RHS); 9180 } 9181 // Sanity-check shift operands 9182 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9183 9184 // "The type of the result is that of the promoted left operand." 9185 return LHSType; 9186 } 9187 9188 static bool IsWithinTemplateSpecialization(Decl *D) { 9189 if (DeclContext *DC = D->getDeclContext()) { 9190 if (isa<ClassTemplateSpecializationDecl>(DC)) 9191 return true; 9192 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 9193 return FD->isFunctionTemplateSpecialization(); 9194 } 9195 return false; 9196 } 9197 9198 /// If two different enums are compared, raise a warning. 9199 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9200 Expr *RHS) { 9201 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9202 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9203 9204 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9205 if (!LHSEnumType) 9206 return; 9207 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9208 if (!RHSEnumType) 9209 return; 9210 9211 // Ignore anonymous enums. 9212 if (!LHSEnumType->getDecl()->getIdentifier()) 9213 return; 9214 if (!RHSEnumType->getDecl()->getIdentifier()) 9215 return; 9216 9217 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9218 return; 9219 9220 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9221 << LHSStrippedType << RHSStrippedType 9222 << LHS->getSourceRange() << RHS->getSourceRange(); 9223 } 9224 9225 /// \brief Diagnose bad pointer comparisons. 9226 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9227 ExprResult &LHS, ExprResult &RHS, 9228 bool IsError) { 9229 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9230 : diag::ext_typecheck_comparison_of_distinct_pointers) 9231 << LHS.get()->getType() << RHS.get()->getType() 9232 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9233 } 9234 9235 /// \brief Returns false if the pointers are converted to a composite type, 9236 /// true otherwise. 9237 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9238 ExprResult &LHS, ExprResult &RHS) { 9239 // C++ [expr.rel]p2: 9240 // [...] Pointer conversions (4.10) and qualification 9241 // conversions (4.4) are performed on pointer operands (or on 9242 // a pointer operand and a null pointer constant) to bring 9243 // them to their composite pointer type. [...] 9244 // 9245 // C++ [expr.eq]p1 uses the same notion for (in)equality 9246 // comparisons of pointers. 9247 9248 QualType LHSType = LHS.get()->getType(); 9249 QualType RHSType = RHS.get()->getType(); 9250 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9251 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9252 9253 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9254 if (T.isNull()) { 9255 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9256 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9257 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9258 else 9259 S.InvalidOperands(Loc, LHS, RHS); 9260 return true; 9261 } 9262 9263 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9264 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9265 return false; 9266 } 9267 9268 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9269 ExprResult &LHS, 9270 ExprResult &RHS, 9271 bool IsError) { 9272 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9273 : diag::ext_typecheck_comparison_of_fptr_to_void) 9274 << LHS.get()->getType() << RHS.get()->getType() 9275 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9276 } 9277 9278 static bool isObjCObjectLiteral(ExprResult &E) { 9279 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9280 case Stmt::ObjCArrayLiteralClass: 9281 case Stmt::ObjCDictionaryLiteralClass: 9282 case Stmt::ObjCStringLiteralClass: 9283 case Stmt::ObjCBoxedExprClass: 9284 return true; 9285 default: 9286 // Note that ObjCBoolLiteral is NOT an object literal! 9287 return false; 9288 } 9289 } 9290 9291 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9292 const ObjCObjectPointerType *Type = 9293 LHS->getType()->getAs<ObjCObjectPointerType>(); 9294 9295 // If this is not actually an Objective-C object, bail out. 9296 if (!Type) 9297 return false; 9298 9299 // Get the LHS object's interface type. 9300 QualType InterfaceType = Type->getPointeeType(); 9301 9302 // If the RHS isn't an Objective-C object, bail out. 9303 if (!RHS->getType()->isObjCObjectPointerType()) 9304 return false; 9305 9306 // Try to find the -isEqual: method. 9307 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9308 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9309 InterfaceType, 9310 /*instance=*/true); 9311 if (!Method) { 9312 if (Type->isObjCIdType()) { 9313 // For 'id', just check the global pool. 9314 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9315 /*receiverId=*/true); 9316 } else { 9317 // Check protocols. 9318 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9319 /*instance=*/true); 9320 } 9321 } 9322 9323 if (!Method) 9324 return false; 9325 9326 QualType T = Method->parameters()[0]->getType(); 9327 if (!T->isObjCObjectPointerType()) 9328 return false; 9329 9330 QualType R = Method->getReturnType(); 9331 if (!R->isScalarType()) 9332 return false; 9333 9334 return true; 9335 } 9336 9337 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9338 FromE = FromE->IgnoreParenImpCasts(); 9339 switch (FromE->getStmtClass()) { 9340 default: 9341 break; 9342 case Stmt::ObjCStringLiteralClass: 9343 // "string literal" 9344 return LK_String; 9345 case Stmt::ObjCArrayLiteralClass: 9346 // "array literal" 9347 return LK_Array; 9348 case Stmt::ObjCDictionaryLiteralClass: 9349 // "dictionary literal" 9350 return LK_Dictionary; 9351 case Stmt::BlockExprClass: 9352 return LK_Block; 9353 case Stmt::ObjCBoxedExprClass: { 9354 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9355 switch (Inner->getStmtClass()) { 9356 case Stmt::IntegerLiteralClass: 9357 case Stmt::FloatingLiteralClass: 9358 case Stmt::CharacterLiteralClass: 9359 case Stmt::ObjCBoolLiteralExprClass: 9360 case Stmt::CXXBoolLiteralExprClass: 9361 // "numeric literal" 9362 return LK_Numeric; 9363 case Stmt::ImplicitCastExprClass: { 9364 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9365 // Boolean literals can be represented by implicit casts. 9366 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9367 return LK_Numeric; 9368 break; 9369 } 9370 default: 9371 break; 9372 } 9373 return LK_Boxed; 9374 } 9375 } 9376 return LK_None; 9377 } 9378 9379 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9380 ExprResult &LHS, ExprResult &RHS, 9381 BinaryOperator::Opcode Opc){ 9382 Expr *Literal; 9383 Expr *Other; 9384 if (isObjCObjectLiteral(LHS)) { 9385 Literal = LHS.get(); 9386 Other = RHS.get(); 9387 } else { 9388 Literal = RHS.get(); 9389 Other = LHS.get(); 9390 } 9391 9392 // Don't warn on comparisons against nil. 9393 Other = Other->IgnoreParenCasts(); 9394 if (Other->isNullPointerConstant(S.getASTContext(), 9395 Expr::NPC_ValueDependentIsNotNull)) 9396 return; 9397 9398 // This should be kept in sync with warn_objc_literal_comparison. 9399 // LK_String should always be after the other literals, since it has its own 9400 // warning flag. 9401 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9402 assert(LiteralKind != Sema::LK_Block); 9403 if (LiteralKind == Sema::LK_None) { 9404 llvm_unreachable("Unknown Objective-C object literal kind"); 9405 } 9406 9407 if (LiteralKind == Sema::LK_String) 9408 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9409 << Literal->getSourceRange(); 9410 else 9411 S.Diag(Loc, diag::warn_objc_literal_comparison) 9412 << LiteralKind << Literal->getSourceRange(); 9413 9414 if (BinaryOperator::isEqualityOp(Opc) && 9415 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9416 SourceLocation Start = LHS.get()->getLocStart(); 9417 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9418 CharSourceRange OpRange = 9419 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9420 9421 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9422 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9423 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9424 << FixItHint::CreateInsertion(End, "]"); 9425 } 9426 } 9427 9428 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9429 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9430 ExprResult &RHS, SourceLocation Loc, 9431 BinaryOperatorKind Opc) { 9432 // Check that left hand side is !something. 9433 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9434 if (!UO || UO->getOpcode() != UO_LNot) return; 9435 9436 // Only check if the right hand side is non-bool arithmetic type. 9437 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9438 9439 // Make sure that the something in !something is not bool. 9440 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9441 if (SubExpr->isKnownToHaveBooleanValue()) return; 9442 9443 // Emit warning. 9444 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9445 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9446 << Loc << IsBitwiseOp; 9447 9448 // First note suggest !(x < y) 9449 SourceLocation FirstOpen = SubExpr->getLocStart(); 9450 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9451 FirstClose = S.getLocForEndOfToken(FirstClose); 9452 if (FirstClose.isInvalid()) 9453 FirstOpen = SourceLocation(); 9454 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9455 << IsBitwiseOp 9456 << FixItHint::CreateInsertion(FirstOpen, "(") 9457 << FixItHint::CreateInsertion(FirstClose, ")"); 9458 9459 // Second note suggests (!x) < y 9460 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9461 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9462 SecondClose = S.getLocForEndOfToken(SecondClose); 9463 if (SecondClose.isInvalid()) 9464 SecondOpen = SourceLocation(); 9465 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9466 << FixItHint::CreateInsertion(SecondOpen, "(") 9467 << FixItHint::CreateInsertion(SecondClose, ")"); 9468 } 9469 9470 // Get the decl for a simple expression: a reference to a variable, 9471 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9472 static ValueDecl *getCompareDecl(Expr *E) { 9473 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9474 return DR->getDecl(); 9475 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9476 if (Ivar->isFreeIvar()) 9477 return Ivar->getDecl(); 9478 } 9479 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9480 if (Mem->isImplicitAccess()) 9481 return Mem->getMemberDecl(); 9482 } 9483 return nullptr; 9484 } 9485 9486 // C99 6.5.8, C++ [expr.rel] 9487 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9488 SourceLocation Loc, BinaryOperatorKind Opc, 9489 bool IsRelational) { 9490 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9491 9492 // Handle vector comparisons separately. 9493 if (LHS.get()->getType()->isVectorType() || 9494 RHS.get()->getType()->isVectorType()) 9495 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9496 9497 QualType LHSType = LHS.get()->getType(); 9498 QualType RHSType = RHS.get()->getType(); 9499 9500 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9501 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9502 9503 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9504 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9505 9506 if (!LHSType->hasFloatingRepresentation() && 9507 !(LHSType->isBlockPointerType() && IsRelational) && 9508 !LHS.get()->getLocStart().isMacroID() && 9509 !RHS.get()->getLocStart().isMacroID() && 9510 !inTemplateInstantiation()) { 9511 // For non-floating point types, check for self-comparisons of the form 9512 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9513 // often indicate logic errors in the program. 9514 // 9515 // NOTE: Don't warn about comparison expressions resulting from macro 9516 // expansion. Also don't warn about comparisons which are only self 9517 // comparisons within a template specialization. The warnings should catch 9518 // obvious cases in the definition of the template anyways. The idea is to 9519 // warn when the typed comparison operator will always evaluate to the same 9520 // result. 9521 ValueDecl *DL = getCompareDecl(LHSStripped); 9522 ValueDecl *DR = getCompareDecl(RHSStripped); 9523 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9524 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9525 << 0 // self- 9526 << (Opc == BO_EQ 9527 || Opc == BO_LE 9528 || Opc == BO_GE)); 9529 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9530 !DL->getType()->isReferenceType() && 9531 !DR->getType()->isReferenceType()) { 9532 // what is it always going to eval to? 9533 char always_evals_to; 9534 switch(Opc) { 9535 case BO_EQ: // e.g. array1 == array2 9536 always_evals_to = 0; // false 9537 break; 9538 case BO_NE: // e.g. array1 != array2 9539 always_evals_to = 1; // true 9540 break; 9541 default: 9542 // best we can say is 'a constant' 9543 always_evals_to = 2; // e.g. array1 <= array2 9544 break; 9545 } 9546 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9547 << 1 // array 9548 << always_evals_to); 9549 } 9550 9551 if (isa<CastExpr>(LHSStripped)) 9552 LHSStripped = LHSStripped->IgnoreParenCasts(); 9553 if (isa<CastExpr>(RHSStripped)) 9554 RHSStripped = RHSStripped->IgnoreParenCasts(); 9555 9556 // Warn about comparisons against a string constant (unless the other 9557 // operand is null), the user probably wants strcmp. 9558 Expr *literalString = nullptr; 9559 Expr *literalStringStripped = nullptr; 9560 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9561 !RHSStripped->isNullPointerConstant(Context, 9562 Expr::NPC_ValueDependentIsNull)) { 9563 literalString = LHS.get(); 9564 literalStringStripped = LHSStripped; 9565 } else if ((isa<StringLiteral>(RHSStripped) || 9566 isa<ObjCEncodeExpr>(RHSStripped)) && 9567 !LHSStripped->isNullPointerConstant(Context, 9568 Expr::NPC_ValueDependentIsNull)) { 9569 literalString = RHS.get(); 9570 literalStringStripped = RHSStripped; 9571 } 9572 9573 if (literalString) { 9574 DiagRuntimeBehavior(Loc, nullptr, 9575 PDiag(diag::warn_stringcompare) 9576 << isa<ObjCEncodeExpr>(literalStringStripped) 9577 << literalString->getSourceRange()); 9578 } 9579 } 9580 9581 // C99 6.5.8p3 / C99 6.5.9p4 9582 UsualArithmeticConversions(LHS, RHS); 9583 if (LHS.isInvalid() || RHS.isInvalid()) 9584 return QualType(); 9585 9586 LHSType = LHS.get()->getType(); 9587 RHSType = RHS.get()->getType(); 9588 9589 // The result of comparisons is 'bool' in C++, 'int' in C. 9590 QualType ResultTy = Context.getLogicalOperationType(); 9591 9592 if (IsRelational) { 9593 if (LHSType->isRealType() && RHSType->isRealType()) 9594 return ResultTy; 9595 } else { 9596 // Check for comparisons of floating point operands using != and ==. 9597 if (LHSType->hasFloatingRepresentation()) 9598 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9599 9600 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9601 return ResultTy; 9602 } 9603 9604 const Expr::NullPointerConstantKind LHSNullKind = 9605 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9606 const Expr::NullPointerConstantKind RHSNullKind = 9607 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9608 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9609 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9610 9611 if (!IsRelational && LHSIsNull != RHSIsNull) { 9612 bool IsEquality = Opc == BO_EQ; 9613 if (RHSIsNull) 9614 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9615 RHS.get()->getSourceRange()); 9616 else 9617 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9618 LHS.get()->getSourceRange()); 9619 } 9620 9621 if ((LHSType->isIntegerType() && !LHSIsNull) || 9622 (RHSType->isIntegerType() && !RHSIsNull)) { 9623 // Skip normal pointer conversion checks in this case; we have better 9624 // diagnostics for this below. 9625 } else if (getLangOpts().CPlusPlus) { 9626 // Equality comparison of a function pointer to a void pointer is invalid, 9627 // but we allow it as an extension. 9628 // FIXME: If we really want to allow this, should it be part of composite 9629 // pointer type computation so it works in conditionals too? 9630 if (!IsRelational && 9631 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9632 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9633 // This is a gcc extension compatibility comparison. 9634 // In a SFINAE context, we treat this as a hard error to maintain 9635 // conformance with the C++ standard. 9636 diagnoseFunctionPointerToVoidComparison( 9637 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9638 9639 if (isSFINAEContext()) 9640 return QualType(); 9641 9642 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9643 return ResultTy; 9644 } 9645 9646 // C++ [expr.eq]p2: 9647 // If at least one operand is a pointer [...] bring them to their 9648 // composite pointer type. 9649 // C++ [expr.rel]p2: 9650 // If both operands are pointers, [...] bring them to their composite 9651 // pointer type. 9652 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9653 (IsRelational ? 2 : 1) && 9654 (!LangOpts.ObjCAutoRefCount || 9655 !(LHSType->isObjCObjectPointerType() || 9656 RHSType->isObjCObjectPointerType()))) { 9657 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9658 return QualType(); 9659 else 9660 return ResultTy; 9661 } 9662 } else if (LHSType->isPointerType() && 9663 RHSType->isPointerType()) { // C99 6.5.8p2 9664 // All of the following pointer-related warnings are GCC extensions, except 9665 // when handling null pointer constants. 9666 QualType LCanPointeeTy = 9667 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9668 QualType RCanPointeeTy = 9669 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9670 9671 // C99 6.5.9p2 and C99 6.5.8p2 9672 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9673 RCanPointeeTy.getUnqualifiedType())) { 9674 // Valid unless a relational comparison of function pointers 9675 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9676 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9677 << LHSType << RHSType << LHS.get()->getSourceRange() 9678 << RHS.get()->getSourceRange(); 9679 } 9680 } else if (!IsRelational && 9681 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9682 // Valid unless comparison between non-null pointer and function pointer 9683 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9684 && !LHSIsNull && !RHSIsNull) 9685 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9686 /*isError*/false); 9687 } else { 9688 // Invalid 9689 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9690 } 9691 if (LCanPointeeTy != RCanPointeeTy) { 9692 // Treat NULL constant as a special case in OpenCL. 9693 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9694 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9695 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9696 Diag(Loc, 9697 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9698 << LHSType << RHSType << 0 /* comparison */ 9699 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9700 } 9701 } 9702 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9703 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9704 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9705 : CK_BitCast; 9706 if (LHSIsNull && !RHSIsNull) 9707 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9708 else 9709 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9710 } 9711 return ResultTy; 9712 } 9713 9714 if (getLangOpts().CPlusPlus) { 9715 // C++ [expr.eq]p4: 9716 // Two operands of type std::nullptr_t or one operand of type 9717 // std::nullptr_t and the other a null pointer constant compare equal. 9718 if (!IsRelational && LHSIsNull && RHSIsNull) { 9719 if (LHSType->isNullPtrType()) { 9720 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9721 return ResultTy; 9722 } 9723 if (RHSType->isNullPtrType()) { 9724 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9725 return ResultTy; 9726 } 9727 } 9728 9729 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9730 // These aren't covered by the composite pointer type rules. 9731 if (!IsRelational && RHSType->isNullPtrType() && 9732 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9733 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9734 return ResultTy; 9735 } 9736 if (!IsRelational && LHSType->isNullPtrType() && 9737 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9738 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9739 return ResultTy; 9740 } 9741 9742 if (IsRelational && 9743 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9744 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9745 // HACK: Relational comparison of nullptr_t against a pointer type is 9746 // invalid per DR583, but we allow it within std::less<> and friends, 9747 // since otherwise common uses of it break. 9748 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9749 // friends to have std::nullptr_t overload candidates. 9750 DeclContext *DC = CurContext; 9751 if (isa<FunctionDecl>(DC)) 9752 DC = DC->getParent(); 9753 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9754 if (CTSD->isInStdNamespace() && 9755 llvm::StringSwitch<bool>(CTSD->getName()) 9756 .Cases("less", "less_equal", "greater", "greater_equal", true) 9757 .Default(false)) { 9758 if (RHSType->isNullPtrType()) 9759 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9760 else 9761 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9762 return ResultTy; 9763 } 9764 } 9765 } 9766 9767 // C++ [expr.eq]p2: 9768 // If at least one operand is a pointer to member, [...] bring them to 9769 // their composite pointer type. 9770 if (!IsRelational && 9771 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9772 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9773 return QualType(); 9774 else 9775 return ResultTy; 9776 } 9777 9778 // Handle scoped enumeration types specifically, since they don't promote 9779 // to integers. 9780 if (LHS.get()->getType()->isEnumeralType() && 9781 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9782 RHS.get()->getType())) 9783 return ResultTy; 9784 } 9785 9786 // Handle block pointer types. 9787 if (!IsRelational && LHSType->isBlockPointerType() && 9788 RHSType->isBlockPointerType()) { 9789 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9790 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9791 9792 if (!LHSIsNull && !RHSIsNull && 9793 !Context.typesAreCompatible(lpointee, rpointee)) { 9794 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9795 << LHSType << RHSType << LHS.get()->getSourceRange() 9796 << RHS.get()->getSourceRange(); 9797 } 9798 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9799 return ResultTy; 9800 } 9801 9802 // Allow block pointers to be compared with null pointer constants. 9803 if (!IsRelational 9804 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9805 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9806 if (!LHSIsNull && !RHSIsNull) { 9807 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9808 ->getPointeeType()->isVoidType()) 9809 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9810 ->getPointeeType()->isVoidType()))) 9811 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9812 << LHSType << RHSType << LHS.get()->getSourceRange() 9813 << RHS.get()->getSourceRange(); 9814 } 9815 if (LHSIsNull && !RHSIsNull) 9816 LHS = ImpCastExprToType(LHS.get(), RHSType, 9817 RHSType->isPointerType() ? CK_BitCast 9818 : CK_AnyPointerToBlockPointerCast); 9819 else 9820 RHS = ImpCastExprToType(RHS.get(), LHSType, 9821 LHSType->isPointerType() ? CK_BitCast 9822 : CK_AnyPointerToBlockPointerCast); 9823 return ResultTy; 9824 } 9825 9826 if (LHSType->isObjCObjectPointerType() || 9827 RHSType->isObjCObjectPointerType()) { 9828 const PointerType *LPT = LHSType->getAs<PointerType>(); 9829 const PointerType *RPT = RHSType->getAs<PointerType>(); 9830 if (LPT || RPT) { 9831 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9832 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9833 9834 if (!LPtrToVoid && !RPtrToVoid && 9835 !Context.typesAreCompatible(LHSType, RHSType)) { 9836 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9837 /*isError*/false); 9838 } 9839 if (LHSIsNull && !RHSIsNull) { 9840 Expr *E = LHS.get(); 9841 if (getLangOpts().ObjCAutoRefCount) 9842 CheckObjCConversion(SourceRange(), RHSType, E, 9843 CCK_ImplicitConversion); 9844 LHS = ImpCastExprToType(E, RHSType, 9845 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9846 } 9847 else { 9848 Expr *E = RHS.get(); 9849 if (getLangOpts().ObjCAutoRefCount) 9850 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 9851 /*Diagnose=*/true, 9852 /*DiagnoseCFAudited=*/false, Opc); 9853 RHS = ImpCastExprToType(E, LHSType, 9854 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9855 } 9856 return ResultTy; 9857 } 9858 if (LHSType->isObjCObjectPointerType() && 9859 RHSType->isObjCObjectPointerType()) { 9860 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9861 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9862 /*isError*/false); 9863 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9864 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9865 9866 if (LHSIsNull && !RHSIsNull) 9867 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9868 else 9869 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9870 return ResultTy; 9871 } 9872 } 9873 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9874 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9875 unsigned DiagID = 0; 9876 bool isError = false; 9877 if (LangOpts.DebuggerSupport) { 9878 // Under a debugger, allow the comparison of pointers to integers, 9879 // since users tend to want to compare addresses. 9880 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9881 (RHSIsNull && RHSType->isIntegerType())) { 9882 if (IsRelational) { 9883 isError = getLangOpts().CPlusPlus; 9884 DiagID = 9885 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9886 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9887 } 9888 } else if (getLangOpts().CPlusPlus) { 9889 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9890 isError = true; 9891 } else if (IsRelational) 9892 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9893 else 9894 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9895 9896 if (DiagID) { 9897 Diag(Loc, DiagID) 9898 << LHSType << RHSType << LHS.get()->getSourceRange() 9899 << RHS.get()->getSourceRange(); 9900 if (isError) 9901 return QualType(); 9902 } 9903 9904 if (LHSType->isIntegerType()) 9905 LHS = ImpCastExprToType(LHS.get(), RHSType, 9906 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9907 else 9908 RHS = ImpCastExprToType(RHS.get(), LHSType, 9909 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9910 return ResultTy; 9911 } 9912 9913 // Handle block pointers. 9914 if (!IsRelational && RHSIsNull 9915 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9916 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9917 return ResultTy; 9918 } 9919 if (!IsRelational && LHSIsNull 9920 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9921 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9922 return ResultTy; 9923 } 9924 9925 if (getLangOpts().OpenCLVersion >= 200) { 9926 if (LHSIsNull && RHSType->isQueueT()) { 9927 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9928 return ResultTy; 9929 } 9930 9931 if (LHSType->isQueueT() && RHSIsNull) { 9932 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9933 return ResultTy; 9934 } 9935 } 9936 9937 return InvalidOperands(Loc, LHS, RHS); 9938 } 9939 9940 // Return a signed ext_vector_type that is of identical size and number of 9941 // elements. For floating point vectors, return an integer type of identical 9942 // size and number of elements. In the non ext_vector_type case, search from 9943 // the largest type to the smallest type to avoid cases where long long == long, 9944 // where long gets picked over long long. 9945 QualType Sema::GetSignedVectorType(QualType V) { 9946 const VectorType *VTy = V->getAs<VectorType>(); 9947 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9948 9949 if (isa<ExtVectorType>(VTy)) { 9950 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9951 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9952 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9953 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9954 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9955 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9956 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9957 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9958 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9959 "Unhandled vector element size in vector compare"); 9960 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9961 } 9962 9963 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 9964 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 9965 VectorType::GenericVector); 9966 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9967 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 9968 VectorType::GenericVector); 9969 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9970 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 9971 VectorType::GenericVector); 9972 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9973 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 9974 VectorType::GenericVector); 9975 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 9976 "Unhandled vector element size in vector compare"); 9977 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 9978 VectorType::GenericVector); 9979 } 9980 9981 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9982 /// operates on extended vector types. Instead of producing an IntTy result, 9983 /// like a scalar comparison, a vector comparison produces a vector of integer 9984 /// types. 9985 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9986 SourceLocation Loc, 9987 bool IsRelational) { 9988 // Check to make sure we're operating on vectors of the same type and width, 9989 // Allowing one side to be a scalar of element type. 9990 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9991 /*AllowBothBool*/true, 9992 /*AllowBoolConversions*/getLangOpts().ZVector); 9993 if (vType.isNull()) 9994 return vType; 9995 9996 QualType LHSType = LHS.get()->getType(); 9997 9998 // If AltiVec, the comparison results in a numeric type, i.e. 9999 // bool for C++, int for C 10000 if (getLangOpts().AltiVec && 10001 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10002 return Context.getLogicalOperationType(); 10003 10004 // For non-floating point types, check for self-comparisons of the form 10005 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10006 // often indicate logic errors in the program. 10007 if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) { 10008 if (DeclRefExpr* DRL 10009 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 10010 if (DeclRefExpr* DRR 10011 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 10012 if (DRL->getDecl() == DRR->getDecl()) 10013 DiagRuntimeBehavior(Loc, nullptr, 10014 PDiag(diag::warn_comparison_always) 10015 << 0 // self- 10016 << 2 // "a constant" 10017 ); 10018 } 10019 10020 // Check for comparisons of floating point operands using != and ==. 10021 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 10022 assert (RHS.get()->getType()->hasFloatingRepresentation()); 10023 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10024 } 10025 10026 // Return a signed type for the vector. 10027 return GetSignedVectorType(vType); 10028 } 10029 10030 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10031 SourceLocation Loc) { 10032 // Ensure that either both operands are of the same vector type, or 10033 // one operand is of a vector type and the other is of its element type. 10034 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10035 /*AllowBothBool*/true, 10036 /*AllowBoolConversions*/false); 10037 if (vType.isNull()) 10038 return InvalidOperands(Loc, LHS, RHS); 10039 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10040 vType->hasFloatingRepresentation()) 10041 return InvalidOperands(Loc, LHS, RHS); 10042 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10043 // usage of the logical operators && and || with vectors in C. This 10044 // check could be notionally dropped. 10045 if (!getLangOpts().CPlusPlus && 10046 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10047 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10048 10049 return GetSignedVectorType(LHS.get()->getType()); 10050 } 10051 10052 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10053 SourceLocation Loc, 10054 BinaryOperatorKind Opc) { 10055 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10056 10057 bool IsCompAssign = 10058 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10059 10060 if (LHS.get()->getType()->isVectorType() || 10061 RHS.get()->getType()->isVectorType()) { 10062 if (LHS.get()->getType()->hasIntegerRepresentation() && 10063 RHS.get()->getType()->hasIntegerRepresentation()) 10064 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10065 /*AllowBothBool*/true, 10066 /*AllowBoolConversions*/getLangOpts().ZVector); 10067 return InvalidOperands(Loc, LHS, RHS); 10068 } 10069 10070 if (Opc == BO_And) 10071 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10072 10073 ExprResult LHSResult = LHS, RHSResult = RHS; 10074 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10075 IsCompAssign); 10076 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10077 return QualType(); 10078 LHS = LHSResult.get(); 10079 RHS = RHSResult.get(); 10080 10081 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10082 return compType; 10083 return InvalidOperands(Loc, LHS, RHS); 10084 } 10085 10086 // C99 6.5.[13,14] 10087 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10088 SourceLocation Loc, 10089 BinaryOperatorKind Opc) { 10090 // Check vector operands differently. 10091 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10092 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10093 10094 // Diagnose cases where the user write a logical and/or but probably meant a 10095 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10096 // is a constant. 10097 if (LHS.get()->getType()->isIntegerType() && 10098 !LHS.get()->getType()->isBooleanType() && 10099 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10100 // Don't warn in macros or template instantiations. 10101 !Loc.isMacroID() && !inTemplateInstantiation()) { 10102 // If the RHS can be constant folded, and if it constant folds to something 10103 // that isn't 0 or 1 (which indicate a potential logical operation that 10104 // happened to fold to true/false) then warn. 10105 // Parens on the RHS are ignored. 10106 llvm::APSInt Result; 10107 if (RHS.get()->EvaluateAsInt(Result, Context)) 10108 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10109 !RHS.get()->getExprLoc().isMacroID()) || 10110 (Result != 0 && Result != 1)) { 10111 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10112 << RHS.get()->getSourceRange() 10113 << (Opc == BO_LAnd ? "&&" : "||"); 10114 // Suggest replacing the logical operator with the bitwise version 10115 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10116 << (Opc == BO_LAnd ? "&" : "|") 10117 << FixItHint::CreateReplacement(SourceRange( 10118 Loc, getLocForEndOfToken(Loc)), 10119 Opc == BO_LAnd ? "&" : "|"); 10120 if (Opc == BO_LAnd) 10121 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10122 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10123 << FixItHint::CreateRemoval( 10124 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10125 RHS.get()->getLocEnd())); 10126 } 10127 } 10128 10129 if (!Context.getLangOpts().CPlusPlus) { 10130 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10131 // not operate on the built-in scalar and vector float types. 10132 if (Context.getLangOpts().OpenCL && 10133 Context.getLangOpts().OpenCLVersion < 120) { 10134 if (LHS.get()->getType()->isFloatingType() || 10135 RHS.get()->getType()->isFloatingType()) 10136 return InvalidOperands(Loc, LHS, RHS); 10137 } 10138 10139 LHS = UsualUnaryConversions(LHS.get()); 10140 if (LHS.isInvalid()) 10141 return QualType(); 10142 10143 RHS = UsualUnaryConversions(RHS.get()); 10144 if (RHS.isInvalid()) 10145 return QualType(); 10146 10147 if (!LHS.get()->getType()->isScalarType() || 10148 !RHS.get()->getType()->isScalarType()) 10149 return InvalidOperands(Loc, LHS, RHS); 10150 10151 return Context.IntTy; 10152 } 10153 10154 // The following is safe because we only use this method for 10155 // non-overloadable operands. 10156 10157 // C++ [expr.log.and]p1 10158 // C++ [expr.log.or]p1 10159 // The operands are both contextually converted to type bool. 10160 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10161 if (LHSRes.isInvalid()) 10162 return InvalidOperands(Loc, LHS, RHS); 10163 LHS = LHSRes; 10164 10165 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10166 if (RHSRes.isInvalid()) 10167 return InvalidOperands(Loc, LHS, RHS); 10168 RHS = RHSRes; 10169 10170 // C++ [expr.log.and]p2 10171 // C++ [expr.log.or]p2 10172 // The result is a bool. 10173 return Context.BoolTy; 10174 } 10175 10176 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10177 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10178 if (!ME) return false; 10179 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10180 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10181 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10182 if (!Base) return false; 10183 return Base->getMethodDecl() != nullptr; 10184 } 10185 10186 /// Is the given expression (which must be 'const') a reference to a 10187 /// variable which was originally non-const, but which has become 10188 /// 'const' due to being captured within a block? 10189 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10190 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10191 assert(E->isLValue() && E->getType().isConstQualified()); 10192 E = E->IgnoreParens(); 10193 10194 // Must be a reference to a declaration from an enclosing scope. 10195 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10196 if (!DRE) return NCCK_None; 10197 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10198 10199 // The declaration must be a variable which is not declared 'const'. 10200 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10201 if (!var) return NCCK_None; 10202 if (var->getType().isConstQualified()) return NCCK_None; 10203 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10204 10205 // Decide whether the first capture was for a block or a lambda. 10206 DeclContext *DC = S.CurContext, *Prev = nullptr; 10207 // Decide whether the first capture was for a block or a lambda. 10208 while (DC) { 10209 // For init-capture, it is possible that the variable belongs to the 10210 // template pattern of the current context. 10211 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10212 if (var->isInitCapture() && 10213 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10214 break; 10215 if (DC == var->getDeclContext()) 10216 break; 10217 Prev = DC; 10218 DC = DC->getParent(); 10219 } 10220 // Unless we have an init-capture, we've gone one step too far. 10221 if (!var->isInitCapture()) 10222 DC = Prev; 10223 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10224 } 10225 10226 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10227 Ty = Ty.getNonReferenceType(); 10228 if (IsDereference && Ty->isPointerType()) 10229 Ty = Ty->getPointeeType(); 10230 return !Ty.isConstQualified(); 10231 } 10232 10233 /// Emit the "read-only variable not assignable" error and print notes to give 10234 /// more information about why the variable is not assignable, such as pointing 10235 /// to the declaration of a const variable, showing that a method is const, or 10236 /// that the function is returning a const reference. 10237 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10238 SourceLocation Loc) { 10239 // Update err_typecheck_assign_const and note_typecheck_assign_const 10240 // when this enum is changed. 10241 enum { 10242 ConstFunction, 10243 ConstVariable, 10244 ConstMember, 10245 ConstMethod, 10246 ConstUnknown, // Keep as last element 10247 }; 10248 10249 SourceRange ExprRange = E->getSourceRange(); 10250 10251 // Only emit one error on the first const found. All other consts will emit 10252 // a note to the error. 10253 bool DiagnosticEmitted = false; 10254 10255 // Track if the current expression is the result of a dereference, and if the 10256 // next checked expression is the result of a dereference. 10257 bool IsDereference = false; 10258 bool NextIsDereference = false; 10259 10260 // Loop to process MemberExpr chains. 10261 while (true) { 10262 IsDereference = NextIsDereference; 10263 10264 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10265 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10266 NextIsDereference = ME->isArrow(); 10267 const ValueDecl *VD = ME->getMemberDecl(); 10268 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10269 // Mutable fields can be modified even if the class is const. 10270 if (Field->isMutable()) { 10271 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10272 break; 10273 } 10274 10275 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10276 if (!DiagnosticEmitted) { 10277 S.Diag(Loc, diag::err_typecheck_assign_const) 10278 << ExprRange << ConstMember << false /*static*/ << Field 10279 << Field->getType(); 10280 DiagnosticEmitted = true; 10281 } 10282 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10283 << ConstMember << false /*static*/ << Field << Field->getType() 10284 << Field->getSourceRange(); 10285 } 10286 E = ME->getBase(); 10287 continue; 10288 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10289 if (VDecl->getType().isConstQualified()) { 10290 if (!DiagnosticEmitted) { 10291 S.Diag(Loc, diag::err_typecheck_assign_const) 10292 << ExprRange << ConstMember << true /*static*/ << VDecl 10293 << VDecl->getType(); 10294 DiagnosticEmitted = true; 10295 } 10296 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10297 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10298 << VDecl->getSourceRange(); 10299 } 10300 // Static fields do not inherit constness from parents. 10301 break; 10302 } 10303 break; 10304 } // End MemberExpr 10305 break; 10306 } 10307 10308 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10309 // Function calls 10310 const FunctionDecl *FD = CE->getDirectCallee(); 10311 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10312 if (!DiagnosticEmitted) { 10313 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10314 << ConstFunction << FD; 10315 DiagnosticEmitted = true; 10316 } 10317 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10318 diag::note_typecheck_assign_const) 10319 << ConstFunction << FD << FD->getReturnType() 10320 << FD->getReturnTypeSourceRange(); 10321 } 10322 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10323 // Point to variable declaration. 10324 if (const ValueDecl *VD = DRE->getDecl()) { 10325 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10326 if (!DiagnosticEmitted) { 10327 S.Diag(Loc, diag::err_typecheck_assign_const) 10328 << ExprRange << ConstVariable << VD << VD->getType(); 10329 DiagnosticEmitted = true; 10330 } 10331 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10332 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10333 } 10334 } 10335 } else if (isa<CXXThisExpr>(E)) { 10336 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10337 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10338 if (MD->isConst()) { 10339 if (!DiagnosticEmitted) { 10340 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10341 << ConstMethod << MD; 10342 DiagnosticEmitted = true; 10343 } 10344 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10345 << ConstMethod << MD << MD->getSourceRange(); 10346 } 10347 } 10348 } 10349 } 10350 10351 if (DiagnosticEmitted) 10352 return; 10353 10354 // Can't determine a more specific message, so display the generic error. 10355 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10356 } 10357 10358 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10359 /// emit an error and return true. If so, return false. 10360 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10361 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10362 10363 S.CheckShadowingDeclModification(E, Loc); 10364 10365 SourceLocation OrigLoc = Loc; 10366 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10367 &Loc); 10368 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10369 IsLV = Expr::MLV_InvalidMessageExpression; 10370 if (IsLV == Expr::MLV_Valid) 10371 return false; 10372 10373 unsigned DiagID = 0; 10374 bool NeedType = false; 10375 switch (IsLV) { // C99 6.5.16p2 10376 case Expr::MLV_ConstQualified: 10377 // Use a specialized diagnostic when we're assigning to an object 10378 // from an enclosing function or block. 10379 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10380 if (NCCK == NCCK_Block) 10381 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10382 else 10383 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10384 break; 10385 } 10386 10387 // In ARC, use some specialized diagnostics for occasions where we 10388 // infer 'const'. These are always pseudo-strong variables. 10389 if (S.getLangOpts().ObjCAutoRefCount) { 10390 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10391 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10392 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10393 10394 // Use the normal diagnostic if it's pseudo-__strong but the 10395 // user actually wrote 'const'. 10396 if (var->isARCPseudoStrong() && 10397 (!var->getTypeSourceInfo() || 10398 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10399 // There are two pseudo-strong cases: 10400 // - self 10401 ObjCMethodDecl *method = S.getCurMethodDecl(); 10402 if (method && var == method->getSelfDecl()) 10403 DiagID = method->isClassMethod() 10404 ? diag::err_typecheck_arc_assign_self_class_method 10405 : diag::err_typecheck_arc_assign_self; 10406 10407 // - fast enumeration variables 10408 else 10409 DiagID = diag::err_typecheck_arr_assign_enumeration; 10410 10411 SourceRange Assign; 10412 if (Loc != OrigLoc) 10413 Assign = SourceRange(OrigLoc, OrigLoc); 10414 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10415 // We need to preserve the AST regardless, so migration tool 10416 // can do its job. 10417 return false; 10418 } 10419 } 10420 } 10421 10422 // If none of the special cases above are triggered, then this is a 10423 // simple const assignment. 10424 if (DiagID == 0) { 10425 DiagnoseConstAssignment(S, E, Loc); 10426 return true; 10427 } 10428 10429 break; 10430 case Expr::MLV_ConstAddrSpace: 10431 DiagnoseConstAssignment(S, E, Loc); 10432 return true; 10433 case Expr::MLV_ArrayType: 10434 case Expr::MLV_ArrayTemporary: 10435 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10436 NeedType = true; 10437 break; 10438 case Expr::MLV_NotObjectType: 10439 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10440 NeedType = true; 10441 break; 10442 case Expr::MLV_LValueCast: 10443 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10444 break; 10445 case Expr::MLV_Valid: 10446 llvm_unreachable("did not take early return for MLV_Valid"); 10447 case Expr::MLV_InvalidExpression: 10448 case Expr::MLV_MemberFunction: 10449 case Expr::MLV_ClassTemporary: 10450 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10451 break; 10452 case Expr::MLV_IncompleteType: 10453 case Expr::MLV_IncompleteVoidType: 10454 return S.RequireCompleteType(Loc, E->getType(), 10455 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10456 case Expr::MLV_DuplicateVectorComponents: 10457 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10458 break; 10459 case Expr::MLV_NoSetterProperty: 10460 llvm_unreachable("readonly properties should be processed differently"); 10461 case Expr::MLV_InvalidMessageExpression: 10462 DiagID = diag::err_readonly_message_assignment; 10463 break; 10464 case Expr::MLV_SubObjCPropertySetting: 10465 DiagID = diag::err_no_subobject_property_setting; 10466 break; 10467 } 10468 10469 SourceRange Assign; 10470 if (Loc != OrigLoc) 10471 Assign = SourceRange(OrigLoc, OrigLoc); 10472 if (NeedType) 10473 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10474 else 10475 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10476 return true; 10477 } 10478 10479 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10480 SourceLocation Loc, 10481 Sema &Sema) { 10482 // C / C++ fields 10483 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10484 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10485 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10486 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10487 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10488 } 10489 10490 // Objective-C instance variables 10491 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10492 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10493 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10494 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10495 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10496 if (RL && RR && RL->getDecl() == RR->getDecl()) 10497 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10498 } 10499 } 10500 10501 // C99 6.5.16.1 10502 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10503 SourceLocation Loc, 10504 QualType CompoundType) { 10505 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10506 10507 // Verify that LHS is a modifiable lvalue, and emit error if not. 10508 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10509 return QualType(); 10510 10511 QualType LHSType = LHSExpr->getType(); 10512 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10513 CompoundType; 10514 // OpenCL v1.2 s6.1.1.1 p2: 10515 // The half data type can only be used to declare a pointer to a buffer that 10516 // contains half values 10517 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10518 LHSType->isHalfType()) { 10519 Diag(Loc, diag::err_opencl_half_load_store) << 1 10520 << LHSType.getUnqualifiedType(); 10521 return QualType(); 10522 } 10523 10524 AssignConvertType ConvTy; 10525 if (CompoundType.isNull()) { 10526 Expr *RHSCheck = RHS.get(); 10527 10528 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10529 10530 QualType LHSTy(LHSType); 10531 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10532 if (RHS.isInvalid()) 10533 return QualType(); 10534 // Special case of NSObject attributes on c-style pointer types. 10535 if (ConvTy == IncompatiblePointer && 10536 ((Context.isObjCNSObjectType(LHSType) && 10537 RHSType->isObjCObjectPointerType()) || 10538 (Context.isObjCNSObjectType(RHSType) && 10539 LHSType->isObjCObjectPointerType()))) 10540 ConvTy = Compatible; 10541 10542 if (ConvTy == Compatible && 10543 LHSType->isObjCObjectType()) 10544 Diag(Loc, diag::err_objc_object_assignment) 10545 << LHSType; 10546 10547 // If the RHS is a unary plus or minus, check to see if they = and + are 10548 // right next to each other. If so, the user may have typo'd "x =+ 4" 10549 // instead of "x += 4". 10550 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10551 RHSCheck = ICE->getSubExpr(); 10552 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10553 if ((UO->getOpcode() == UO_Plus || 10554 UO->getOpcode() == UO_Minus) && 10555 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10556 // Only if the two operators are exactly adjacent. 10557 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10558 // And there is a space or other character before the subexpr of the 10559 // unary +/-. We don't want to warn on "x=-1". 10560 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10561 UO->getSubExpr()->getLocStart().isFileID()) { 10562 Diag(Loc, diag::warn_not_compound_assign) 10563 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10564 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10565 } 10566 } 10567 10568 if (ConvTy == Compatible) { 10569 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10570 // Warn about retain cycles where a block captures the LHS, but 10571 // not if the LHS is a simple variable into which the block is 10572 // being stored...unless that variable can be captured by reference! 10573 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10574 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10575 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10576 checkRetainCycles(LHSExpr, RHS.get()); 10577 } 10578 10579 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10580 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10581 // It is safe to assign a weak reference into a strong variable. 10582 // Although this code can still have problems: 10583 // id x = self.weakProp; 10584 // id y = self.weakProp; 10585 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10586 // paths through the function. This should be revisited if 10587 // -Wrepeated-use-of-weak is made flow-sensitive. 10588 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10589 // variable, which will be valid for the current autorelease scope. 10590 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10591 RHS.get()->getLocStart())) 10592 getCurFunction()->markSafeWeakUse(RHS.get()); 10593 10594 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10595 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10596 } 10597 } 10598 } else { 10599 // Compound assignment "x += y" 10600 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10601 } 10602 10603 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10604 RHS.get(), AA_Assigning)) 10605 return QualType(); 10606 10607 CheckForNullPointerDereference(*this, LHSExpr); 10608 10609 // C99 6.5.16p3: The type of an assignment expression is the type of the 10610 // left operand unless the left operand has qualified type, in which case 10611 // it is the unqualified version of the type of the left operand. 10612 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10613 // is converted to the type of the assignment expression (above). 10614 // C++ 5.17p1: the type of the assignment expression is that of its left 10615 // operand. 10616 return (getLangOpts().CPlusPlus 10617 ? LHSType : LHSType.getUnqualifiedType()); 10618 } 10619 10620 // Only ignore explicit casts to void. 10621 static bool IgnoreCommaOperand(const Expr *E) { 10622 E = E->IgnoreParens(); 10623 10624 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10625 if (CE->getCastKind() == CK_ToVoid) { 10626 return true; 10627 } 10628 } 10629 10630 return false; 10631 } 10632 10633 // Look for instances where it is likely the comma operator is confused with 10634 // another operator. There is a whitelist of acceptable expressions for the 10635 // left hand side of the comma operator, otherwise emit a warning. 10636 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10637 // No warnings in macros 10638 if (Loc.isMacroID()) 10639 return; 10640 10641 // Don't warn in template instantiations. 10642 if (inTemplateInstantiation()) 10643 return; 10644 10645 // Scope isn't fine-grained enough to whitelist the specific cases, so 10646 // instead, skip more than needed, then call back into here with the 10647 // CommaVisitor in SemaStmt.cpp. 10648 // The whitelisted locations are the initialization and increment portions 10649 // of a for loop. The additional checks are on the condition of 10650 // if statements, do/while loops, and for loops. 10651 const unsigned ForIncrementFlags = 10652 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10653 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10654 const unsigned ScopeFlags = getCurScope()->getFlags(); 10655 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10656 (ScopeFlags & ForInitFlags) == ForInitFlags) 10657 return; 10658 10659 // If there are multiple comma operators used together, get the RHS of the 10660 // of the comma operator as the LHS. 10661 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10662 if (BO->getOpcode() != BO_Comma) 10663 break; 10664 LHS = BO->getRHS(); 10665 } 10666 10667 // Only allow some expressions on LHS to not warn. 10668 if (IgnoreCommaOperand(LHS)) 10669 return; 10670 10671 Diag(Loc, diag::warn_comma_operator); 10672 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10673 << LHS->getSourceRange() 10674 << FixItHint::CreateInsertion(LHS->getLocStart(), 10675 LangOpts.CPlusPlus ? "static_cast<void>(" 10676 : "(void)(") 10677 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10678 ")"); 10679 } 10680 10681 // C99 6.5.17 10682 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10683 SourceLocation Loc) { 10684 LHS = S.CheckPlaceholderExpr(LHS.get()); 10685 RHS = S.CheckPlaceholderExpr(RHS.get()); 10686 if (LHS.isInvalid() || RHS.isInvalid()) 10687 return QualType(); 10688 10689 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10690 // operands, but not unary promotions. 10691 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10692 10693 // So we treat the LHS as a ignored value, and in C++ we allow the 10694 // containing site to determine what should be done with the RHS. 10695 LHS = S.IgnoredValueConversions(LHS.get()); 10696 if (LHS.isInvalid()) 10697 return QualType(); 10698 10699 S.DiagnoseUnusedExprResult(LHS.get()); 10700 10701 if (!S.getLangOpts().CPlusPlus) { 10702 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10703 if (RHS.isInvalid()) 10704 return QualType(); 10705 if (!RHS.get()->getType()->isVoidType()) 10706 S.RequireCompleteType(Loc, RHS.get()->getType(), 10707 diag::err_incomplete_type); 10708 } 10709 10710 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10711 S.DiagnoseCommaOperator(LHS.get(), Loc); 10712 10713 return RHS.get()->getType(); 10714 } 10715 10716 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10717 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10718 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10719 ExprValueKind &VK, 10720 ExprObjectKind &OK, 10721 SourceLocation OpLoc, 10722 bool IsInc, bool IsPrefix) { 10723 if (Op->isTypeDependent()) 10724 return S.Context.DependentTy; 10725 10726 QualType ResType = Op->getType(); 10727 // Atomic types can be used for increment / decrement where the non-atomic 10728 // versions can, so ignore the _Atomic() specifier for the purpose of 10729 // checking. 10730 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10731 ResType = ResAtomicType->getValueType(); 10732 10733 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10734 10735 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10736 // Decrement of bool is not allowed. 10737 if (!IsInc) { 10738 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10739 return QualType(); 10740 } 10741 // Increment of bool sets it to true, but is deprecated. 10742 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10743 : diag::warn_increment_bool) 10744 << Op->getSourceRange(); 10745 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10746 // Error on enum increments and decrements in C++ mode 10747 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10748 return QualType(); 10749 } else if (ResType->isRealType()) { 10750 // OK! 10751 } else if (ResType->isPointerType()) { 10752 // C99 6.5.2.4p2, 6.5.6p2 10753 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10754 return QualType(); 10755 } else if (ResType->isObjCObjectPointerType()) { 10756 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10757 // Otherwise, we just need a complete type. 10758 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10759 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10760 return QualType(); 10761 } else if (ResType->isAnyComplexType()) { 10762 // C99 does not support ++/-- on complex types, we allow as an extension. 10763 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10764 << ResType << Op->getSourceRange(); 10765 } else if (ResType->isPlaceholderType()) { 10766 ExprResult PR = S.CheckPlaceholderExpr(Op); 10767 if (PR.isInvalid()) return QualType(); 10768 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10769 IsInc, IsPrefix); 10770 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10771 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10772 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10773 (ResType->getAs<VectorType>()->getVectorKind() != 10774 VectorType::AltiVecBool)) { 10775 // The z vector extensions allow ++ and -- for non-bool vectors. 10776 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10777 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10778 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10779 } else { 10780 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10781 << ResType << int(IsInc) << Op->getSourceRange(); 10782 return QualType(); 10783 } 10784 // At this point, we know we have a real, complex or pointer type. 10785 // Now make sure the operand is a modifiable lvalue. 10786 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10787 return QualType(); 10788 // In C++, a prefix increment is the same type as the operand. Otherwise 10789 // (in C or with postfix), the increment is the unqualified type of the 10790 // operand. 10791 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10792 VK = VK_LValue; 10793 OK = Op->getObjectKind(); 10794 return ResType; 10795 } else { 10796 VK = VK_RValue; 10797 return ResType.getUnqualifiedType(); 10798 } 10799 } 10800 10801 10802 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10803 /// This routine allows us to typecheck complex/recursive expressions 10804 /// where the declaration is needed for type checking. We only need to 10805 /// handle cases when the expression references a function designator 10806 /// or is an lvalue. Here are some examples: 10807 /// - &(x) => x 10808 /// - &*****f => f for f a function designator. 10809 /// - &s.xx => s 10810 /// - &s.zz[1].yy -> s, if zz is an array 10811 /// - *(x + 1) -> x, if x is an array 10812 /// - &"123"[2] -> 0 10813 /// - & __real__ x -> x 10814 static ValueDecl *getPrimaryDecl(Expr *E) { 10815 switch (E->getStmtClass()) { 10816 case Stmt::DeclRefExprClass: 10817 return cast<DeclRefExpr>(E)->getDecl(); 10818 case Stmt::MemberExprClass: 10819 // If this is an arrow operator, the address is an offset from 10820 // the base's value, so the object the base refers to is 10821 // irrelevant. 10822 if (cast<MemberExpr>(E)->isArrow()) 10823 return nullptr; 10824 // Otherwise, the expression refers to a part of the base 10825 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10826 case Stmt::ArraySubscriptExprClass: { 10827 // FIXME: This code shouldn't be necessary! We should catch the implicit 10828 // promotion of register arrays earlier. 10829 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10830 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10831 if (ICE->getSubExpr()->getType()->isArrayType()) 10832 return getPrimaryDecl(ICE->getSubExpr()); 10833 } 10834 return nullptr; 10835 } 10836 case Stmt::UnaryOperatorClass: { 10837 UnaryOperator *UO = cast<UnaryOperator>(E); 10838 10839 switch(UO->getOpcode()) { 10840 case UO_Real: 10841 case UO_Imag: 10842 case UO_Extension: 10843 return getPrimaryDecl(UO->getSubExpr()); 10844 default: 10845 return nullptr; 10846 } 10847 } 10848 case Stmt::ParenExprClass: 10849 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10850 case Stmt::ImplicitCastExprClass: 10851 // If the result of an implicit cast is an l-value, we care about 10852 // the sub-expression; otherwise, the result here doesn't matter. 10853 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10854 default: 10855 return nullptr; 10856 } 10857 } 10858 10859 namespace { 10860 enum { 10861 AO_Bit_Field = 0, 10862 AO_Vector_Element = 1, 10863 AO_Property_Expansion = 2, 10864 AO_Register_Variable = 3, 10865 AO_No_Error = 4 10866 }; 10867 } 10868 /// \brief Diagnose invalid operand for address of operations. 10869 /// 10870 /// \param Type The type of operand which cannot have its address taken. 10871 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10872 Expr *E, unsigned Type) { 10873 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10874 } 10875 10876 /// CheckAddressOfOperand - The operand of & must be either a function 10877 /// designator or an lvalue designating an object. If it is an lvalue, the 10878 /// object cannot be declared with storage class register or be a bit field. 10879 /// Note: The usual conversions are *not* applied to the operand of the & 10880 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10881 /// In C++, the operand might be an overloaded function name, in which case 10882 /// we allow the '&' but retain the overloaded-function type. 10883 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10884 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10885 if (PTy->getKind() == BuiltinType::Overload) { 10886 Expr *E = OrigOp.get()->IgnoreParens(); 10887 if (!isa<OverloadExpr>(E)) { 10888 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10889 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10890 << OrigOp.get()->getSourceRange(); 10891 return QualType(); 10892 } 10893 10894 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10895 if (isa<UnresolvedMemberExpr>(Ovl)) 10896 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10897 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10898 << OrigOp.get()->getSourceRange(); 10899 return QualType(); 10900 } 10901 10902 return Context.OverloadTy; 10903 } 10904 10905 if (PTy->getKind() == BuiltinType::UnknownAny) 10906 return Context.UnknownAnyTy; 10907 10908 if (PTy->getKind() == BuiltinType::BoundMember) { 10909 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10910 << OrigOp.get()->getSourceRange(); 10911 return QualType(); 10912 } 10913 10914 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10915 if (OrigOp.isInvalid()) return QualType(); 10916 } 10917 10918 if (OrigOp.get()->isTypeDependent()) 10919 return Context.DependentTy; 10920 10921 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10922 10923 // Make sure to ignore parentheses in subsequent checks 10924 Expr *op = OrigOp.get()->IgnoreParens(); 10925 10926 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10927 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10928 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10929 return QualType(); 10930 } 10931 10932 if (getLangOpts().C99) { 10933 // Implement C99-only parts of addressof rules. 10934 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10935 if (uOp->getOpcode() == UO_Deref) 10936 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10937 // (assuming the deref expression is valid). 10938 return uOp->getSubExpr()->getType(); 10939 } 10940 // Technically, there should be a check for array subscript 10941 // expressions here, but the result of one is always an lvalue anyway. 10942 } 10943 ValueDecl *dcl = getPrimaryDecl(op); 10944 10945 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10946 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10947 op->getLocStart())) 10948 return QualType(); 10949 10950 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10951 unsigned AddressOfError = AO_No_Error; 10952 10953 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10954 bool sfinae = (bool)isSFINAEContext(); 10955 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10956 : diag::ext_typecheck_addrof_temporary) 10957 << op->getType() << op->getSourceRange(); 10958 if (sfinae) 10959 return QualType(); 10960 // Materialize the temporary as an lvalue so that we can take its address. 10961 OrigOp = op = 10962 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10963 } else if (isa<ObjCSelectorExpr>(op)) { 10964 return Context.getPointerType(op->getType()); 10965 } else if (lval == Expr::LV_MemberFunction) { 10966 // If it's an instance method, make a member pointer. 10967 // The expression must have exactly the form &A::foo. 10968 10969 // If the underlying expression isn't a decl ref, give up. 10970 if (!isa<DeclRefExpr>(op)) { 10971 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10972 << OrigOp.get()->getSourceRange(); 10973 return QualType(); 10974 } 10975 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10976 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10977 10978 // The id-expression was parenthesized. 10979 if (OrigOp.get() != DRE) { 10980 Diag(OpLoc, diag::err_parens_pointer_member_function) 10981 << OrigOp.get()->getSourceRange(); 10982 10983 // The method was named without a qualifier. 10984 } else if (!DRE->getQualifier()) { 10985 if (MD->getParent()->getName().empty()) 10986 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10987 << op->getSourceRange(); 10988 else { 10989 SmallString<32> Str; 10990 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10991 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10992 << op->getSourceRange() 10993 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10994 } 10995 } 10996 10997 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10998 if (isa<CXXDestructorDecl>(MD)) 10999 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11000 11001 QualType MPTy = Context.getMemberPointerType( 11002 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11003 // Under the MS ABI, lock down the inheritance model now. 11004 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11005 (void)isCompleteType(OpLoc, MPTy); 11006 return MPTy; 11007 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11008 // C99 6.5.3.2p1 11009 // The operand must be either an l-value or a function designator 11010 if (!op->getType()->isFunctionType()) { 11011 // Use a special diagnostic for loads from property references. 11012 if (isa<PseudoObjectExpr>(op)) { 11013 AddressOfError = AO_Property_Expansion; 11014 } else { 11015 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11016 << op->getType() << op->getSourceRange(); 11017 return QualType(); 11018 } 11019 } 11020 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11021 // The operand cannot be a bit-field 11022 AddressOfError = AO_Bit_Field; 11023 } else if (op->getObjectKind() == OK_VectorComponent) { 11024 // The operand cannot be an element of a vector 11025 AddressOfError = AO_Vector_Element; 11026 } else if (dcl) { // C99 6.5.3.2p1 11027 // We have an lvalue with a decl. Make sure the decl is not declared 11028 // with the register storage-class specifier. 11029 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11030 // in C++ it is not error to take address of a register 11031 // variable (c++03 7.1.1P3) 11032 if (vd->getStorageClass() == SC_Register && 11033 !getLangOpts().CPlusPlus) { 11034 AddressOfError = AO_Register_Variable; 11035 } 11036 } else if (isa<MSPropertyDecl>(dcl)) { 11037 AddressOfError = AO_Property_Expansion; 11038 } else if (isa<FunctionTemplateDecl>(dcl)) { 11039 return Context.OverloadTy; 11040 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11041 // Okay: we can take the address of a field. 11042 // Could be a pointer to member, though, if there is an explicit 11043 // scope qualifier for the class. 11044 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11045 DeclContext *Ctx = dcl->getDeclContext(); 11046 if (Ctx && Ctx->isRecord()) { 11047 if (dcl->getType()->isReferenceType()) { 11048 Diag(OpLoc, 11049 diag::err_cannot_form_pointer_to_member_of_reference_type) 11050 << dcl->getDeclName() << dcl->getType(); 11051 return QualType(); 11052 } 11053 11054 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11055 Ctx = Ctx->getParent(); 11056 11057 QualType MPTy = Context.getMemberPointerType( 11058 op->getType(), 11059 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11060 // Under the MS ABI, lock down the inheritance model now. 11061 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11062 (void)isCompleteType(OpLoc, MPTy); 11063 return MPTy; 11064 } 11065 } 11066 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11067 !isa<BindingDecl>(dcl)) 11068 llvm_unreachable("Unknown/unexpected decl type"); 11069 } 11070 11071 if (AddressOfError != AO_No_Error) { 11072 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11073 return QualType(); 11074 } 11075 11076 if (lval == Expr::LV_IncompleteVoidType) { 11077 // Taking the address of a void variable is technically illegal, but we 11078 // allow it in cases which are otherwise valid. 11079 // Example: "extern void x; void* y = &x;". 11080 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11081 } 11082 11083 // If the operand has type "type", the result has type "pointer to type". 11084 if (op->getType()->isObjCObjectType()) 11085 return Context.getObjCObjectPointerType(op->getType()); 11086 11087 CheckAddressOfPackedMember(op); 11088 11089 return Context.getPointerType(op->getType()); 11090 } 11091 11092 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11093 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11094 if (!DRE) 11095 return; 11096 const Decl *D = DRE->getDecl(); 11097 if (!D) 11098 return; 11099 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11100 if (!Param) 11101 return; 11102 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11103 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11104 return; 11105 if (FunctionScopeInfo *FD = S.getCurFunction()) 11106 if (!FD->ModifiedNonNullParams.count(Param)) 11107 FD->ModifiedNonNullParams.insert(Param); 11108 } 11109 11110 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11111 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11112 SourceLocation OpLoc) { 11113 if (Op->isTypeDependent()) 11114 return S.Context.DependentTy; 11115 11116 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11117 if (ConvResult.isInvalid()) 11118 return QualType(); 11119 Op = ConvResult.get(); 11120 QualType OpTy = Op->getType(); 11121 QualType Result; 11122 11123 if (isa<CXXReinterpretCastExpr>(Op)) { 11124 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11125 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11126 Op->getSourceRange()); 11127 } 11128 11129 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11130 { 11131 Result = PT->getPointeeType(); 11132 } 11133 else if (const ObjCObjectPointerType *OPT = 11134 OpTy->getAs<ObjCObjectPointerType>()) 11135 Result = OPT->getPointeeType(); 11136 else { 11137 ExprResult PR = S.CheckPlaceholderExpr(Op); 11138 if (PR.isInvalid()) return QualType(); 11139 if (PR.get() != Op) 11140 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11141 } 11142 11143 if (Result.isNull()) { 11144 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11145 << OpTy << Op->getSourceRange(); 11146 return QualType(); 11147 } 11148 11149 // Note that per both C89 and C99, indirection is always legal, even if Result 11150 // is an incomplete type or void. It would be possible to warn about 11151 // dereferencing a void pointer, but it's completely well-defined, and such a 11152 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11153 // for pointers to 'void' but is fine for any other pointer type: 11154 // 11155 // C++ [expr.unary.op]p1: 11156 // [...] the expression to which [the unary * operator] is applied shall 11157 // be a pointer to an object type, or a pointer to a function type 11158 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11159 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11160 << OpTy << Op->getSourceRange(); 11161 11162 // Dereferences are usually l-values... 11163 VK = VK_LValue; 11164 11165 // ...except that certain expressions are never l-values in C. 11166 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11167 VK = VK_RValue; 11168 11169 return Result; 11170 } 11171 11172 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11173 BinaryOperatorKind Opc; 11174 switch (Kind) { 11175 default: llvm_unreachable("Unknown binop!"); 11176 case tok::periodstar: Opc = BO_PtrMemD; break; 11177 case tok::arrowstar: Opc = BO_PtrMemI; break; 11178 case tok::star: Opc = BO_Mul; break; 11179 case tok::slash: Opc = BO_Div; break; 11180 case tok::percent: Opc = BO_Rem; break; 11181 case tok::plus: Opc = BO_Add; break; 11182 case tok::minus: Opc = BO_Sub; break; 11183 case tok::lessless: Opc = BO_Shl; break; 11184 case tok::greatergreater: Opc = BO_Shr; break; 11185 case tok::lessequal: Opc = BO_LE; break; 11186 case tok::less: Opc = BO_LT; break; 11187 case tok::greaterequal: Opc = BO_GE; break; 11188 case tok::greater: Opc = BO_GT; break; 11189 case tok::exclaimequal: Opc = BO_NE; break; 11190 case tok::equalequal: Opc = BO_EQ; break; 11191 case tok::amp: Opc = BO_And; break; 11192 case tok::caret: Opc = BO_Xor; break; 11193 case tok::pipe: Opc = BO_Or; break; 11194 case tok::ampamp: Opc = BO_LAnd; break; 11195 case tok::pipepipe: Opc = BO_LOr; break; 11196 case tok::equal: Opc = BO_Assign; break; 11197 case tok::starequal: Opc = BO_MulAssign; break; 11198 case tok::slashequal: Opc = BO_DivAssign; break; 11199 case tok::percentequal: Opc = BO_RemAssign; break; 11200 case tok::plusequal: Opc = BO_AddAssign; break; 11201 case tok::minusequal: Opc = BO_SubAssign; break; 11202 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11203 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11204 case tok::ampequal: Opc = BO_AndAssign; break; 11205 case tok::caretequal: Opc = BO_XorAssign; break; 11206 case tok::pipeequal: Opc = BO_OrAssign; break; 11207 case tok::comma: Opc = BO_Comma; break; 11208 } 11209 return Opc; 11210 } 11211 11212 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11213 tok::TokenKind Kind) { 11214 UnaryOperatorKind Opc; 11215 switch (Kind) { 11216 default: llvm_unreachable("Unknown unary op!"); 11217 case tok::plusplus: Opc = UO_PreInc; break; 11218 case tok::minusminus: Opc = UO_PreDec; break; 11219 case tok::amp: Opc = UO_AddrOf; break; 11220 case tok::star: Opc = UO_Deref; break; 11221 case tok::plus: Opc = UO_Plus; break; 11222 case tok::minus: Opc = UO_Minus; break; 11223 case tok::tilde: Opc = UO_Not; break; 11224 case tok::exclaim: Opc = UO_LNot; break; 11225 case tok::kw___real: Opc = UO_Real; break; 11226 case tok::kw___imag: Opc = UO_Imag; break; 11227 case tok::kw___extension__: Opc = UO_Extension; break; 11228 } 11229 return Opc; 11230 } 11231 11232 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11233 /// This warning is only emitted for builtin assignment operations. It is also 11234 /// suppressed in the event of macro expansions. 11235 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11236 SourceLocation OpLoc) { 11237 if (S.inTemplateInstantiation()) 11238 return; 11239 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11240 return; 11241 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11242 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11243 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11244 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11245 if (!LHSDeclRef || !RHSDeclRef || 11246 LHSDeclRef->getLocation().isMacroID() || 11247 RHSDeclRef->getLocation().isMacroID()) 11248 return; 11249 const ValueDecl *LHSDecl = 11250 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11251 const ValueDecl *RHSDecl = 11252 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11253 if (LHSDecl != RHSDecl) 11254 return; 11255 if (LHSDecl->getType().isVolatileQualified()) 11256 return; 11257 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11258 if (RefTy->getPointeeType().isVolatileQualified()) 11259 return; 11260 11261 S.Diag(OpLoc, diag::warn_self_assignment) 11262 << LHSDeclRef->getType() 11263 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11264 } 11265 11266 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11267 /// is usually indicative of introspection within the Objective-C pointer. 11268 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11269 SourceLocation OpLoc) { 11270 if (!S.getLangOpts().ObjC1) 11271 return; 11272 11273 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11274 const Expr *LHS = L.get(); 11275 const Expr *RHS = R.get(); 11276 11277 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11278 ObjCPointerExpr = LHS; 11279 OtherExpr = RHS; 11280 } 11281 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11282 ObjCPointerExpr = RHS; 11283 OtherExpr = LHS; 11284 } 11285 11286 // This warning is deliberately made very specific to reduce false 11287 // positives with logic that uses '&' for hashing. This logic mainly 11288 // looks for code trying to introspect into tagged pointers, which 11289 // code should generally never do. 11290 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11291 unsigned Diag = diag::warn_objc_pointer_masking; 11292 // Determine if we are introspecting the result of performSelectorXXX. 11293 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11294 // Special case messages to -performSelector and friends, which 11295 // can return non-pointer values boxed in a pointer value. 11296 // Some clients may wish to silence warnings in this subcase. 11297 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11298 Selector S = ME->getSelector(); 11299 StringRef SelArg0 = S.getNameForSlot(0); 11300 if (SelArg0.startswith("performSelector")) 11301 Diag = diag::warn_objc_pointer_masking_performSelector; 11302 } 11303 11304 S.Diag(OpLoc, Diag) 11305 << ObjCPointerExpr->getSourceRange(); 11306 } 11307 } 11308 11309 static NamedDecl *getDeclFromExpr(Expr *E) { 11310 if (!E) 11311 return nullptr; 11312 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11313 return DRE->getDecl(); 11314 if (auto *ME = dyn_cast<MemberExpr>(E)) 11315 return ME->getMemberDecl(); 11316 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11317 return IRE->getDecl(); 11318 return nullptr; 11319 } 11320 11321 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11322 /// operator @p Opc at location @c TokLoc. This routine only supports 11323 /// built-in operations; ActOnBinOp handles overloaded operators. 11324 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11325 BinaryOperatorKind Opc, 11326 Expr *LHSExpr, Expr *RHSExpr) { 11327 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11328 // The syntax only allows initializer lists on the RHS of assignment, 11329 // so we don't need to worry about accepting invalid code for 11330 // non-assignment operators. 11331 // C++11 5.17p9: 11332 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11333 // of x = {} is x = T(). 11334 InitializationKind Kind = 11335 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11336 InitializedEntity Entity = 11337 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11338 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11339 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11340 if (Init.isInvalid()) 11341 return Init; 11342 RHSExpr = Init.get(); 11343 } 11344 11345 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11346 QualType ResultTy; // Result type of the binary operator. 11347 // The following two variables are used for compound assignment operators 11348 QualType CompLHSTy; // Type of LHS after promotions for computation 11349 QualType CompResultTy; // Type of computation result 11350 ExprValueKind VK = VK_RValue; 11351 ExprObjectKind OK = OK_Ordinary; 11352 11353 if (!getLangOpts().CPlusPlus) { 11354 // C cannot handle TypoExpr nodes on either side of a binop because it 11355 // doesn't handle dependent types properly, so make sure any TypoExprs have 11356 // been dealt with before checking the operands. 11357 LHS = CorrectDelayedTyposInExpr(LHSExpr); 11358 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 11359 if (Opc != BO_Assign) 11360 return ExprResult(E); 11361 // Avoid correcting the RHS to the same Expr as the LHS. 11362 Decl *D = getDeclFromExpr(E); 11363 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11364 }); 11365 if (!LHS.isUsable() || !RHS.isUsable()) 11366 return ExprError(); 11367 } 11368 11369 if (getLangOpts().OpenCL) { 11370 QualType LHSTy = LHSExpr->getType(); 11371 QualType RHSTy = RHSExpr->getType(); 11372 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11373 // the ATOMIC_VAR_INIT macro. 11374 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11375 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11376 if (BO_Assign == Opc) 11377 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11378 else 11379 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11380 return ExprError(); 11381 } 11382 11383 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11384 // only with a builtin functions and therefore should be disallowed here. 11385 if (LHSTy->isImageType() || RHSTy->isImageType() || 11386 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11387 LHSTy->isPipeType() || RHSTy->isPipeType() || 11388 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11389 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11390 return ExprError(); 11391 } 11392 } 11393 11394 switch (Opc) { 11395 case BO_Assign: 11396 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11397 if (getLangOpts().CPlusPlus && 11398 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11399 VK = LHS.get()->getValueKind(); 11400 OK = LHS.get()->getObjectKind(); 11401 } 11402 if (!ResultTy.isNull()) { 11403 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11404 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11405 } 11406 RecordModifiableNonNullParam(*this, LHS.get()); 11407 break; 11408 case BO_PtrMemD: 11409 case BO_PtrMemI: 11410 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11411 Opc == BO_PtrMemI); 11412 break; 11413 case BO_Mul: 11414 case BO_Div: 11415 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11416 Opc == BO_Div); 11417 break; 11418 case BO_Rem: 11419 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11420 break; 11421 case BO_Add: 11422 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11423 break; 11424 case BO_Sub: 11425 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11426 break; 11427 case BO_Shl: 11428 case BO_Shr: 11429 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11430 break; 11431 case BO_LE: 11432 case BO_LT: 11433 case BO_GE: 11434 case BO_GT: 11435 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11436 break; 11437 case BO_EQ: 11438 case BO_NE: 11439 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11440 break; 11441 case BO_And: 11442 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11443 case BO_Xor: 11444 case BO_Or: 11445 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11446 break; 11447 case BO_LAnd: 11448 case BO_LOr: 11449 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11450 break; 11451 case BO_MulAssign: 11452 case BO_DivAssign: 11453 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11454 Opc == BO_DivAssign); 11455 CompLHSTy = CompResultTy; 11456 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11457 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11458 break; 11459 case BO_RemAssign: 11460 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11461 CompLHSTy = CompResultTy; 11462 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11463 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11464 break; 11465 case BO_AddAssign: 11466 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11467 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11468 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11469 break; 11470 case BO_SubAssign: 11471 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11472 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11473 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11474 break; 11475 case BO_ShlAssign: 11476 case BO_ShrAssign: 11477 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11478 CompLHSTy = CompResultTy; 11479 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11480 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11481 break; 11482 case BO_AndAssign: 11483 case BO_OrAssign: // fallthrough 11484 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11485 case BO_XorAssign: 11486 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11487 CompLHSTy = CompResultTy; 11488 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11489 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11490 break; 11491 case BO_Comma: 11492 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11493 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11494 VK = RHS.get()->getValueKind(); 11495 OK = RHS.get()->getObjectKind(); 11496 } 11497 break; 11498 } 11499 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11500 return ExprError(); 11501 11502 // Check for array bounds violations for both sides of the BinaryOperator 11503 CheckArrayAccess(LHS.get()); 11504 CheckArrayAccess(RHS.get()); 11505 11506 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11507 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11508 &Context.Idents.get("object_setClass"), 11509 SourceLocation(), LookupOrdinaryName); 11510 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11511 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11512 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11513 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11514 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11515 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11516 } 11517 else 11518 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11519 } 11520 else if (const ObjCIvarRefExpr *OIRE = 11521 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11522 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11523 11524 if (CompResultTy.isNull()) 11525 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11526 OK, OpLoc, FPFeatures); 11527 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11528 OK_ObjCProperty) { 11529 VK = VK_LValue; 11530 OK = LHS.get()->getObjectKind(); 11531 } 11532 return new (Context) CompoundAssignOperator( 11533 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11534 OpLoc, FPFeatures); 11535 } 11536 11537 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11538 /// operators are mixed in a way that suggests that the programmer forgot that 11539 /// comparison operators have higher precedence. The most typical example of 11540 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11541 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11542 SourceLocation OpLoc, Expr *LHSExpr, 11543 Expr *RHSExpr) { 11544 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11545 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11546 11547 // Check that one of the sides is a comparison operator and the other isn't. 11548 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11549 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11550 if (isLeftComp == isRightComp) 11551 return; 11552 11553 // Bitwise operations are sometimes used as eager logical ops. 11554 // Don't diagnose this. 11555 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11556 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11557 if (isLeftBitwise || isRightBitwise) 11558 return; 11559 11560 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11561 OpLoc) 11562 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11563 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11564 SourceRange ParensRange = isLeftComp ? 11565 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11566 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11567 11568 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11569 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11570 SuggestParentheses(Self, OpLoc, 11571 Self.PDiag(diag::note_precedence_silence) << OpStr, 11572 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11573 SuggestParentheses(Self, OpLoc, 11574 Self.PDiag(diag::note_precedence_bitwise_first) 11575 << BinaryOperator::getOpcodeStr(Opc), 11576 ParensRange); 11577 } 11578 11579 /// \brief It accepts a '&&' expr that is inside a '||' one. 11580 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11581 /// in parentheses. 11582 static void 11583 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11584 BinaryOperator *Bop) { 11585 assert(Bop->getOpcode() == BO_LAnd); 11586 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11587 << Bop->getSourceRange() << OpLoc; 11588 SuggestParentheses(Self, Bop->getOperatorLoc(), 11589 Self.PDiag(diag::note_precedence_silence) 11590 << Bop->getOpcodeStr(), 11591 Bop->getSourceRange()); 11592 } 11593 11594 /// \brief Returns true if the given expression can be evaluated as a constant 11595 /// 'true'. 11596 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11597 bool Res; 11598 return !E->isValueDependent() && 11599 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11600 } 11601 11602 /// \brief Returns true if the given expression can be evaluated as a constant 11603 /// 'false'. 11604 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11605 bool Res; 11606 return !E->isValueDependent() && 11607 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11608 } 11609 11610 /// \brief Look for '&&' in the left hand of a '||' expr. 11611 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11612 Expr *LHSExpr, Expr *RHSExpr) { 11613 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11614 if (Bop->getOpcode() == BO_LAnd) { 11615 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11616 if (EvaluatesAsFalse(S, RHSExpr)) 11617 return; 11618 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11619 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11620 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11621 } else if (Bop->getOpcode() == BO_LOr) { 11622 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11623 // If it's "a || b && 1 || c" we didn't warn earlier for 11624 // "a || b && 1", but warn now. 11625 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11626 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11627 } 11628 } 11629 } 11630 } 11631 11632 /// \brief Look for '&&' in the right hand of a '||' expr. 11633 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11634 Expr *LHSExpr, Expr *RHSExpr) { 11635 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11636 if (Bop->getOpcode() == BO_LAnd) { 11637 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11638 if (EvaluatesAsFalse(S, LHSExpr)) 11639 return; 11640 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11641 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11642 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11643 } 11644 } 11645 } 11646 11647 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11648 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11649 /// the '&' expression in parentheses. 11650 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11651 SourceLocation OpLoc, Expr *SubExpr) { 11652 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11653 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11654 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11655 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11656 << Bop->getSourceRange() << OpLoc; 11657 SuggestParentheses(S, Bop->getOperatorLoc(), 11658 S.PDiag(diag::note_precedence_silence) 11659 << Bop->getOpcodeStr(), 11660 Bop->getSourceRange()); 11661 } 11662 } 11663 } 11664 11665 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11666 Expr *SubExpr, StringRef Shift) { 11667 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11668 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11669 StringRef Op = Bop->getOpcodeStr(); 11670 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11671 << Bop->getSourceRange() << OpLoc << Shift << Op; 11672 SuggestParentheses(S, Bop->getOperatorLoc(), 11673 S.PDiag(diag::note_precedence_silence) << Op, 11674 Bop->getSourceRange()); 11675 } 11676 } 11677 } 11678 11679 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11680 Expr *LHSExpr, Expr *RHSExpr) { 11681 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11682 if (!OCE) 11683 return; 11684 11685 FunctionDecl *FD = OCE->getDirectCallee(); 11686 if (!FD || !FD->isOverloadedOperator()) 11687 return; 11688 11689 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11690 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11691 return; 11692 11693 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11694 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11695 << (Kind == OO_LessLess); 11696 SuggestParentheses(S, OCE->getOperatorLoc(), 11697 S.PDiag(diag::note_precedence_silence) 11698 << (Kind == OO_LessLess ? "<<" : ">>"), 11699 OCE->getSourceRange()); 11700 SuggestParentheses(S, OpLoc, 11701 S.PDiag(diag::note_evaluate_comparison_first), 11702 SourceRange(OCE->getArg(1)->getLocStart(), 11703 RHSExpr->getLocEnd())); 11704 } 11705 11706 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11707 /// precedence. 11708 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11709 SourceLocation OpLoc, Expr *LHSExpr, 11710 Expr *RHSExpr){ 11711 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11712 if (BinaryOperator::isBitwiseOp(Opc)) 11713 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11714 11715 // Diagnose "arg1 & arg2 | arg3" 11716 if ((Opc == BO_Or || Opc == BO_Xor) && 11717 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11718 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11719 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11720 } 11721 11722 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11723 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11724 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11725 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11726 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11727 } 11728 11729 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11730 || Opc == BO_Shr) { 11731 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11732 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11733 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11734 } 11735 11736 // Warn on overloaded shift operators and comparisons, such as: 11737 // cout << 5 == 4; 11738 if (BinaryOperator::isComparisonOp(Opc)) 11739 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11740 } 11741 11742 // Binary Operators. 'Tok' is the token for the operator. 11743 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11744 tok::TokenKind Kind, 11745 Expr *LHSExpr, Expr *RHSExpr) { 11746 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11747 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11748 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11749 11750 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11751 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11752 11753 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11754 } 11755 11756 /// Build an overloaded binary operator expression in the given scope. 11757 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11758 BinaryOperatorKind Opc, 11759 Expr *LHS, Expr *RHS) { 11760 // Find all of the overloaded operators visible from this 11761 // point. We perform both an operator-name lookup from the local 11762 // scope and an argument-dependent lookup based on the types of 11763 // the arguments. 11764 UnresolvedSet<16> Functions; 11765 OverloadedOperatorKind OverOp 11766 = BinaryOperator::getOverloadedOperator(Opc); 11767 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11768 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11769 RHS->getType(), Functions); 11770 11771 // Build the (potentially-overloaded, potentially-dependent) 11772 // binary operation. 11773 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11774 } 11775 11776 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11777 BinaryOperatorKind Opc, 11778 Expr *LHSExpr, Expr *RHSExpr) { 11779 // We want to end up calling one of checkPseudoObjectAssignment 11780 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11781 // both expressions are overloadable or either is type-dependent), 11782 // or CreateBuiltinBinOp (in any other case). We also want to get 11783 // any placeholder types out of the way. 11784 11785 // Handle pseudo-objects in the LHS. 11786 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11787 // Assignments with a pseudo-object l-value need special analysis. 11788 if (pty->getKind() == BuiltinType::PseudoObject && 11789 BinaryOperator::isAssignmentOp(Opc)) 11790 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11791 11792 // Don't resolve overloads if the other type is overloadable. 11793 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 11794 // We can't actually test that if we still have a placeholder, 11795 // though. Fortunately, none of the exceptions we see in that 11796 // code below are valid when the LHS is an overload set. Note 11797 // that an overload set can be dependently-typed, but it never 11798 // instantiates to having an overloadable type. 11799 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11800 if (resolvedRHS.isInvalid()) return ExprError(); 11801 RHSExpr = resolvedRHS.get(); 11802 11803 if (RHSExpr->isTypeDependent() || 11804 RHSExpr->getType()->isOverloadableType()) 11805 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11806 } 11807 11808 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11809 if (LHS.isInvalid()) return ExprError(); 11810 LHSExpr = LHS.get(); 11811 } 11812 11813 // Handle pseudo-objects in the RHS. 11814 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11815 // An overload in the RHS can potentially be resolved by the type 11816 // being assigned to. 11817 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11818 if (getLangOpts().CPlusPlus && 11819 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 11820 LHSExpr->getType()->isOverloadableType())) 11821 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11822 11823 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11824 } 11825 11826 // Don't resolve overloads if the other type is overloadable. 11827 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 11828 LHSExpr->getType()->isOverloadableType()) 11829 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11830 11831 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11832 if (!resolvedRHS.isUsable()) return ExprError(); 11833 RHSExpr = resolvedRHS.get(); 11834 } 11835 11836 if (getLangOpts().CPlusPlus) { 11837 // If either expression is type-dependent, always build an 11838 // overloaded op. 11839 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11840 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11841 11842 // Otherwise, build an overloaded op if either expression has an 11843 // overloadable type. 11844 if (LHSExpr->getType()->isOverloadableType() || 11845 RHSExpr->getType()->isOverloadableType()) 11846 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11847 } 11848 11849 // Build a built-in binary operation. 11850 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11851 } 11852 11853 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11854 UnaryOperatorKind Opc, 11855 Expr *InputExpr) { 11856 ExprResult Input = InputExpr; 11857 ExprValueKind VK = VK_RValue; 11858 ExprObjectKind OK = OK_Ordinary; 11859 QualType resultType; 11860 if (getLangOpts().OpenCL) { 11861 QualType Ty = InputExpr->getType(); 11862 // The only legal unary operation for atomics is '&'. 11863 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11864 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11865 // only with a builtin functions and therefore should be disallowed here. 11866 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11867 || Ty->isBlockPointerType())) { 11868 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11869 << InputExpr->getType() 11870 << Input.get()->getSourceRange()); 11871 } 11872 } 11873 switch (Opc) { 11874 case UO_PreInc: 11875 case UO_PreDec: 11876 case UO_PostInc: 11877 case UO_PostDec: 11878 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11879 OpLoc, 11880 Opc == UO_PreInc || 11881 Opc == UO_PostInc, 11882 Opc == UO_PreInc || 11883 Opc == UO_PreDec); 11884 break; 11885 case UO_AddrOf: 11886 resultType = CheckAddressOfOperand(Input, OpLoc); 11887 RecordModifiableNonNullParam(*this, InputExpr); 11888 break; 11889 case UO_Deref: { 11890 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11891 if (Input.isInvalid()) return ExprError(); 11892 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11893 break; 11894 } 11895 case UO_Plus: 11896 case UO_Minus: 11897 Input = UsualUnaryConversions(Input.get()); 11898 if (Input.isInvalid()) return ExprError(); 11899 resultType = Input.get()->getType(); 11900 if (resultType->isDependentType()) 11901 break; 11902 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11903 break; 11904 else if (resultType->isVectorType() && 11905 // The z vector extensions don't allow + or - with bool vectors. 11906 (!Context.getLangOpts().ZVector || 11907 resultType->getAs<VectorType>()->getVectorKind() != 11908 VectorType::AltiVecBool)) 11909 break; 11910 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11911 Opc == UO_Plus && 11912 resultType->isPointerType()) 11913 break; 11914 11915 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11916 << resultType << Input.get()->getSourceRange()); 11917 11918 case UO_Not: // bitwise complement 11919 Input = UsualUnaryConversions(Input.get()); 11920 if (Input.isInvalid()) 11921 return ExprError(); 11922 resultType = Input.get()->getType(); 11923 if (resultType->isDependentType()) 11924 break; 11925 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11926 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11927 // C99 does not support '~' for complex conjugation. 11928 Diag(OpLoc, diag::ext_integer_complement_complex) 11929 << resultType << Input.get()->getSourceRange(); 11930 else if (resultType->hasIntegerRepresentation()) 11931 break; 11932 else if (resultType->isExtVectorType()) { 11933 if (Context.getLangOpts().OpenCL) { 11934 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11935 // on vector float types. 11936 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11937 if (!T->isIntegerType()) 11938 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11939 << resultType << Input.get()->getSourceRange()); 11940 } 11941 break; 11942 } else { 11943 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11944 << resultType << Input.get()->getSourceRange()); 11945 } 11946 break; 11947 11948 case UO_LNot: // logical negation 11949 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11950 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11951 if (Input.isInvalid()) return ExprError(); 11952 resultType = Input.get()->getType(); 11953 11954 // Though we still have to promote half FP to float... 11955 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11956 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11957 resultType = Context.FloatTy; 11958 } 11959 11960 if (resultType->isDependentType()) 11961 break; 11962 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11963 // C99 6.5.3.3p1: ok, fallthrough; 11964 if (Context.getLangOpts().CPlusPlus) { 11965 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11966 // operand contextually converted to bool. 11967 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11968 ScalarTypeToBooleanCastKind(resultType)); 11969 } else if (Context.getLangOpts().OpenCL && 11970 Context.getLangOpts().OpenCLVersion < 120) { 11971 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11972 // operate on scalar float types. 11973 if (!resultType->isIntegerType() && !resultType->isPointerType()) 11974 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11975 << resultType << Input.get()->getSourceRange()); 11976 } 11977 } else if (resultType->isExtVectorType()) { 11978 if (Context.getLangOpts().OpenCL && 11979 Context.getLangOpts().OpenCLVersion < 120) { 11980 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11981 // operate on vector float types. 11982 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11983 if (!T->isIntegerType()) 11984 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11985 << resultType << Input.get()->getSourceRange()); 11986 } 11987 // Vector logical not returns the signed variant of the operand type. 11988 resultType = GetSignedVectorType(resultType); 11989 break; 11990 } else { 11991 // FIXME: GCC's vector extension permits the usage of '!' with a vector 11992 // type in C++. We should allow that here too. 11993 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11994 << resultType << Input.get()->getSourceRange()); 11995 } 11996 11997 // LNot always has type int. C99 6.5.3.3p5. 11998 // In C++, it's bool. C++ 5.3.1p8 11999 resultType = Context.getLogicalOperationType(); 12000 break; 12001 case UO_Real: 12002 case UO_Imag: 12003 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12004 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12005 // complex l-values to ordinary l-values and all other values to r-values. 12006 if (Input.isInvalid()) return ExprError(); 12007 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12008 if (Input.get()->getValueKind() != VK_RValue && 12009 Input.get()->getObjectKind() == OK_Ordinary) 12010 VK = Input.get()->getValueKind(); 12011 } else if (!getLangOpts().CPlusPlus) { 12012 // In C, a volatile scalar is read by __imag. In C++, it is not. 12013 Input = DefaultLvalueConversion(Input.get()); 12014 } 12015 break; 12016 case UO_Extension: 12017 case UO_Coawait: 12018 resultType = Input.get()->getType(); 12019 VK = Input.get()->getValueKind(); 12020 OK = Input.get()->getObjectKind(); 12021 break; 12022 } 12023 if (resultType.isNull() || Input.isInvalid()) 12024 return ExprError(); 12025 12026 // Check for array bounds violations in the operand of the UnaryOperator, 12027 // except for the '*' and '&' operators that have to be handled specially 12028 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12029 // that are explicitly defined as valid by the standard). 12030 if (Opc != UO_AddrOf && Opc != UO_Deref) 12031 CheckArrayAccess(Input.get()); 12032 12033 return new (Context) 12034 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 12035 } 12036 12037 /// \brief Determine whether the given expression is a qualified member 12038 /// access expression, of a form that could be turned into a pointer to member 12039 /// with the address-of operator. 12040 static bool isQualifiedMemberAccess(Expr *E) { 12041 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12042 if (!DRE->getQualifier()) 12043 return false; 12044 12045 ValueDecl *VD = DRE->getDecl(); 12046 if (!VD->isCXXClassMember()) 12047 return false; 12048 12049 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12050 return true; 12051 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12052 return Method->isInstance(); 12053 12054 return false; 12055 } 12056 12057 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12058 if (!ULE->getQualifier()) 12059 return false; 12060 12061 for (NamedDecl *D : ULE->decls()) { 12062 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12063 if (Method->isInstance()) 12064 return true; 12065 } else { 12066 // Overload set does not contain methods. 12067 break; 12068 } 12069 } 12070 12071 return false; 12072 } 12073 12074 return false; 12075 } 12076 12077 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12078 UnaryOperatorKind Opc, Expr *Input) { 12079 // First things first: handle placeholders so that the 12080 // overloaded-operator check considers the right type. 12081 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12082 // Increment and decrement of pseudo-object references. 12083 if (pty->getKind() == BuiltinType::PseudoObject && 12084 UnaryOperator::isIncrementDecrementOp(Opc)) 12085 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12086 12087 // extension is always a builtin operator. 12088 if (Opc == UO_Extension) 12089 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12090 12091 // & gets special logic for several kinds of placeholder. 12092 // The builtin code knows what to do. 12093 if (Opc == UO_AddrOf && 12094 (pty->getKind() == BuiltinType::Overload || 12095 pty->getKind() == BuiltinType::UnknownAny || 12096 pty->getKind() == BuiltinType::BoundMember)) 12097 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12098 12099 // Anything else needs to be handled now. 12100 ExprResult Result = CheckPlaceholderExpr(Input); 12101 if (Result.isInvalid()) return ExprError(); 12102 Input = Result.get(); 12103 } 12104 12105 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12106 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12107 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12108 // Find all of the overloaded operators visible from this 12109 // point. We perform both an operator-name lookup from the local 12110 // scope and an argument-dependent lookup based on the types of 12111 // the arguments. 12112 UnresolvedSet<16> Functions; 12113 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12114 if (S && OverOp != OO_None) 12115 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12116 Functions); 12117 12118 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12119 } 12120 12121 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12122 } 12123 12124 // Unary Operators. 'Tok' is the token for the operator. 12125 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12126 tok::TokenKind Op, Expr *Input) { 12127 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12128 } 12129 12130 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12131 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12132 LabelDecl *TheDecl) { 12133 TheDecl->markUsed(Context); 12134 // Create the AST node. The address of a label always has type 'void*'. 12135 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12136 Context.getPointerType(Context.VoidTy)); 12137 } 12138 12139 /// Given the last statement in a statement-expression, check whether 12140 /// the result is a producing expression (like a call to an 12141 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12142 /// release out of the full-expression. Otherwise, return null. 12143 /// Cannot fail. 12144 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12145 // Should always be wrapped with one of these. 12146 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12147 if (!cleanups) return nullptr; 12148 12149 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12150 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12151 return nullptr; 12152 12153 // Splice out the cast. This shouldn't modify any interesting 12154 // features of the statement. 12155 Expr *producer = cast->getSubExpr(); 12156 assert(producer->getType() == cast->getType()); 12157 assert(producer->getValueKind() == cast->getValueKind()); 12158 cleanups->setSubExpr(producer); 12159 return cleanups; 12160 } 12161 12162 void Sema::ActOnStartStmtExpr() { 12163 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12164 } 12165 12166 void Sema::ActOnStmtExprError() { 12167 // Note that function is also called by TreeTransform when leaving a 12168 // StmtExpr scope without rebuilding anything. 12169 12170 DiscardCleanupsInEvaluationContext(); 12171 PopExpressionEvaluationContext(); 12172 } 12173 12174 ExprResult 12175 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12176 SourceLocation RPLoc) { // "({..})" 12177 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12178 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12179 12180 if (hasAnyUnrecoverableErrorsInThisFunction()) 12181 DiscardCleanupsInEvaluationContext(); 12182 assert(!Cleanup.exprNeedsCleanups() && 12183 "cleanups within StmtExpr not correctly bound!"); 12184 PopExpressionEvaluationContext(); 12185 12186 // FIXME: there are a variety of strange constraints to enforce here, for 12187 // example, it is not possible to goto into a stmt expression apparently. 12188 // More semantic analysis is needed. 12189 12190 // If there are sub-stmts in the compound stmt, take the type of the last one 12191 // as the type of the stmtexpr. 12192 QualType Ty = Context.VoidTy; 12193 bool StmtExprMayBindToTemp = false; 12194 if (!Compound->body_empty()) { 12195 Stmt *LastStmt = Compound->body_back(); 12196 LabelStmt *LastLabelStmt = nullptr; 12197 // If LastStmt is a label, skip down through into the body. 12198 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12199 LastLabelStmt = Label; 12200 LastStmt = Label->getSubStmt(); 12201 } 12202 12203 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12204 // Do function/array conversion on the last expression, but not 12205 // lvalue-to-rvalue. However, initialize an unqualified type. 12206 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12207 if (LastExpr.isInvalid()) 12208 return ExprError(); 12209 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12210 12211 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12212 // In ARC, if the final expression ends in a consume, splice 12213 // the consume out and bind it later. In the alternate case 12214 // (when dealing with a retainable type), the result 12215 // initialization will create a produce. In both cases the 12216 // result will be +1, and we'll need to balance that out with 12217 // a bind. 12218 if (Expr *rebuiltLastStmt 12219 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12220 LastExpr = rebuiltLastStmt; 12221 } else { 12222 LastExpr = PerformCopyInitialization( 12223 InitializedEntity::InitializeResult(LPLoc, 12224 Ty, 12225 false), 12226 SourceLocation(), 12227 LastExpr); 12228 } 12229 12230 if (LastExpr.isInvalid()) 12231 return ExprError(); 12232 if (LastExpr.get() != nullptr) { 12233 if (!LastLabelStmt) 12234 Compound->setLastStmt(LastExpr.get()); 12235 else 12236 LastLabelStmt->setSubStmt(LastExpr.get()); 12237 StmtExprMayBindToTemp = true; 12238 } 12239 } 12240 } 12241 } 12242 12243 // FIXME: Check that expression type is complete/non-abstract; statement 12244 // expressions are not lvalues. 12245 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12246 if (StmtExprMayBindToTemp) 12247 return MaybeBindToTemporary(ResStmtExpr); 12248 return ResStmtExpr; 12249 } 12250 12251 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12252 TypeSourceInfo *TInfo, 12253 ArrayRef<OffsetOfComponent> Components, 12254 SourceLocation RParenLoc) { 12255 QualType ArgTy = TInfo->getType(); 12256 bool Dependent = ArgTy->isDependentType(); 12257 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12258 12259 // We must have at least one component that refers to the type, and the first 12260 // one is known to be a field designator. Verify that the ArgTy represents 12261 // a struct/union/class. 12262 if (!Dependent && !ArgTy->isRecordType()) 12263 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12264 << ArgTy << TypeRange); 12265 12266 // Type must be complete per C99 7.17p3 because a declaring a variable 12267 // with an incomplete type would be ill-formed. 12268 if (!Dependent 12269 && RequireCompleteType(BuiltinLoc, ArgTy, 12270 diag::err_offsetof_incomplete_type, TypeRange)) 12271 return ExprError(); 12272 12273 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 12274 // GCC extension, diagnose them. 12275 // FIXME: This diagnostic isn't actually visible because the location is in 12276 // a system header! 12277 if (Components.size() != 1) 12278 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 12279 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 12280 12281 bool DidWarnAboutNonPOD = false; 12282 QualType CurrentType = ArgTy; 12283 SmallVector<OffsetOfNode, 4> Comps; 12284 SmallVector<Expr*, 4> Exprs; 12285 for (const OffsetOfComponent &OC : Components) { 12286 if (OC.isBrackets) { 12287 // Offset of an array sub-field. TODO: Should we allow vector elements? 12288 if (!CurrentType->isDependentType()) { 12289 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12290 if(!AT) 12291 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12292 << CurrentType); 12293 CurrentType = AT->getElementType(); 12294 } else 12295 CurrentType = Context.DependentTy; 12296 12297 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12298 if (IdxRval.isInvalid()) 12299 return ExprError(); 12300 Expr *Idx = IdxRval.get(); 12301 12302 // The expression must be an integral expression. 12303 // FIXME: An integral constant expression? 12304 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12305 !Idx->getType()->isIntegerType()) 12306 return ExprError(Diag(Idx->getLocStart(), 12307 diag::err_typecheck_subscript_not_integer) 12308 << Idx->getSourceRange()); 12309 12310 // Record this array index. 12311 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12312 Exprs.push_back(Idx); 12313 continue; 12314 } 12315 12316 // Offset of a field. 12317 if (CurrentType->isDependentType()) { 12318 // We have the offset of a field, but we can't look into the dependent 12319 // type. Just record the identifier of the field. 12320 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12321 CurrentType = Context.DependentTy; 12322 continue; 12323 } 12324 12325 // We need to have a complete type to look into. 12326 if (RequireCompleteType(OC.LocStart, CurrentType, 12327 diag::err_offsetof_incomplete_type)) 12328 return ExprError(); 12329 12330 // Look for the designated field. 12331 const RecordType *RC = CurrentType->getAs<RecordType>(); 12332 if (!RC) 12333 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12334 << CurrentType); 12335 RecordDecl *RD = RC->getDecl(); 12336 12337 // C++ [lib.support.types]p5: 12338 // The macro offsetof accepts a restricted set of type arguments in this 12339 // International Standard. type shall be a POD structure or a POD union 12340 // (clause 9). 12341 // C++11 [support.types]p4: 12342 // If type is not a standard-layout class (Clause 9), the results are 12343 // undefined. 12344 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12345 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12346 unsigned DiagID = 12347 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12348 : diag::ext_offsetof_non_pod_type; 12349 12350 if (!IsSafe && !DidWarnAboutNonPOD && 12351 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12352 PDiag(DiagID) 12353 << SourceRange(Components[0].LocStart, OC.LocEnd) 12354 << CurrentType)) 12355 DidWarnAboutNonPOD = true; 12356 } 12357 12358 // Look for the field. 12359 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12360 LookupQualifiedName(R, RD); 12361 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12362 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12363 if (!MemberDecl) { 12364 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12365 MemberDecl = IndirectMemberDecl->getAnonField(); 12366 } 12367 12368 if (!MemberDecl) 12369 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12370 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12371 OC.LocEnd)); 12372 12373 // C99 7.17p3: 12374 // (If the specified member is a bit-field, the behavior is undefined.) 12375 // 12376 // We diagnose this as an error. 12377 if (MemberDecl->isBitField()) { 12378 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12379 << MemberDecl->getDeclName() 12380 << SourceRange(BuiltinLoc, RParenLoc); 12381 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12382 return ExprError(); 12383 } 12384 12385 RecordDecl *Parent = MemberDecl->getParent(); 12386 if (IndirectMemberDecl) 12387 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12388 12389 // If the member was found in a base class, introduce OffsetOfNodes for 12390 // the base class indirections. 12391 CXXBasePaths Paths; 12392 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12393 Paths)) { 12394 if (Paths.getDetectedVirtual()) { 12395 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12396 << MemberDecl->getDeclName() 12397 << SourceRange(BuiltinLoc, RParenLoc); 12398 return ExprError(); 12399 } 12400 12401 CXXBasePath &Path = Paths.front(); 12402 for (const CXXBasePathElement &B : Path) 12403 Comps.push_back(OffsetOfNode(B.Base)); 12404 } 12405 12406 if (IndirectMemberDecl) { 12407 for (auto *FI : IndirectMemberDecl->chain()) { 12408 assert(isa<FieldDecl>(FI)); 12409 Comps.push_back(OffsetOfNode(OC.LocStart, 12410 cast<FieldDecl>(FI), OC.LocEnd)); 12411 } 12412 } else 12413 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12414 12415 CurrentType = MemberDecl->getType().getNonReferenceType(); 12416 } 12417 12418 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12419 Comps, Exprs, RParenLoc); 12420 } 12421 12422 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12423 SourceLocation BuiltinLoc, 12424 SourceLocation TypeLoc, 12425 ParsedType ParsedArgTy, 12426 ArrayRef<OffsetOfComponent> Components, 12427 SourceLocation RParenLoc) { 12428 12429 TypeSourceInfo *ArgTInfo; 12430 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12431 if (ArgTy.isNull()) 12432 return ExprError(); 12433 12434 if (!ArgTInfo) 12435 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12436 12437 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12438 } 12439 12440 12441 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12442 Expr *CondExpr, 12443 Expr *LHSExpr, Expr *RHSExpr, 12444 SourceLocation RPLoc) { 12445 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12446 12447 ExprValueKind VK = VK_RValue; 12448 ExprObjectKind OK = OK_Ordinary; 12449 QualType resType; 12450 bool ValueDependent = false; 12451 bool CondIsTrue = false; 12452 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12453 resType = Context.DependentTy; 12454 ValueDependent = true; 12455 } else { 12456 // The conditional expression is required to be a constant expression. 12457 llvm::APSInt condEval(32); 12458 ExprResult CondICE 12459 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12460 diag::err_typecheck_choose_expr_requires_constant, false); 12461 if (CondICE.isInvalid()) 12462 return ExprError(); 12463 CondExpr = CondICE.get(); 12464 CondIsTrue = condEval.getZExtValue(); 12465 12466 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12467 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12468 12469 resType = ActiveExpr->getType(); 12470 ValueDependent = ActiveExpr->isValueDependent(); 12471 VK = ActiveExpr->getValueKind(); 12472 OK = ActiveExpr->getObjectKind(); 12473 } 12474 12475 return new (Context) 12476 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12477 CondIsTrue, resType->isDependentType(), ValueDependent); 12478 } 12479 12480 //===----------------------------------------------------------------------===// 12481 // Clang Extensions. 12482 //===----------------------------------------------------------------------===// 12483 12484 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12485 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12486 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12487 12488 if (LangOpts.CPlusPlus) { 12489 Decl *ManglingContextDecl; 12490 if (MangleNumberingContext *MCtx = 12491 getCurrentMangleNumberContext(Block->getDeclContext(), 12492 ManglingContextDecl)) { 12493 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12494 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12495 } 12496 } 12497 12498 PushBlockScope(CurScope, Block); 12499 CurContext->addDecl(Block); 12500 if (CurScope) 12501 PushDeclContext(CurScope, Block); 12502 else 12503 CurContext = Block; 12504 12505 getCurBlock()->HasImplicitReturnType = true; 12506 12507 // Enter a new evaluation context to insulate the block from any 12508 // cleanups from the enclosing full-expression. 12509 PushExpressionEvaluationContext( 12510 ExpressionEvaluationContext::PotentiallyEvaluated); 12511 } 12512 12513 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12514 Scope *CurScope) { 12515 assert(ParamInfo.getIdentifier() == nullptr && 12516 "block-id should have no identifier!"); 12517 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12518 BlockScopeInfo *CurBlock = getCurBlock(); 12519 12520 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12521 QualType T = Sig->getType(); 12522 12523 // FIXME: We should allow unexpanded parameter packs here, but that would, 12524 // in turn, make the block expression contain unexpanded parameter packs. 12525 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12526 // Drop the parameters. 12527 FunctionProtoType::ExtProtoInfo EPI; 12528 EPI.HasTrailingReturn = false; 12529 EPI.TypeQuals |= DeclSpec::TQ_const; 12530 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12531 Sig = Context.getTrivialTypeSourceInfo(T); 12532 } 12533 12534 // GetTypeForDeclarator always produces a function type for a block 12535 // literal signature. Furthermore, it is always a FunctionProtoType 12536 // unless the function was written with a typedef. 12537 assert(T->isFunctionType() && 12538 "GetTypeForDeclarator made a non-function block signature"); 12539 12540 // Look for an explicit signature in that function type. 12541 FunctionProtoTypeLoc ExplicitSignature; 12542 12543 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12544 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12545 12546 // Check whether that explicit signature was synthesized by 12547 // GetTypeForDeclarator. If so, don't save that as part of the 12548 // written signature. 12549 if (ExplicitSignature.getLocalRangeBegin() == 12550 ExplicitSignature.getLocalRangeEnd()) { 12551 // This would be much cheaper if we stored TypeLocs instead of 12552 // TypeSourceInfos. 12553 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12554 unsigned Size = Result.getFullDataSize(); 12555 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12556 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12557 12558 ExplicitSignature = FunctionProtoTypeLoc(); 12559 } 12560 } 12561 12562 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12563 CurBlock->FunctionType = T; 12564 12565 const FunctionType *Fn = T->getAs<FunctionType>(); 12566 QualType RetTy = Fn->getReturnType(); 12567 bool isVariadic = 12568 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12569 12570 CurBlock->TheDecl->setIsVariadic(isVariadic); 12571 12572 // Context.DependentTy is used as a placeholder for a missing block 12573 // return type. TODO: what should we do with declarators like: 12574 // ^ * { ... } 12575 // If the answer is "apply template argument deduction".... 12576 if (RetTy != Context.DependentTy) { 12577 CurBlock->ReturnType = RetTy; 12578 CurBlock->TheDecl->setBlockMissingReturnType(false); 12579 CurBlock->HasImplicitReturnType = false; 12580 } 12581 12582 // Push block parameters from the declarator if we had them. 12583 SmallVector<ParmVarDecl*, 8> Params; 12584 if (ExplicitSignature) { 12585 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12586 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12587 if (Param->getIdentifier() == nullptr && 12588 !Param->isImplicit() && 12589 !Param->isInvalidDecl() && 12590 !getLangOpts().CPlusPlus) 12591 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12592 Params.push_back(Param); 12593 } 12594 12595 // Fake up parameter variables if we have a typedef, like 12596 // ^ fntype { ... } 12597 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12598 for (const auto &I : Fn->param_types()) { 12599 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12600 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12601 Params.push_back(Param); 12602 } 12603 } 12604 12605 // Set the parameters on the block decl. 12606 if (!Params.empty()) { 12607 CurBlock->TheDecl->setParams(Params); 12608 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12609 /*CheckParameterNames=*/false); 12610 } 12611 12612 // Finally we can process decl attributes. 12613 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12614 12615 // Put the parameter variables in scope. 12616 for (auto AI : CurBlock->TheDecl->parameters()) { 12617 AI->setOwningFunction(CurBlock->TheDecl); 12618 12619 // If this has an identifier, add it to the scope stack. 12620 if (AI->getIdentifier()) { 12621 CheckShadow(CurBlock->TheScope, AI); 12622 12623 PushOnScopeChains(AI, CurBlock->TheScope); 12624 } 12625 } 12626 } 12627 12628 /// ActOnBlockError - If there is an error parsing a block, this callback 12629 /// is invoked to pop the information about the block from the action impl. 12630 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12631 // Leave the expression-evaluation context. 12632 DiscardCleanupsInEvaluationContext(); 12633 PopExpressionEvaluationContext(); 12634 12635 // Pop off CurBlock, handle nested blocks. 12636 PopDeclContext(); 12637 PopFunctionScopeInfo(); 12638 } 12639 12640 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12641 /// literal was successfully completed. ^(int x){...} 12642 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12643 Stmt *Body, Scope *CurScope) { 12644 // If blocks are disabled, emit an error. 12645 if (!LangOpts.Blocks) 12646 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12647 12648 // Leave the expression-evaluation context. 12649 if (hasAnyUnrecoverableErrorsInThisFunction()) 12650 DiscardCleanupsInEvaluationContext(); 12651 assert(!Cleanup.exprNeedsCleanups() && 12652 "cleanups within block not correctly bound!"); 12653 PopExpressionEvaluationContext(); 12654 12655 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12656 12657 if (BSI->HasImplicitReturnType) 12658 deduceClosureReturnType(*BSI); 12659 12660 PopDeclContext(); 12661 12662 QualType RetTy = Context.VoidTy; 12663 if (!BSI->ReturnType.isNull()) 12664 RetTy = BSI->ReturnType; 12665 12666 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12667 QualType BlockTy; 12668 12669 // Set the captured variables on the block. 12670 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12671 SmallVector<BlockDecl::Capture, 4> Captures; 12672 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12673 if (Cap.isThisCapture()) 12674 continue; 12675 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12676 Cap.isNested(), Cap.getInitExpr()); 12677 Captures.push_back(NewCap); 12678 } 12679 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12680 12681 // If the user wrote a function type in some form, try to use that. 12682 if (!BSI->FunctionType.isNull()) { 12683 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12684 12685 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12686 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12687 12688 // Turn protoless block types into nullary block types. 12689 if (isa<FunctionNoProtoType>(FTy)) { 12690 FunctionProtoType::ExtProtoInfo EPI; 12691 EPI.ExtInfo = Ext; 12692 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12693 12694 // Otherwise, if we don't need to change anything about the function type, 12695 // preserve its sugar structure. 12696 } else if (FTy->getReturnType() == RetTy && 12697 (!NoReturn || FTy->getNoReturnAttr())) { 12698 BlockTy = BSI->FunctionType; 12699 12700 // Otherwise, make the minimal modifications to the function type. 12701 } else { 12702 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12703 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12704 EPI.TypeQuals = 0; // FIXME: silently? 12705 EPI.ExtInfo = Ext; 12706 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12707 } 12708 12709 // If we don't have a function type, just build one from nothing. 12710 } else { 12711 FunctionProtoType::ExtProtoInfo EPI; 12712 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12713 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12714 } 12715 12716 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12717 BlockTy = Context.getBlockPointerType(BlockTy); 12718 12719 // If needed, diagnose invalid gotos and switches in the block. 12720 if (getCurFunction()->NeedsScopeChecking() && 12721 !PP.isCodeCompletionEnabled()) 12722 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12723 12724 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12725 12726 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12727 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 12728 12729 // Try to apply the named return value optimization. We have to check again 12730 // if we can do this, though, because blocks keep return statements around 12731 // to deduce an implicit return type. 12732 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12733 !BSI->TheDecl->isDependentContext()) 12734 computeNRVO(Body, BSI); 12735 12736 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12737 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12738 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12739 12740 // If the block isn't obviously global, i.e. it captures anything at 12741 // all, then we need to do a few things in the surrounding context: 12742 if (Result->getBlockDecl()->hasCaptures()) { 12743 // First, this expression has a new cleanup object. 12744 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12745 Cleanup.setExprNeedsCleanups(true); 12746 12747 // It also gets a branch-protected scope if any of the captured 12748 // variables needs destruction. 12749 for (const auto &CI : Result->getBlockDecl()->captures()) { 12750 const VarDecl *var = CI.getVariable(); 12751 if (var->getType().isDestructedType() != QualType::DK_none) { 12752 getCurFunction()->setHasBranchProtectedScope(); 12753 break; 12754 } 12755 } 12756 } 12757 12758 return Result; 12759 } 12760 12761 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12762 SourceLocation RPLoc) { 12763 TypeSourceInfo *TInfo; 12764 GetTypeFromParser(Ty, &TInfo); 12765 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12766 } 12767 12768 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12769 Expr *E, TypeSourceInfo *TInfo, 12770 SourceLocation RPLoc) { 12771 Expr *OrigExpr = E; 12772 bool IsMS = false; 12773 12774 // CUDA device code does not support varargs. 12775 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12776 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12777 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12778 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12779 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12780 } 12781 } 12782 12783 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12784 // as Microsoft ABI on an actual Microsoft platform, where 12785 // __builtin_ms_va_list and __builtin_va_list are the same.) 12786 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12787 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12788 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12789 if (Context.hasSameType(MSVaListType, E->getType())) { 12790 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12791 return ExprError(); 12792 IsMS = true; 12793 } 12794 } 12795 12796 // Get the va_list type 12797 QualType VaListType = Context.getBuiltinVaListType(); 12798 if (!IsMS) { 12799 if (VaListType->isArrayType()) { 12800 // Deal with implicit array decay; for example, on x86-64, 12801 // va_list is an array, but it's supposed to decay to 12802 // a pointer for va_arg. 12803 VaListType = Context.getArrayDecayedType(VaListType); 12804 // Make sure the input expression also decays appropriately. 12805 ExprResult Result = UsualUnaryConversions(E); 12806 if (Result.isInvalid()) 12807 return ExprError(); 12808 E = Result.get(); 12809 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12810 // If va_list is a record type and we are compiling in C++ mode, 12811 // check the argument using reference binding. 12812 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12813 Context, Context.getLValueReferenceType(VaListType), false); 12814 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12815 if (Init.isInvalid()) 12816 return ExprError(); 12817 E = Init.getAs<Expr>(); 12818 } else { 12819 // Otherwise, the va_list argument must be an l-value because 12820 // it is modified by va_arg. 12821 if (!E->isTypeDependent() && 12822 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12823 return ExprError(); 12824 } 12825 } 12826 12827 if (!IsMS && !E->isTypeDependent() && 12828 !Context.hasSameType(VaListType, E->getType())) 12829 return ExprError(Diag(E->getLocStart(), 12830 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12831 << OrigExpr->getType() << E->getSourceRange()); 12832 12833 if (!TInfo->getType()->isDependentType()) { 12834 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12835 diag::err_second_parameter_to_va_arg_incomplete, 12836 TInfo->getTypeLoc())) 12837 return ExprError(); 12838 12839 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12840 TInfo->getType(), 12841 diag::err_second_parameter_to_va_arg_abstract, 12842 TInfo->getTypeLoc())) 12843 return ExprError(); 12844 12845 if (!TInfo->getType().isPODType(Context)) { 12846 Diag(TInfo->getTypeLoc().getBeginLoc(), 12847 TInfo->getType()->isObjCLifetimeType() 12848 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12849 : diag::warn_second_parameter_to_va_arg_not_pod) 12850 << TInfo->getType() 12851 << TInfo->getTypeLoc().getSourceRange(); 12852 } 12853 12854 // Check for va_arg where arguments of the given type will be promoted 12855 // (i.e. this va_arg is guaranteed to have undefined behavior). 12856 QualType PromoteType; 12857 if (TInfo->getType()->isPromotableIntegerType()) { 12858 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12859 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12860 PromoteType = QualType(); 12861 } 12862 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12863 PromoteType = Context.DoubleTy; 12864 if (!PromoteType.isNull()) 12865 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12866 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12867 << TInfo->getType() 12868 << PromoteType 12869 << TInfo->getTypeLoc().getSourceRange()); 12870 } 12871 12872 QualType T = TInfo->getType().getNonLValueExprType(Context); 12873 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12874 } 12875 12876 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12877 // The type of __null will be int or long, depending on the size of 12878 // pointers on the target. 12879 QualType Ty; 12880 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12881 if (pw == Context.getTargetInfo().getIntWidth()) 12882 Ty = Context.IntTy; 12883 else if (pw == Context.getTargetInfo().getLongWidth()) 12884 Ty = Context.LongTy; 12885 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12886 Ty = Context.LongLongTy; 12887 else { 12888 llvm_unreachable("I don't know size of pointer!"); 12889 } 12890 12891 return new (Context) GNUNullExpr(Ty, TokenLoc); 12892 } 12893 12894 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12895 bool Diagnose) { 12896 if (!getLangOpts().ObjC1) 12897 return false; 12898 12899 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12900 if (!PT) 12901 return false; 12902 12903 if (!PT->isObjCIdType()) { 12904 // Check if the destination is the 'NSString' interface. 12905 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12906 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12907 return false; 12908 } 12909 12910 // Ignore any parens, implicit casts (should only be 12911 // array-to-pointer decays), and not-so-opaque values. The last is 12912 // important for making this trigger for property assignments. 12913 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12914 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12915 if (OV->getSourceExpr()) 12916 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12917 12918 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12919 if (!SL || !SL->isAscii()) 12920 return false; 12921 if (Diagnose) { 12922 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12923 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12924 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12925 } 12926 return true; 12927 } 12928 12929 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12930 const Expr *SrcExpr) { 12931 if (!DstType->isFunctionPointerType() || 12932 !SrcExpr->getType()->isFunctionType()) 12933 return false; 12934 12935 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12936 if (!DRE) 12937 return false; 12938 12939 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12940 if (!FD) 12941 return false; 12942 12943 return !S.checkAddressOfFunctionIsAvailable(FD, 12944 /*Complain=*/true, 12945 SrcExpr->getLocStart()); 12946 } 12947 12948 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12949 SourceLocation Loc, 12950 QualType DstType, QualType SrcType, 12951 Expr *SrcExpr, AssignmentAction Action, 12952 bool *Complained) { 12953 if (Complained) 12954 *Complained = false; 12955 12956 // Decode the result (notice that AST's are still created for extensions). 12957 bool CheckInferredResultType = false; 12958 bool isInvalid = false; 12959 unsigned DiagKind = 0; 12960 FixItHint Hint; 12961 ConversionFixItGenerator ConvHints; 12962 bool MayHaveConvFixit = false; 12963 bool MayHaveFunctionDiff = false; 12964 const ObjCInterfaceDecl *IFace = nullptr; 12965 const ObjCProtocolDecl *PDecl = nullptr; 12966 12967 switch (ConvTy) { 12968 case Compatible: 12969 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12970 return false; 12971 12972 case PointerToInt: 12973 DiagKind = diag::ext_typecheck_convert_pointer_int; 12974 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12975 MayHaveConvFixit = true; 12976 break; 12977 case IntToPointer: 12978 DiagKind = diag::ext_typecheck_convert_int_pointer; 12979 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12980 MayHaveConvFixit = true; 12981 break; 12982 case IncompatiblePointer: 12983 if (Action == AA_Passing_CFAudited) 12984 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12985 else if (SrcType->isFunctionPointerType() && 12986 DstType->isFunctionPointerType()) 12987 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12988 else 12989 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12990 12991 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12992 SrcType->isObjCObjectPointerType(); 12993 if (Hint.isNull() && !CheckInferredResultType) { 12994 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12995 } 12996 else if (CheckInferredResultType) { 12997 SrcType = SrcType.getUnqualifiedType(); 12998 DstType = DstType.getUnqualifiedType(); 12999 } 13000 MayHaveConvFixit = true; 13001 break; 13002 case IncompatiblePointerSign: 13003 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13004 break; 13005 case FunctionVoidPointer: 13006 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13007 break; 13008 case IncompatiblePointerDiscardsQualifiers: { 13009 // Perform array-to-pointer decay if necessary. 13010 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13011 13012 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13013 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13014 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13015 DiagKind = diag::err_typecheck_incompatible_address_space; 13016 break; 13017 13018 13019 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13020 DiagKind = diag::err_typecheck_incompatible_ownership; 13021 break; 13022 } 13023 13024 llvm_unreachable("unknown error case for discarding qualifiers!"); 13025 // fallthrough 13026 } 13027 case CompatiblePointerDiscardsQualifiers: 13028 // If the qualifiers lost were because we were applying the 13029 // (deprecated) C++ conversion from a string literal to a char* 13030 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13031 // Ideally, this check would be performed in 13032 // checkPointerTypesForAssignment. However, that would require a 13033 // bit of refactoring (so that the second argument is an 13034 // expression, rather than a type), which should be done as part 13035 // of a larger effort to fix checkPointerTypesForAssignment for 13036 // C++ semantics. 13037 if (getLangOpts().CPlusPlus && 13038 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13039 return false; 13040 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13041 break; 13042 case IncompatibleNestedPointerQualifiers: 13043 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13044 break; 13045 case IntToBlockPointer: 13046 DiagKind = diag::err_int_to_block_pointer; 13047 break; 13048 case IncompatibleBlockPointer: 13049 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13050 break; 13051 case IncompatibleObjCQualifiedId: { 13052 if (SrcType->isObjCQualifiedIdType()) { 13053 const ObjCObjectPointerType *srcOPT = 13054 SrcType->getAs<ObjCObjectPointerType>(); 13055 for (auto *srcProto : srcOPT->quals()) { 13056 PDecl = srcProto; 13057 break; 13058 } 13059 if (const ObjCInterfaceType *IFaceT = 13060 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13061 IFace = IFaceT->getDecl(); 13062 } 13063 else if (DstType->isObjCQualifiedIdType()) { 13064 const ObjCObjectPointerType *dstOPT = 13065 DstType->getAs<ObjCObjectPointerType>(); 13066 for (auto *dstProto : dstOPT->quals()) { 13067 PDecl = dstProto; 13068 break; 13069 } 13070 if (const ObjCInterfaceType *IFaceT = 13071 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13072 IFace = IFaceT->getDecl(); 13073 } 13074 DiagKind = diag::warn_incompatible_qualified_id; 13075 break; 13076 } 13077 case IncompatibleVectors: 13078 DiagKind = diag::warn_incompatible_vectors; 13079 break; 13080 case IncompatibleObjCWeakRef: 13081 DiagKind = diag::err_arc_weak_unavailable_assign; 13082 break; 13083 case Incompatible: 13084 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13085 if (Complained) 13086 *Complained = true; 13087 return true; 13088 } 13089 13090 DiagKind = diag::err_typecheck_convert_incompatible; 13091 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13092 MayHaveConvFixit = true; 13093 isInvalid = true; 13094 MayHaveFunctionDiff = true; 13095 break; 13096 } 13097 13098 QualType FirstType, SecondType; 13099 switch (Action) { 13100 case AA_Assigning: 13101 case AA_Initializing: 13102 // The destination type comes first. 13103 FirstType = DstType; 13104 SecondType = SrcType; 13105 break; 13106 13107 case AA_Returning: 13108 case AA_Passing: 13109 case AA_Passing_CFAudited: 13110 case AA_Converting: 13111 case AA_Sending: 13112 case AA_Casting: 13113 // The source type comes first. 13114 FirstType = SrcType; 13115 SecondType = DstType; 13116 break; 13117 } 13118 13119 PartialDiagnostic FDiag = PDiag(DiagKind); 13120 if (Action == AA_Passing_CFAudited) 13121 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13122 else 13123 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13124 13125 // If we can fix the conversion, suggest the FixIts. 13126 assert(ConvHints.isNull() || Hint.isNull()); 13127 if (!ConvHints.isNull()) { 13128 for (FixItHint &H : ConvHints.Hints) 13129 FDiag << H; 13130 } else { 13131 FDiag << Hint; 13132 } 13133 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13134 13135 if (MayHaveFunctionDiff) 13136 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13137 13138 Diag(Loc, FDiag); 13139 if (DiagKind == diag::warn_incompatible_qualified_id && 13140 PDecl && IFace && !IFace->hasDefinition()) 13141 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13142 << IFace->getName() << PDecl->getName(); 13143 13144 if (SecondType == Context.OverloadTy) 13145 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13146 FirstType, /*TakingAddress=*/true); 13147 13148 if (CheckInferredResultType) 13149 EmitRelatedResultTypeNote(SrcExpr); 13150 13151 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13152 EmitRelatedResultTypeNoteForReturn(DstType); 13153 13154 if (Complained) 13155 *Complained = true; 13156 return isInvalid; 13157 } 13158 13159 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13160 llvm::APSInt *Result) { 13161 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13162 public: 13163 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13164 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13165 } 13166 } Diagnoser; 13167 13168 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13169 } 13170 13171 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13172 llvm::APSInt *Result, 13173 unsigned DiagID, 13174 bool AllowFold) { 13175 class IDDiagnoser : public VerifyICEDiagnoser { 13176 unsigned DiagID; 13177 13178 public: 13179 IDDiagnoser(unsigned DiagID) 13180 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13181 13182 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13183 S.Diag(Loc, DiagID) << SR; 13184 } 13185 } Diagnoser(DiagID); 13186 13187 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13188 } 13189 13190 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13191 SourceRange SR) { 13192 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13193 } 13194 13195 ExprResult 13196 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13197 VerifyICEDiagnoser &Diagnoser, 13198 bool AllowFold) { 13199 SourceLocation DiagLoc = E->getLocStart(); 13200 13201 if (getLangOpts().CPlusPlus11) { 13202 // C++11 [expr.const]p5: 13203 // If an expression of literal class type is used in a context where an 13204 // integral constant expression is required, then that class type shall 13205 // have a single non-explicit conversion function to an integral or 13206 // unscoped enumeration type 13207 ExprResult Converted; 13208 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13209 public: 13210 CXX11ConvertDiagnoser(bool Silent) 13211 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13212 Silent, true) {} 13213 13214 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13215 QualType T) override { 13216 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13217 } 13218 13219 SemaDiagnosticBuilder diagnoseIncomplete( 13220 Sema &S, SourceLocation Loc, QualType T) override { 13221 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13222 } 13223 13224 SemaDiagnosticBuilder diagnoseExplicitConv( 13225 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13226 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13227 } 13228 13229 SemaDiagnosticBuilder noteExplicitConv( 13230 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13231 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13232 << ConvTy->isEnumeralType() << ConvTy; 13233 } 13234 13235 SemaDiagnosticBuilder diagnoseAmbiguous( 13236 Sema &S, SourceLocation Loc, QualType T) override { 13237 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13238 } 13239 13240 SemaDiagnosticBuilder noteAmbiguous( 13241 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13242 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13243 << ConvTy->isEnumeralType() << ConvTy; 13244 } 13245 13246 SemaDiagnosticBuilder diagnoseConversion( 13247 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13248 llvm_unreachable("conversion functions are permitted"); 13249 } 13250 } ConvertDiagnoser(Diagnoser.Suppress); 13251 13252 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13253 ConvertDiagnoser); 13254 if (Converted.isInvalid()) 13255 return Converted; 13256 E = Converted.get(); 13257 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13258 return ExprError(); 13259 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13260 // An ICE must be of integral or unscoped enumeration type. 13261 if (!Diagnoser.Suppress) 13262 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13263 return ExprError(); 13264 } 13265 13266 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13267 // in the non-ICE case. 13268 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13269 if (Result) 13270 *Result = E->EvaluateKnownConstInt(Context); 13271 return E; 13272 } 13273 13274 Expr::EvalResult EvalResult; 13275 SmallVector<PartialDiagnosticAt, 8> Notes; 13276 EvalResult.Diag = &Notes; 13277 13278 // Try to evaluate the expression, and produce diagnostics explaining why it's 13279 // not a constant expression as a side-effect. 13280 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13281 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13282 13283 // In C++11, we can rely on diagnostics being produced for any expression 13284 // which is not a constant expression. If no diagnostics were produced, then 13285 // this is a constant expression. 13286 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13287 if (Result) 13288 *Result = EvalResult.Val.getInt(); 13289 return E; 13290 } 13291 13292 // If our only note is the usual "invalid subexpression" note, just point 13293 // the caret at its location rather than producing an essentially 13294 // redundant note. 13295 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13296 diag::note_invalid_subexpr_in_const_expr) { 13297 DiagLoc = Notes[0].first; 13298 Notes.clear(); 13299 } 13300 13301 if (!Folded || !AllowFold) { 13302 if (!Diagnoser.Suppress) { 13303 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13304 for (const PartialDiagnosticAt &Note : Notes) 13305 Diag(Note.first, Note.second); 13306 } 13307 13308 return ExprError(); 13309 } 13310 13311 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13312 for (const PartialDiagnosticAt &Note : Notes) 13313 Diag(Note.first, Note.second); 13314 13315 if (Result) 13316 *Result = EvalResult.Val.getInt(); 13317 return E; 13318 } 13319 13320 namespace { 13321 // Handle the case where we conclude a expression which we speculatively 13322 // considered to be unevaluated is actually evaluated. 13323 class TransformToPE : public TreeTransform<TransformToPE> { 13324 typedef TreeTransform<TransformToPE> BaseTransform; 13325 13326 public: 13327 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13328 13329 // Make sure we redo semantic analysis 13330 bool AlwaysRebuild() { return true; } 13331 13332 // Make sure we handle LabelStmts correctly. 13333 // FIXME: This does the right thing, but maybe we need a more general 13334 // fix to TreeTransform? 13335 StmtResult TransformLabelStmt(LabelStmt *S) { 13336 S->getDecl()->setStmt(nullptr); 13337 return BaseTransform::TransformLabelStmt(S); 13338 } 13339 13340 // We need to special-case DeclRefExprs referring to FieldDecls which 13341 // are not part of a member pointer formation; normal TreeTransforming 13342 // doesn't catch this case because of the way we represent them in the AST. 13343 // FIXME: This is a bit ugly; is it really the best way to handle this 13344 // case? 13345 // 13346 // Error on DeclRefExprs referring to FieldDecls. 13347 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13348 if (isa<FieldDecl>(E->getDecl()) && 13349 !SemaRef.isUnevaluatedContext()) 13350 return SemaRef.Diag(E->getLocation(), 13351 diag::err_invalid_non_static_member_use) 13352 << E->getDecl() << E->getSourceRange(); 13353 13354 return BaseTransform::TransformDeclRefExpr(E); 13355 } 13356 13357 // Exception: filter out member pointer formation 13358 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13359 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13360 return E; 13361 13362 return BaseTransform::TransformUnaryOperator(E); 13363 } 13364 13365 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13366 // Lambdas never need to be transformed. 13367 return E; 13368 } 13369 }; 13370 } 13371 13372 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13373 assert(isUnevaluatedContext() && 13374 "Should only transform unevaluated expressions"); 13375 ExprEvalContexts.back().Context = 13376 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13377 if (isUnevaluatedContext()) 13378 return E; 13379 return TransformToPE(*this).TransformExpr(E); 13380 } 13381 13382 void 13383 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13384 Decl *LambdaContextDecl, 13385 bool IsDecltype) { 13386 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13387 LambdaContextDecl, IsDecltype); 13388 Cleanup.reset(); 13389 if (!MaybeODRUseExprs.empty()) 13390 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13391 } 13392 13393 void 13394 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13395 ReuseLambdaContextDecl_t, 13396 bool IsDecltype) { 13397 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13398 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13399 } 13400 13401 void Sema::PopExpressionEvaluationContext() { 13402 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13403 unsigned NumTypos = Rec.NumTypos; 13404 13405 if (!Rec.Lambdas.empty()) { 13406 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13407 unsigned D; 13408 if (Rec.isUnevaluated()) { 13409 // C++11 [expr.prim.lambda]p2: 13410 // A lambda-expression shall not appear in an unevaluated operand 13411 // (Clause 5). 13412 D = diag::err_lambda_unevaluated_operand; 13413 } else { 13414 // C++1y [expr.const]p2: 13415 // A conditional-expression e is a core constant expression unless the 13416 // evaluation of e, following the rules of the abstract machine, would 13417 // evaluate [...] a lambda-expression. 13418 D = diag::err_lambda_in_constant_expression; 13419 } 13420 13421 // C++1z allows lambda expressions as core constant expressions. 13422 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13423 // 1607) from appearing within template-arguments and array-bounds that 13424 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13425 // unevaluated contexts) might lift some of these restrictions in a 13426 // future version. 13427 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z) 13428 for (const auto *L : Rec.Lambdas) 13429 Diag(L->getLocStart(), D); 13430 } else { 13431 // Mark the capture expressions odr-used. This was deferred 13432 // during lambda expression creation. 13433 for (auto *Lambda : Rec.Lambdas) { 13434 for (auto *C : Lambda->capture_inits()) 13435 MarkDeclarationsReferencedInExpr(C); 13436 } 13437 } 13438 } 13439 13440 // When are coming out of an unevaluated context, clear out any 13441 // temporaries that we may have created as part of the evaluation of 13442 // the expression in that context: they aren't relevant because they 13443 // will never be constructed. 13444 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13445 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13446 ExprCleanupObjects.end()); 13447 Cleanup = Rec.ParentCleanup; 13448 CleanupVarDeclMarking(); 13449 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13450 // Otherwise, merge the contexts together. 13451 } else { 13452 Cleanup.mergeFrom(Rec.ParentCleanup); 13453 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13454 Rec.SavedMaybeODRUseExprs.end()); 13455 } 13456 13457 // Pop the current expression evaluation context off the stack. 13458 ExprEvalContexts.pop_back(); 13459 13460 if (!ExprEvalContexts.empty()) 13461 ExprEvalContexts.back().NumTypos += NumTypos; 13462 else 13463 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13464 "last ExpressionEvaluationContextRecord"); 13465 } 13466 13467 void Sema::DiscardCleanupsInEvaluationContext() { 13468 ExprCleanupObjects.erase( 13469 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13470 ExprCleanupObjects.end()); 13471 Cleanup.reset(); 13472 MaybeODRUseExprs.clear(); 13473 } 13474 13475 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13476 if (!E->getType()->isVariablyModifiedType()) 13477 return E; 13478 return TransformToPotentiallyEvaluated(E); 13479 } 13480 13481 /// Are we within a context in which some evaluation could be performed (be it 13482 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13483 /// captured by C++'s idea of an "unevaluated context". 13484 static bool isEvaluatableContext(Sema &SemaRef) { 13485 switch (SemaRef.ExprEvalContexts.back().Context) { 13486 case Sema::ExpressionEvaluationContext::Unevaluated: 13487 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13488 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13489 // Expressions in this context are never evaluated. 13490 return false; 13491 13492 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13493 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13494 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13495 // Expressions in this context could be evaluated. 13496 return true; 13497 13498 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13499 // Referenced declarations will only be used if the construct in the 13500 // containing expression is used, at which point we'll be given another 13501 // turn to mark them. 13502 return false; 13503 } 13504 llvm_unreachable("Invalid context"); 13505 } 13506 13507 /// Are we within a context in which references to resolved functions or to 13508 /// variables result in odr-use? 13509 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13510 // An expression in a template is not really an expression until it's been 13511 // instantiated, so it doesn't trigger odr-use. 13512 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13513 return false; 13514 13515 switch (SemaRef.ExprEvalContexts.back().Context) { 13516 case Sema::ExpressionEvaluationContext::Unevaluated: 13517 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13518 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13519 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13520 return false; 13521 13522 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13523 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13524 return true; 13525 13526 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13527 return false; 13528 } 13529 llvm_unreachable("Invalid context"); 13530 } 13531 13532 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13533 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13534 return Func->isConstexpr() && 13535 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13536 } 13537 13538 /// \brief Mark a function referenced, and check whether it is odr-used 13539 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13540 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13541 bool MightBeOdrUse) { 13542 assert(Func && "No function?"); 13543 13544 Func->setReferenced(); 13545 13546 // C++11 [basic.def.odr]p3: 13547 // A function whose name appears as a potentially-evaluated expression is 13548 // odr-used if it is the unique lookup result or the selected member of a 13549 // set of overloaded functions [...]. 13550 // 13551 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13552 // can just check that here. 13553 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13554 13555 // Determine whether we require a function definition to exist, per 13556 // C++11 [temp.inst]p3: 13557 // Unless a function template specialization has been explicitly 13558 // instantiated or explicitly specialized, the function template 13559 // specialization is implicitly instantiated when the specialization is 13560 // referenced in a context that requires a function definition to exist. 13561 // 13562 // That is either when this is an odr-use, or when a usage of a constexpr 13563 // function occurs within an evaluatable context. 13564 bool NeedDefinition = 13565 OdrUse || (isEvaluatableContext(*this) && 13566 isImplicitlyDefinableConstexprFunction(Func)); 13567 13568 // C++14 [temp.expl.spec]p6: 13569 // If a template [...] is explicitly specialized then that specialization 13570 // shall be declared before the first use of that specialization that would 13571 // cause an implicit instantiation to take place, in every translation unit 13572 // in which such a use occurs 13573 if (NeedDefinition && 13574 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13575 Func->getMemberSpecializationInfo())) 13576 checkSpecializationVisibility(Loc, Func); 13577 13578 // C++14 [except.spec]p17: 13579 // An exception-specification is considered to be needed when: 13580 // - the function is odr-used or, if it appears in an unevaluated operand, 13581 // would be odr-used if the expression were potentially-evaluated; 13582 // 13583 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13584 // function is a pure virtual function we're calling, and in that case the 13585 // function was selected by overload resolution and we need to resolve its 13586 // exception specification for a different reason. 13587 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13588 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13589 ResolveExceptionSpec(Loc, FPT); 13590 13591 // If we don't need to mark the function as used, and we don't need to 13592 // try to provide a definition, there's nothing more to do. 13593 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13594 (!NeedDefinition || Func->getBody())) 13595 return; 13596 13597 // Note that this declaration has been used. 13598 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13599 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13600 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13601 if (Constructor->isDefaultConstructor()) { 13602 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13603 return; 13604 DefineImplicitDefaultConstructor(Loc, Constructor); 13605 } else if (Constructor->isCopyConstructor()) { 13606 DefineImplicitCopyConstructor(Loc, Constructor); 13607 } else if (Constructor->isMoveConstructor()) { 13608 DefineImplicitMoveConstructor(Loc, Constructor); 13609 } 13610 } else if (Constructor->getInheritedConstructor()) { 13611 DefineInheritingConstructor(Loc, Constructor); 13612 } 13613 } else if (CXXDestructorDecl *Destructor = 13614 dyn_cast<CXXDestructorDecl>(Func)) { 13615 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13616 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13617 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13618 return; 13619 DefineImplicitDestructor(Loc, Destructor); 13620 } 13621 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13622 MarkVTableUsed(Loc, Destructor->getParent()); 13623 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13624 if (MethodDecl->isOverloadedOperator() && 13625 MethodDecl->getOverloadedOperator() == OO_Equal) { 13626 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13627 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13628 if (MethodDecl->isCopyAssignmentOperator()) 13629 DefineImplicitCopyAssignment(Loc, MethodDecl); 13630 else if (MethodDecl->isMoveAssignmentOperator()) 13631 DefineImplicitMoveAssignment(Loc, MethodDecl); 13632 } 13633 } else if (isa<CXXConversionDecl>(MethodDecl) && 13634 MethodDecl->getParent()->isLambda()) { 13635 CXXConversionDecl *Conversion = 13636 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13637 if (Conversion->isLambdaToBlockPointerConversion()) 13638 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13639 else 13640 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13641 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13642 MarkVTableUsed(Loc, MethodDecl->getParent()); 13643 } 13644 13645 // Recursive functions should be marked when used from another function. 13646 // FIXME: Is this really right? 13647 if (CurContext == Func) return; 13648 13649 // Implicit instantiation of function templates and member functions of 13650 // class templates. 13651 if (Func->isImplicitlyInstantiable()) { 13652 bool AlreadyInstantiated = false; 13653 SourceLocation PointOfInstantiation = Loc; 13654 if (FunctionTemplateSpecializationInfo *SpecInfo 13655 = Func->getTemplateSpecializationInfo()) { 13656 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13657 SpecInfo->setPointOfInstantiation(Loc); 13658 else if (SpecInfo->getTemplateSpecializationKind() 13659 == TSK_ImplicitInstantiation) { 13660 AlreadyInstantiated = true; 13661 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13662 } 13663 } else if (MemberSpecializationInfo *MSInfo 13664 = Func->getMemberSpecializationInfo()) { 13665 if (MSInfo->getPointOfInstantiation().isInvalid()) 13666 MSInfo->setPointOfInstantiation(Loc); 13667 else if (MSInfo->getTemplateSpecializationKind() 13668 == TSK_ImplicitInstantiation) { 13669 AlreadyInstantiated = true; 13670 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13671 } 13672 } 13673 13674 if (!AlreadyInstantiated || Func->isConstexpr()) { 13675 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13676 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13677 CodeSynthesisContexts.size()) 13678 PendingLocalImplicitInstantiations.push_back( 13679 std::make_pair(Func, PointOfInstantiation)); 13680 else if (Func->isConstexpr()) 13681 // Do not defer instantiations of constexpr functions, to avoid the 13682 // expression evaluator needing to call back into Sema if it sees a 13683 // call to such a function. 13684 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13685 else { 13686 PendingInstantiations.push_back(std::make_pair(Func, 13687 PointOfInstantiation)); 13688 // Notify the consumer that a function was implicitly instantiated. 13689 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13690 } 13691 } 13692 } else { 13693 // Walk redefinitions, as some of them may be instantiable. 13694 for (auto i : Func->redecls()) { 13695 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13696 MarkFunctionReferenced(Loc, i, OdrUse); 13697 } 13698 } 13699 13700 if (!OdrUse) return; 13701 13702 // Keep track of used but undefined functions. 13703 if (!Func->isDefined()) { 13704 if (mightHaveNonExternalLinkage(Func)) 13705 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13706 else if (Func->getMostRecentDecl()->isInlined() && 13707 !LangOpts.GNUInline && 13708 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13709 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13710 } 13711 13712 Func->markUsed(Context); 13713 } 13714 13715 static void 13716 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13717 ValueDecl *var, DeclContext *DC) { 13718 DeclContext *VarDC = var->getDeclContext(); 13719 13720 // If the parameter still belongs to the translation unit, then 13721 // we're actually just using one parameter in the declaration of 13722 // the next. 13723 if (isa<ParmVarDecl>(var) && 13724 isa<TranslationUnitDecl>(VarDC)) 13725 return; 13726 13727 // For C code, don't diagnose about capture if we're not actually in code 13728 // right now; it's impossible to write a non-constant expression outside of 13729 // function context, so we'll get other (more useful) diagnostics later. 13730 // 13731 // For C++, things get a bit more nasty... it would be nice to suppress this 13732 // diagnostic for certain cases like using a local variable in an array bound 13733 // for a member of a local class, but the correct predicate is not obvious. 13734 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13735 return; 13736 13737 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13738 unsigned ContextKind = 3; // unknown 13739 if (isa<CXXMethodDecl>(VarDC) && 13740 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13741 ContextKind = 2; 13742 } else if (isa<FunctionDecl>(VarDC)) { 13743 ContextKind = 0; 13744 } else if (isa<BlockDecl>(VarDC)) { 13745 ContextKind = 1; 13746 } 13747 13748 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13749 << var << ValueKind << ContextKind << VarDC; 13750 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13751 << var; 13752 13753 // FIXME: Add additional diagnostic info about class etc. which prevents 13754 // capture. 13755 } 13756 13757 13758 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13759 bool &SubCapturesAreNested, 13760 QualType &CaptureType, 13761 QualType &DeclRefType) { 13762 // Check whether we've already captured it. 13763 if (CSI->CaptureMap.count(Var)) { 13764 // If we found a capture, any subcaptures are nested. 13765 SubCapturesAreNested = true; 13766 13767 // Retrieve the capture type for this variable. 13768 CaptureType = CSI->getCapture(Var).getCaptureType(); 13769 13770 // Compute the type of an expression that refers to this variable. 13771 DeclRefType = CaptureType.getNonReferenceType(); 13772 13773 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13774 // are mutable in the sense that user can change their value - they are 13775 // private instances of the captured declarations. 13776 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13777 if (Cap.isCopyCapture() && 13778 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13779 !(isa<CapturedRegionScopeInfo>(CSI) && 13780 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13781 DeclRefType.addConst(); 13782 return true; 13783 } 13784 return false; 13785 } 13786 13787 // Only block literals, captured statements, and lambda expressions can 13788 // capture; other scopes don't work. 13789 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13790 SourceLocation Loc, 13791 const bool Diagnose, Sema &S) { 13792 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13793 return getLambdaAwareParentOfDeclContext(DC); 13794 else if (Var->hasLocalStorage()) { 13795 if (Diagnose) 13796 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13797 } 13798 return nullptr; 13799 } 13800 13801 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13802 // certain types of variables (unnamed, variably modified types etc.) 13803 // so check for eligibility. 13804 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13805 SourceLocation Loc, 13806 const bool Diagnose, Sema &S) { 13807 13808 bool IsBlock = isa<BlockScopeInfo>(CSI); 13809 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13810 13811 // Lambdas are not allowed to capture unnamed variables 13812 // (e.g. anonymous unions). 13813 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13814 // assuming that's the intent. 13815 if (IsLambda && !Var->getDeclName()) { 13816 if (Diagnose) { 13817 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13818 S.Diag(Var->getLocation(), diag::note_declared_at); 13819 } 13820 return false; 13821 } 13822 13823 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13824 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13825 if (Diagnose) { 13826 S.Diag(Loc, diag::err_ref_vm_type); 13827 S.Diag(Var->getLocation(), diag::note_previous_decl) 13828 << Var->getDeclName(); 13829 } 13830 return false; 13831 } 13832 // Prohibit structs with flexible array members too. 13833 // We cannot capture what is in the tail end of the struct. 13834 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13835 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13836 if (Diagnose) { 13837 if (IsBlock) 13838 S.Diag(Loc, diag::err_ref_flexarray_type); 13839 else 13840 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13841 << Var->getDeclName(); 13842 S.Diag(Var->getLocation(), diag::note_previous_decl) 13843 << Var->getDeclName(); 13844 } 13845 return false; 13846 } 13847 } 13848 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13849 // Lambdas and captured statements are not allowed to capture __block 13850 // variables; they don't support the expected semantics. 13851 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13852 if (Diagnose) { 13853 S.Diag(Loc, diag::err_capture_block_variable) 13854 << Var->getDeclName() << !IsLambda; 13855 S.Diag(Var->getLocation(), diag::note_previous_decl) 13856 << Var->getDeclName(); 13857 } 13858 return false; 13859 } 13860 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 13861 if (S.getLangOpts().OpenCL && IsBlock && 13862 Var->getType()->isBlockPointerType()) { 13863 if (Diagnose) 13864 S.Diag(Loc, diag::err_opencl_block_ref_block); 13865 return false; 13866 } 13867 13868 return true; 13869 } 13870 13871 // Returns true if the capture by block was successful. 13872 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13873 SourceLocation Loc, 13874 const bool BuildAndDiagnose, 13875 QualType &CaptureType, 13876 QualType &DeclRefType, 13877 const bool Nested, 13878 Sema &S) { 13879 Expr *CopyExpr = nullptr; 13880 bool ByRef = false; 13881 13882 // Blocks are not allowed to capture arrays. 13883 if (CaptureType->isArrayType()) { 13884 if (BuildAndDiagnose) { 13885 S.Diag(Loc, diag::err_ref_array_type); 13886 S.Diag(Var->getLocation(), diag::note_previous_decl) 13887 << Var->getDeclName(); 13888 } 13889 return false; 13890 } 13891 13892 // Forbid the block-capture of autoreleasing variables. 13893 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13894 if (BuildAndDiagnose) { 13895 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13896 << /*block*/ 0; 13897 S.Diag(Var->getLocation(), diag::note_previous_decl) 13898 << Var->getDeclName(); 13899 } 13900 return false; 13901 } 13902 13903 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13904 if (const auto *PT = CaptureType->getAs<PointerType>()) { 13905 // This function finds out whether there is an AttributedType of kind 13906 // attr_objc_ownership in Ty. The existence of AttributedType of kind 13907 // attr_objc_ownership implies __autoreleasing was explicitly specified 13908 // rather than being added implicitly by the compiler. 13909 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 13910 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 13911 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 13912 return true; 13913 13914 // Peel off AttributedTypes that are not of kind objc_ownership. 13915 Ty = AttrTy->getModifiedType(); 13916 } 13917 13918 return false; 13919 }; 13920 13921 QualType PointeeTy = PT->getPointeeType(); 13922 13923 if (PointeeTy->getAs<ObjCObjectPointerType>() && 13924 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13925 !IsObjCOwnershipAttributedType(PointeeTy)) { 13926 if (BuildAndDiagnose) { 13927 SourceLocation VarLoc = Var->getLocation(); 13928 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13929 { 13930 auto AddAutoreleaseNote = 13931 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 13932 // Provide a fix-it for the '__autoreleasing' keyword at the 13933 // appropriate location in the variable's type. 13934 if (const auto *TSI = Var->getTypeSourceInfo()) { 13935 PointerTypeLoc PTL = 13936 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 13937 if (PTL) { 13938 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 13939 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 13940 S.getLangOpts()); 13941 if (Loc.isValid()) { 13942 StringRef CharAtLoc = Lexer::getSourceText( 13943 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 13944 S.getSourceManager(), S.getLangOpts()); 13945 AddAutoreleaseNote << FixItHint::CreateInsertion( 13946 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 13947 ? " __autoreleasing " 13948 : " __autoreleasing"); 13949 } 13950 } 13951 } 13952 } 13953 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13954 } 13955 } 13956 } 13957 13958 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13959 if (HasBlocksAttr || CaptureType->isReferenceType() || 13960 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13961 // Block capture by reference does not change the capture or 13962 // declaration reference types. 13963 ByRef = true; 13964 } else { 13965 // Block capture by copy introduces 'const'. 13966 CaptureType = CaptureType.getNonReferenceType().withConst(); 13967 DeclRefType = CaptureType; 13968 13969 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13970 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13971 // The capture logic needs the destructor, so make sure we mark it. 13972 // Usually this is unnecessary because most local variables have 13973 // their destructors marked at declaration time, but parameters are 13974 // an exception because it's technically only the call site that 13975 // actually requires the destructor. 13976 if (isa<ParmVarDecl>(Var)) 13977 S.FinalizeVarWithDestructor(Var, Record); 13978 13979 // Enter a new evaluation context to insulate the copy 13980 // full-expression. 13981 EnterExpressionEvaluationContext scope( 13982 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 13983 13984 // According to the blocks spec, the capture of a variable from 13985 // the stack requires a const copy constructor. This is not true 13986 // of the copy/move done to move a __block variable to the heap. 13987 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13988 DeclRefType.withConst(), 13989 VK_LValue, Loc); 13990 13991 ExprResult Result 13992 = S.PerformCopyInitialization( 13993 InitializedEntity::InitializeBlock(Var->getLocation(), 13994 CaptureType, false), 13995 Loc, DeclRef); 13996 13997 // Build a full-expression copy expression if initialization 13998 // succeeded and used a non-trivial constructor. Recover from 13999 // errors by pretending that the copy isn't necessary. 14000 if (!Result.isInvalid() && 14001 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14002 ->isTrivial()) { 14003 Result = S.MaybeCreateExprWithCleanups(Result); 14004 CopyExpr = Result.get(); 14005 } 14006 } 14007 } 14008 } 14009 14010 // Actually capture the variable. 14011 if (BuildAndDiagnose) 14012 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14013 SourceLocation(), CaptureType, CopyExpr); 14014 14015 return true; 14016 14017 } 14018 14019 14020 /// \brief Capture the given variable in the captured region. 14021 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14022 VarDecl *Var, 14023 SourceLocation Loc, 14024 const bool BuildAndDiagnose, 14025 QualType &CaptureType, 14026 QualType &DeclRefType, 14027 const bool RefersToCapturedVariable, 14028 Sema &S) { 14029 // By default, capture variables by reference. 14030 bool ByRef = true; 14031 // Using an LValue reference type is consistent with Lambdas (see below). 14032 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14033 if (S.IsOpenMPCapturedDecl(Var)) 14034 DeclRefType = DeclRefType.getUnqualifiedType(); 14035 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14036 } 14037 14038 if (ByRef) 14039 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14040 else 14041 CaptureType = DeclRefType; 14042 14043 Expr *CopyExpr = nullptr; 14044 if (BuildAndDiagnose) { 14045 // The current implementation assumes that all variables are captured 14046 // by references. Since there is no capture by copy, no expression 14047 // evaluation will be needed. 14048 RecordDecl *RD = RSI->TheRecordDecl; 14049 14050 FieldDecl *Field 14051 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14052 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14053 nullptr, false, ICIS_NoInit); 14054 Field->setImplicit(true); 14055 Field->setAccess(AS_private); 14056 RD->addDecl(Field); 14057 14058 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14059 DeclRefType, VK_LValue, Loc); 14060 Var->setReferenced(true); 14061 Var->markUsed(S.Context); 14062 } 14063 14064 // Actually capture the variable. 14065 if (BuildAndDiagnose) 14066 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14067 SourceLocation(), CaptureType, CopyExpr); 14068 14069 14070 return true; 14071 } 14072 14073 /// \brief Create a field within the lambda class for the variable 14074 /// being captured. 14075 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14076 QualType FieldType, QualType DeclRefType, 14077 SourceLocation Loc, 14078 bool RefersToCapturedVariable) { 14079 CXXRecordDecl *Lambda = LSI->Lambda; 14080 14081 // Build the non-static data member. 14082 FieldDecl *Field 14083 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14084 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14085 nullptr, false, ICIS_NoInit); 14086 Field->setImplicit(true); 14087 Field->setAccess(AS_private); 14088 Lambda->addDecl(Field); 14089 } 14090 14091 /// \brief Capture the given variable in the lambda. 14092 static bool captureInLambda(LambdaScopeInfo *LSI, 14093 VarDecl *Var, 14094 SourceLocation Loc, 14095 const bool BuildAndDiagnose, 14096 QualType &CaptureType, 14097 QualType &DeclRefType, 14098 const bool RefersToCapturedVariable, 14099 const Sema::TryCaptureKind Kind, 14100 SourceLocation EllipsisLoc, 14101 const bool IsTopScope, 14102 Sema &S) { 14103 14104 // Determine whether we are capturing by reference or by value. 14105 bool ByRef = false; 14106 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14107 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14108 } else { 14109 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14110 } 14111 14112 // Compute the type of the field that will capture this variable. 14113 if (ByRef) { 14114 // C++11 [expr.prim.lambda]p15: 14115 // An entity is captured by reference if it is implicitly or 14116 // explicitly captured but not captured by copy. It is 14117 // unspecified whether additional unnamed non-static data 14118 // members are declared in the closure type for entities 14119 // captured by reference. 14120 // 14121 // FIXME: It is not clear whether we want to build an lvalue reference 14122 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14123 // to do the former, while EDG does the latter. Core issue 1249 will 14124 // clarify, but for now we follow GCC because it's a more permissive and 14125 // easily defensible position. 14126 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14127 } else { 14128 // C++11 [expr.prim.lambda]p14: 14129 // For each entity captured by copy, an unnamed non-static 14130 // data member is declared in the closure type. The 14131 // declaration order of these members is unspecified. The type 14132 // of such a data member is the type of the corresponding 14133 // captured entity if the entity is not a reference to an 14134 // object, or the referenced type otherwise. [Note: If the 14135 // captured entity is a reference to a function, the 14136 // corresponding data member is also a reference to a 14137 // function. - end note ] 14138 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14139 if (!RefType->getPointeeType()->isFunctionType()) 14140 CaptureType = RefType->getPointeeType(); 14141 } 14142 14143 // Forbid the lambda copy-capture of autoreleasing variables. 14144 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14145 if (BuildAndDiagnose) { 14146 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14147 S.Diag(Var->getLocation(), diag::note_previous_decl) 14148 << Var->getDeclName(); 14149 } 14150 return false; 14151 } 14152 14153 // Make sure that by-copy captures are of a complete and non-abstract type. 14154 if (BuildAndDiagnose) { 14155 if (!CaptureType->isDependentType() && 14156 S.RequireCompleteType(Loc, CaptureType, 14157 diag::err_capture_of_incomplete_type, 14158 Var->getDeclName())) 14159 return false; 14160 14161 if (S.RequireNonAbstractType(Loc, CaptureType, 14162 diag::err_capture_of_abstract_type)) 14163 return false; 14164 } 14165 } 14166 14167 // Capture this variable in the lambda. 14168 if (BuildAndDiagnose) 14169 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14170 RefersToCapturedVariable); 14171 14172 // Compute the type of a reference to this captured variable. 14173 if (ByRef) 14174 DeclRefType = CaptureType.getNonReferenceType(); 14175 else { 14176 // C++ [expr.prim.lambda]p5: 14177 // The closure type for a lambda-expression has a public inline 14178 // function call operator [...]. This function call operator is 14179 // declared const (9.3.1) if and only if the lambda-expression's 14180 // parameter-declaration-clause is not followed by mutable. 14181 DeclRefType = CaptureType.getNonReferenceType(); 14182 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14183 DeclRefType.addConst(); 14184 } 14185 14186 // Add the capture. 14187 if (BuildAndDiagnose) 14188 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14189 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14190 14191 return true; 14192 } 14193 14194 bool Sema::tryCaptureVariable( 14195 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14196 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14197 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14198 // An init-capture is notionally from the context surrounding its 14199 // declaration, but its parent DC is the lambda class. 14200 DeclContext *VarDC = Var->getDeclContext(); 14201 if (Var->isInitCapture()) 14202 VarDC = VarDC->getParent(); 14203 14204 DeclContext *DC = CurContext; 14205 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14206 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14207 // We need to sync up the Declaration Context with the 14208 // FunctionScopeIndexToStopAt 14209 if (FunctionScopeIndexToStopAt) { 14210 unsigned FSIndex = FunctionScopes.size() - 1; 14211 while (FSIndex != MaxFunctionScopesIndex) { 14212 DC = getLambdaAwareParentOfDeclContext(DC); 14213 --FSIndex; 14214 } 14215 } 14216 14217 14218 // If the variable is declared in the current context, there is no need to 14219 // capture it. 14220 if (VarDC == DC) return true; 14221 14222 // Capture global variables if it is required to use private copy of this 14223 // variable. 14224 bool IsGlobal = !Var->hasLocalStorage(); 14225 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14226 return true; 14227 14228 // Walk up the stack to determine whether we can capture the variable, 14229 // performing the "simple" checks that don't depend on type. We stop when 14230 // we've either hit the declared scope of the variable or find an existing 14231 // capture of that variable. We start from the innermost capturing-entity 14232 // (the DC) and ensure that all intervening capturing-entities 14233 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14234 // declcontext can either capture the variable or have already captured 14235 // the variable. 14236 CaptureType = Var->getType(); 14237 DeclRefType = CaptureType.getNonReferenceType(); 14238 bool Nested = false; 14239 bool Explicit = (Kind != TryCapture_Implicit); 14240 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14241 do { 14242 // Only block literals, captured statements, and lambda expressions can 14243 // capture; other scopes don't work. 14244 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14245 ExprLoc, 14246 BuildAndDiagnose, 14247 *this); 14248 // We need to check for the parent *first* because, if we *have* 14249 // private-captured a global variable, we need to recursively capture it in 14250 // intermediate blocks, lambdas, etc. 14251 if (!ParentDC) { 14252 if (IsGlobal) { 14253 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14254 break; 14255 } 14256 return true; 14257 } 14258 14259 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14260 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14261 14262 14263 // Check whether we've already captured it. 14264 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14265 DeclRefType)) { 14266 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14267 break; 14268 } 14269 // If we are instantiating a generic lambda call operator body, 14270 // we do not want to capture new variables. What was captured 14271 // during either a lambdas transformation or initial parsing 14272 // should be used. 14273 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14274 if (BuildAndDiagnose) { 14275 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14276 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14277 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14278 Diag(Var->getLocation(), diag::note_previous_decl) 14279 << Var->getDeclName(); 14280 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14281 } else 14282 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14283 } 14284 return true; 14285 } 14286 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14287 // certain types of variables (unnamed, variably modified types etc.) 14288 // so check for eligibility. 14289 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14290 return true; 14291 14292 // Try to capture variable-length arrays types. 14293 if (Var->getType()->isVariablyModifiedType()) { 14294 // We're going to walk down into the type and look for VLA 14295 // expressions. 14296 QualType QTy = Var->getType(); 14297 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14298 QTy = PVD->getOriginalType(); 14299 captureVariablyModifiedType(Context, QTy, CSI); 14300 } 14301 14302 if (getLangOpts().OpenMP) { 14303 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14304 // OpenMP private variables should not be captured in outer scope, so 14305 // just break here. Similarly, global variables that are captured in a 14306 // target region should not be captured outside the scope of the region. 14307 if (RSI->CapRegionKind == CR_OpenMP) { 14308 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14309 // When we detect target captures we are looking from inside the 14310 // target region, therefore we need to propagate the capture from the 14311 // enclosing region. Therefore, the capture is not initially nested. 14312 if (IsTargetCap) 14313 FunctionScopesIndex--; 14314 14315 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 14316 Nested = !IsTargetCap; 14317 DeclRefType = DeclRefType.getUnqualifiedType(); 14318 CaptureType = Context.getLValueReferenceType(DeclRefType); 14319 break; 14320 } 14321 } 14322 } 14323 } 14324 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14325 // No capture-default, and this is not an explicit capture 14326 // so cannot capture this variable. 14327 if (BuildAndDiagnose) { 14328 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14329 Diag(Var->getLocation(), diag::note_previous_decl) 14330 << Var->getDeclName(); 14331 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14332 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14333 diag::note_lambda_decl); 14334 // FIXME: If we error out because an outer lambda can not implicitly 14335 // capture a variable that an inner lambda explicitly captures, we 14336 // should have the inner lambda do the explicit capture - because 14337 // it makes for cleaner diagnostics later. This would purely be done 14338 // so that the diagnostic does not misleadingly claim that a variable 14339 // can not be captured by a lambda implicitly even though it is captured 14340 // explicitly. Suggestion: 14341 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14342 // at the function head 14343 // - cache the StartingDeclContext - this must be a lambda 14344 // - captureInLambda in the innermost lambda the variable. 14345 } 14346 return true; 14347 } 14348 14349 FunctionScopesIndex--; 14350 DC = ParentDC; 14351 Explicit = false; 14352 } while (!VarDC->Equals(DC)); 14353 14354 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14355 // computing the type of the capture at each step, checking type-specific 14356 // requirements, and adding captures if requested. 14357 // If the variable had already been captured previously, we start capturing 14358 // at the lambda nested within that one. 14359 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14360 ++I) { 14361 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14362 14363 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14364 if (!captureInBlock(BSI, Var, ExprLoc, 14365 BuildAndDiagnose, CaptureType, 14366 DeclRefType, Nested, *this)) 14367 return true; 14368 Nested = true; 14369 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14370 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14371 BuildAndDiagnose, CaptureType, 14372 DeclRefType, Nested, *this)) 14373 return true; 14374 Nested = true; 14375 } else { 14376 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14377 if (!captureInLambda(LSI, Var, ExprLoc, 14378 BuildAndDiagnose, CaptureType, 14379 DeclRefType, Nested, Kind, EllipsisLoc, 14380 /*IsTopScope*/I == N - 1, *this)) 14381 return true; 14382 Nested = true; 14383 } 14384 } 14385 return false; 14386 } 14387 14388 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14389 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14390 QualType CaptureType; 14391 QualType DeclRefType; 14392 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14393 /*BuildAndDiagnose=*/true, CaptureType, 14394 DeclRefType, nullptr); 14395 } 14396 14397 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14398 QualType CaptureType; 14399 QualType DeclRefType; 14400 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14401 /*BuildAndDiagnose=*/false, CaptureType, 14402 DeclRefType, nullptr); 14403 } 14404 14405 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14406 QualType CaptureType; 14407 QualType DeclRefType; 14408 14409 // Determine whether we can capture this variable. 14410 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14411 /*BuildAndDiagnose=*/false, CaptureType, 14412 DeclRefType, nullptr)) 14413 return QualType(); 14414 14415 return DeclRefType; 14416 } 14417 14418 14419 14420 // If either the type of the variable or the initializer is dependent, 14421 // return false. Otherwise, determine whether the variable is a constant 14422 // expression. Use this if you need to know if a variable that might or 14423 // might not be dependent is truly a constant expression. 14424 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14425 ASTContext &Context) { 14426 14427 if (Var->getType()->isDependentType()) 14428 return false; 14429 const VarDecl *DefVD = nullptr; 14430 Var->getAnyInitializer(DefVD); 14431 if (!DefVD) 14432 return false; 14433 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14434 Expr *Init = cast<Expr>(Eval->Value); 14435 if (Init->isValueDependent()) 14436 return false; 14437 return IsVariableAConstantExpression(Var, Context); 14438 } 14439 14440 14441 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14442 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14443 // an object that satisfies the requirements for appearing in a 14444 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14445 // is immediately applied." This function handles the lvalue-to-rvalue 14446 // conversion part. 14447 MaybeODRUseExprs.erase(E->IgnoreParens()); 14448 14449 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14450 // to a variable that is a constant expression, and if so, identify it as 14451 // a reference to a variable that does not involve an odr-use of that 14452 // variable. 14453 if (LambdaScopeInfo *LSI = getCurLambda()) { 14454 Expr *SansParensExpr = E->IgnoreParens(); 14455 VarDecl *Var = nullptr; 14456 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14457 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14458 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14459 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14460 14461 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14462 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14463 } 14464 } 14465 14466 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14467 Res = CorrectDelayedTyposInExpr(Res); 14468 14469 if (!Res.isUsable()) 14470 return Res; 14471 14472 // If a constant-expression is a reference to a variable where we delay 14473 // deciding whether it is an odr-use, just assume we will apply the 14474 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14475 // (a non-type template argument), we have special handling anyway. 14476 UpdateMarkingForLValueToRValue(Res.get()); 14477 return Res; 14478 } 14479 14480 void Sema::CleanupVarDeclMarking() { 14481 for (Expr *E : MaybeODRUseExprs) { 14482 VarDecl *Var; 14483 SourceLocation Loc; 14484 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14485 Var = cast<VarDecl>(DRE->getDecl()); 14486 Loc = DRE->getLocation(); 14487 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14488 Var = cast<VarDecl>(ME->getMemberDecl()); 14489 Loc = ME->getMemberLoc(); 14490 } else { 14491 llvm_unreachable("Unexpected expression"); 14492 } 14493 14494 MarkVarDeclODRUsed(Var, Loc, *this, 14495 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14496 } 14497 14498 MaybeODRUseExprs.clear(); 14499 } 14500 14501 14502 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14503 VarDecl *Var, Expr *E) { 14504 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14505 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14506 Var->setReferenced(); 14507 14508 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14509 14510 bool OdrUseContext = isOdrUseContext(SemaRef); 14511 bool NeedDefinition = 14512 OdrUseContext || (isEvaluatableContext(SemaRef) && 14513 Var->isUsableInConstantExpressions(SemaRef.Context)); 14514 14515 VarTemplateSpecializationDecl *VarSpec = 14516 dyn_cast<VarTemplateSpecializationDecl>(Var); 14517 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14518 "Can't instantiate a partial template specialization."); 14519 14520 // If this might be a member specialization of a static data member, check 14521 // the specialization is visible. We already did the checks for variable 14522 // template specializations when we created them. 14523 if (NeedDefinition && TSK != TSK_Undeclared && 14524 !isa<VarTemplateSpecializationDecl>(Var)) 14525 SemaRef.checkSpecializationVisibility(Loc, Var); 14526 14527 // Perform implicit instantiation of static data members, static data member 14528 // templates of class templates, and variable template specializations. Delay 14529 // instantiations of variable templates, except for those that could be used 14530 // in a constant expression. 14531 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14532 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14533 14534 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14535 if (Var->getPointOfInstantiation().isInvalid()) { 14536 // This is a modification of an existing AST node. Notify listeners. 14537 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14538 L->StaticDataMemberInstantiated(Var); 14539 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14540 // Don't bother trying to instantiate it again, unless we might need 14541 // its initializer before we get to the end of the TU. 14542 TryInstantiating = false; 14543 } 14544 14545 if (Var->getPointOfInstantiation().isInvalid()) 14546 Var->setTemplateSpecializationKind(TSK, Loc); 14547 14548 if (TryInstantiating) { 14549 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14550 bool InstantiationDependent = false; 14551 bool IsNonDependent = 14552 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14553 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14554 : true; 14555 14556 // Do not instantiate specializations that are still type-dependent. 14557 if (IsNonDependent) { 14558 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14559 // Do not defer instantiations of variables which could be used in a 14560 // constant expression. 14561 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14562 } else { 14563 SemaRef.PendingInstantiations 14564 .push_back(std::make_pair(Var, PointOfInstantiation)); 14565 } 14566 } 14567 } 14568 } 14569 14570 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14571 // the requirements for appearing in a constant expression (5.19) and, if 14572 // it is an object, the lvalue-to-rvalue conversion (4.1) 14573 // is immediately applied." We check the first part here, and 14574 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14575 // Note that we use the C++11 definition everywhere because nothing in 14576 // C++03 depends on whether we get the C++03 version correct. The second 14577 // part does not apply to references, since they are not objects. 14578 if (OdrUseContext && E && 14579 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14580 // A reference initialized by a constant expression can never be 14581 // odr-used, so simply ignore it. 14582 if (!Var->getType()->isReferenceType()) 14583 SemaRef.MaybeODRUseExprs.insert(E); 14584 } else if (OdrUseContext) { 14585 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14586 /*MaxFunctionScopeIndex ptr*/ nullptr); 14587 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14588 // If this is a dependent context, we don't need to mark variables as 14589 // odr-used, but we may still need to track them for lambda capture. 14590 // FIXME: Do we also need to do this inside dependent typeid expressions 14591 // (which are modeled as unevaluated at this point)? 14592 const bool RefersToEnclosingScope = 14593 (SemaRef.CurContext != Var->getDeclContext() && 14594 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14595 if (RefersToEnclosingScope) { 14596 LambdaScopeInfo *const LSI = 14597 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14598 if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) { 14599 // If a variable could potentially be odr-used, defer marking it so 14600 // until we finish analyzing the full expression for any 14601 // lvalue-to-rvalue 14602 // or discarded value conversions that would obviate odr-use. 14603 // Add it to the list of potential captures that will be analyzed 14604 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14605 // unless the variable is a reference that was initialized by a constant 14606 // expression (this will never need to be captured or odr-used). 14607 assert(E && "Capture variable should be used in an expression."); 14608 if (!Var->getType()->isReferenceType() || 14609 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14610 LSI->addPotentialCapture(E->IgnoreParens()); 14611 } 14612 } 14613 } 14614 } 14615 14616 /// \brief Mark a variable referenced, and check whether it is odr-used 14617 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14618 /// used directly for normal expressions referring to VarDecl. 14619 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14620 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14621 } 14622 14623 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14624 Decl *D, Expr *E, bool MightBeOdrUse) { 14625 if (SemaRef.isInOpenMPDeclareTargetContext()) 14626 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14627 14628 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14629 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14630 return; 14631 } 14632 14633 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14634 14635 // If this is a call to a method via a cast, also mark the method in the 14636 // derived class used in case codegen can devirtualize the call. 14637 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14638 if (!ME) 14639 return; 14640 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14641 if (!MD) 14642 return; 14643 // Only attempt to devirtualize if this is truly a virtual call. 14644 bool IsVirtualCall = MD->isVirtual() && 14645 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14646 if (!IsVirtualCall) 14647 return; 14648 const Expr *Base = ME->getBase(); 14649 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14650 if (!MostDerivedClassDecl) 14651 return; 14652 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14653 if (!DM || DM->isPure()) 14654 return; 14655 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14656 } 14657 14658 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14659 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14660 // TODO: update this with DR# once a defect report is filed. 14661 // C++11 defect. The address of a pure member should not be an ODR use, even 14662 // if it's a qualified reference. 14663 bool OdrUse = true; 14664 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14665 if (Method->isVirtual()) 14666 OdrUse = false; 14667 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14668 } 14669 14670 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14671 void Sema::MarkMemberReferenced(MemberExpr *E) { 14672 // C++11 [basic.def.odr]p2: 14673 // A non-overloaded function whose name appears as a potentially-evaluated 14674 // expression or a member of a set of candidate functions, if selected by 14675 // overload resolution when referred to from a potentially-evaluated 14676 // expression, is odr-used, unless it is a pure virtual function and its 14677 // name is not explicitly qualified. 14678 bool MightBeOdrUse = true; 14679 if (E->performsVirtualDispatch(getLangOpts())) { 14680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14681 if (Method->isPure()) 14682 MightBeOdrUse = false; 14683 } 14684 SourceLocation Loc = E->getMemberLoc().isValid() ? 14685 E->getMemberLoc() : E->getLocStart(); 14686 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14687 } 14688 14689 /// \brief Perform marking for a reference to an arbitrary declaration. It 14690 /// marks the declaration referenced, and performs odr-use checking for 14691 /// functions and variables. This method should not be used when building a 14692 /// normal expression which refers to a variable. 14693 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14694 bool MightBeOdrUse) { 14695 if (MightBeOdrUse) { 14696 if (auto *VD = dyn_cast<VarDecl>(D)) { 14697 MarkVariableReferenced(Loc, VD); 14698 return; 14699 } 14700 } 14701 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14702 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14703 return; 14704 } 14705 D->setReferenced(); 14706 } 14707 14708 namespace { 14709 // Mark all of the declarations used by a type as referenced. 14710 // FIXME: Not fully implemented yet! We need to have a better understanding 14711 // of when we're entering a context we should not recurse into. 14712 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 14713 // TreeTransforms rebuilding the type in a new context. Rather than 14714 // duplicating the TreeTransform logic, we should consider reusing it here. 14715 // Currently that causes problems when rebuilding LambdaExprs. 14716 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14717 Sema &S; 14718 SourceLocation Loc; 14719 14720 public: 14721 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14722 14723 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14724 14725 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14726 }; 14727 } 14728 14729 bool MarkReferencedDecls::TraverseTemplateArgument( 14730 const TemplateArgument &Arg) { 14731 { 14732 // A non-type template argument is a constant-evaluated context. 14733 EnterExpressionEvaluationContext Evaluated( 14734 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 14735 if (Arg.getKind() == TemplateArgument::Declaration) { 14736 if (Decl *D = Arg.getAsDecl()) 14737 S.MarkAnyDeclReferenced(Loc, D, true); 14738 } else if (Arg.getKind() == TemplateArgument::Expression) { 14739 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 14740 } 14741 } 14742 14743 return Inherited::TraverseTemplateArgument(Arg); 14744 } 14745 14746 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14747 MarkReferencedDecls Marker(*this, Loc); 14748 Marker.TraverseType(T); 14749 } 14750 14751 namespace { 14752 /// \brief Helper class that marks all of the declarations referenced by 14753 /// potentially-evaluated subexpressions as "referenced". 14754 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14755 Sema &S; 14756 bool SkipLocalVariables; 14757 14758 public: 14759 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14760 14761 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14762 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14763 14764 void VisitDeclRefExpr(DeclRefExpr *E) { 14765 // If we were asked not to visit local variables, don't. 14766 if (SkipLocalVariables) { 14767 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14768 if (VD->hasLocalStorage()) 14769 return; 14770 } 14771 14772 S.MarkDeclRefReferenced(E); 14773 } 14774 14775 void VisitMemberExpr(MemberExpr *E) { 14776 S.MarkMemberReferenced(E); 14777 Inherited::VisitMemberExpr(E); 14778 } 14779 14780 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14781 S.MarkFunctionReferenced(E->getLocStart(), 14782 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14783 Visit(E->getSubExpr()); 14784 } 14785 14786 void VisitCXXNewExpr(CXXNewExpr *E) { 14787 if (E->getOperatorNew()) 14788 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14789 if (E->getOperatorDelete()) 14790 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14791 Inherited::VisitCXXNewExpr(E); 14792 } 14793 14794 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14795 if (E->getOperatorDelete()) 14796 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14797 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14798 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14799 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14800 S.MarkFunctionReferenced(E->getLocStart(), 14801 S.LookupDestructor(Record)); 14802 } 14803 14804 Inherited::VisitCXXDeleteExpr(E); 14805 } 14806 14807 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14808 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14809 Inherited::VisitCXXConstructExpr(E); 14810 } 14811 14812 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14813 Visit(E->getExpr()); 14814 } 14815 14816 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14817 Inherited::VisitImplicitCastExpr(E); 14818 14819 if (E->getCastKind() == CK_LValueToRValue) 14820 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14821 } 14822 }; 14823 } 14824 14825 /// \brief Mark any declarations that appear within this expression or any 14826 /// potentially-evaluated subexpressions as "referenced". 14827 /// 14828 /// \param SkipLocalVariables If true, don't mark local variables as 14829 /// 'referenced'. 14830 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14831 bool SkipLocalVariables) { 14832 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14833 } 14834 14835 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14836 /// of the program being compiled. 14837 /// 14838 /// This routine emits the given diagnostic when the code currently being 14839 /// type-checked is "potentially evaluated", meaning that there is a 14840 /// possibility that the code will actually be executable. Code in sizeof() 14841 /// expressions, code used only during overload resolution, etc., are not 14842 /// potentially evaluated. This routine will suppress such diagnostics or, 14843 /// in the absolutely nutty case of potentially potentially evaluated 14844 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14845 /// later. 14846 /// 14847 /// This routine should be used for all diagnostics that describe the run-time 14848 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14849 /// Failure to do so will likely result in spurious diagnostics or failures 14850 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14851 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14852 const PartialDiagnostic &PD) { 14853 switch (ExprEvalContexts.back().Context) { 14854 case ExpressionEvaluationContext::Unevaluated: 14855 case ExpressionEvaluationContext::UnevaluatedList: 14856 case ExpressionEvaluationContext::UnevaluatedAbstract: 14857 case ExpressionEvaluationContext::DiscardedStatement: 14858 // The argument will never be evaluated, so don't complain. 14859 break; 14860 14861 case ExpressionEvaluationContext::ConstantEvaluated: 14862 // Relevant diagnostics should be produced by constant evaluation. 14863 break; 14864 14865 case ExpressionEvaluationContext::PotentiallyEvaluated: 14866 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14867 if (Statement && getCurFunctionOrMethodDecl()) { 14868 FunctionScopes.back()->PossiblyUnreachableDiags. 14869 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14870 } 14871 else 14872 Diag(Loc, PD); 14873 14874 return true; 14875 } 14876 14877 return false; 14878 } 14879 14880 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14881 CallExpr *CE, FunctionDecl *FD) { 14882 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14883 return false; 14884 14885 // If we're inside a decltype's expression, don't check for a valid return 14886 // type or construct temporaries until we know whether this is the last call. 14887 if (ExprEvalContexts.back().IsDecltype) { 14888 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14889 return false; 14890 } 14891 14892 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14893 FunctionDecl *FD; 14894 CallExpr *CE; 14895 14896 public: 14897 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14898 : FD(FD), CE(CE) { } 14899 14900 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14901 if (!FD) { 14902 S.Diag(Loc, diag::err_call_incomplete_return) 14903 << T << CE->getSourceRange(); 14904 return; 14905 } 14906 14907 S.Diag(Loc, diag::err_call_function_incomplete_return) 14908 << CE->getSourceRange() << FD->getDeclName() << T; 14909 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14910 << FD->getDeclName(); 14911 } 14912 } Diagnoser(FD, CE); 14913 14914 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14915 return true; 14916 14917 return false; 14918 } 14919 14920 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14921 // will prevent this condition from triggering, which is what we want. 14922 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14923 SourceLocation Loc; 14924 14925 unsigned diagnostic = diag::warn_condition_is_assignment; 14926 bool IsOrAssign = false; 14927 14928 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14929 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14930 return; 14931 14932 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14933 14934 // Greylist some idioms by putting them into a warning subcategory. 14935 if (ObjCMessageExpr *ME 14936 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14937 Selector Sel = ME->getSelector(); 14938 14939 // self = [<foo> init...] 14940 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14941 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14942 14943 // <foo> = [<bar> nextObject] 14944 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14945 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14946 } 14947 14948 Loc = Op->getOperatorLoc(); 14949 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14950 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14951 return; 14952 14953 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14954 Loc = Op->getOperatorLoc(); 14955 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14956 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14957 else { 14958 // Not an assignment. 14959 return; 14960 } 14961 14962 Diag(Loc, diagnostic) << E->getSourceRange(); 14963 14964 SourceLocation Open = E->getLocStart(); 14965 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14966 Diag(Loc, diag::note_condition_assign_silence) 14967 << FixItHint::CreateInsertion(Open, "(") 14968 << FixItHint::CreateInsertion(Close, ")"); 14969 14970 if (IsOrAssign) 14971 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14972 << FixItHint::CreateReplacement(Loc, "!="); 14973 else 14974 Diag(Loc, diag::note_condition_assign_to_comparison) 14975 << FixItHint::CreateReplacement(Loc, "=="); 14976 } 14977 14978 /// \brief Redundant parentheses over an equality comparison can indicate 14979 /// that the user intended an assignment used as condition. 14980 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14981 // Don't warn if the parens came from a macro. 14982 SourceLocation parenLoc = ParenE->getLocStart(); 14983 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14984 return; 14985 // Don't warn for dependent expressions. 14986 if (ParenE->isTypeDependent()) 14987 return; 14988 14989 Expr *E = ParenE->IgnoreParens(); 14990 14991 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14992 if (opE->getOpcode() == BO_EQ && 14993 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14994 == Expr::MLV_Valid) { 14995 SourceLocation Loc = opE->getOperatorLoc(); 14996 14997 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14998 SourceRange ParenERange = ParenE->getSourceRange(); 14999 Diag(Loc, diag::note_equality_comparison_silence) 15000 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15001 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15002 Diag(Loc, diag::note_equality_comparison_to_assign) 15003 << FixItHint::CreateReplacement(Loc, "="); 15004 } 15005 } 15006 15007 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15008 bool IsConstexpr) { 15009 DiagnoseAssignmentAsCondition(E); 15010 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15011 DiagnoseEqualityWithExtraParens(parenE); 15012 15013 ExprResult result = CheckPlaceholderExpr(E); 15014 if (result.isInvalid()) return ExprError(); 15015 E = result.get(); 15016 15017 if (!E->isTypeDependent()) { 15018 if (getLangOpts().CPlusPlus) 15019 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15020 15021 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15022 if (ERes.isInvalid()) 15023 return ExprError(); 15024 E = ERes.get(); 15025 15026 QualType T = E->getType(); 15027 if (!T->isScalarType()) { // C99 6.8.4.1p1 15028 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15029 << T << E->getSourceRange(); 15030 return ExprError(); 15031 } 15032 CheckBoolLikeConversion(E, Loc); 15033 } 15034 15035 return E; 15036 } 15037 15038 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15039 Expr *SubExpr, ConditionKind CK) { 15040 // Empty conditions are valid in for-statements. 15041 if (!SubExpr) 15042 return ConditionResult(); 15043 15044 ExprResult Cond; 15045 switch (CK) { 15046 case ConditionKind::Boolean: 15047 Cond = CheckBooleanCondition(Loc, SubExpr); 15048 break; 15049 15050 case ConditionKind::ConstexprIf: 15051 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15052 break; 15053 15054 case ConditionKind::Switch: 15055 Cond = CheckSwitchCondition(Loc, SubExpr); 15056 break; 15057 } 15058 if (Cond.isInvalid()) 15059 return ConditionError(); 15060 15061 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15062 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15063 if (!FullExpr.get()) 15064 return ConditionError(); 15065 15066 return ConditionResult(*this, nullptr, FullExpr, 15067 CK == ConditionKind::ConstexprIf); 15068 } 15069 15070 namespace { 15071 /// A visitor for rebuilding a call to an __unknown_any expression 15072 /// to have an appropriate type. 15073 struct RebuildUnknownAnyFunction 15074 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15075 15076 Sema &S; 15077 15078 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15079 15080 ExprResult VisitStmt(Stmt *S) { 15081 llvm_unreachable("unexpected statement!"); 15082 } 15083 15084 ExprResult VisitExpr(Expr *E) { 15085 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15086 << E->getSourceRange(); 15087 return ExprError(); 15088 } 15089 15090 /// Rebuild an expression which simply semantically wraps another 15091 /// expression which it shares the type and value kind of. 15092 template <class T> ExprResult rebuildSugarExpr(T *E) { 15093 ExprResult SubResult = Visit(E->getSubExpr()); 15094 if (SubResult.isInvalid()) return ExprError(); 15095 15096 Expr *SubExpr = SubResult.get(); 15097 E->setSubExpr(SubExpr); 15098 E->setType(SubExpr->getType()); 15099 E->setValueKind(SubExpr->getValueKind()); 15100 assert(E->getObjectKind() == OK_Ordinary); 15101 return E; 15102 } 15103 15104 ExprResult VisitParenExpr(ParenExpr *E) { 15105 return rebuildSugarExpr(E); 15106 } 15107 15108 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15109 return rebuildSugarExpr(E); 15110 } 15111 15112 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15113 ExprResult SubResult = Visit(E->getSubExpr()); 15114 if (SubResult.isInvalid()) return ExprError(); 15115 15116 Expr *SubExpr = SubResult.get(); 15117 E->setSubExpr(SubExpr); 15118 E->setType(S.Context.getPointerType(SubExpr->getType())); 15119 assert(E->getValueKind() == VK_RValue); 15120 assert(E->getObjectKind() == OK_Ordinary); 15121 return E; 15122 } 15123 15124 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15125 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15126 15127 E->setType(VD->getType()); 15128 15129 assert(E->getValueKind() == VK_RValue); 15130 if (S.getLangOpts().CPlusPlus && 15131 !(isa<CXXMethodDecl>(VD) && 15132 cast<CXXMethodDecl>(VD)->isInstance())) 15133 E->setValueKind(VK_LValue); 15134 15135 return E; 15136 } 15137 15138 ExprResult VisitMemberExpr(MemberExpr *E) { 15139 return resolveDecl(E, E->getMemberDecl()); 15140 } 15141 15142 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15143 return resolveDecl(E, E->getDecl()); 15144 } 15145 }; 15146 } 15147 15148 /// Given a function expression of unknown-any type, try to rebuild it 15149 /// to have a function type. 15150 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15151 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15152 if (Result.isInvalid()) return ExprError(); 15153 return S.DefaultFunctionArrayConversion(Result.get()); 15154 } 15155 15156 namespace { 15157 /// A visitor for rebuilding an expression of type __unknown_anytype 15158 /// into one which resolves the type directly on the referring 15159 /// expression. Strict preservation of the original source 15160 /// structure is not a goal. 15161 struct RebuildUnknownAnyExpr 15162 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15163 15164 Sema &S; 15165 15166 /// The current destination type. 15167 QualType DestType; 15168 15169 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15170 : S(S), DestType(CastType) {} 15171 15172 ExprResult VisitStmt(Stmt *S) { 15173 llvm_unreachable("unexpected statement!"); 15174 } 15175 15176 ExprResult VisitExpr(Expr *E) { 15177 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15178 << E->getSourceRange(); 15179 return ExprError(); 15180 } 15181 15182 ExprResult VisitCallExpr(CallExpr *E); 15183 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15184 15185 /// Rebuild an expression which simply semantically wraps another 15186 /// expression which it shares the type and value kind of. 15187 template <class T> ExprResult rebuildSugarExpr(T *E) { 15188 ExprResult SubResult = Visit(E->getSubExpr()); 15189 if (SubResult.isInvalid()) return ExprError(); 15190 Expr *SubExpr = SubResult.get(); 15191 E->setSubExpr(SubExpr); 15192 E->setType(SubExpr->getType()); 15193 E->setValueKind(SubExpr->getValueKind()); 15194 assert(E->getObjectKind() == OK_Ordinary); 15195 return E; 15196 } 15197 15198 ExprResult VisitParenExpr(ParenExpr *E) { 15199 return rebuildSugarExpr(E); 15200 } 15201 15202 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15203 return rebuildSugarExpr(E); 15204 } 15205 15206 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15207 const PointerType *Ptr = DestType->getAs<PointerType>(); 15208 if (!Ptr) { 15209 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15210 << E->getSourceRange(); 15211 return ExprError(); 15212 } 15213 15214 if (isa<CallExpr>(E->getSubExpr())) { 15215 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15216 << E->getSourceRange(); 15217 return ExprError(); 15218 } 15219 15220 assert(E->getValueKind() == VK_RValue); 15221 assert(E->getObjectKind() == OK_Ordinary); 15222 E->setType(DestType); 15223 15224 // Build the sub-expression as if it were an object of the pointee type. 15225 DestType = Ptr->getPointeeType(); 15226 ExprResult SubResult = Visit(E->getSubExpr()); 15227 if (SubResult.isInvalid()) return ExprError(); 15228 E->setSubExpr(SubResult.get()); 15229 return E; 15230 } 15231 15232 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15233 15234 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15235 15236 ExprResult VisitMemberExpr(MemberExpr *E) { 15237 return resolveDecl(E, E->getMemberDecl()); 15238 } 15239 15240 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15241 return resolveDecl(E, E->getDecl()); 15242 } 15243 }; 15244 } 15245 15246 /// Rebuilds a call expression which yielded __unknown_anytype. 15247 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15248 Expr *CalleeExpr = E->getCallee(); 15249 15250 enum FnKind { 15251 FK_MemberFunction, 15252 FK_FunctionPointer, 15253 FK_BlockPointer 15254 }; 15255 15256 FnKind Kind; 15257 QualType CalleeType = CalleeExpr->getType(); 15258 if (CalleeType == S.Context.BoundMemberTy) { 15259 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15260 Kind = FK_MemberFunction; 15261 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15262 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15263 CalleeType = Ptr->getPointeeType(); 15264 Kind = FK_FunctionPointer; 15265 } else { 15266 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15267 Kind = FK_BlockPointer; 15268 } 15269 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15270 15271 // Verify that this is a legal result type of a function. 15272 if (DestType->isArrayType() || DestType->isFunctionType()) { 15273 unsigned diagID = diag::err_func_returning_array_function; 15274 if (Kind == FK_BlockPointer) 15275 diagID = diag::err_block_returning_array_function; 15276 15277 S.Diag(E->getExprLoc(), diagID) 15278 << DestType->isFunctionType() << DestType; 15279 return ExprError(); 15280 } 15281 15282 // Otherwise, go ahead and set DestType as the call's result. 15283 E->setType(DestType.getNonLValueExprType(S.Context)); 15284 E->setValueKind(Expr::getValueKindForType(DestType)); 15285 assert(E->getObjectKind() == OK_Ordinary); 15286 15287 // Rebuild the function type, replacing the result type with DestType. 15288 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15289 if (Proto) { 15290 // __unknown_anytype(...) is a special case used by the debugger when 15291 // it has no idea what a function's signature is. 15292 // 15293 // We want to build this call essentially under the K&R 15294 // unprototyped rules, but making a FunctionNoProtoType in C++ 15295 // would foul up all sorts of assumptions. However, we cannot 15296 // simply pass all arguments as variadic arguments, nor can we 15297 // portably just call the function under a non-variadic type; see 15298 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15299 // However, it turns out that in practice it is generally safe to 15300 // call a function declared as "A foo(B,C,D);" under the prototype 15301 // "A foo(B,C,D,...);". The only known exception is with the 15302 // Windows ABI, where any variadic function is implicitly cdecl 15303 // regardless of its normal CC. Therefore we change the parameter 15304 // types to match the types of the arguments. 15305 // 15306 // This is a hack, but it is far superior to moving the 15307 // corresponding target-specific code from IR-gen to Sema/AST. 15308 15309 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15310 SmallVector<QualType, 8> ArgTypes; 15311 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15312 ArgTypes.reserve(E->getNumArgs()); 15313 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15314 Expr *Arg = E->getArg(i); 15315 QualType ArgType = Arg->getType(); 15316 if (E->isLValue()) { 15317 ArgType = S.Context.getLValueReferenceType(ArgType); 15318 } else if (E->isXValue()) { 15319 ArgType = S.Context.getRValueReferenceType(ArgType); 15320 } 15321 ArgTypes.push_back(ArgType); 15322 } 15323 ParamTypes = ArgTypes; 15324 } 15325 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15326 Proto->getExtProtoInfo()); 15327 } else { 15328 DestType = S.Context.getFunctionNoProtoType(DestType, 15329 FnType->getExtInfo()); 15330 } 15331 15332 // Rebuild the appropriate pointer-to-function type. 15333 switch (Kind) { 15334 case FK_MemberFunction: 15335 // Nothing to do. 15336 break; 15337 15338 case FK_FunctionPointer: 15339 DestType = S.Context.getPointerType(DestType); 15340 break; 15341 15342 case FK_BlockPointer: 15343 DestType = S.Context.getBlockPointerType(DestType); 15344 break; 15345 } 15346 15347 // Finally, we can recurse. 15348 ExprResult CalleeResult = Visit(CalleeExpr); 15349 if (!CalleeResult.isUsable()) return ExprError(); 15350 E->setCallee(CalleeResult.get()); 15351 15352 // Bind a temporary if necessary. 15353 return S.MaybeBindToTemporary(E); 15354 } 15355 15356 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15357 // Verify that this is a legal result type of a call. 15358 if (DestType->isArrayType() || DestType->isFunctionType()) { 15359 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15360 << DestType->isFunctionType() << DestType; 15361 return ExprError(); 15362 } 15363 15364 // Rewrite the method result type if available. 15365 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15366 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15367 Method->setReturnType(DestType); 15368 } 15369 15370 // Change the type of the message. 15371 E->setType(DestType.getNonReferenceType()); 15372 E->setValueKind(Expr::getValueKindForType(DestType)); 15373 15374 return S.MaybeBindToTemporary(E); 15375 } 15376 15377 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15378 // The only case we should ever see here is a function-to-pointer decay. 15379 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15380 assert(E->getValueKind() == VK_RValue); 15381 assert(E->getObjectKind() == OK_Ordinary); 15382 15383 E->setType(DestType); 15384 15385 // Rebuild the sub-expression as the pointee (function) type. 15386 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15387 15388 ExprResult Result = Visit(E->getSubExpr()); 15389 if (!Result.isUsable()) return ExprError(); 15390 15391 E->setSubExpr(Result.get()); 15392 return E; 15393 } else if (E->getCastKind() == CK_LValueToRValue) { 15394 assert(E->getValueKind() == VK_RValue); 15395 assert(E->getObjectKind() == OK_Ordinary); 15396 15397 assert(isa<BlockPointerType>(E->getType())); 15398 15399 E->setType(DestType); 15400 15401 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15402 DestType = S.Context.getLValueReferenceType(DestType); 15403 15404 ExprResult Result = Visit(E->getSubExpr()); 15405 if (!Result.isUsable()) return ExprError(); 15406 15407 E->setSubExpr(Result.get()); 15408 return E; 15409 } else { 15410 llvm_unreachable("Unhandled cast type!"); 15411 } 15412 } 15413 15414 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15415 ExprValueKind ValueKind = VK_LValue; 15416 QualType Type = DestType; 15417 15418 // We know how to make this work for certain kinds of decls: 15419 15420 // - functions 15421 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15422 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15423 DestType = Ptr->getPointeeType(); 15424 ExprResult Result = resolveDecl(E, VD); 15425 if (Result.isInvalid()) return ExprError(); 15426 return S.ImpCastExprToType(Result.get(), Type, 15427 CK_FunctionToPointerDecay, VK_RValue); 15428 } 15429 15430 if (!Type->isFunctionType()) { 15431 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15432 << VD << E->getSourceRange(); 15433 return ExprError(); 15434 } 15435 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15436 // We must match the FunctionDecl's type to the hack introduced in 15437 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15438 // type. See the lengthy commentary in that routine. 15439 QualType FDT = FD->getType(); 15440 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15441 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15442 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15443 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15444 SourceLocation Loc = FD->getLocation(); 15445 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15446 FD->getDeclContext(), 15447 Loc, Loc, FD->getNameInfo().getName(), 15448 DestType, FD->getTypeSourceInfo(), 15449 SC_None, false/*isInlineSpecified*/, 15450 FD->hasPrototype(), 15451 false/*isConstexprSpecified*/); 15452 15453 if (FD->getQualifier()) 15454 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15455 15456 SmallVector<ParmVarDecl*, 16> Params; 15457 for (const auto &AI : FT->param_types()) { 15458 ParmVarDecl *Param = 15459 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15460 Param->setScopeInfo(0, Params.size()); 15461 Params.push_back(Param); 15462 } 15463 NewFD->setParams(Params); 15464 DRE->setDecl(NewFD); 15465 VD = DRE->getDecl(); 15466 } 15467 } 15468 15469 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15470 if (MD->isInstance()) { 15471 ValueKind = VK_RValue; 15472 Type = S.Context.BoundMemberTy; 15473 } 15474 15475 // Function references aren't l-values in C. 15476 if (!S.getLangOpts().CPlusPlus) 15477 ValueKind = VK_RValue; 15478 15479 // - variables 15480 } else if (isa<VarDecl>(VD)) { 15481 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15482 Type = RefTy->getPointeeType(); 15483 } else if (Type->isFunctionType()) { 15484 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15485 << VD << E->getSourceRange(); 15486 return ExprError(); 15487 } 15488 15489 // - nothing else 15490 } else { 15491 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15492 << VD << E->getSourceRange(); 15493 return ExprError(); 15494 } 15495 15496 // Modifying the declaration like this is friendly to IR-gen but 15497 // also really dangerous. 15498 VD->setType(DestType); 15499 E->setType(Type); 15500 E->setValueKind(ValueKind); 15501 return E; 15502 } 15503 15504 /// Check a cast of an unknown-any type. We intentionally only 15505 /// trigger this for C-style casts. 15506 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15507 Expr *CastExpr, CastKind &CastKind, 15508 ExprValueKind &VK, CXXCastPath &Path) { 15509 // The type we're casting to must be either void or complete. 15510 if (!CastType->isVoidType() && 15511 RequireCompleteType(TypeRange.getBegin(), CastType, 15512 diag::err_typecheck_cast_to_incomplete)) 15513 return ExprError(); 15514 15515 // Rewrite the casted expression from scratch. 15516 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15517 if (!result.isUsable()) return ExprError(); 15518 15519 CastExpr = result.get(); 15520 VK = CastExpr->getValueKind(); 15521 CastKind = CK_NoOp; 15522 15523 return CastExpr; 15524 } 15525 15526 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15527 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15528 } 15529 15530 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15531 Expr *arg, QualType ¶mType) { 15532 // If the syntactic form of the argument is not an explicit cast of 15533 // any sort, just do default argument promotion. 15534 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15535 if (!castArg) { 15536 ExprResult result = DefaultArgumentPromotion(arg); 15537 if (result.isInvalid()) return ExprError(); 15538 paramType = result.get()->getType(); 15539 return result; 15540 } 15541 15542 // Otherwise, use the type that was written in the explicit cast. 15543 assert(!arg->hasPlaceholderType()); 15544 paramType = castArg->getTypeAsWritten(); 15545 15546 // Copy-initialize a parameter of that type. 15547 InitializedEntity entity = 15548 InitializedEntity::InitializeParameter(Context, paramType, 15549 /*consumed*/ false); 15550 return PerformCopyInitialization(entity, callLoc, arg); 15551 } 15552 15553 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15554 Expr *orig = E; 15555 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15556 while (true) { 15557 E = E->IgnoreParenImpCasts(); 15558 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15559 E = call->getCallee(); 15560 diagID = diag::err_uncasted_call_of_unknown_any; 15561 } else { 15562 break; 15563 } 15564 } 15565 15566 SourceLocation loc; 15567 NamedDecl *d; 15568 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15569 loc = ref->getLocation(); 15570 d = ref->getDecl(); 15571 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15572 loc = mem->getMemberLoc(); 15573 d = mem->getMemberDecl(); 15574 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15575 diagID = diag::err_uncasted_call_of_unknown_any; 15576 loc = msg->getSelectorStartLoc(); 15577 d = msg->getMethodDecl(); 15578 if (!d) { 15579 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15580 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15581 << orig->getSourceRange(); 15582 return ExprError(); 15583 } 15584 } else { 15585 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15586 << E->getSourceRange(); 15587 return ExprError(); 15588 } 15589 15590 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15591 15592 // Never recoverable. 15593 return ExprError(); 15594 } 15595 15596 /// Check for operands with placeholder types and complain if found. 15597 /// Returns ExprError() if there was an error and no recovery was possible. 15598 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15599 if (!getLangOpts().CPlusPlus) { 15600 // C cannot handle TypoExpr nodes on either side of a binop because it 15601 // doesn't handle dependent types properly, so make sure any TypoExprs have 15602 // been dealt with before checking the operands. 15603 ExprResult Result = CorrectDelayedTyposInExpr(E); 15604 if (!Result.isUsable()) return ExprError(); 15605 E = Result.get(); 15606 } 15607 15608 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15609 if (!placeholderType) return E; 15610 15611 switch (placeholderType->getKind()) { 15612 15613 // Overloaded expressions. 15614 case BuiltinType::Overload: { 15615 // Try to resolve a single function template specialization. 15616 // This is obligatory. 15617 ExprResult Result = E; 15618 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15619 return Result; 15620 15621 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15622 // leaves Result unchanged on failure. 15623 Result = E; 15624 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15625 return Result; 15626 15627 // If that failed, try to recover with a call. 15628 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15629 /*complain*/ true); 15630 return Result; 15631 } 15632 15633 // Bound member functions. 15634 case BuiltinType::BoundMember: { 15635 ExprResult result = E; 15636 const Expr *BME = E->IgnoreParens(); 15637 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15638 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15639 if (isa<CXXPseudoDestructorExpr>(BME)) { 15640 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15641 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15642 if (ME->getMemberNameInfo().getName().getNameKind() == 15643 DeclarationName::CXXDestructorName) 15644 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15645 } 15646 tryToRecoverWithCall(result, PD, 15647 /*complain*/ true); 15648 return result; 15649 } 15650 15651 // ARC unbridged casts. 15652 case BuiltinType::ARCUnbridgedCast: { 15653 Expr *realCast = stripARCUnbridgedCast(E); 15654 diagnoseARCUnbridgedCast(realCast); 15655 return realCast; 15656 } 15657 15658 // Expressions of unknown type. 15659 case BuiltinType::UnknownAny: 15660 return diagnoseUnknownAnyExpr(*this, E); 15661 15662 // Pseudo-objects. 15663 case BuiltinType::PseudoObject: 15664 return checkPseudoObjectRValue(E); 15665 15666 case BuiltinType::BuiltinFn: { 15667 // Accept __noop without parens by implicitly converting it to a call expr. 15668 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15669 if (DRE) { 15670 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15671 if (FD->getBuiltinID() == Builtin::BI__noop) { 15672 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15673 CK_BuiltinFnToFnPtr).get(); 15674 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15675 VK_RValue, SourceLocation()); 15676 } 15677 } 15678 15679 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15680 return ExprError(); 15681 } 15682 15683 // Expressions of unknown type. 15684 case BuiltinType::OMPArraySection: 15685 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15686 return ExprError(); 15687 15688 // Everything else should be impossible. 15689 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15690 case BuiltinType::Id: 15691 #include "clang/Basic/OpenCLImageTypes.def" 15692 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15693 #define PLACEHOLDER_TYPE(Id, SingletonId) 15694 #include "clang/AST/BuiltinTypes.def" 15695 break; 15696 } 15697 15698 llvm_unreachable("invalid placeholder type!"); 15699 } 15700 15701 bool Sema::CheckCaseExpression(Expr *E) { 15702 if (E->isTypeDependent()) 15703 return true; 15704 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15705 return E->getType()->isIntegralOrEnumerationType(); 15706 return false; 15707 } 15708 15709 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15710 ExprResult 15711 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15712 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15713 "Unknown Objective-C Boolean value!"); 15714 QualType BoolT = Context.ObjCBuiltinBoolTy; 15715 if (!Context.getBOOLDecl()) { 15716 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15717 Sema::LookupOrdinaryName); 15718 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15719 NamedDecl *ND = Result.getFoundDecl(); 15720 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15721 Context.setBOOLDecl(TD); 15722 } 15723 } 15724 if (Context.getBOOLDecl()) 15725 BoolT = Context.getBOOLType(); 15726 return new (Context) 15727 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15728 } 15729 15730 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15731 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15732 SourceLocation RParen) { 15733 15734 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15735 15736 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15737 [&](const AvailabilitySpec &Spec) { 15738 return Spec.getPlatform() == Platform; 15739 }); 15740 15741 VersionTuple Version; 15742 if (Spec != AvailSpecs.end()) 15743 Version = Spec->getVersion(); 15744 15745 return new (Context) 15746 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15747 } 15748