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 && S.getCurFunctionOrMethodDecl()) { 175 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 176 return; 177 } 178 179 const ObjCPropertyDecl *ObjCPDecl = nullptr; 180 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 181 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 182 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 183 if (PDeclResult == Result) 184 ObjCPDecl = PD; 185 } 186 } 187 188 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass, 189 ObjCPDecl, ObjCPropertyAccess); 190 } 191 } 192 193 /// \brief Emit a note explaining that this function is deleted. 194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 195 assert(Decl->isDeleted()); 196 197 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 198 199 if (Method && Method->isDeleted() && Method->isDefaulted()) { 200 // If the method was explicitly defaulted, point at that declaration. 201 if (!Method->isImplicit()) 202 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 203 204 // Try to diagnose why this special member function was implicitly 205 // deleted. This might fail, if that reason no longer applies. 206 CXXSpecialMember CSM = getSpecialMember(Method); 207 if (CSM != CXXInvalid) 208 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 209 210 return; 211 } 212 213 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 214 if (Ctor && Ctor->isInheritingConstructor()) 215 return NoteDeletedInheritingConstructor(Ctor); 216 217 Diag(Decl->getLocation(), diag::note_availability_specified_here) 218 << Decl << true; 219 } 220 221 /// \brief Determine whether a FunctionDecl was ever declared with an 222 /// explicit storage class. 223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 224 for (auto I : D->redecls()) { 225 if (I->getStorageClass() != SC_None) 226 return true; 227 } 228 return false; 229 } 230 231 /// \brief Check whether we're in an extern inline function and referring to a 232 /// variable or function with internal linkage (C11 6.7.4p3). 233 /// 234 /// This is only a warning because we used to silently accept this code, but 235 /// in many cases it will not behave correctly. This is not enabled in C++ mode 236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 237 /// and so while there may still be user mistakes, most of the time we can't 238 /// prove that there are errors. 239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 240 const NamedDecl *D, 241 SourceLocation Loc) { 242 // This is disabled under C++; there are too many ways for this to fire in 243 // contexts where the warning is a false positive, or where it is technically 244 // correct but benign. 245 if (S.getLangOpts().CPlusPlus) 246 return; 247 248 // Check if this is an inlined function or method. 249 FunctionDecl *Current = S.getCurFunctionDecl(); 250 if (!Current) 251 return; 252 if (!Current->isInlined()) 253 return; 254 if (!Current->isExternallyVisible()) 255 return; 256 257 // Check if the decl has internal linkage. 258 if (D->getFormalLinkage() != InternalLinkage) 259 return; 260 261 // Downgrade from ExtWarn to Extension if 262 // (1) the supposedly external inline function is in the main file, 263 // and probably won't be included anywhere else. 264 // (2) the thing we're referencing is a pure function. 265 // (3) the thing we're referencing is another inline function. 266 // This last can give us false negatives, but it's better than warning on 267 // wrappers for simple C library functions. 268 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 269 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 270 if (!DowngradeWarning && UsedFn) 271 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 272 273 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 274 : diag::ext_internal_in_extern_inline) 275 << /*IsVar=*/!UsedFn << D; 276 277 S.MaybeSuggestAddingStaticToDecl(Current); 278 279 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 280 << D; 281 } 282 283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 284 const FunctionDecl *First = Cur->getFirstDecl(); 285 286 // Suggest "static" on the function, if possible. 287 if (!hasAnyExplicitStorageClass(First)) { 288 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 289 Diag(DeclBegin, diag::note_convert_inline_to_static) 290 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 291 } 292 } 293 294 /// \brief Determine whether the use of this declaration is valid, and 295 /// emit any corresponding diagnostics. 296 /// 297 /// This routine diagnoses various problems with referencing 298 /// declarations that can occur when using a declaration. For example, 299 /// it might warn if a deprecated or unavailable declaration is being 300 /// used, or produce an error (and return true) if a C++0x deleted 301 /// function is being used. 302 /// 303 /// \returns true if there was an error (this declaration cannot be 304 /// referenced), false otherwise. 305 /// 306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 307 const ObjCInterfaceDecl *UnknownObjCClass, 308 bool ObjCPropertyAccess) { 309 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 310 // If there were any diagnostics suppressed by template argument deduction, 311 // emit them now. 312 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 313 if (Pos != SuppressedDiagnostics.end()) { 314 for (const PartialDiagnosticAt &Suppressed : Pos->second) 315 Diag(Suppressed.first, Suppressed.second); 316 317 // Clear out the list of suppressed diagnostics, so that we don't emit 318 // them again for this specialization. However, we don't obsolete this 319 // entry from the table, because we want to avoid ever emitting these 320 // diagnostics again. 321 Pos->second.clear(); 322 } 323 324 // C++ [basic.start.main]p3: 325 // The function 'main' shall not be used within a program. 326 if (cast<FunctionDecl>(D)->isMain()) 327 Diag(Loc, diag::ext_main_used); 328 } 329 330 // See if this is an auto-typed variable whose initializer we are parsing. 331 if (ParsingInitForAutoVars.count(D)) { 332 if (isa<BindingDecl>(D)) { 333 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 334 << D->getDeclName(); 335 } else { 336 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 337 338 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 339 << D->getDeclName() << (unsigned)AT->getKeyword(); 340 } 341 return true; 342 } 343 344 // See if this is a deleted function. 345 SmallVector<DiagnoseIfAttr *, 4> DiagnoseIfWarnings; 346 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 347 if (FD->isDeleted()) { 348 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 349 if (Ctor && Ctor->isInheritingConstructor()) 350 Diag(Loc, diag::err_deleted_inherited_ctor_use) 351 << Ctor->getParent() 352 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 353 else 354 Diag(Loc, diag::err_deleted_function_use); 355 NoteDeletedFunction(FD); 356 return true; 357 } 358 359 // If the function has a deduced return type, and we can't deduce it, 360 // then we can't use it either. 361 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 362 DeduceReturnType(FD, Loc)) 363 return true; 364 365 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 366 return true; 367 368 if (const DiagnoseIfAttr *A = 369 checkArgIndependentDiagnoseIf(FD, DiagnoseIfWarnings)) { 370 emitDiagnoseIfDiagnostic(Loc, A); 371 return true; 372 } 373 } 374 375 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 376 // Only the variables omp_in and omp_out are allowed in the combiner. 377 // Only the variables omp_priv and omp_orig are allowed in the 378 // initializer-clause. 379 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 380 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 381 isa<VarDecl>(D)) { 382 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 383 << getCurFunction()->HasOMPDeclareReductionCombiner; 384 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 385 return true; 386 } 387 388 for (const auto *W : DiagnoseIfWarnings) 389 emitDiagnoseIfDiagnostic(Loc, W); 390 391 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 392 ObjCPropertyAccess); 393 394 DiagnoseUnusedOfDecl(*this, D, Loc); 395 396 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 397 398 return false; 399 } 400 401 /// \brief Retrieve the message suffix that should be added to a 402 /// diagnostic complaining about the given function being deleted or 403 /// unavailable. 404 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 405 std::string Message; 406 if (FD->getAvailability(&Message)) 407 return ": " + Message; 408 409 return std::string(); 410 } 411 412 /// DiagnoseSentinelCalls - This routine checks whether a call or 413 /// message-send is to a declaration with the sentinel attribute, and 414 /// if so, it checks that the requirements of the sentinel are 415 /// satisfied. 416 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 417 ArrayRef<Expr *> Args) { 418 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 419 if (!attr) 420 return; 421 422 // The number of formal parameters of the declaration. 423 unsigned numFormalParams; 424 425 // The kind of declaration. This is also an index into a %select in 426 // the diagnostic. 427 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 428 429 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 430 numFormalParams = MD->param_size(); 431 calleeType = CT_Method; 432 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 433 numFormalParams = FD->param_size(); 434 calleeType = CT_Function; 435 } else if (isa<VarDecl>(D)) { 436 QualType type = cast<ValueDecl>(D)->getType(); 437 const FunctionType *fn = nullptr; 438 if (const PointerType *ptr = type->getAs<PointerType>()) { 439 fn = ptr->getPointeeType()->getAs<FunctionType>(); 440 if (!fn) return; 441 calleeType = CT_Function; 442 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 443 fn = ptr->getPointeeType()->castAs<FunctionType>(); 444 calleeType = CT_Block; 445 } else { 446 return; 447 } 448 449 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 450 numFormalParams = proto->getNumParams(); 451 } else { 452 numFormalParams = 0; 453 } 454 } else { 455 return; 456 } 457 458 // "nullPos" is the number of formal parameters at the end which 459 // effectively count as part of the variadic arguments. This is 460 // useful if you would prefer to not have *any* formal parameters, 461 // but the language forces you to have at least one. 462 unsigned nullPos = attr->getNullPos(); 463 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 464 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 465 466 // The number of arguments which should follow the sentinel. 467 unsigned numArgsAfterSentinel = attr->getSentinel(); 468 469 // If there aren't enough arguments for all the formal parameters, 470 // the sentinel, and the args after the sentinel, complain. 471 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 472 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 473 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 474 return; 475 } 476 477 // Otherwise, find the sentinel expression. 478 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 479 if (!sentinelExpr) return; 480 if (sentinelExpr->isValueDependent()) return; 481 if (Context.isSentinelNullExpr(sentinelExpr)) return; 482 483 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 484 // or 'NULL' if those are actually defined in the context. Only use 485 // 'nil' for ObjC methods, where it's much more likely that the 486 // variadic arguments form a list of object pointers. 487 SourceLocation MissingNilLoc 488 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 489 std::string NullValue; 490 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 491 NullValue = "nil"; 492 else if (getLangOpts().CPlusPlus11) 493 NullValue = "nullptr"; 494 else if (PP.isMacroDefined("NULL")) 495 NullValue = "NULL"; 496 else 497 NullValue = "(void*) 0"; 498 499 if (MissingNilLoc.isInvalid()) 500 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 501 else 502 Diag(MissingNilLoc, diag::warn_missing_sentinel) 503 << int(calleeType) 504 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 505 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 506 } 507 508 SourceRange Sema::getExprRange(Expr *E) const { 509 return E ? E->getSourceRange() : SourceRange(); 510 } 511 512 //===----------------------------------------------------------------------===// 513 // Standard Promotions and Conversions 514 //===----------------------------------------------------------------------===// 515 516 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 517 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 518 // Handle any placeholder expressions which made it here. 519 if (E->getType()->isPlaceholderType()) { 520 ExprResult result = CheckPlaceholderExpr(E); 521 if (result.isInvalid()) return ExprError(); 522 E = result.get(); 523 } 524 525 QualType Ty = E->getType(); 526 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 527 528 if (Ty->isFunctionType()) { 529 // If we are here, we are not calling a function but taking 530 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 531 if (getLangOpts().OpenCL) { 532 if (Diagnose) 533 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 534 return ExprError(); 535 } 536 537 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 538 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 539 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 540 return ExprError(); 541 542 E = ImpCastExprToType(E, Context.getPointerType(Ty), 543 CK_FunctionToPointerDecay).get(); 544 } else if (Ty->isArrayType()) { 545 // In C90 mode, arrays only promote to pointers if the array expression is 546 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 547 // type 'array of type' is converted to an expression that has type 'pointer 548 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 549 // that has type 'array of type' ...". The relevant change is "an lvalue" 550 // (C90) to "an expression" (C99). 551 // 552 // C++ 4.2p1: 553 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 554 // T" can be converted to an rvalue of type "pointer to T". 555 // 556 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 557 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 558 CK_ArrayToPointerDecay).get(); 559 } 560 return E; 561 } 562 563 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 564 // Check to see if we are dereferencing a null pointer. If so, 565 // and if not volatile-qualified, this is undefined behavior that the 566 // optimizer will delete, so warn about it. People sometimes try to use this 567 // to get a deterministic trap and are surprised by clang's behavior. This 568 // only handles the pattern "*null", which is a very syntactic check. 569 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 570 if (UO->getOpcode() == UO_Deref && 571 UO->getSubExpr()->IgnoreParenCasts()-> 572 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 573 !UO->getType().isVolatileQualified()) { 574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 575 S.PDiag(diag::warn_indirection_through_null) 576 << UO->getSubExpr()->getSourceRange()); 577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 578 S.PDiag(diag::note_indirection_through_null)); 579 } 580 } 581 582 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 583 SourceLocation AssignLoc, 584 const Expr* RHS) { 585 const ObjCIvarDecl *IV = OIRE->getDecl(); 586 if (!IV) 587 return; 588 589 DeclarationName MemberName = IV->getDeclName(); 590 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 591 if (!Member || !Member->isStr("isa")) 592 return; 593 594 const Expr *Base = OIRE->getBase(); 595 QualType BaseType = Base->getType(); 596 if (OIRE->isArrow()) 597 BaseType = BaseType->getPointeeType(); 598 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 599 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 600 ObjCInterfaceDecl *ClassDeclared = nullptr; 601 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 602 if (!ClassDeclared->getSuperClass() 603 && (*ClassDeclared->ivar_begin()) == IV) { 604 if (RHS) { 605 NamedDecl *ObjectSetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_setClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectSetClass) { 610 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 611 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 612 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 613 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 614 AssignLoc), ",") << 615 FixItHint::CreateInsertion(RHSLocEnd, ")"); 616 } 617 else 618 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 619 } else { 620 NamedDecl *ObjectGetClass = 621 S.LookupSingleName(S.TUScope, 622 &S.Context.Idents.get("object_getClass"), 623 SourceLocation(), S.LookupOrdinaryName); 624 if (ObjectGetClass) 625 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 626 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 627 FixItHint::CreateReplacement( 628 SourceRange(OIRE->getOpLoc(), 629 OIRE->getLocEnd()), ")"); 630 else 631 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 632 } 633 S.Diag(IV->getLocation(), diag::note_ivar_decl); 634 } 635 } 636 } 637 638 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 639 // Handle any placeholder expressions which made it here. 640 if (E->getType()->isPlaceholderType()) { 641 ExprResult result = CheckPlaceholderExpr(E); 642 if (result.isInvalid()) return ExprError(); 643 E = result.get(); 644 } 645 646 // C++ [conv.lval]p1: 647 // A glvalue of a non-function, non-array type T can be 648 // converted to a prvalue. 649 if (!E->isGLValue()) return E; 650 651 QualType T = E->getType(); 652 assert(!T.isNull() && "r-value conversion on typeless expression?"); 653 654 // We don't want to throw lvalue-to-rvalue casts on top of 655 // expressions of certain types in C++. 656 if (getLangOpts().CPlusPlus && 657 (E->getType() == Context.OverloadTy || 658 T->isDependentType() || 659 T->isRecordType())) 660 return E; 661 662 // The C standard is actually really unclear on this point, and 663 // DR106 tells us what the result should be but not why. It's 664 // generally best to say that void types just doesn't undergo 665 // lvalue-to-rvalue at all. Note that expressions of unqualified 666 // 'void' type are never l-values, but qualified void can be. 667 if (T->isVoidType()) 668 return E; 669 670 // OpenCL usually rejects direct accesses to values of 'half' type. 671 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 672 T->isHalfType()) { 673 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 674 << 0 << T; 675 return ExprError(); 676 } 677 678 CheckForNullPointerDereference(*this, E); 679 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 680 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 681 &Context.Idents.get("object_getClass"), 682 SourceLocation(), LookupOrdinaryName); 683 if (ObjectGetClass) 684 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 685 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 686 FixItHint::CreateReplacement( 687 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 688 else 689 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 690 } 691 else if (const ObjCIvarRefExpr *OIRE = 692 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 693 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 694 695 // C++ [conv.lval]p1: 696 // [...] If T is a non-class type, the type of the prvalue is the 697 // cv-unqualified version of T. Otherwise, the type of the 698 // rvalue is T. 699 // 700 // C99 6.3.2.1p2: 701 // If the lvalue has qualified type, the value has the unqualified 702 // version of the type of the lvalue; otherwise, the value has the 703 // type of the lvalue. 704 if (T.hasQualifiers()) 705 T = T.getUnqualifiedType(); 706 707 // Under the MS ABI, lock down the inheritance model now. 708 if (T->isMemberPointerType() && 709 Context.getTargetInfo().getCXXABI().isMicrosoft()) 710 (void)isCompleteType(E->getExprLoc(), T); 711 712 UpdateMarkingForLValueToRValue(E); 713 714 // Loading a __weak object implicitly retains the value, so we need a cleanup to 715 // balance that. 716 if (getLangOpts().ObjCAutoRefCount && 717 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 718 Cleanup.setExprNeedsCleanups(true); 719 720 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 721 nullptr, VK_RValue); 722 723 // C11 6.3.2.1p2: 724 // ... if the lvalue has atomic type, the value has the non-atomic version 725 // of the type of the lvalue ... 726 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 727 T = Atomic->getValueType().getUnqualifiedType(); 728 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 729 nullptr, VK_RValue); 730 } 731 732 return Res; 733 } 734 735 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 736 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 737 if (Res.isInvalid()) 738 return ExprError(); 739 Res = DefaultLvalueConversion(Res.get()); 740 if (Res.isInvalid()) 741 return ExprError(); 742 return Res; 743 } 744 745 /// CallExprUnaryConversions - a special case of an unary conversion 746 /// performed on a function designator of a call expression. 747 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 748 QualType Ty = E->getType(); 749 ExprResult Res = E; 750 // Only do implicit cast for a function type, but not for a pointer 751 // to function type. 752 if (Ty->isFunctionType()) { 753 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 754 CK_FunctionToPointerDecay).get(); 755 if (Res.isInvalid()) 756 return ExprError(); 757 } 758 Res = DefaultLvalueConversion(Res.get()); 759 if (Res.isInvalid()) 760 return ExprError(); 761 return Res.get(); 762 } 763 764 /// UsualUnaryConversions - Performs various conversions that are common to most 765 /// operators (C99 6.3). The conversions of array and function types are 766 /// sometimes suppressed. For example, the array->pointer conversion doesn't 767 /// apply if the array is an argument to the sizeof or address (&) operators. 768 /// In these instances, this routine should *not* be called. 769 ExprResult Sema::UsualUnaryConversions(Expr *E) { 770 // First, convert to an r-value. 771 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 772 if (Res.isInvalid()) 773 return ExprError(); 774 E = Res.get(); 775 776 QualType Ty = E->getType(); 777 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 778 779 // Half FP have to be promoted to float unless it is natively supported 780 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 781 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 782 783 // Try to perform integral promotions if the object has a theoretically 784 // promotable type. 785 if (Ty->isIntegralOrUnscopedEnumerationType()) { 786 // C99 6.3.1.1p2: 787 // 788 // The following may be used in an expression wherever an int or 789 // unsigned int may be used: 790 // - an object or expression with an integer type whose integer 791 // conversion rank is less than or equal to the rank of int 792 // and unsigned int. 793 // - A bit-field of type _Bool, int, signed int, or unsigned int. 794 // 795 // If an int can represent all values of the original type, the 796 // value is converted to an int; otherwise, it is converted to an 797 // unsigned int. These are called the integer promotions. All 798 // other types are unchanged by the integer promotions. 799 800 QualType PTy = Context.isPromotableBitField(E); 801 if (!PTy.isNull()) { 802 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 803 return E; 804 } 805 if (Ty->isPromotableIntegerType()) { 806 QualType PT = Context.getPromotedIntegerType(Ty); 807 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 808 return E; 809 } 810 } 811 return E; 812 } 813 814 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 815 /// do not have a prototype. Arguments that have type float or __fp16 816 /// are promoted to double. All other argument types are converted by 817 /// UsualUnaryConversions(). 818 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 819 QualType Ty = E->getType(); 820 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 821 822 ExprResult Res = UsualUnaryConversions(E); 823 if (Res.isInvalid()) 824 return ExprError(); 825 E = Res.get(); 826 827 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 828 // double. 829 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 830 if (BTy && (BTy->getKind() == BuiltinType::Half || 831 BTy->getKind() == BuiltinType::Float)) { 832 if (getLangOpts().OpenCL && 833 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 834 if (BTy->getKind() == BuiltinType::Half) { 835 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 836 } 837 } else { 838 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 839 } 840 } 841 842 // C++ performs lvalue-to-rvalue conversion as a default argument 843 // promotion, even on class types, but note: 844 // C++11 [conv.lval]p2: 845 // When an lvalue-to-rvalue conversion occurs in an unevaluated 846 // operand or a subexpression thereof the value contained in the 847 // referenced object is not accessed. Otherwise, if the glvalue 848 // has a class type, the conversion copy-initializes a temporary 849 // of type T from the glvalue and the result of the conversion 850 // is a prvalue for the temporary. 851 // FIXME: add some way to gate this entire thing for correctness in 852 // potentially potentially evaluated contexts. 853 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 854 ExprResult Temp = PerformCopyInitialization( 855 InitializedEntity::InitializeTemporary(E->getType()), 856 E->getExprLoc(), E); 857 if (Temp.isInvalid()) 858 return ExprError(); 859 E = Temp.get(); 860 } 861 862 return E; 863 } 864 865 /// Determine the degree of POD-ness for an expression. 866 /// Incomplete types are considered POD, since this check can be performed 867 /// when we're in an unevaluated context. 868 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 869 if (Ty->isIncompleteType()) { 870 // C++11 [expr.call]p7: 871 // After these conversions, if the argument does not have arithmetic, 872 // enumeration, pointer, pointer to member, or class type, the program 873 // is ill-formed. 874 // 875 // Since we've already performed array-to-pointer and function-to-pointer 876 // decay, the only such type in C++ is cv void. This also handles 877 // initializer lists as variadic arguments. 878 if (Ty->isVoidType()) 879 return VAK_Invalid; 880 881 if (Ty->isObjCObjectType()) 882 return VAK_Invalid; 883 return VAK_Valid; 884 } 885 886 if (Ty.isCXX98PODType(Context)) 887 return VAK_Valid; 888 889 // C++11 [expr.call]p7: 890 // Passing a potentially-evaluated argument of class type (Clause 9) 891 // having a non-trivial copy constructor, a non-trivial move constructor, 892 // or a non-trivial destructor, with no corresponding parameter, 893 // is conditionally-supported with implementation-defined semantics. 894 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 895 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 896 if (!Record->hasNonTrivialCopyConstructor() && 897 !Record->hasNonTrivialMoveConstructor() && 898 !Record->hasNonTrivialDestructor()) 899 return VAK_ValidInCXX11; 900 901 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 902 return VAK_Valid; 903 904 if (Ty->isObjCObjectType()) 905 return VAK_Invalid; 906 907 if (getLangOpts().MSVCCompat) 908 return VAK_MSVCUndefined; 909 910 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 911 // permitted to reject them. We should consider doing so. 912 return VAK_Undefined; 913 } 914 915 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 916 // Don't allow one to pass an Objective-C interface to a vararg. 917 const QualType &Ty = E->getType(); 918 VarArgKind VAK = isValidVarArgType(Ty); 919 920 // Complain about passing non-POD types through varargs. 921 switch (VAK) { 922 case VAK_ValidInCXX11: 923 DiagRuntimeBehavior( 924 E->getLocStart(), nullptr, 925 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 926 << Ty << CT); 927 // Fall through. 928 case VAK_Valid: 929 if (Ty->isRecordType()) { 930 // This is unlikely to be what the user intended. If the class has a 931 // 'c_str' member function, the user probably meant to call that. 932 DiagRuntimeBehavior(E->getLocStart(), nullptr, 933 PDiag(diag::warn_pass_class_arg_to_vararg) 934 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 935 } 936 break; 937 938 case VAK_Undefined: 939 case VAK_MSVCUndefined: 940 DiagRuntimeBehavior( 941 E->getLocStart(), nullptr, 942 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 943 << getLangOpts().CPlusPlus11 << Ty << CT); 944 break; 945 946 case VAK_Invalid: 947 if (Ty->isObjCObjectType()) 948 DiagRuntimeBehavior( 949 E->getLocStart(), nullptr, 950 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 951 << Ty << CT); 952 else 953 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 954 << isa<InitListExpr>(E) << Ty << CT; 955 break; 956 } 957 } 958 959 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 960 /// will create a trap if the resulting type is not a POD type. 961 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 962 FunctionDecl *FDecl) { 963 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 964 // Strip the unbridged-cast placeholder expression off, if applicable. 965 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 966 (CT == VariadicMethod || 967 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 968 E = stripARCUnbridgedCast(E); 969 970 // Otherwise, do normal placeholder checking. 971 } else { 972 ExprResult ExprRes = CheckPlaceholderExpr(E); 973 if (ExprRes.isInvalid()) 974 return ExprError(); 975 E = ExprRes.get(); 976 } 977 } 978 979 ExprResult ExprRes = DefaultArgumentPromotion(E); 980 if (ExprRes.isInvalid()) 981 return ExprError(); 982 E = ExprRes.get(); 983 984 // Diagnostics regarding non-POD argument types are 985 // emitted along with format string checking in Sema::CheckFunctionCall(). 986 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 987 // Turn this into a trap. 988 CXXScopeSpec SS; 989 SourceLocation TemplateKWLoc; 990 UnqualifiedId Name; 991 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 992 E->getLocStart()); 993 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 994 Name, true, false); 995 if (TrapFn.isInvalid()) 996 return ExprError(); 997 998 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 999 E->getLocStart(), None, 1000 E->getLocEnd()); 1001 if (Call.isInvalid()) 1002 return ExprError(); 1003 1004 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 1005 Call.get(), E); 1006 if (Comma.isInvalid()) 1007 return ExprError(); 1008 return Comma.get(); 1009 } 1010 1011 if (!getLangOpts().CPlusPlus && 1012 RequireCompleteType(E->getExprLoc(), E->getType(), 1013 diag::err_call_incomplete_argument)) 1014 return ExprError(); 1015 1016 return E; 1017 } 1018 1019 /// \brief Converts an integer to complex float type. Helper function of 1020 /// UsualArithmeticConversions() 1021 /// 1022 /// \return false if the integer expression is an integer type and is 1023 /// successfully converted to the complex type. 1024 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1025 ExprResult &ComplexExpr, 1026 QualType IntTy, 1027 QualType ComplexTy, 1028 bool SkipCast) { 1029 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1030 if (SkipCast) return false; 1031 if (IntTy->isIntegerType()) { 1032 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1033 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1034 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1035 CK_FloatingRealToComplex); 1036 } else { 1037 assert(IntTy->isComplexIntegerType()); 1038 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1039 CK_IntegralComplexToFloatingComplex); 1040 } 1041 return false; 1042 } 1043 1044 /// \brief Handle arithmetic conversion with complex types. Helper function of 1045 /// UsualArithmeticConversions() 1046 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1047 ExprResult &RHS, QualType LHSType, 1048 QualType RHSType, 1049 bool IsCompAssign) { 1050 // if we have an integer operand, the result is the complex type. 1051 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1052 /*skipCast*/false)) 1053 return LHSType; 1054 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1055 /*skipCast*/IsCompAssign)) 1056 return RHSType; 1057 1058 // This handles complex/complex, complex/float, or float/complex. 1059 // When both operands are complex, the shorter operand is converted to the 1060 // type of the longer, and that is the type of the result. This corresponds 1061 // to what is done when combining two real floating-point operands. 1062 // The fun begins when size promotion occur across type domains. 1063 // From H&S 6.3.4: When one operand is complex and the other is a real 1064 // floating-point type, the less precise type is converted, within it's 1065 // real or complex domain, to the precision of the other type. For example, 1066 // when combining a "long double" with a "double _Complex", the 1067 // "double _Complex" is promoted to "long double _Complex". 1068 1069 // Compute the rank of the two types, regardless of whether they are complex. 1070 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1071 1072 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1073 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1074 QualType LHSElementType = 1075 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1076 QualType RHSElementType = 1077 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1078 1079 QualType ResultType = S.Context.getComplexType(LHSElementType); 1080 if (Order < 0) { 1081 // Promote the precision of the LHS if not an assignment. 1082 ResultType = S.Context.getComplexType(RHSElementType); 1083 if (!IsCompAssign) { 1084 if (LHSComplexType) 1085 LHS = 1086 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1087 else 1088 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1089 } 1090 } else if (Order > 0) { 1091 // Promote the precision of the RHS. 1092 if (RHSComplexType) 1093 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1094 else 1095 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1096 } 1097 return ResultType; 1098 } 1099 1100 /// \brief Hande arithmetic conversion from integer to float. Helper function 1101 /// of UsualArithmeticConversions() 1102 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1103 ExprResult &IntExpr, 1104 QualType FloatTy, QualType IntTy, 1105 bool ConvertFloat, bool ConvertInt) { 1106 if (IntTy->isIntegerType()) { 1107 if (ConvertInt) 1108 // Convert intExpr to the lhs floating point type. 1109 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1110 CK_IntegralToFloating); 1111 return FloatTy; 1112 } 1113 1114 // Convert both sides to the appropriate complex float. 1115 assert(IntTy->isComplexIntegerType()); 1116 QualType result = S.Context.getComplexType(FloatTy); 1117 1118 // _Complex int -> _Complex float 1119 if (ConvertInt) 1120 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1121 CK_IntegralComplexToFloatingComplex); 1122 1123 // float -> _Complex float 1124 if (ConvertFloat) 1125 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1126 CK_FloatingRealToComplex); 1127 1128 return result; 1129 } 1130 1131 /// \brief Handle arithmethic conversion with floating point types. Helper 1132 /// function of UsualArithmeticConversions() 1133 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1134 ExprResult &RHS, QualType LHSType, 1135 QualType RHSType, bool IsCompAssign) { 1136 bool LHSFloat = LHSType->isRealFloatingType(); 1137 bool RHSFloat = RHSType->isRealFloatingType(); 1138 1139 // If we have two real floating types, convert the smaller operand 1140 // to the bigger result. 1141 if (LHSFloat && RHSFloat) { 1142 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1143 if (order > 0) { 1144 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1145 return LHSType; 1146 } 1147 1148 assert(order < 0 && "illegal float comparison"); 1149 if (!IsCompAssign) 1150 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1151 return RHSType; 1152 } 1153 1154 if (LHSFloat) { 1155 // Half FP has to be promoted to float unless it is natively supported 1156 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1157 LHSType = S.Context.FloatTy; 1158 1159 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1160 /*convertFloat=*/!IsCompAssign, 1161 /*convertInt=*/ true); 1162 } 1163 assert(RHSFloat); 1164 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1165 /*convertInt=*/ true, 1166 /*convertFloat=*/!IsCompAssign); 1167 } 1168 1169 /// \brief Diagnose attempts to convert between __float128 and long double if 1170 /// there is no support for such conversion. Helper function of 1171 /// UsualArithmeticConversions(). 1172 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1173 QualType RHSType) { 1174 /* No issue converting if at least one of the types is not a floating point 1175 type or the two types have the same rank. 1176 */ 1177 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1178 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1179 return false; 1180 1181 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1182 "The remaining types must be floating point types."); 1183 1184 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1185 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1186 1187 QualType LHSElemType = LHSComplex ? 1188 LHSComplex->getElementType() : LHSType; 1189 QualType RHSElemType = RHSComplex ? 1190 RHSComplex->getElementType() : RHSType; 1191 1192 // No issue if the two types have the same representation 1193 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1194 &S.Context.getFloatTypeSemantics(RHSElemType)) 1195 return false; 1196 1197 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1198 RHSElemType == S.Context.LongDoubleTy); 1199 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1200 RHSElemType == S.Context.Float128Ty); 1201 1202 /* We've handled the situation where __float128 and long double have the same 1203 representation. The only other allowable conversion is if long double is 1204 really just double. 1205 */ 1206 return Float128AndLongDouble && 1207 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1208 &llvm::APFloat::IEEEdouble()); 1209 } 1210 1211 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1212 1213 namespace { 1214 /// These helper callbacks are placed in an anonymous namespace to 1215 /// permit their use as function template parameters. 1216 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1217 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1218 } 1219 1220 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1221 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1222 CK_IntegralComplexCast); 1223 } 1224 } 1225 1226 /// \brief Handle integer arithmetic conversions. Helper function of 1227 /// UsualArithmeticConversions() 1228 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1229 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1230 ExprResult &RHS, QualType LHSType, 1231 QualType RHSType, bool IsCompAssign) { 1232 // The rules for this case are in C99 6.3.1.8 1233 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1234 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1235 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1236 if (LHSSigned == RHSSigned) { 1237 // Same signedness; use the higher-ranked type 1238 if (order >= 0) { 1239 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1240 return LHSType; 1241 } else if (!IsCompAssign) 1242 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1243 return RHSType; 1244 } else if (order != (LHSSigned ? 1 : -1)) { 1245 // The unsigned type has greater than or equal rank to the 1246 // signed type, so use the unsigned type 1247 if (RHSSigned) { 1248 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1249 return LHSType; 1250 } else if (!IsCompAssign) 1251 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1252 return RHSType; 1253 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1254 // The two types are different widths; if we are here, that 1255 // means the signed type is larger than the unsigned type, so 1256 // use the signed type. 1257 if (LHSSigned) { 1258 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1259 return LHSType; 1260 } else if (!IsCompAssign) 1261 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1262 return RHSType; 1263 } else { 1264 // The signed type is higher-ranked than the unsigned type, 1265 // but isn't actually any bigger (like unsigned int and long 1266 // on most 32-bit systems). Use the unsigned type corresponding 1267 // to the signed type. 1268 QualType result = 1269 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1270 RHS = (*doRHSCast)(S, RHS.get(), result); 1271 if (!IsCompAssign) 1272 LHS = (*doLHSCast)(S, LHS.get(), result); 1273 return result; 1274 } 1275 } 1276 1277 /// \brief Handle conversions with GCC complex int extension. Helper function 1278 /// of UsualArithmeticConversions() 1279 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1280 ExprResult &RHS, QualType LHSType, 1281 QualType RHSType, 1282 bool IsCompAssign) { 1283 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1284 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1285 1286 if (LHSComplexInt && RHSComplexInt) { 1287 QualType LHSEltType = LHSComplexInt->getElementType(); 1288 QualType RHSEltType = RHSComplexInt->getElementType(); 1289 QualType ScalarType = 1290 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1291 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1292 1293 return S.Context.getComplexType(ScalarType); 1294 } 1295 1296 if (LHSComplexInt) { 1297 QualType LHSEltType = LHSComplexInt->getElementType(); 1298 QualType ScalarType = 1299 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1300 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1301 QualType ComplexType = S.Context.getComplexType(ScalarType); 1302 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1303 CK_IntegralRealToComplex); 1304 1305 return ComplexType; 1306 } 1307 1308 assert(RHSComplexInt); 1309 1310 QualType RHSEltType = RHSComplexInt->getElementType(); 1311 QualType ScalarType = 1312 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1313 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1314 QualType ComplexType = S.Context.getComplexType(ScalarType); 1315 1316 if (!IsCompAssign) 1317 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1318 CK_IntegralRealToComplex); 1319 return ComplexType; 1320 } 1321 1322 /// UsualArithmeticConversions - Performs various conversions that are common to 1323 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1324 /// routine returns the first non-arithmetic type found. The client is 1325 /// responsible for emitting appropriate error diagnostics. 1326 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1327 bool IsCompAssign) { 1328 if (!IsCompAssign) { 1329 LHS = UsualUnaryConversions(LHS.get()); 1330 if (LHS.isInvalid()) 1331 return QualType(); 1332 } 1333 1334 RHS = UsualUnaryConversions(RHS.get()); 1335 if (RHS.isInvalid()) 1336 return QualType(); 1337 1338 // For conversion purposes, we ignore any qualifiers. 1339 // For example, "const float" and "float" are equivalent. 1340 QualType LHSType = 1341 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1342 QualType RHSType = 1343 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1344 1345 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1346 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1347 LHSType = AtomicLHS->getValueType(); 1348 1349 // If both types are identical, no conversion is needed. 1350 if (LHSType == RHSType) 1351 return LHSType; 1352 1353 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1354 // The caller can deal with this (e.g. pointer + int). 1355 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1356 return QualType(); 1357 1358 // Apply unary and bitfield promotions to the LHS's type. 1359 QualType LHSUnpromotedType = LHSType; 1360 if (LHSType->isPromotableIntegerType()) 1361 LHSType = Context.getPromotedIntegerType(LHSType); 1362 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1363 if (!LHSBitfieldPromoteTy.isNull()) 1364 LHSType = LHSBitfieldPromoteTy; 1365 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1366 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1367 1368 // If both types are identical, no conversion is needed. 1369 if (LHSType == RHSType) 1370 return LHSType; 1371 1372 // At this point, we have two different arithmetic types. 1373 1374 // Diagnose attempts to convert between __float128 and long double where 1375 // such conversions currently can't be handled. 1376 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1377 return QualType(); 1378 1379 // Handle complex types first (C99 6.3.1.8p1). 1380 if (LHSType->isComplexType() || RHSType->isComplexType()) 1381 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1382 IsCompAssign); 1383 1384 // Now handle "real" floating types (i.e. float, double, long double). 1385 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1386 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1387 IsCompAssign); 1388 1389 // Handle GCC complex int extension. 1390 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1391 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1392 IsCompAssign); 1393 1394 // Finally, we have two differing integer types. 1395 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1396 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1397 } 1398 1399 1400 //===----------------------------------------------------------------------===// 1401 // Semantic Analysis for various Expression Types 1402 //===----------------------------------------------------------------------===// 1403 1404 1405 ExprResult 1406 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1407 SourceLocation DefaultLoc, 1408 SourceLocation RParenLoc, 1409 Expr *ControllingExpr, 1410 ArrayRef<ParsedType> ArgTypes, 1411 ArrayRef<Expr *> ArgExprs) { 1412 unsigned NumAssocs = ArgTypes.size(); 1413 assert(NumAssocs == ArgExprs.size()); 1414 1415 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1416 for (unsigned i = 0; i < NumAssocs; ++i) { 1417 if (ArgTypes[i]) 1418 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1419 else 1420 Types[i] = nullptr; 1421 } 1422 1423 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1424 ControllingExpr, 1425 llvm::makeArrayRef(Types, NumAssocs), 1426 ArgExprs); 1427 delete [] Types; 1428 return ER; 1429 } 1430 1431 ExprResult 1432 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1433 SourceLocation DefaultLoc, 1434 SourceLocation RParenLoc, 1435 Expr *ControllingExpr, 1436 ArrayRef<TypeSourceInfo *> Types, 1437 ArrayRef<Expr *> Exprs) { 1438 unsigned NumAssocs = Types.size(); 1439 assert(NumAssocs == Exprs.size()); 1440 1441 // Decay and strip qualifiers for the controlling expression type, and handle 1442 // placeholder type replacement. See committee discussion from WG14 DR423. 1443 { 1444 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 1445 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1446 if (R.isInvalid()) 1447 return ExprError(); 1448 ControllingExpr = R.get(); 1449 } 1450 1451 // The controlling expression is an unevaluated operand, so side effects are 1452 // likely unintended. 1453 if (ActiveTemplateInstantiations.empty() && 1454 ControllingExpr->HasSideEffects(Context, false)) 1455 Diag(ControllingExpr->getExprLoc(), 1456 diag::warn_side_effects_unevaluated_context); 1457 1458 bool TypeErrorFound = false, 1459 IsResultDependent = ControllingExpr->isTypeDependent(), 1460 ContainsUnexpandedParameterPack 1461 = ControllingExpr->containsUnexpandedParameterPack(); 1462 1463 for (unsigned i = 0; i < NumAssocs; ++i) { 1464 if (Exprs[i]->containsUnexpandedParameterPack()) 1465 ContainsUnexpandedParameterPack = true; 1466 1467 if (Types[i]) { 1468 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1469 ContainsUnexpandedParameterPack = true; 1470 1471 if (Types[i]->getType()->isDependentType()) { 1472 IsResultDependent = true; 1473 } else { 1474 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1475 // complete object type other than a variably modified type." 1476 unsigned D = 0; 1477 if (Types[i]->getType()->isIncompleteType()) 1478 D = diag::err_assoc_type_incomplete; 1479 else if (!Types[i]->getType()->isObjectType()) 1480 D = diag::err_assoc_type_nonobject; 1481 else if (Types[i]->getType()->isVariablyModifiedType()) 1482 D = diag::err_assoc_type_variably_modified; 1483 1484 if (D != 0) { 1485 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1486 << Types[i]->getTypeLoc().getSourceRange() 1487 << Types[i]->getType(); 1488 TypeErrorFound = true; 1489 } 1490 1491 // C11 6.5.1.1p2 "No two generic associations in the same generic 1492 // selection shall specify compatible types." 1493 for (unsigned j = i+1; j < NumAssocs; ++j) 1494 if (Types[j] && !Types[j]->getType()->isDependentType() && 1495 Context.typesAreCompatible(Types[i]->getType(), 1496 Types[j]->getType())) { 1497 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1498 diag::err_assoc_compatible_types) 1499 << Types[j]->getTypeLoc().getSourceRange() 1500 << Types[j]->getType() 1501 << Types[i]->getType(); 1502 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1503 diag::note_compat_assoc) 1504 << Types[i]->getTypeLoc().getSourceRange() 1505 << Types[i]->getType(); 1506 TypeErrorFound = true; 1507 } 1508 } 1509 } 1510 } 1511 if (TypeErrorFound) 1512 return ExprError(); 1513 1514 // If we determined that the generic selection is result-dependent, don't 1515 // try to compute the result expression. 1516 if (IsResultDependent) 1517 return new (Context) GenericSelectionExpr( 1518 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1519 ContainsUnexpandedParameterPack); 1520 1521 SmallVector<unsigned, 1> CompatIndices; 1522 unsigned DefaultIndex = -1U; 1523 for (unsigned i = 0; i < NumAssocs; ++i) { 1524 if (!Types[i]) 1525 DefaultIndex = i; 1526 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1527 Types[i]->getType())) 1528 CompatIndices.push_back(i); 1529 } 1530 1531 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1532 // type compatible with at most one of the types named in its generic 1533 // association list." 1534 if (CompatIndices.size() > 1) { 1535 // We strip parens here because the controlling expression is typically 1536 // parenthesized in macro definitions. 1537 ControllingExpr = ControllingExpr->IgnoreParens(); 1538 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1539 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1540 << (unsigned) CompatIndices.size(); 1541 for (unsigned I : CompatIndices) { 1542 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1543 diag::note_compat_assoc) 1544 << Types[I]->getTypeLoc().getSourceRange() 1545 << Types[I]->getType(); 1546 } 1547 return ExprError(); 1548 } 1549 1550 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1551 // its controlling expression shall have type compatible with exactly one of 1552 // the types named in its generic association list." 1553 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1554 // We strip parens here because the controlling expression is typically 1555 // parenthesized in macro definitions. 1556 ControllingExpr = ControllingExpr->IgnoreParens(); 1557 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1558 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1559 return ExprError(); 1560 } 1561 1562 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1563 // type name that is compatible with the type of the controlling expression, 1564 // then the result expression of the generic selection is the expression 1565 // in that generic association. Otherwise, the result expression of the 1566 // generic selection is the expression in the default generic association." 1567 unsigned ResultIndex = 1568 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1569 1570 return new (Context) GenericSelectionExpr( 1571 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1572 ContainsUnexpandedParameterPack, ResultIndex); 1573 } 1574 1575 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1576 /// location of the token and the offset of the ud-suffix within it. 1577 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1578 unsigned Offset) { 1579 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1580 S.getLangOpts()); 1581 } 1582 1583 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1584 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1585 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1586 IdentifierInfo *UDSuffix, 1587 SourceLocation UDSuffixLoc, 1588 ArrayRef<Expr*> Args, 1589 SourceLocation LitEndLoc) { 1590 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1591 1592 QualType ArgTy[2]; 1593 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1594 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1595 if (ArgTy[ArgIdx]->isArrayType()) 1596 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1597 } 1598 1599 DeclarationName OpName = 1600 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1601 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1602 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1603 1604 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1605 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1606 /*AllowRaw*/false, /*AllowTemplate*/false, 1607 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1608 return ExprError(); 1609 1610 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1611 } 1612 1613 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1614 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1615 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1616 /// multiple tokens. However, the common case is that StringToks points to one 1617 /// string. 1618 /// 1619 ExprResult 1620 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1621 assert(!StringToks.empty() && "Must have at least one string!"); 1622 1623 StringLiteralParser Literal(StringToks, PP); 1624 if (Literal.hadError) 1625 return ExprError(); 1626 1627 SmallVector<SourceLocation, 4> StringTokLocs; 1628 for (const Token &Tok : StringToks) 1629 StringTokLocs.push_back(Tok.getLocation()); 1630 1631 QualType CharTy = Context.CharTy; 1632 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1633 if (Literal.isWide()) { 1634 CharTy = Context.getWideCharType(); 1635 Kind = StringLiteral::Wide; 1636 } else if (Literal.isUTF8()) { 1637 Kind = StringLiteral::UTF8; 1638 } else if (Literal.isUTF16()) { 1639 CharTy = Context.Char16Ty; 1640 Kind = StringLiteral::UTF16; 1641 } else if (Literal.isUTF32()) { 1642 CharTy = Context.Char32Ty; 1643 Kind = StringLiteral::UTF32; 1644 } else if (Literal.isPascal()) { 1645 CharTy = Context.UnsignedCharTy; 1646 } 1647 1648 QualType CharTyConst = CharTy; 1649 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1650 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1651 CharTyConst.addConst(); 1652 1653 // Get an array type for the string, according to C99 6.4.5. This includes 1654 // the nul terminator character as well as the string length for pascal 1655 // strings. 1656 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1657 llvm::APInt(32, Literal.GetNumStringChars()+1), 1658 ArrayType::Normal, 0); 1659 1660 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1661 if (getLangOpts().OpenCL) { 1662 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1663 } 1664 1665 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1666 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1667 Kind, Literal.Pascal, StrTy, 1668 &StringTokLocs[0], 1669 StringTokLocs.size()); 1670 if (Literal.getUDSuffix().empty()) 1671 return Lit; 1672 1673 // We're building a user-defined literal. 1674 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1675 SourceLocation UDSuffixLoc = 1676 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1677 Literal.getUDSuffixOffset()); 1678 1679 // Make sure we're allowed user-defined literals here. 1680 if (!UDLScope) 1681 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1682 1683 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1684 // operator "" X (str, len) 1685 QualType SizeType = Context.getSizeType(); 1686 1687 DeclarationName OpName = 1688 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1689 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1690 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1691 1692 QualType ArgTy[] = { 1693 Context.getArrayDecayedType(StrTy), SizeType 1694 }; 1695 1696 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1697 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1698 /*AllowRaw*/false, /*AllowTemplate*/false, 1699 /*AllowStringTemplate*/true)) { 1700 1701 case LOLR_Cooked: { 1702 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1703 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1704 StringTokLocs[0]); 1705 Expr *Args[] = { Lit, LenArg }; 1706 1707 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1708 } 1709 1710 case LOLR_StringTemplate: { 1711 TemplateArgumentListInfo ExplicitArgs; 1712 1713 unsigned CharBits = Context.getIntWidth(CharTy); 1714 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1715 llvm::APSInt Value(CharBits, CharIsUnsigned); 1716 1717 TemplateArgument TypeArg(CharTy); 1718 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1719 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1720 1721 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1722 Value = Lit->getCodeUnit(I); 1723 TemplateArgument Arg(Context, Value, CharTy); 1724 TemplateArgumentLocInfo ArgInfo; 1725 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1726 } 1727 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1728 &ExplicitArgs); 1729 } 1730 case LOLR_Raw: 1731 case LOLR_Template: 1732 llvm_unreachable("unexpected literal operator lookup result"); 1733 case LOLR_Error: 1734 return ExprError(); 1735 } 1736 llvm_unreachable("unexpected literal operator lookup result"); 1737 } 1738 1739 ExprResult 1740 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1741 SourceLocation Loc, 1742 const CXXScopeSpec *SS) { 1743 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1744 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1745 } 1746 1747 /// BuildDeclRefExpr - Build an expression that references a 1748 /// declaration that does not require a closure capture. 1749 ExprResult 1750 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1751 const DeclarationNameInfo &NameInfo, 1752 const CXXScopeSpec *SS, NamedDecl *FoundD, 1753 const TemplateArgumentListInfo *TemplateArgs) { 1754 bool RefersToCapturedVariable = 1755 isa<VarDecl>(D) && 1756 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1757 1758 DeclRefExpr *E; 1759 if (isa<VarTemplateSpecializationDecl>(D)) { 1760 VarTemplateSpecializationDecl *VarSpec = 1761 cast<VarTemplateSpecializationDecl>(D); 1762 1763 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1764 : NestedNameSpecifierLoc(), 1765 VarSpec->getTemplateKeywordLoc(), D, 1766 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1767 FoundD, TemplateArgs); 1768 } else { 1769 assert(!TemplateArgs && "No template arguments for non-variable" 1770 " template specialization references"); 1771 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1772 : NestedNameSpecifierLoc(), 1773 SourceLocation(), D, RefersToCapturedVariable, 1774 NameInfo, Ty, VK, FoundD); 1775 } 1776 1777 MarkDeclRefReferenced(E); 1778 1779 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1780 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1781 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1782 recordUseOfEvaluatedWeak(E); 1783 1784 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1785 UnusedPrivateFields.remove(FD); 1786 // Just in case we're building an illegal pointer-to-member. 1787 if (FD->isBitField()) 1788 E->setObjectKind(OK_BitField); 1789 } 1790 1791 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1792 // designates a bit-field. 1793 if (auto *BD = dyn_cast<BindingDecl>(D)) 1794 if (auto *BE = BD->getBinding()) 1795 E->setObjectKind(BE->getObjectKind()); 1796 1797 return E; 1798 } 1799 1800 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1801 /// possibly a list of template arguments. 1802 /// 1803 /// If this produces template arguments, it is permitted to call 1804 /// DecomposeTemplateName. 1805 /// 1806 /// This actually loses a lot of source location information for 1807 /// non-standard name kinds; we should consider preserving that in 1808 /// some way. 1809 void 1810 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1811 TemplateArgumentListInfo &Buffer, 1812 DeclarationNameInfo &NameInfo, 1813 const TemplateArgumentListInfo *&TemplateArgs) { 1814 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1815 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1816 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1817 1818 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1819 Id.TemplateId->NumArgs); 1820 translateTemplateArguments(TemplateArgsPtr, Buffer); 1821 1822 TemplateName TName = Id.TemplateId->Template.get(); 1823 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1824 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1825 TemplateArgs = &Buffer; 1826 } else { 1827 NameInfo = GetNameFromUnqualifiedId(Id); 1828 TemplateArgs = nullptr; 1829 } 1830 } 1831 1832 static void emitEmptyLookupTypoDiagnostic( 1833 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1834 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1835 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1836 DeclContext *Ctx = 1837 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1838 if (!TC) { 1839 // Emit a special diagnostic for failed member lookups. 1840 // FIXME: computing the declaration context might fail here (?) 1841 if (Ctx) 1842 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1843 << SS.getRange(); 1844 else 1845 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1846 return; 1847 } 1848 1849 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1850 bool DroppedSpecifier = 1851 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1852 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1853 ? diag::note_implicit_param_decl 1854 : diag::note_previous_decl; 1855 if (!Ctx) 1856 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1857 SemaRef.PDiag(NoteID)); 1858 else 1859 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1860 << Typo << Ctx << DroppedSpecifier 1861 << SS.getRange(), 1862 SemaRef.PDiag(NoteID)); 1863 } 1864 1865 /// Diagnose an empty lookup. 1866 /// 1867 /// \return false if new lookup candidates were found 1868 bool 1869 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1870 std::unique_ptr<CorrectionCandidateCallback> CCC, 1871 TemplateArgumentListInfo *ExplicitTemplateArgs, 1872 ArrayRef<Expr *> Args, TypoExpr **Out) { 1873 DeclarationName Name = R.getLookupName(); 1874 1875 unsigned diagnostic = diag::err_undeclared_var_use; 1876 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1877 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1878 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1879 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1880 diagnostic = diag::err_undeclared_use; 1881 diagnostic_suggest = diag::err_undeclared_use_suggest; 1882 } 1883 1884 // If the original lookup was an unqualified lookup, fake an 1885 // unqualified lookup. This is useful when (for example) the 1886 // original lookup would not have found something because it was a 1887 // dependent name. 1888 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1889 while (DC) { 1890 if (isa<CXXRecordDecl>(DC)) { 1891 LookupQualifiedName(R, DC); 1892 1893 if (!R.empty()) { 1894 // Don't give errors about ambiguities in this lookup. 1895 R.suppressDiagnostics(); 1896 1897 // During a default argument instantiation the CurContext points 1898 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1899 // function parameter list, hence add an explicit check. 1900 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1901 ActiveTemplateInstantiations.back().Kind == 1902 ActiveTemplateInstantiation::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 // C++ [temp.dep.expr]p3: 2138 // An id-expression is type-dependent if it contains: 2139 // -- an identifier that was declared with a dependent type, 2140 // (note: handled after lookup) 2141 // -- a template-id that is dependent, 2142 // (note: handled in BuildTemplateIdExpr) 2143 // -- a conversion-function-id that specifies a dependent type, 2144 // -- a nested-name-specifier that contains a class-name that 2145 // names a dependent type. 2146 // Determine whether this is a member of an unknown specialization; 2147 // we need to handle these differently. 2148 bool DependentID = false; 2149 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2150 Name.getCXXNameType()->isDependentType()) { 2151 DependentID = true; 2152 } else if (SS.isSet()) { 2153 if (DeclContext *DC = computeDeclContext(SS, false)) { 2154 if (RequireCompleteDeclContext(SS, DC)) 2155 return ExprError(); 2156 } else { 2157 DependentID = true; 2158 } 2159 } 2160 2161 if (DependentID) 2162 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2163 IsAddressOfOperand, TemplateArgs); 2164 2165 // Perform the required lookup. 2166 LookupResult R(*this, NameInfo, 2167 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2168 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2169 if (TemplateArgs) { 2170 // Lookup the template name again to correctly establish the context in 2171 // which it was found. This is really unfortunate as we already did the 2172 // lookup to determine that it was a template name in the first place. If 2173 // this becomes a performance hit, we can work harder to preserve those 2174 // results until we get here but it's likely not worth it. 2175 bool MemberOfUnknownSpecialization; 2176 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2177 MemberOfUnknownSpecialization); 2178 2179 if (MemberOfUnknownSpecialization || 2180 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2181 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2182 IsAddressOfOperand, TemplateArgs); 2183 } else { 2184 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2185 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2186 2187 // If the result might be in a dependent base class, this is a dependent 2188 // id-expression. 2189 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2190 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2191 IsAddressOfOperand, TemplateArgs); 2192 2193 // If this reference is in an Objective-C method, then we need to do 2194 // some special Objective-C lookup, too. 2195 if (IvarLookupFollowUp) { 2196 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2197 if (E.isInvalid()) 2198 return ExprError(); 2199 2200 if (Expr *Ex = E.getAs<Expr>()) 2201 return Ex; 2202 } 2203 } 2204 2205 if (R.isAmbiguous()) 2206 return ExprError(); 2207 2208 // This could be an implicitly declared function reference (legal in C90, 2209 // extension in C99, forbidden in C++). 2210 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2211 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2212 if (D) R.addDecl(D); 2213 } 2214 2215 // Determine whether this name might be a candidate for 2216 // argument-dependent lookup. 2217 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2218 2219 if (R.empty() && !ADL) { 2220 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2221 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2222 TemplateKWLoc, TemplateArgs)) 2223 return E; 2224 } 2225 2226 // Don't diagnose an empty lookup for inline assembly. 2227 if (IsInlineAsmIdentifier) 2228 return ExprError(); 2229 2230 // If this name wasn't predeclared and if this is not a function 2231 // call, diagnose the problem. 2232 TypoExpr *TE = nullptr; 2233 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2234 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2235 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2236 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2237 "Typo correction callback misconfigured"); 2238 if (CCC) { 2239 // Make sure the callback knows what the typo being diagnosed is. 2240 CCC->setTypoName(II); 2241 if (SS.isValid()) 2242 CCC->setTypoNNS(SS.getScopeRep()); 2243 } 2244 if (DiagnoseEmptyLookup(S, SS, R, 2245 CCC ? std::move(CCC) : std::move(DefaultValidator), 2246 nullptr, None, &TE)) { 2247 if (TE && KeywordReplacement) { 2248 auto &State = getTypoExprState(TE); 2249 auto BestTC = State.Consumer->getNextCorrection(); 2250 if (BestTC.isKeyword()) { 2251 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2252 if (State.DiagHandler) 2253 State.DiagHandler(BestTC); 2254 KeywordReplacement->startToken(); 2255 KeywordReplacement->setKind(II->getTokenID()); 2256 KeywordReplacement->setIdentifierInfo(II); 2257 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2258 // Clean up the state associated with the TypoExpr, since it has 2259 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2260 clearDelayedTypo(TE); 2261 // Signal that a correction to a keyword was performed by returning a 2262 // valid-but-null ExprResult. 2263 return (Expr*)nullptr; 2264 } 2265 State.Consumer->resetCorrectionStream(); 2266 } 2267 return TE ? TE : ExprError(); 2268 } 2269 2270 assert(!R.empty() && 2271 "DiagnoseEmptyLookup returned false but added no results"); 2272 2273 // If we found an Objective-C instance variable, let 2274 // LookupInObjCMethod build the appropriate expression to 2275 // reference the ivar. 2276 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2277 R.clear(); 2278 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2279 // In a hopelessly buggy code, Objective-C instance variable 2280 // lookup fails and no expression will be built to reference it. 2281 if (!E.isInvalid() && !E.get()) 2282 return ExprError(); 2283 return E; 2284 } 2285 } 2286 2287 // This is guaranteed from this point on. 2288 assert(!R.empty() || ADL); 2289 2290 // Check whether this might be a C++ implicit instance member access. 2291 // C++ [class.mfct.non-static]p3: 2292 // When an id-expression that is not part of a class member access 2293 // syntax and not used to form a pointer to member is used in the 2294 // body of a non-static member function of class X, if name lookup 2295 // resolves the name in the id-expression to a non-static non-type 2296 // member of some class C, the id-expression is transformed into a 2297 // class member access expression using (*this) as the 2298 // postfix-expression to the left of the . operator. 2299 // 2300 // But we don't actually need to do this for '&' operands if R 2301 // resolved to a function or overloaded function set, because the 2302 // expression is ill-formed if it actually works out to be a 2303 // non-static member function: 2304 // 2305 // C++ [expr.ref]p4: 2306 // Otherwise, if E1.E2 refers to a non-static member function. . . 2307 // [t]he expression can be used only as the left-hand operand of a 2308 // member function call. 2309 // 2310 // There are other safeguards against such uses, but it's important 2311 // to get this right here so that we don't end up making a 2312 // spuriously dependent expression if we're inside a dependent 2313 // instance method. 2314 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2315 bool MightBeImplicitMember; 2316 if (!IsAddressOfOperand) 2317 MightBeImplicitMember = true; 2318 else if (!SS.isEmpty()) 2319 MightBeImplicitMember = false; 2320 else if (R.isOverloadedResult()) 2321 MightBeImplicitMember = false; 2322 else if (R.isUnresolvableResult()) 2323 MightBeImplicitMember = true; 2324 else 2325 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2326 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2327 isa<MSPropertyDecl>(R.getFoundDecl()); 2328 2329 if (MightBeImplicitMember) 2330 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2331 R, TemplateArgs, S); 2332 } 2333 2334 if (TemplateArgs || TemplateKWLoc.isValid()) { 2335 2336 // In C++1y, if this is a variable template id, then check it 2337 // in BuildTemplateIdExpr(). 2338 // The single lookup result must be a variable template declaration. 2339 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2340 Id.TemplateId->Kind == TNK_Var_template) { 2341 assert(R.getAsSingle<VarTemplateDecl>() && 2342 "There should only be one declaration found."); 2343 } 2344 2345 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2346 } 2347 2348 return BuildDeclarationNameExpr(SS, R, ADL); 2349 } 2350 2351 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2352 /// declaration name, generally during template instantiation. 2353 /// There's a large number of things which don't need to be done along 2354 /// this path. 2355 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2356 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2357 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2358 DeclContext *DC = computeDeclContext(SS, false); 2359 if (!DC) 2360 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2361 NameInfo, /*TemplateArgs=*/nullptr); 2362 2363 if (RequireCompleteDeclContext(SS, DC)) 2364 return ExprError(); 2365 2366 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2367 LookupQualifiedName(R, DC); 2368 2369 if (R.isAmbiguous()) 2370 return ExprError(); 2371 2372 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2373 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2374 NameInfo, /*TemplateArgs=*/nullptr); 2375 2376 if (R.empty()) { 2377 Diag(NameInfo.getLoc(), diag::err_no_member) 2378 << NameInfo.getName() << DC << SS.getRange(); 2379 return ExprError(); 2380 } 2381 2382 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2383 // Diagnose a missing typename if this resolved unambiguously to a type in 2384 // a dependent context. If we can recover with a type, downgrade this to 2385 // a warning in Microsoft compatibility mode. 2386 unsigned DiagID = diag::err_typename_missing; 2387 if (RecoveryTSI && getLangOpts().MSVCCompat) 2388 DiagID = diag::ext_typename_missing; 2389 SourceLocation Loc = SS.getBeginLoc(); 2390 auto D = Diag(Loc, DiagID); 2391 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2392 << SourceRange(Loc, NameInfo.getEndLoc()); 2393 2394 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2395 // context. 2396 if (!RecoveryTSI) 2397 return ExprError(); 2398 2399 // Only issue the fixit if we're prepared to recover. 2400 D << FixItHint::CreateInsertion(Loc, "typename "); 2401 2402 // Recover by pretending this was an elaborated type. 2403 QualType Ty = Context.getTypeDeclType(TD); 2404 TypeLocBuilder TLB; 2405 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2406 2407 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2408 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2409 QTL.setElaboratedKeywordLoc(SourceLocation()); 2410 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2411 2412 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2413 2414 return ExprEmpty(); 2415 } 2416 2417 // Defend against this resolving to an implicit member access. We usually 2418 // won't get here if this might be a legitimate a class member (we end up in 2419 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2420 // a pointer-to-member or in an unevaluated context in C++11. 2421 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2422 return BuildPossibleImplicitMemberExpr(SS, 2423 /*TemplateKWLoc=*/SourceLocation(), 2424 R, /*TemplateArgs=*/nullptr, S); 2425 2426 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2427 } 2428 2429 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2430 /// detected that we're currently inside an ObjC method. Perform some 2431 /// additional lookup. 2432 /// 2433 /// Ideally, most of this would be done by lookup, but there's 2434 /// actually quite a lot of extra work involved. 2435 /// 2436 /// Returns a null sentinel to indicate trivial success. 2437 ExprResult 2438 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2439 IdentifierInfo *II, bool AllowBuiltinCreation) { 2440 SourceLocation Loc = Lookup.getNameLoc(); 2441 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2442 2443 // Check for error condition which is already reported. 2444 if (!CurMethod) 2445 return ExprError(); 2446 2447 // There are two cases to handle here. 1) scoped lookup could have failed, 2448 // in which case we should look for an ivar. 2) scoped lookup could have 2449 // found a decl, but that decl is outside the current instance method (i.e. 2450 // a global variable). In these two cases, we do a lookup for an ivar with 2451 // this name, if the lookup sucedes, we replace it our current decl. 2452 2453 // If we're in a class method, we don't normally want to look for 2454 // ivars. But if we don't find anything else, and there's an 2455 // ivar, that's an error. 2456 bool IsClassMethod = CurMethod->isClassMethod(); 2457 2458 bool LookForIvars; 2459 if (Lookup.empty()) 2460 LookForIvars = true; 2461 else if (IsClassMethod) 2462 LookForIvars = false; 2463 else 2464 LookForIvars = (Lookup.isSingleResult() && 2465 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2466 ObjCInterfaceDecl *IFace = nullptr; 2467 if (LookForIvars) { 2468 IFace = CurMethod->getClassInterface(); 2469 ObjCInterfaceDecl *ClassDeclared; 2470 ObjCIvarDecl *IV = nullptr; 2471 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2472 // Diagnose using an ivar in a class method. 2473 if (IsClassMethod) 2474 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2475 << IV->getDeclName()); 2476 2477 // If we're referencing an invalid decl, just return this as a silent 2478 // error node. The error diagnostic was already emitted on the decl. 2479 if (IV->isInvalidDecl()) 2480 return ExprError(); 2481 2482 // Check if referencing a field with __attribute__((deprecated)). 2483 if (DiagnoseUseOfDecl(IV, Loc)) 2484 return ExprError(); 2485 2486 // Diagnose the use of an ivar outside of the declaring class. 2487 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2488 !declaresSameEntity(ClassDeclared, IFace) && 2489 !getLangOpts().DebuggerSupport) 2490 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2491 2492 // FIXME: This should use a new expr for a direct reference, don't 2493 // turn this into Self->ivar, just return a BareIVarExpr or something. 2494 IdentifierInfo &II = Context.Idents.get("self"); 2495 UnqualifiedId SelfName; 2496 SelfName.setIdentifier(&II, SourceLocation()); 2497 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2498 CXXScopeSpec SelfScopeSpec; 2499 SourceLocation TemplateKWLoc; 2500 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2501 SelfName, false, false); 2502 if (SelfExpr.isInvalid()) 2503 return ExprError(); 2504 2505 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2506 if (SelfExpr.isInvalid()) 2507 return ExprError(); 2508 2509 MarkAnyDeclReferenced(Loc, IV, true); 2510 2511 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2512 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2513 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2514 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2515 2516 ObjCIvarRefExpr *Result = new (Context) 2517 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2518 IV->getLocation(), SelfExpr.get(), true, true); 2519 2520 if (getLangOpts().ObjCAutoRefCount) { 2521 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2522 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2523 recordUseOfEvaluatedWeak(Result); 2524 } 2525 if (CurContext->isClosure()) 2526 Diag(Loc, diag::warn_implicitly_retains_self) 2527 << FixItHint::CreateInsertion(Loc, "self->"); 2528 } 2529 2530 return Result; 2531 } 2532 } else if (CurMethod->isInstanceMethod()) { 2533 // We should warn if a local variable hides an ivar. 2534 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2535 ObjCInterfaceDecl *ClassDeclared; 2536 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2537 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2538 declaresSameEntity(IFace, ClassDeclared)) 2539 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2540 } 2541 } 2542 } else if (Lookup.isSingleResult() && 2543 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2544 // If accessing a stand-alone ivar in a class method, this is an error. 2545 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2546 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2547 << IV->getDeclName()); 2548 } 2549 2550 if (Lookup.empty() && II && AllowBuiltinCreation) { 2551 // FIXME. Consolidate this with similar code in LookupName. 2552 if (unsigned BuiltinID = II->getBuiltinID()) { 2553 if (!(getLangOpts().CPlusPlus && 2554 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2555 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2556 S, Lookup.isForRedeclaration(), 2557 Lookup.getNameLoc()); 2558 if (D) Lookup.addDecl(D); 2559 } 2560 } 2561 } 2562 // Sentinel value saying that we didn't do anything special. 2563 return ExprResult((Expr *)nullptr); 2564 } 2565 2566 /// \brief Cast a base object to a member's actual type. 2567 /// 2568 /// Logically this happens in three phases: 2569 /// 2570 /// * First we cast from the base type to the naming class. 2571 /// The naming class is the class into which we were looking 2572 /// when we found the member; it's the qualifier type if a 2573 /// qualifier was provided, and otherwise it's the base type. 2574 /// 2575 /// * Next we cast from the naming class to the declaring class. 2576 /// If the member we found was brought into a class's scope by 2577 /// a using declaration, this is that class; otherwise it's 2578 /// the class declaring the member. 2579 /// 2580 /// * Finally we cast from the declaring class to the "true" 2581 /// declaring class of the member. This conversion does not 2582 /// obey access control. 2583 ExprResult 2584 Sema::PerformObjectMemberConversion(Expr *From, 2585 NestedNameSpecifier *Qualifier, 2586 NamedDecl *FoundDecl, 2587 NamedDecl *Member) { 2588 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2589 if (!RD) 2590 return From; 2591 2592 QualType DestRecordType; 2593 QualType DestType; 2594 QualType FromRecordType; 2595 QualType FromType = From->getType(); 2596 bool PointerConversions = false; 2597 if (isa<FieldDecl>(Member)) { 2598 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2599 2600 if (FromType->getAs<PointerType>()) { 2601 DestType = Context.getPointerType(DestRecordType); 2602 FromRecordType = FromType->getPointeeType(); 2603 PointerConversions = true; 2604 } else { 2605 DestType = DestRecordType; 2606 FromRecordType = FromType; 2607 } 2608 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2609 if (Method->isStatic()) 2610 return From; 2611 2612 DestType = Method->getThisType(Context); 2613 DestRecordType = DestType->getPointeeType(); 2614 2615 if (FromType->getAs<PointerType>()) { 2616 FromRecordType = FromType->getPointeeType(); 2617 PointerConversions = true; 2618 } else { 2619 FromRecordType = FromType; 2620 DestType = DestRecordType; 2621 } 2622 } else { 2623 // No conversion necessary. 2624 return From; 2625 } 2626 2627 if (DestType->isDependentType() || FromType->isDependentType()) 2628 return From; 2629 2630 // If the unqualified types are the same, no conversion is necessary. 2631 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2632 return From; 2633 2634 SourceRange FromRange = From->getSourceRange(); 2635 SourceLocation FromLoc = FromRange.getBegin(); 2636 2637 ExprValueKind VK = From->getValueKind(); 2638 2639 // C++ [class.member.lookup]p8: 2640 // [...] Ambiguities can often be resolved by qualifying a name with its 2641 // class name. 2642 // 2643 // If the member was a qualified name and the qualified referred to a 2644 // specific base subobject type, we'll cast to that intermediate type 2645 // first and then to the object in which the member is declared. That allows 2646 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2647 // 2648 // class Base { public: int x; }; 2649 // class Derived1 : public Base { }; 2650 // class Derived2 : public Base { }; 2651 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2652 // 2653 // void VeryDerived::f() { 2654 // x = 17; // error: ambiguous base subobjects 2655 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2656 // } 2657 if (Qualifier && Qualifier->getAsType()) { 2658 QualType QType = QualType(Qualifier->getAsType(), 0); 2659 assert(QType->isRecordType() && "lookup done with non-record type"); 2660 2661 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2662 2663 // In C++98, the qualifier type doesn't actually have to be a base 2664 // type of the object type, in which case we just ignore it. 2665 // Otherwise build the appropriate casts. 2666 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2667 CXXCastPath BasePath; 2668 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2669 FromLoc, FromRange, &BasePath)) 2670 return ExprError(); 2671 2672 if (PointerConversions) 2673 QType = Context.getPointerType(QType); 2674 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2675 VK, &BasePath).get(); 2676 2677 FromType = QType; 2678 FromRecordType = QRecordType; 2679 2680 // If the qualifier type was the same as the destination type, 2681 // we're done. 2682 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2683 return From; 2684 } 2685 } 2686 2687 bool IgnoreAccess = false; 2688 2689 // If we actually found the member through a using declaration, cast 2690 // down to the using declaration's type. 2691 // 2692 // Pointer equality is fine here because only one declaration of a 2693 // class ever has member declarations. 2694 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2695 assert(isa<UsingShadowDecl>(FoundDecl)); 2696 QualType URecordType = Context.getTypeDeclType( 2697 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2698 2699 // We only need to do this if the naming-class to declaring-class 2700 // conversion is non-trivial. 2701 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2702 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2703 CXXCastPath BasePath; 2704 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2705 FromLoc, FromRange, &BasePath)) 2706 return ExprError(); 2707 2708 QualType UType = URecordType; 2709 if (PointerConversions) 2710 UType = Context.getPointerType(UType); 2711 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2712 VK, &BasePath).get(); 2713 FromType = UType; 2714 FromRecordType = URecordType; 2715 } 2716 2717 // We don't do access control for the conversion from the 2718 // declaring class to the true declaring class. 2719 IgnoreAccess = true; 2720 } 2721 2722 CXXCastPath BasePath; 2723 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2724 FromLoc, FromRange, &BasePath, 2725 IgnoreAccess)) 2726 return ExprError(); 2727 2728 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2729 VK, &BasePath); 2730 } 2731 2732 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2733 const LookupResult &R, 2734 bool HasTrailingLParen) { 2735 // Only when used directly as the postfix-expression of a call. 2736 if (!HasTrailingLParen) 2737 return false; 2738 2739 // Never if a scope specifier was provided. 2740 if (SS.isSet()) 2741 return false; 2742 2743 // Only in C++ or ObjC++. 2744 if (!getLangOpts().CPlusPlus) 2745 return false; 2746 2747 // Turn off ADL when we find certain kinds of declarations during 2748 // normal lookup: 2749 for (NamedDecl *D : R) { 2750 // C++0x [basic.lookup.argdep]p3: 2751 // -- a declaration of a class member 2752 // Since using decls preserve this property, we check this on the 2753 // original decl. 2754 if (D->isCXXClassMember()) 2755 return false; 2756 2757 // C++0x [basic.lookup.argdep]p3: 2758 // -- a block-scope function declaration that is not a 2759 // using-declaration 2760 // NOTE: we also trigger this for function templates (in fact, we 2761 // don't check the decl type at all, since all other decl types 2762 // turn off ADL anyway). 2763 if (isa<UsingShadowDecl>(D)) 2764 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2765 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2766 return false; 2767 2768 // C++0x [basic.lookup.argdep]p3: 2769 // -- a declaration that is neither a function or a function 2770 // template 2771 // And also for builtin functions. 2772 if (isa<FunctionDecl>(D)) { 2773 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2774 2775 // But also builtin functions. 2776 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2777 return false; 2778 } else if (!isa<FunctionTemplateDecl>(D)) 2779 return false; 2780 } 2781 2782 return true; 2783 } 2784 2785 2786 /// Diagnoses obvious problems with the use of the given declaration 2787 /// as an expression. This is only actually called for lookups that 2788 /// were not overloaded, and it doesn't promise that the declaration 2789 /// will in fact be used. 2790 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2791 if (D->isInvalidDecl()) 2792 return true; 2793 2794 if (isa<TypedefNameDecl>(D)) { 2795 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2796 return true; 2797 } 2798 2799 if (isa<ObjCInterfaceDecl>(D)) { 2800 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2801 return true; 2802 } 2803 2804 if (isa<NamespaceDecl>(D)) { 2805 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2806 return true; 2807 } 2808 2809 return false; 2810 } 2811 2812 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2813 LookupResult &R, bool NeedsADL, 2814 bool AcceptInvalidDecl) { 2815 // If this is a single, fully-resolved result and we don't need ADL, 2816 // just build an ordinary singleton decl ref. 2817 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2818 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2819 R.getRepresentativeDecl(), nullptr, 2820 AcceptInvalidDecl); 2821 2822 // We only need to check the declaration if there's exactly one 2823 // result, because in the overloaded case the results can only be 2824 // functions and function templates. 2825 if (R.isSingleResult() && 2826 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2827 return ExprError(); 2828 2829 // Otherwise, just build an unresolved lookup expression. Suppress 2830 // any lookup-related diagnostics; we'll hash these out later, when 2831 // we've picked a target. 2832 R.suppressDiagnostics(); 2833 2834 UnresolvedLookupExpr *ULE 2835 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2836 SS.getWithLocInContext(Context), 2837 R.getLookupNameInfo(), 2838 NeedsADL, R.isOverloadedResult(), 2839 R.begin(), R.end()); 2840 2841 return ULE; 2842 } 2843 2844 static void 2845 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2846 ValueDecl *var, DeclContext *DC); 2847 2848 /// \brief Complete semantic analysis for a reference to the given declaration. 2849 ExprResult Sema::BuildDeclarationNameExpr( 2850 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2851 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2852 bool AcceptInvalidDecl) { 2853 assert(D && "Cannot refer to a NULL declaration"); 2854 assert(!isa<FunctionTemplateDecl>(D) && 2855 "Cannot refer unambiguously to a function template"); 2856 2857 SourceLocation Loc = NameInfo.getLoc(); 2858 if (CheckDeclInExpr(*this, Loc, D)) 2859 return ExprError(); 2860 2861 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2862 // Specifically diagnose references to class templates that are missing 2863 // a template argument list. 2864 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2865 << Template << SS.getRange(); 2866 Diag(Template->getLocation(), diag::note_template_decl_here); 2867 return ExprError(); 2868 } 2869 2870 // Make sure that we're referring to a value. 2871 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2872 if (!VD) { 2873 Diag(Loc, diag::err_ref_non_value) 2874 << D << SS.getRange(); 2875 Diag(D->getLocation(), diag::note_declared_at); 2876 return ExprError(); 2877 } 2878 2879 // Check whether this declaration can be used. Note that we suppress 2880 // this check when we're going to perform argument-dependent lookup 2881 // on this function name, because this might not be the function 2882 // that overload resolution actually selects. 2883 if (DiagnoseUseOfDecl(VD, Loc)) 2884 return ExprError(); 2885 2886 // Only create DeclRefExpr's for valid Decl's. 2887 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2888 return ExprError(); 2889 2890 // Handle members of anonymous structs and unions. If we got here, 2891 // and the reference is to a class member indirect field, then this 2892 // must be the subject of a pointer-to-member expression. 2893 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2894 if (!indirectField->isCXXClassMember()) 2895 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2896 indirectField); 2897 2898 { 2899 QualType type = VD->getType(); 2900 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2901 // C++ [except.spec]p17: 2902 // An exception-specification is considered to be needed when: 2903 // - in an expression, the function is the unique lookup result or 2904 // the selected member of a set of overloaded functions. 2905 ResolveExceptionSpec(Loc, FPT); 2906 type = VD->getType(); 2907 } 2908 ExprValueKind valueKind = VK_RValue; 2909 2910 switch (D->getKind()) { 2911 // Ignore all the non-ValueDecl kinds. 2912 #define ABSTRACT_DECL(kind) 2913 #define VALUE(type, base) 2914 #define DECL(type, base) \ 2915 case Decl::type: 2916 #include "clang/AST/DeclNodes.inc" 2917 llvm_unreachable("invalid value decl kind"); 2918 2919 // These shouldn't make it here. 2920 case Decl::ObjCAtDefsField: 2921 case Decl::ObjCIvar: 2922 llvm_unreachable("forming non-member reference to ivar?"); 2923 2924 // Enum constants are always r-values and never references. 2925 // Unresolved using declarations are dependent. 2926 case Decl::EnumConstant: 2927 case Decl::UnresolvedUsingValue: 2928 case Decl::OMPDeclareReduction: 2929 valueKind = VK_RValue; 2930 break; 2931 2932 // Fields and indirect fields that got here must be for 2933 // pointer-to-member expressions; we just call them l-values for 2934 // internal consistency, because this subexpression doesn't really 2935 // exist in the high-level semantics. 2936 case Decl::Field: 2937 case Decl::IndirectField: 2938 assert(getLangOpts().CPlusPlus && 2939 "building reference to field in C?"); 2940 2941 // These can't have reference type in well-formed programs, but 2942 // for internal consistency we do this anyway. 2943 type = type.getNonReferenceType(); 2944 valueKind = VK_LValue; 2945 break; 2946 2947 // Non-type template parameters are either l-values or r-values 2948 // depending on the type. 2949 case Decl::NonTypeTemplateParm: { 2950 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2951 type = reftype->getPointeeType(); 2952 valueKind = VK_LValue; // even if the parameter is an r-value reference 2953 break; 2954 } 2955 2956 // For non-references, we need to strip qualifiers just in case 2957 // the template parameter was declared as 'const int' or whatever. 2958 valueKind = VK_RValue; 2959 type = type.getUnqualifiedType(); 2960 break; 2961 } 2962 2963 case Decl::Var: 2964 case Decl::VarTemplateSpecialization: 2965 case Decl::VarTemplatePartialSpecialization: 2966 case Decl::Decomposition: 2967 case Decl::OMPCapturedExpr: 2968 // In C, "extern void blah;" is valid and is an r-value. 2969 if (!getLangOpts().CPlusPlus && 2970 !type.hasQualifiers() && 2971 type->isVoidType()) { 2972 valueKind = VK_RValue; 2973 break; 2974 } 2975 // fallthrough 2976 2977 case Decl::ImplicitParam: 2978 case Decl::ParmVar: { 2979 // These are always l-values. 2980 valueKind = VK_LValue; 2981 type = type.getNonReferenceType(); 2982 2983 // FIXME: Does the addition of const really only apply in 2984 // potentially-evaluated contexts? Since the variable isn't actually 2985 // captured in an unevaluated context, it seems that the answer is no. 2986 if (!isUnevaluatedContext()) { 2987 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2988 if (!CapturedType.isNull()) 2989 type = CapturedType; 2990 } 2991 2992 break; 2993 } 2994 2995 case Decl::Binding: { 2996 // These are always lvalues. 2997 valueKind = VK_LValue; 2998 type = type.getNonReferenceType(); 2999 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3000 // decides how that's supposed to work. 3001 auto *BD = cast<BindingDecl>(VD); 3002 if (BD->getDeclContext()->isFunctionOrMethod() && 3003 BD->getDeclContext() != CurContext) 3004 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3005 break; 3006 } 3007 3008 case Decl::Function: { 3009 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3010 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3011 type = Context.BuiltinFnTy; 3012 valueKind = VK_RValue; 3013 break; 3014 } 3015 } 3016 3017 const FunctionType *fty = type->castAs<FunctionType>(); 3018 3019 // If we're referring to a function with an __unknown_anytype 3020 // result type, make the entire expression __unknown_anytype. 3021 if (fty->getReturnType() == Context.UnknownAnyTy) { 3022 type = Context.UnknownAnyTy; 3023 valueKind = VK_RValue; 3024 break; 3025 } 3026 3027 // Functions are l-values in C++. 3028 if (getLangOpts().CPlusPlus) { 3029 valueKind = VK_LValue; 3030 break; 3031 } 3032 3033 // C99 DR 316 says that, if a function type comes from a 3034 // function definition (without a prototype), that type is only 3035 // used for checking compatibility. Therefore, when referencing 3036 // the function, we pretend that we don't have the full function 3037 // type. 3038 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3039 isa<FunctionProtoType>(fty)) 3040 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3041 fty->getExtInfo()); 3042 3043 // Functions are r-values in C. 3044 valueKind = VK_RValue; 3045 break; 3046 } 3047 3048 case Decl::MSProperty: 3049 valueKind = VK_LValue; 3050 break; 3051 3052 case Decl::CXXMethod: 3053 // If we're referring to a method with an __unknown_anytype 3054 // result type, make the entire expression __unknown_anytype. 3055 // This should only be possible with a type written directly. 3056 if (const FunctionProtoType *proto 3057 = dyn_cast<FunctionProtoType>(VD->getType())) 3058 if (proto->getReturnType() == Context.UnknownAnyTy) { 3059 type = Context.UnknownAnyTy; 3060 valueKind = VK_RValue; 3061 break; 3062 } 3063 3064 // C++ methods are l-values if static, r-values if non-static. 3065 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3066 valueKind = VK_LValue; 3067 break; 3068 } 3069 // fallthrough 3070 3071 case Decl::CXXConversion: 3072 case Decl::CXXDestructor: 3073 case Decl::CXXConstructor: 3074 valueKind = VK_RValue; 3075 break; 3076 } 3077 3078 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3079 TemplateArgs); 3080 } 3081 } 3082 3083 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3084 SmallString<32> &Target) { 3085 Target.resize(CharByteWidth * (Source.size() + 1)); 3086 char *ResultPtr = &Target[0]; 3087 const llvm::UTF8 *ErrorPtr; 3088 bool success = 3089 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3090 (void)success; 3091 assert(success); 3092 Target.resize(ResultPtr - &Target[0]); 3093 } 3094 3095 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3096 PredefinedExpr::IdentType IT) { 3097 // Pick the current block, lambda, captured statement or function. 3098 Decl *currentDecl = nullptr; 3099 if (const BlockScopeInfo *BSI = getCurBlock()) 3100 currentDecl = BSI->TheDecl; 3101 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3102 currentDecl = LSI->CallOperator; 3103 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3104 currentDecl = CSI->TheCapturedDecl; 3105 else 3106 currentDecl = getCurFunctionOrMethodDecl(); 3107 3108 if (!currentDecl) { 3109 Diag(Loc, diag::ext_predef_outside_function); 3110 currentDecl = Context.getTranslationUnitDecl(); 3111 } 3112 3113 QualType ResTy; 3114 StringLiteral *SL = nullptr; 3115 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3116 ResTy = Context.DependentTy; 3117 else { 3118 // Pre-defined identifiers are of type char[x], where x is the length of 3119 // the string. 3120 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3121 unsigned Length = Str.length(); 3122 3123 llvm::APInt LengthI(32, Length + 1); 3124 if (IT == PredefinedExpr::LFunction) { 3125 ResTy = Context.WideCharTy.withConst(); 3126 SmallString<32> RawChars; 3127 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3128 Str, RawChars); 3129 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3130 /*IndexTypeQuals*/ 0); 3131 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3132 /*Pascal*/ false, ResTy, Loc); 3133 } else { 3134 ResTy = Context.CharTy.withConst(); 3135 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3136 /*IndexTypeQuals*/ 0); 3137 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3138 /*Pascal*/ false, ResTy, Loc); 3139 } 3140 } 3141 3142 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3143 } 3144 3145 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3146 PredefinedExpr::IdentType IT; 3147 3148 switch (Kind) { 3149 default: llvm_unreachable("Unknown simple primary expr!"); 3150 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3151 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3152 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3153 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3154 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3155 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3156 } 3157 3158 return BuildPredefinedExpr(Loc, IT); 3159 } 3160 3161 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3162 SmallString<16> CharBuffer; 3163 bool Invalid = false; 3164 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3165 if (Invalid) 3166 return ExprError(); 3167 3168 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3169 PP, Tok.getKind()); 3170 if (Literal.hadError()) 3171 return ExprError(); 3172 3173 QualType Ty; 3174 if (Literal.isWide()) 3175 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3176 else if (Literal.isUTF16()) 3177 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3178 else if (Literal.isUTF32()) 3179 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3180 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3181 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3182 else 3183 Ty = Context.CharTy; // 'x' -> char in C++ 3184 3185 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3186 if (Literal.isWide()) 3187 Kind = CharacterLiteral::Wide; 3188 else if (Literal.isUTF16()) 3189 Kind = CharacterLiteral::UTF16; 3190 else if (Literal.isUTF32()) 3191 Kind = CharacterLiteral::UTF32; 3192 else if (Literal.isUTF8()) 3193 Kind = CharacterLiteral::UTF8; 3194 3195 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3196 Tok.getLocation()); 3197 3198 if (Literal.getUDSuffix().empty()) 3199 return Lit; 3200 3201 // We're building a user-defined literal. 3202 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3203 SourceLocation UDSuffixLoc = 3204 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3205 3206 // Make sure we're allowed user-defined literals here. 3207 if (!UDLScope) 3208 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3209 3210 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3211 // operator "" X (ch) 3212 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3213 Lit, Tok.getLocation()); 3214 } 3215 3216 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3217 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3218 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3219 Context.IntTy, Loc); 3220 } 3221 3222 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3223 QualType Ty, SourceLocation Loc) { 3224 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3225 3226 using llvm::APFloat; 3227 APFloat Val(Format); 3228 3229 APFloat::opStatus result = Literal.GetFloatValue(Val); 3230 3231 // Overflow is always an error, but underflow is only an error if 3232 // we underflowed to zero (APFloat reports denormals as underflow). 3233 if ((result & APFloat::opOverflow) || 3234 ((result & APFloat::opUnderflow) && Val.isZero())) { 3235 unsigned diagnostic; 3236 SmallString<20> buffer; 3237 if (result & APFloat::opOverflow) { 3238 diagnostic = diag::warn_float_overflow; 3239 APFloat::getLargest(Format).toString(buffer); 3240 } else { 3241 diagnostic = diag::warn_float_underflow; 3242 APFloat::getSmallest(Format).toString(buffer); 3243 } 3244 3245 S.Diag(Loc, diagnostic) 3246 << Ty 3247 << StringRef(buffer.data(), buffer.size()); 3248 } 3249 3250 bool isExact = (result == APFloat::opOK); 3251 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3252 } 3253 3254 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3255 assert(E && "Invalid expression"); 3256 3257 if (E->isValueDependent()) 3258 return false; 3259 3260 QualType QT = E->getType(); 3261 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3262 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3263 return true; 3264 } 3265 3266 llvm::APSInt ValueAPS; 3267 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3268 3269 if (R.isInvalid()) 3270 return true; 3271 3272 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3273 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3274 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3275 << ValueAPS.toString(10) << ValueIsPositive; 3276 return true; 3277 } 3278 3279 return false; 3280 } 3281 3282 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3283 // Fast path for a single digit (which is quite common). A single digit 3284 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3285 if (Tok.getLength() == 1) { 3286 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3287 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3288 } 3289 3290 SmallString<128> SpellingBuffer; 3291 // NumericLiteralParser wants to overread by one character. Add padding to 3292 // the buffer in case the token is copied to the buffer. If getSpelling() 3293 // returns a StringRef to the memory buffer, it should have a null char at 3294 // the EOF, so it is also safe. 3295 SpellingBuffer.resize(Tok.getLength() + 1); 3296 3297 // Get the spelling of the token, which eliminates trigraphs, etc. 3298 bool Invalid = false; 3299 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3300 if (Invalid) 3301 return ExprError(); 3302 3303 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3304 if (Literal.hadError) 3305 return ExprError(); 3306 3307 if (Literal.hasUDSuffix()) { 3308 // We're building a user-defined literal. 3309 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3310 SourceLocation UDSuffixLoc = 3311 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3312 3313 // Make sure we're allowed user-defined literals here. 3314 if (!UDLScope) 3315 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3316 3317 QualType CookedTy; 3318 if (Literal.isFloatingLiteral()) { 3319 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3320 // long double, the literal is treated as a call of the form 3321 // operator "" X (f L) 3322 CookedTy = Context.LongDoubleTy; 3323 } else { 3324 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3325 // unsigned long long, the literal is treated as a call of the form 3326 // operator "" X (n ULL) 3327 CookedTy = Context.UnsignedLongLongTy; 3328 } 3329 3330 DeclarationName OpName = 3331 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3332 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3333 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3334 3335 SourceLocation TokLoc = Tok.getLocation(); 3336 3337 // Perform literal operator lookup to determine if we're building a raw 3338 // literal or a cooked one. 3339 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3340 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3341 /*AllowRaw*/true, /*AllowTemplate*/true, 3342 /*AllowStringTemplate*/false)) { 3343 case LOLR_Error: 3344 return ExprError(); 3345 3346 case LOLR_Cooked: { 3347 Expr *Lit; 3348 if (Literal.isFloatingLiteral()) { 3349 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3350 } else { 3351 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3352 if (Literal.GetIntegerValue(ResultVal)) 3353 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3354 << /* Unsigned */ 1; 3355 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3356 Tok.getLocation()); 3357 } 3358 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3359 } 3360 3361 case LOLR_Raw: { 3362 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3363 // literal is treated as a call of the form 3364 // operator "" X ("n") 3365 unsigned Length = Literal.getUDSuffixOffset(); 3366 QualType StrTy = Context.getConstantArrayType( 3367 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3368 ArrayType::Normal, 0); 3369 Expr *Lit = StringLiteral::Create( 3370 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3371 /*Pascal*/false, StrTy, &TokLoc, 1); 3372 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3373 } 3374 3375 case LOLR_Template: { 3376 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3377 // template), L is treated as a call fo the form 3378 // operator "" X <'c1', 'c2', ... 'ck'>() 3379 // where n is the source character sequence c1 c2 ... ck. 3380 TemplateArgumentListInfo ExplicitArgs; 3381 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3382 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3383 llvm::APSInt Value(CharBits, CharIsUnsigned); 3384 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3385 Value = TokSpelling[I]; 3386 TemplateArgument Arg(Context, Value, Context.CharTy); 3387 TemplateArgumentLocInfo ArgInfo; 3388 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3389 } 3390 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3391 &ExplicitArgs); 3392 } 3393 case LOLR_StringTemplate: 3394 llvm_unreachable("unexpected literal operator lookup result"); 3395 } 3396 } 3397 3398 Expr *Res; 3399 3400 if (Literal.isFloatingLiteral()) { 3401 QualType Ty; 3402 if (Literal.isHalf){ 3403 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3404 Ty = Context.HalfTy; 3405 else { 3406 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3407 return ExprError(); 3408 } 3409 } else if (Literal.isFloat) 3410 Ty = Context.FloatTy; 3411 else if (Literal.isLong) 3412 Ty = Context.LongDoubleTy; 3413 else if (Literal.isFloat128) 3414 Ty = Context.Float128Ty; 3415 else 3416 Ty = Context.DoubleTy; 3417 3418 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3419 3420 if (Ty == Context.DoubleTy) { 3421 if (getLangOpts().SinglePrecisionConstants) { 3422 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3423 if (BTy->getKind() != BuiltinType::Float) { 3424 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3425 } 3426 } else if (getLangOpts().OpenCL && 3427 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3428 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3429 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3430 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3431 } 3432 } 3433 } else if (!Literal.isIntegerLiteral()) { 3434 return ExprError(); 3435 } else { 3436 QualType Ty; 3437 3438 // 'long long' is a C99 or C++11 feature. 3439 if (!getLangOpts().C99 && Literal.isLongLong) { 3440 if (getLangOpts().CPlusPlus) 3441 Diag(Tok.getLocation(), 3442 getLangOpts().CPlusPlus11 ? 3443 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3444 else 3445 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3446 } 3447 3448 // Get the value in the widest-possible width. 3449 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3450 llvm::APInt ResultVal(MaxWidth, 0); 3451 3452 if (Literal.GetIntegerValue(ResultVal)) { 3453 // If this value didn't fit into uintmax_t, error and force to ull. 3454 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3455 << /* Unsigned */ 1; 3456 Ty = Context.UnsignedLongLongTy; 3457 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3458 "long long is not intmax_t?"); 3459 } else { 3460 // If this value fits into a ULL, try to figure out what else it fits into 3461 // according to the rules of C99 6.4.4.1p5. 3462 3463 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3464 // be an unsigned int. 3465 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3466 3467 // Check from smallest to largest, picking the smallest type we can. 3468 unsigned Width = 0; 3469 3470 // Microsoft specific integer suffixes are explicitly sized. 3471 if (Literal.MicrosoftInteger) { 3472 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3473 Width = 8; 3474 Ty = Context.CharTy; 3475 } else { 3476 Width = Literal.MicrosoftInteger; 3477 Ty = Context.getIntTypeForBitwidth(Width, 3478 /*Signed=*/!Literal.isUnsigned); 3479 } 3480 } 3481 3482 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3483 // Are int/unsigned possibilities? 3484 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3485 3486 // Does it fit in a unsigned int? 3487 if (ResultVal.isIntN(IntSize)) { 3488 // Does it fit in a signed int? 3489 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3490 Ty = Context.IntTy; 3491 else if (AllowUnsigned) 3492 Ty = Context.UnsignedIntTy; 3493 Width = IntSize; 3494 } 3495 } 3496 3497 // Are long/unsigned long possibilities? 3498 if (Ty.isNull() && !Literal.isLongLong) { 3499 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3500 3501 // Does it fit in a unsigned long? 3502 if (ResultVal.isIntN(LongSize)) { 3503 // Does it fit in a signed long? 3504 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3505 Ty = Context.LongTy; 3506 else if (AllowUnsigned) 3507 Ty = Context.UnsignedLongTy; 3508 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3509 // is compatible. 3510 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3511 const unsigned LongLongSize = 3512 Context.getTargetInfo().getLongLongWidth(); 3513 Diag(Tok.getLocation(), 3514 getLangOpts().CPlusPlus 3515 ? Literal.isLong 3516 ? diag::warn_old_implicitly_unsigned_long_cxx 3517 : /*C++98 UB*/ diag:: 3518 ext_old_implicitly_unsigned_long_cxx 3519 : diag::warn_old_implicitly_unsigned_long) 3520 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3521 : /*will be ill-formed*/ 1); 3522 Ty = Context.UnsignedLongTy; 3523 } 3524 Width = LongSize; 3525 } 3526 } 3527 3528 // Check long long if needed. 3529 if (Ty.isNull()) { 3530 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3531 3532 // Does it fit in a unsigned long long? 3533 if (ResultVal.isIntN(LongLongSize)) { 3534 // Does it fit in a signed long long? 3535 // To be compatible with MSVC, hex integer literals ending with the 3536 // LL or i64 suffix are always signed in Microsoft mode. 3537 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3538 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3539 Ty = Context.LongLongTy; 3540 else if (AllowUnsigned) 3541 Ty = Context.UnsignedLongLongTy; 3542 Width = LongLongSize; 3543 } 3544 } 3545 3546 // If we still couldn't decide a type, we probably have something that 3547 // does not fit in a signed long long, but has no U suffix. 3548 if (Ty.isNull()) { 3549 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3550 Ty = Context.UnsignedLongLongTy; 3551 Width = Context.getTargetInfo().getLongLongWidth(); 3552 } 3553 3554 if (ResultVal.getBitWidth() != Width) 3555 ResultVal = ResultVal.trunc(Width); 3556 } 3557 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3558 } 3559 3560 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3561 if (Literal.isImaginary) 3562 Res = new (Context) ImaginaryLiteral(Res, 3563 Context.getComplexType(Res->getType())); 3564 3565 return Res; 3566 } 3567 3568 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3569 assert(E && "ActOnParenExpr() missing expr"); 3570 return new (Context) ParenExpr(L, R, E); 3571 } 3572 3573 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3574 SourceLocation Loc, 3575 SourceRange ArgRange) { 3576 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3577 // scalar or vector data type argument..." 3578 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3579 // type (C99 6.2.5p18) or void. 3580 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3581 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3582 << T << ArgRange; 3583 return true; 3584 } 3585 3586 assert((T->isVoidType() || !T->isIncompleteType()) && 3587 "Scalar types should always be complete"); 3588 return false; 3589 } 3590 3591 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3592 SourceLocation Loc, 3593 SourceRange ArgRange, 3594 UnaryExprOrTypeTrait TraitKind) { 3595 // Invalid types must be hard errors for SFINAE in C++. 3596 if (S.LangOpts.CPlusPlus) 3597 return true; 3598 3599 // C99 6.5.3.4p1: 3600 if (T->isFunctionType() && 3601 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3602 // sizeof(function)/alignof(function) is allowed as an extension. 3603 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3604 << TraitKind << ArgRange; 3605 return false; 3606 } 3607 3608 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3609 // this is an error (OpenCL v1.1 s6.3.k) 3610 if (T->isVoidType()) { 3611 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3612 : diag::ext_sizeof_alignof_void_type; 3613 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3614 return false; 3615 } 3616 3617 return true; 3618 } 3619 3620 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3621 SourceLocation Loc, 3622 SourceRange ArgRange, 3623 UnaryExprOrTypeTrait TraitKind) { 3624 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3625 // runtime doesn't allow it. 3626 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3627 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3628 << T << (TraitKind == UETT_SizeOf) 3629 << ArgRange; 3630 return true; 3631 } 3632 3633 return false; 3634 } 3635 3636 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3637 /// pointer type is equal to T) and emit a warning if it is. 3638 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3639 Expr *E) { 3640 // Don't warn if the operation changed the type. 3641 if (T != E->getType()) 3642 return; 3643 3644 // Now look for array decays. 3645 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3646 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3647 return; 3648 3649 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3650 << ICE->getType() 3651 << ICE->getSubExpr()->getType(); 3652 } 3653 3654 /// \brief Check the constraints on expression operands to unary type expression 3655 /// and type traits. 3656 /// 3657 /// Completes any types necessary and validates the constraints on the operand 3658 /// expression. The logic mostly mirrors the type-based overload, but may modify 3659 /// the expression as it completes the type for that expression through template 3660 /// instantiation, etc. 3661 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3662 UnaryExprOrTypeTrait ExprKind) { 3663 QualType ExprTy = E->getType(); 3664 assert(!ExprTy->isReferenceType()); 3665 3666 if (ExprKind == UETT_VecStep) 3667 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3668 E->getSourceRange()); 3669 3670 // Whitelist some types as extensions 3671 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3672 E->getSourceRange(), ExprKind)) 3673 return false; 3674 3675 // 'alignof' applied to an expression only requires the base element type of 3676 // the expression to be complete. 'sizeof' requires the expression's type to 3677 // be complete (and will attempt to complete it if it's an array of unknown 3678 // bound). 3679 if (ExprKind == UETT_AlignOf) { 3680 if (RequireCompleteType(E->getExprLoc(), 3681 Context.getBaseElementType(E->getType()), 3682 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3683 E->getSourceRange())) 3684 return true; 3685 } else { 3686 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3687 ExprKind, E->getSourceRange())) 3688 return true; 3689 } 3690 3691 // Completing the expression's type may have changed it. 3692 ExprTy = E->getType(); 3693 assert(!ExprTy->isReferenceType()); 3694 3695 if (ExprTy->isFunctionType()) { 3696 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3697 << ExprKind << E->getSourceRange(); 3698 return true; 3699 } 3700 3701 // The operand for sizeof and alignof is in an unevaluated expression context, 3702 // so side effects could result in unintended consequences. 3703 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3704 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3705 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3706 3707 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3708 E->getSourceRange(), ExprKind)) 3709 return true; 3710 3711 if (ExprKind == UETT_SizeOf) { 3712 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3713 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3714 QualType OType = PVD->getOriginalType(); 3715 QualType Type = PVD->getType(); 3716 if (Type->isPointerType() && OType->isArrayType()) { 3717 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3718 << Type << OType; 3719 Diag(PVD->getLocation(), diag::note_declared_at); 3720 } 3721 } 3722 } 3723 3724 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3725 // decays into a pointer and returns an unintended result. This is most 3726 // likely a typo for "sizeof(array) op x". 3727 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3728 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3729 BO->getLHS()); 3730 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3731 BO->getRHS()); 3732 } 3733 } 3734 3735 return false; 3736 } 3737 3738 /// \brief Check the constraints on operands to unary expression and type 3739 /// traits. 3740 /// 3741 /// This will complete any types necessary, and validate the various constraints 3742 /// on those operands. 3743 /// 3744 /// The UsualUnaryConversions() function is *not* called by this routine. 3745 /// C99 6.3.2.1p[2-4] all state: 3746 /// Except when it is the operand of the sizeof operator ... 3747 /// 3748 /// C++ [expr.sizeof]p4 3749 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3750 /// standard conversions are not applied to the operand of sizeof. 3751 /// 3752 /// This policy is followed for all of the unary trait expressions. 3753 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3754 SourceLocation OpLoc, 3755 SourceRange ExprRange, 3756 UnaryExprOrTypeTrait ExprKind) { 3757 if (ExprType->isDependentType()) 3758 return false; 3759 3760 // C++ [expr.sizeof]p2: 3761 // When applied to a reference or a reference type, the result 3762 // is the size of the referenced type. 3763 // C++11 [expr.alignof]p3: 3764 // When alignof is applied to a reference type, the result 3765 // shall be the alignment of the referenced type. 3766 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3767 ExprType = Ref->getPointeeType(); 3768 3769 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3770 // When alignof or _Alignof is applied to an array type, the result 3771 // is the alignment of the element type. 3772 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3773 ExprType = Context.getBaseElementType(ExprType); 3774 3775 if (ExprKind == UETT_VecStep) 3776 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3777 3778 // Whitelist some types as extensions 3779 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3780 ExprKind)) 3781 return false; 3782 3783 if (RequireCompleteType(OpLoc, ExprType, 3784 diag::err_sizeof_alignof_incomplete_type, 3785 ExprKind, ExprRange)) 3786 return true; 3787 3788 if (ExprType->isFunctionType()) { 3789 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3790 << ExprKind << ExprRange; 3791 return true; 3792 } 3793 3794 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3795 ExprKind)) 3796 return true; 3797 3798 return false; 3799 } 3800 3801 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3802 E = E->IgnoreParens(); 3803 3804 // Cannot know anything else if the expression is dependent. 3805 if (E->isTypeDependent()) 3806 return false; 3807 3808 if (E->getObjectKind() == OK_BitField) { 3809 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3810 << 1 << E->getSourceRange(); 3811 return true; 3812 } 3813 3814 ValueDecl *D = nullptr; 3815 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3816 D = DRE->getDecl(); 3817 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3818 D = ME->getMemberDecl(); 3819 } 3820 3821 // If it's a field, require the containing struct to have a 3822 // complete definition so that we can compute the layout. 3823 // 3824 // This can happen in C++11 onwards, either by naming the member 3825 // in a way that is not transformed into a member access expression 3826 // (in an unevaluated operand, for instance), or by naming the member 3827 // in a trailing-return-type. 3828 // 3829 // For the record, since __alignof__ on expressions is a GCC 3830 // extension, GCC seems to permit this but always gives the 3831 // nonsensical answer 0. 3832 // 3833 // We don't really need the layout here --- we could instead just 3834 // directly check for all the appropriate alignment-lowing 3835 // attributes --- but that would require duplicating a lot of 3836 // logic that just isn't worth duplicating for such a marginal 3837 // use-case. 3838 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3839 // Fast path this check, since we at least know the record has a 3840 // definition if we can find a member of it. 3841 if (!FD->getParent()->isCompleteDefinition()) { 3842 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3843 << E->getSourceRange(); 3844 return true; 3845 } 3846 3847 // Otherwise, if it's a field, and the field doesn't have 3848 // reference type, then it must have a complete type (or be a 3849 // flexible array member, which we explicitly want to 3850 // white-list anyway), which makes the following checks trivial. 3851 if (!FD->getType()->isReferenceType()) 3852 return false; 3853 } 3854 3855 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3856 } 3857 3858 bool Sema::CheckVecStepExpr(Expr *E) { 3859 E = E->IgnoreParens(); 3860 3861 // Cannot know anything else if the expression is dependent. 3862 if (E->isTypeDependent()) 3863 return false; 3864 3865 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3866 } 3867 3868 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3869 CapturingScopeInfo *CSI) { 3870 assert(T->isVariablyModifiedType()); 3871 assert(CSI != nullptr); 3872 3873 // We're going to walk down into the type and look for VLA expressions. 3874 do { 3875 const Type *Ty = T.getTypePtr(); 3876 switch (Ty->getTypeClass()) { 3877 #define TYPE(Class, Base) 3878 #define ABSTRACT_TYPE(Class, Base) 3879 #define NON_CANONICAL_TYPE(Class, Base) 3880 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3881 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3882 #include "clang/AST/TypeNodes.def" 3883 T = QualType(); 3884 break; 3885 // These types are never variably-modified. 3886 case Type::Builtin: 3887 case Type::Complex: 3888 case Type::Vector: 3889 case Type::ExtVector: 3890 case Type::Record: 3891 case Type::Enum: 3892 case Type::Elaborated: 3893 case Type::TemplateSpecialization: 3894 case Type::ObjCObject: 3895 case Type::ObjCInterface: 3896 case Type::ObjCObjectPointer: 3897 case Type::ObjCTypeParam: 3898 case Type::Pipe: 3899 llvm_unreachable("type class is never variably-modified!"); 3900 case Type::Adjusted: 3901 T = cast<AdjustedType>(Ty)->getOriginalType(); 3902 break; 3903 case Type::Decayed: 3904 T = cast<DecayedType>(Ty)->getPointeeType(); 3905 break; 3906 case Type::Pointer: 3907 T = cast<PointerType>(Ty)->getPointeeType(); 3908 break; 3909 case Type::BlockPointer: 3910 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3911 break; 3912 case Type::LValueReference: 3913 case Type::RValueReference: 3914 T = cast<ReferenceType>(Ty)->getPointeeType(); 3915 break; 3916 case Type::MemberPointer: 3917 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3918 break; 3919 case Type::ConstantArray: 3920 case Type::IncompleteArray: 3921 // Losing element qualification here is fine. 3922 T = cast<ArrayType>(Ty)->getElementType(); 3923 break; 3924 case Type::VariableArray: { 3925 // Losing element qualification here is fine. 3926 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3927 3928 // Unknown size indication requires no size computation. 3929 // Otherwise, evaluate and record it. 3930 if (auto Size = VAT->getSizeExpr()) { 3931 if (!CSI->isVLATypeCaptured(VAT)) { 3932 RecordDecl *CapRecord = nullptr; 3933 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3934 CapRecord = LSI->Lambda; 3935 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3936 CapRecord = CRSI->TheRecordDecl; 3937 } 3938 if (CapRecord) { 3939 auto ExprLoc = Size->getExprLoc(); 3940 auto SizeType = Context.getSizeType(); 3941 // Build the non-static data member. 3942 auto Field = 3943 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3944 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3945 /*BW*/ nullptr, /*Mutable*/ false, 3946 /*InitStyle*/ ICIS_NoInit); 3947 Field->setImplicit(true); 3948 Field->setAccess(AS_private); 3949 Field->setCapturedVLAType(VAT); 3950 CapRecord->addDecl(Field); 3951 3952 CSI->addVLATypeCapture(ExprLoc, SizeType); 3953 } 3954 } 3955 } 3956 T = VAT->getElementType(); 3957 break; 3958 } 3959 case Type::FunctionProto: 3960 case Type::FunctionNoProto: 3961 T = cast<FunctionType>(Ty)->getReturnType(); 3962 break; 3963 case Type::Paren: 3964 case Type::TypeOf: 3965 case Type::UnaryTransform: 3966 case Type::Attributed: 3967 case Type::SubstTemplateTypeParm: 3968 case Type::PackExpansion: 3969 // Keep walking after single level desugaring. 3970 T = T.getSingleStepDesugaredType(Context); 3971 break; 3972 case Type::Typedef: 3973 T = cast<TypedefType>(Ty)->desugar(); 3974 break; 3975 case Type::Decltype: 3976 T = cast<DecltypeType>(Ty)->desugar(); 3977 break; 3978 case Type::Auto: 3979 case Type::DeducedTemplateSpecialization: 3980 T = cast<DeducedType>(Ty)->getDeducedType(); 3981 break; 3982 case Type::TypeOfExpr: 3983 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3984 break; 3985 case Type::Atomic: 3986 T = cast<AtomicType>(Ty)->getValueType(); 3987 break; 3988 } 3989 } while (!T.isNull() && T->isVariablyModifiedType()); 3990 } 3991 3992 /// \brief Build a sizeof or alignof expression given a type operand. 3993 ExprResult 3994 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3995 SourceLocation OpLoc, 3996 UnaryExprOrTypeTrait ExprKind, 3997 SourceRange R) { 3998 if (!TInfo) 3999 return ExprError(); 4000 4001 QualType T = TInfo->getType(); 4002 4003 if (!T->isDependentType() && 4004 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4005 return ExprError(); 4006 4007 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4008 if (auto *TT = T->getAs<TypedefType>()) { 4009 for (auto I = FunctionScopes.rbegin(), 4010 E = std::prev(FunctionScopes.rend()); 4011 I != E; ++I) { 4012 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4013 if (CSI == nullptr) 4014 break; 4015 DeclContext *DC = nullptr; 4016 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4017 DC = LSI->CallOperator; 4018 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4019 DC = CRSI->TheCapturedDecl; 4020 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4021 DC = BSI->TheDecl; 4022 if (DC) { 4023 if (DC->containsDecl(TT->getDecl())) 4024 break; 4025 captureVariablyModifiedType(Context, T, CSI); 4026 } 4027 } 4028 } 4029 } 4030 4031 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4032 return new (Context) UnaryExprOrTypeTraitExpr( 4033 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4034 } 4035 4036 /// \brief Build a sizeof or alignof expression given an expression 4037 /// operand. 4038 ExprResult 4039 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4040 UnaryExprOrTypeTrait ExprKind) { 4041 ExprResult PE = CheckPlaceholderExpr(E); 4042 if (PE.isInvalid()) 4043 return ExprError(); 4044 4045 E = PE.get(); 4046 4047 // Verify that the operand is valid. 4048 bool isInvalid = false; 4049 if (E->isTypeDependent()) { 4050 // Delay type-checking for type-dependent expressions. 4051 } else if (ExprKind == UETT_AlignOf) { 4052 isInvalid = CheckAlignOfExpr(*this, E); 4053 } else if (ExprKind == UETT_VecStep) { 4054 isInvalid = CheckVecStepExpr(E); 4055 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4056 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4057 isInvalid = true; 4058 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4059 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4060 isInvalid = true; 4061 } else { 4062 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4063 } 4064 4065 if (isInvalid) 4066 return ExprError(); 4067 4068 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4069 PE = TransformToPotentiallyEvaluated(E); 4070 if (PE.isInvalid()) return ExprError(); 4071 E = PE.get(); 4072 } 4073 4074 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4075 return new (Context) UnaryExprOrTypeTraitExpr( 4076 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4077 } 4078 4079 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4080 /// expr and the same for @c alignof and @c __alignof 4081 /// Note that the ArgRange is invalid if isType is false. 4082 ExprResult 4083 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4084 UnaryExprOrTypeTrait ExprKind, bool IsType, 4085 void *TyOrEx, SourceRange ArgRange) { 4086 // If error parsing type, ignore. 4087 if (!TyOrEx) return ExprError(); 4088 4089 if (IsType) { 4090 TypeSourceInfo *TInfo; 4091 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4092 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4093 } 4094 4095 Expr *ArgEx = (Expr *)TyOrEx; 4096 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4097 return Result; 4098 } 4099 4100 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4101 bool IsReal) { 4102 if (V.get()->isTypeDependent()) 4103 return S.Context.DependentTy; 4104 4105 // _Real and _Imag are only l-values for normal l-values. 4106 if (V.get()->getObjectKind() != OK_Ordinary) { 4107 V = S.DefaultLvalueConversion(V.get()); 4108 if (V.isInvalid()) 4109 return QualType(); 4110 } 4111 4112 // These operators return the element type of a complex type. 4113 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4114 return CT->getElementType(); 4115 4116 // Otherwise they pass through real integer and floating point types here. 4117 if (V.get()->getType()->isArithmeticType()) 4118 return V.get()->getType(); 4119 4120 // Test for placeholders. 4121 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4122 if (PR.isInvalid()) return QualType(); 4123 if (PR.get() != V.get()) { 4124 V = PR; 4125 return CheckRealImagOperand(S, V, Loc, IsReal); 4126 } 4127 4128 // Reject anything else. 4129 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4130 << (IsReal ? "__real" : "__imag"); 4131 return QualType(); 4132 } 4133 4134 4135 4136 ExprResult 4137 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4138 tok::TokenKind Kind, Expr *Input) { 4139 UnaryOperatorKind Opc; 4140 switch (Kind) { 4141 default: llvm_unreachable("Unknown unary op!"); 4142 case tok::plusplus: Opc = UO_PostInc; break; 4143 case tok::minusminus: Opc = UO_PostDec; break; 4144 } 4145 4146 // Since this might is a postfix expression, get rid of ParenListExprs. 4147 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4148 if (Result.isInvalid()) return ExprError(); 4149 Input = Result.get(); 4150 4151 return BuildUnaryOp(S, OpLoc, Opc, Input); 4152 } 4153 4154 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4155 /// 4156 /// \return true on error 4157 static bool checkArithmeticOnObjCPointer(Sema &S, 4158 SourceLocation opLoc, 4159 Expr *op) { 4160 assert(op->getType()->isObjCObjectPointerType()); 4161 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4162 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4163 return false; 4164 4165 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4166 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4167 << op->getSourceRange(); 4168 return true; 4169 } 4170 4171 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4172 auto *BaseNoParens = Base->IgnoreParens(); 4173 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4174 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4175 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4176 } 4177 4178 ExprResult 4179 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4180 Expr *idx, SourceLocation rbLoc) { 4181 if (base && !base->getType().isNull() && 4182 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4183 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4184 /*Length=*/nullptr, rbLoc); 4185 4186 // Since this might be a postfix expression, get rid of ParenListExprs. 4187 if (isa<ParenListExpr>(base)) { 4188 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4189 if (result.isInvalid()) return ExprError(); 4190 base = result.get(); 4191 } 4192 4193 // Handle any non-overload placeholder types in the base and index 4194 // expressions. We can't handle overloads here because the other 4195 // operand might be an overloadable type, in which case the overload 4196 // resolution for the operator overload should get the first crack 4197 // at the overload. 4198 bool IsMSPropertySubscript = false; 4199 if (base->getType()->isNonOverloadPlaceholderType()) { 4200 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4201 if (!IsMSPropertySubscript) { 4202 ExprResult result = CheckPlaceholderExpr(base); 4203 if (result.isInvalid()) 4204 return ExprError(); 4205 base = result.get(); 4206 } 4207 } 4208 if (idx->getType()->isNonOverloadPlaceholderType()) { 4209 ExprResult result = CheckPlaceholderExpr(idx); 4210 if (result.isInvalid()) return ExprError(); 4211 idx = result.get(); 4212 } 4213 4214 // Build an unanalyzed expression if either operand is type-dependent. 4215 if (getLangOpts().CPlusPlus && 4216 (base->isTypeDependent() || idx->isTypeDependent())) { 4217 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4218 VK_LValue, OK_Ordinary, rbLoc); 4219 } 4220 4221 // MSDN, property (C++) 4222 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4223 // This attribute can also be used in the declaration of an empty array in a 4224 // class or structure definition. For example: 4225 // __declspec(property(get=GetX, put=PutX)) int x[]; 4226 // The above statement indicates that x[] can be used with one or more array 4227 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4228 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4229 if (IsMSPropertySubscript) { 4230 // Build MS property subscript expression if base is MS property reference 4231 // or MS property subscript. 4232 return new (Context) MSPropertySubscriptExpr( 4233 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4234 } 4235 4236 // Use C++ overloaded-operator rules if either operand has record 4237 // type. The spec says to do this if either type is *overloadable*, 4238 // but enum types can't declare subscript operators or conversion 4239 // operators, so there's nothing interesting for overload resolution 4240 // to do if there aren't any record types involved. 4241 // 4242 // ObjC pointers have their own subscripting logic that is not tied 4243 // to overload resolution and so should not take this path. 4244 if (getLangOpts().CPlusPlus && 4245 (base->getType()->isRecordType() || 4246 (!base->getType()->isObjCObjectPointerType() && 4247 idx->getType()->isRecordType()))) { 4248 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4249 } 4250 4251 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4252 } 4253 4254 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4255 Expr *LowerBound, 4256 SourceLocation ColonLoc, Expr *Length, 4257 SourceLocation RBLoc) { 4258 if (Base->getType()->isPlaceholderType() && 4259 !Base->getType()->isSpecificPlaceholderType( 4260 BuiltinType::OMPArraySection)) { 4261 ExprResult Result = CheckPlaceholderExpr(Base); 4262 if (Result.isInvalid()) 4263 return ExprError(); 4264 Base = Result.get(); 4265 } 4266 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4267 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4268 if (Result.isInvalid()) 4269 return ExprError(); 4270 Result = DefaultLvalueConversion(Result.get()); 4271 if (Result.isInvalid()) 4272 return ExprError(); 4273 LowerBound = Result.get(); 4274 } 4275 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4276 ExprResult Result = CheckPlaceholderExpr(Length); 4277 if (Result.isInvalid()) 4278 return ExprError(); 4279 Result = DefaultLvalueConversion(Result.get()); 4280 if (Result.isInvalid()) 4281 return ExprError(); 4282 Length = Result.get(); 4283 } 4284 4285 // Build an unanalyzed expression if either operand is type-dependent. 4286 if (Base->isTypeDependent() || 4287 (LowerBound && 4288 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4289 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4290 return new (Context) 4291 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4292 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4293 } 4294 4295 // Perform default conversions. 4296 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4297 QualType ResultTy; 4298 if (OriginalTy->isAnyPointerType()) { 4299 ResultTy = OriginalTy->getPointeeType(); 4300 } else if (OriginalTy->isArrayType()) { 4301 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4302 } else { 4303 return ExprError( 4304 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4305 << Base->getSourceRange()); 4306 } 4307 // C99 6.5.2.1p1 4308 if (LowerBound) { 4309 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4310 LowerBound); 4311 if (Res.isInvalid()) 4312 return ExprError(Diag(LowerBound->getExprLoc(), 4313 diag::err_omp_typecheck_section_not_integer) 4314 << 0 << LowerBound->getSourceRange()); 4315 LowerBound = Res.get(); 4316 4317 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4318 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4319 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4320 << 0 << LowerBound->getSourceRange(); 4321 } 4322 if (Length) { 4323 auto Res = 4324 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4325 if (Res.isInvalid()) 4326 return ExprError(Diag(Length->getExprLoc(), 4327 diag::err_omp_typecheck_section_not_integer) 4328 << 1 << Length->getSourceRange()); 4329 Length = Res.get(); 4330 4331 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4332 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4333 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4334 << 1 << Length->getSourceRange(); 4335 } 4336 4337 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4338 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4339 // type. Note that functions are not objects, and that (in C99 parlance) 4340 // incomplete types are not object types. 4341 if (ResultTy->isFunctionType()) { 4342 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4343 << ResultTy << Base->getSourceRange(); 4344 return ExprError(); 4345 } 4346 4347 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4348 diag::err_omp_section_incomplete_type, Base)) 4349 return ExprError(); 4350 4351 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4352 llvm::APSInt LowerBoundValue; 4353 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4354 // OpenMP 4.5, [2.4 Array Sections] 4355 // The array section must be a subset of the original array. 4356 if (LowerBoundValue.isNegative()) { 4357 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4358 << LowerBound->getSourceRange(); 4359 return ExprError(); 4360 } 4361 } 4362 } 4363 4364 if (Length) { 4365 llvm::APSInt LengthValue; 4366 if (Length->EvaluateAsInt(LengthValue, Context)) { 4367 // OpenMP 4.5, [2.4 Array Sections] 4368 // The length must evaluate to non-negative integers. 4369 if (LengthValue.isNegative()) { 4370 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4371 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4372 << Length->getSourceRange(); 4373 return ExprError(); 4374 } 4375 } 4376 } else if (ColonLoc.isValid() && 4377 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4378 !OriginalTy->isVariableArrayType()))) { 4379 // OpenMP 4.5, [2.4 Array Sections] 4380 // When the size of the array dimension is not known, the length must be 4381 // specified explicitly. 4382 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4383 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4384 return ExprError(); 4385 } 4386 4387 if (!Base->getType()->isSpecificPlaceholderType( 4388 BuiltinType::OMPArraySection)) { 4389 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4390 if (Result.isInvalid()) 4391 return ExprError(); 4392 Base = Result.get(); 4393 } 4394 return new (Context) 4395 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4396 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4397 } 4398 4399 ExprResult 4400 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4401 Expr *Idx, SourceLocation RLoc) { 4402 Expr *LHSExp = Base; 4403 Expr *RHSExp = Idx; 4404 4405 ExprValueKind VK = VK_LValue; 4406 ExprObjectKind OK = OK_Ordinary; 4407 4408 // Per C++ core issue 1213, the result is an xvalue if either operand is 4409 // a non-lvalue array, and an lvalue otherwise. 4410 if (getLangOpts().CPlusPlus11 && 4411 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4412 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4413 VK = VK_XValue; 4414 4415 // Perform default conversions. 4416 if (!LHSExp->getType()->getAs<VectorType>()) { 4417 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4418 if (Result.isInvalid()) 4419 return ExprError(); 4420 LHSExp = Result.get(); 4421 } 4422 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4423 if (Result.isInvalid()) 4424 return ExprError(); 4425 RHSExp = Result.get(); 4426 4427 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4428 4429 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4430 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4431 // in the subscript position. As a result, we need to derive the array base 4432 // and index from the expression types. 4433 Expr *BaseExpr, *IndexExpr; 4434 QualType ResultType; 4435 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4436 BaseExpr = LHSExp; 4437 IndexExpr = RHSExp; 4438 ResultType = Context.DependentTy; 4439 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4440 BaseExpr = LHSExp; 4441 IndexExpr = RHSExp; 4442 ResultType = PTy->getPointeeType(); 4443 } else if (const ObjCObjectPointerType *PTy = 4444 LHSTy->getAs<ObjCObjectPointerType>()) { 4445 BaseExpr = LHSExp; 4446 IndexExpr = RHSExp; 4447 4448 // Use custom logic if this should be the pseudo-object subscript 4449 // expression. 4450 if (!LangOpts.isSubscriptPointerArithmetic()) 4451 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4452 nullptr); 4453 4454 ResultType = PTy->getPointeeType(); 4455 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4456 // Handle the uncommon case of "123[Ptr]". 4457 BaseExpr = RHSExp; 4458 IndexExpr = LHSExp; 4459 ResultType = PTy->getPointeeType(); 4460 } else if (const ObjCObjectPointerType *PTy = 4461 RHSTy->getAs<ObjCObjectPointerType>()) { 4462 // Handle the uncommon case of "123[Ptr]". 4463 BaseExpr = RHSExp; 4464 IndexExpr = LHSExp; 4465 ResultType = PTy->getPointeeType(); 4466 if (!LangOpts.isSubscriptPointerArithmetic()) { 4467 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4468 << ResultType << BaseExpr->getSourceRange(); 4469 return ExprError(); 4470 } 4471 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4472 BaseExpr = LHSExp; // vectors: V[123] 4473 IndexExpr = RHSExp; 4474 VK = LHSExp->getValueKind(); 4475 if (VK != VK_RValue) 4476 OK = OK_VectorComponent; 4477 4478 // FIXME: need to deal with const... 4479 ResultType = VTy->getElementType(); 4480 } else if (LHSTy->isArrayType()) { 4481 // If we see an array that wasn't promoted by 4482 // DefaultFunctionArrayLvalueConversion, it must be an array that 4483 // wasn't promoted because of the C90 rule that doesn't 4484 // allow promoting non-lvalue arrays. Warn, then 4485 // force the promotion here. 4486 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4487 LHSExp->getSourceRange(); 4488 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4489 CK_ArrayToPointerDecay).get(); 4490 LHSTy = LHSExp->getType(); 4491 4492 BaseExpr = LHSExp; 4493 IndexExpr = RHSExp; 4494 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4495 } else if (RHSTy->isArrayType()) { 4496 // Same as previous, except for 123[f().a] case 4497 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4498 RHSExp->getSourceRange(); 4499 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4500 CK_ArrayToPointerDecay).get(); 4501 RHSTy = RHSExp->getType(); 4502 4503 BaseExpr = RHSExp; 4504 IndexExpr = LHSExp; 4505 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4506 } else { 4507 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4508 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4509 } 4510 // C99 6.5.2.1p1 4511 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4512 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4513 << IndexExpr->getSourceRange()); 4514 4515 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4516 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4517 && !IndexExpr->isTypeDependent()) 4518 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4519 4520 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4521 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4522 // type. Note that Functions are not objects, and that (in C99 parlance) 4523 // incomplete types are not object types. 4524 if (ResultType->isFunctionType()) { 4525 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4526 << ResultType << BaseExpr->getSourceRange(); 4527 return ExprError(); 4528 } 4529 4530 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4531 // GNU extension: subscripting on pointer to void 4532 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4533 << BaseExpr->getSourceRange(); 4534 4535 // C forbids expressions of unqualified void type from being l-values. 4536 // See IsCForbiddenLValueType. 4537 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4538 } else if (!ResultType->isDependentType() && 4539 RequireCompleteType(LLoc, ResultType, 4540 diag::err_subscript_incomplete_type, BaseExpr)) 4541 return ExprError(); 4542 4543 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4544 !ResultType.isCForbiddenLValueType()); 4545 4546 return new (Context) 4547 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4548 } 4549 4550 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4551 ParmVarDecl *Param) { 4552 if (Param->hasUnparsedDefaultArg()) { 4553 Diag(CallLoc, 4554 diag::err_use_of_default_argument_to_function_declared_later) << 4555 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4556 Diag(UnparsedDefaultArgLocs[Param], 4557 diag::note_default_argument_declared_here); 4558 return true; 4559 } 4560 4561 if (Param->hasUninstantiatedDefaultArg()) { 4562 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4563 4564 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4565 Param); 4566 4567 // Instantiate the expression. 4568 MultiLevelTemplateArgumentList MutiLevelArgList 4569 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4570 4571 InstantiatingTemplate Inst(*this, CallLoc, Param, 4572 MutiLevelArgList.getInnermost()); 4573 if (Inst.isInvalid()) 4574 return true; 4575 if (Inst.isAlreadyInstantiating()) { 4576 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4577 Param->setInvalidDecl(); 4578 return true; 4579 } 4580 4581 ExprResult Result; 4582 { 4583 // C++ [dcl.fct.default]p5: 4584 // The names in the [default argument] expression are bound, and 4585 // the semantic constraints are checked, at the point where the 4586 // default argument expression appears. 4587 ContextRAII SavedContext(*this, FD); 4588 LocalInstantiationScope Local(*this); 4589 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4590 /*DirectInit*/false); 4591 } 4592 if (Result.isInvalid()) 4593 return true; 4594 4595 // Check the expression as an initializer for the parameter. 4596 InitializedEntity Entity 4597 = InitializedEntity::InitializeParameter(Context, Param); 4598 InitializationKind Kind 4599 = InitializationKind::CreateCopy(Param->getLocation(), 4600 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4601 Expr *ResultE = Result.getAs<Expr>(); 4602 4603 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4604 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4605 if (Result.isInvalid()) 4606 return true; 4607 4608 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4609 Param->getOuterLocStart()); 4610 if (Result.isInvalid()) 4611 return true; 4612 4613 // Remember the instantiated default argument. 4614 Param->setDefaultArg(Result.getAs<Expr>()); 4615 if (ASTMutationListener *L = getASTMutationListener()) { 4616 L->DefaultArgumentInstantiated(Param); 4617 } 4618 } 4619 4620 // If the default argument expression is not set yet, we are building it now. 4621 if (!Param->hasInit()) { 4622 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4623 Param->setInvalidDecl(); 4624 return true; 4625 } 4626 4627 // If the default expression creates temporaries, we need to 4628 // push them to the current stack of expression temporaries so they'll 4629 // be properly destroyed. 4630 // FIXME: We should really be rebuilding the default argument with new 4631 // bound temporaries; see the comment in PR5810. 4632 // We don't need to do that with block decls, though, because 4633 // blocks in default argument expression can never capture anything. 4634 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4635 // Set the "needs cleanups" bit regardless of whether there are 4636 // any explicit objects. 4637 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4638 4639 // Append all the objects to the cleanup list. Right now, this 4640 // should always be a no-op, because blocks in default argument 4641 // expressions should never be able to capture anything. 4642 assert(!Init->getNumObjects() && 4643 "default argument expression has capturing blocks?"); 4644 } 4645 4646 // We already type-checked the argument, so we know it works. 4647 // Just mark all of the declarations in this potentially-evaluated expression 4648 // as being "referenced". 4649 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4650 /*SkipLocalVariables=*/true); 4651 return false; 4652 } 4653 4654 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4655 FunctionDecl *FD, ParmVarDecl *Param) { 4656 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4657 return ExprError(); 4658 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4659 } 4660 4661 Sema::VariadicCallType 4662 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4663 Expr *Fn) { 4664 if (Proto && Proto->isVariadic()) { 4665 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4666 return VariadicConstructor; 4667 else if (Fn && Fn->getType()->isBlockPointerType()) 4668 return VariadicBlock; 4669 else if (FDecl) { 4670 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4671 if (Method->isInstance()) 4672 return VariadicMethod; 4673 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4674 return VariadicMethod; 4675 return VariadicFunction; 4676 } 4677 return VariadicDoesNotApply; 4678 } 4679 4680 namespace { 4681 class FunctionCallCCC : public FunctionCallFilterCCC { 4682 public: 4683 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4684 unsigned NumArgs, MemberExpr *ME) 4685 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4686 FunctionName(FuncName) {} 4687 4688 bool ValidateCandidate(const TypoCorrection &candidate) override { 4689 if (!candidate.getCorrectionSpecifier() || 4690 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4691 return false; 4692 } 4693 4694 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4695 } 4696 4697 private: 4698 const IdentifierInfo *const FunctionName; 4699 }; 4700 } 4701 4702 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4703 FunctionDecl *FDecl, 4704 ArrayRef<Expr *> Args) { 4705 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4706 DeclarationName FuncName = FDecl->getDeclName(); 4707 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4708 4709 if (TypoCorrection Corrected = S.CorrectTypo( 4710 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4711 S.getScopeForContext(S.CurContext), nullptr, 4712 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4713 Args.size(), ME), 4714 Sema::CTK_ErrorRecovery)) { 4715 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4716 if (Corrected.isOverloaded()) { 4717 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4718 OverloadCandidateSet::iterator Best; 4719 for (NamedDecl *CD : Corrected) { 4720 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4721 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4722 OCS); 4723 } 4724 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4725 case OR_Success: 4726 ND = Best->FoundDecl; 4727 Corrected.setCorrectionDecl(ND); 4728 break; 4729 default: 4730 break; 4731 } 4732 } 4733 ND = ND->getUnderlyingDecl(); 4734 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4735 return Corrected; 4736 } 4737 } 4738 return TypoCorrection(); 4739 } 4740 4741 /// ConvertArgumentsForCall - Converts the arguments specified in 4742 /// Args/NumArgs to the parameter types of the function FDecl with 4743 /// function prototype Proto. Call is the call expression itself, and 4744 /// Fn is the function expression. For a C++ member function, this 4745 /// routine does not attempt to convert the object argument. Returns 4746 /// true if the call is ill-formed. 4747 bool 4748 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4749 FunctionDecl *FDecl, 4750 const FunctionProtoType *Proto, 4751 ArrayRef<Expr *> Args, 4752 SourceLocation RParenLoc, 4753 bool IsExecConfig) { 4754 // Bail out early if calling a builtin with custom typechecking. 4755 if (FDecl) 4756 if (unsigned ID = FDecl->getBuiltinID()) 4757 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4758 return false; 4759 4760 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4761 // assignment, to the types of the corresponding parameter, ... 4762 unsigned NumParams = Proto->getNumParams(); 4763 bool Invalid = false; 4764 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4765 unsigned FnKind = Fn->getType()->isBlockPointerType() 4766 ? 1 /* block */ 4767 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4768 : 0 /* function */); 4769 4770 // If too few arguments are available (and we don't have default 4771 // arguments for the remaining parameters), don't make the call. 4772 if (Args.size() < NumParams) { 4773 if (Args.size() < MinArgs) { 4774 TypoCorrection TC; 4775 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4776 unsigned diag_id = 4777 MinArgs == NumParams && !Proto->isVariadic() 4778 ? diag::err_typecheck_call_too_few_args_suggest 4779 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4780 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4781 << static_cast<unsigned>(Args.size()) 4782 << TC.getCorrectionRange()); 4783 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4784 Diag(RParenLoc, 4785 MinArgs == NumParams && !Proto->isVariadic() 4786 ? diag::err_typecheck_call_too_few_args_one 4787 : diag::err_typecheck_call_too_few_args_at_least_one) 4788 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4789 else 4790 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4791 ? diag::err_typecheck_call_too_few_args 4792 : diag::err_typecheck_call_too_few_args_at_least) 4793 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4794 << Fn->getSourceRange(); 4795 4796 // Emit the location of the prototype. 4797 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4798 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4799 << FDecl; 4800 4801 return true; 4802 } 4803 Call->setNumArgs(Context, NumParams); 4804 } 4805 4806 // If too many are passed and not variadic, error on the extras and drop 4807 // them. 4808 if (Args.size() > NumParams) { 4809 if (!Proto->isVariadic()) { 4810 TypoCorrection TC; 4811 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4812 unsigned diag_id = 4813 MinArgs == NumParams && !Proto->isVariadic() 4814 ? diag::err_typecheck_call_too_many_args_suggest 4815 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4816 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4817 << static_cast<unsigned>(Args.size()) 4818 << TC.getCorrectionRange()); 4819 } else if (NumParams == 1 && FDecl && 4820 FDecl->getParamDecl(0)->getDeclName()) 4821 Diag(Args[NumParams]->getLocStart(), 4822 MinArgs == NumParams 4823 ? diag::err_typecheck_call_too_many_args_one 4824 : diag::err_typecheck_call_too_many_args_at_most_one) 4825 << FnKind << FDecl->getParamDecl(0) 4826 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4827 << SourceRange(Args[NumParams]->getLocStart(), 4828 Args.back()->getLocEnd()); 4829 else 4830 Diag(Args[NumParams]->getLocStart(), 4831 MinArgs == NumParams 4832 ? diag::err_typecheck_call_too_many_args 4833 : diag::err_typecheck_call_too_many_args_at_most) 4834 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4835 << Fn->getSourceRange() 4836 << SourceRange(Args[NumParams]->getLocStart(), 4837 Args.back()->getLocEnd()); 4838 4839 // Emit the location of the prototype. 4840 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4841 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4842 << FDecl; 4843 4844 // This deletes the extra arguments. 4845 Call->setNumArgs(Context, NumParams); 4846 return true; 4847 } 4848 } 4849 SmallVector<Expr *, 8> AllArgs; 4850 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4851 4852 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4853 Proto, 0, Args, AllArgs, CallType); 4854 if (Invalid) 4855 return true; 4856 unsigned TotalNumArgs = AllArgs.size(); 4857 for (unsigned i = 0; i < TotalNumArgs; ++i) 4858 Call->setArg(i, AllArgs[i]); 4859 4860 return false; 4861 } 4862 4863 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4864 const FunctionProtoType *Proto, 4865 unsigned FirstParam, ArrayRef<Expr *> Args, 4866 SmallVectorImpl<Expr *> &AllArgs, 4867 VariadicCallType CallType, bool AllowExplicit, 4868 bool IsListInitialization) { 4869 unsigned NumParams = Proto->getNumParams(); 4870 bool Invalid = false; 4871 size_t ArgIx = 0; 4872 // Continue to check argument types (even if we have too few/many args). 4873 for (unsigned i = FirstParam; i < NumParams; i++) { 4874 QualType ProtoArgType = Proto->getParamType(i); 4875 4876 Expr *Arg; 4877 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4878 if (ArgIx < Args.size()) { 4879 Arg = Args[ArgIx++]; 4880 4881 if (RequireCompleteType(Arg->getLocStart(), 4882 ProtoArgType, 4883 diag::err_call_incomplete_argument, Arg)) 4884 return true; 4885 4886 // Strip the unbridged-cast placeholder expression off, if applicable. 4887 bool CFAudited = false; 4888 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4889 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4890 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4891 Arg = stripARCUnbridgedCast(Arg); 4892 else if (getLangOpts().ObjCAutoRefCount && 4893 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4894 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4895 CFAudited = true; 4896 4897 InitializedEntity Entity = 4898 Param ? InitializedEntity::InitializeParameter(Context, Param, 4899 ProtoArgType) 4900 : InitializedEntity::InitializeParameter( 4901 Context, ProtoArgType, Proto->isParamConsumed(i)); 4902 4903 // Remember that parameter belongs to a CF audited API. 4904 if (CFAudited) 4905 Entity.setParameterCFAudited(); 4906 4907 ExprResult ArgE = PerformCopyInitialization( 4908 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4909 if (ArgE.isInvalid()) 4910 return true; 4911 4912 Arg = ArgE.getAs<Expr>(); 4913 } else { 4914 assert(Param && "can't use default arguments without a known callee"); 4915 4916 ExprResult ArgExpr = 4917 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4918 if (ArgExpr.isInvalid()) 4919 return true; 4920 4921 Arg = ArgExpr.getAs<Expr>(); 4922 } 4923 4924 // Check for array bounds violations for each argument to the call. This 4925 // check only triggers warnings when the argument isn't a more complex Expr 4926 // with its own checking, such as a BinaryOperator. 4927 CheckArrayAccess(Arg); 4928 4929 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4930 CheckStaticArrayArgument(CallLoc, Param, Arg); 4931 4932 AllArgs.push_back(Arg); 4933 } 4934 4935 // If this is a variadic call, handle args passed through "...". 4936 if (CallType != VariadicDoesNotApply) { 4937 // Assume that extern "C" functions with variadic arguments that 4938 // return __unknown_anytype aren't *really* variadic. 4939 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4940 FDecl->isExternC()) { 4941 for (Expr *A : Args.slice(ArgIx)) { 4942 QualType paramType; // ignored 4943 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4944 Invalid |= arg.isInvalid(); 4945 AllArgs.push_back(arg.get()); 4946 } 4947 4948 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4949 } else { 4950 for (Expr *A : Args.slice(ArgIx)) { 4951 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4952 Invalid |= Arg.isInvalid(); 4953 AllArgs.push_back(Arg.get()); 4954 } 4955 } 4956 4957 // Check for array bounds violations. 4958 for (Expr *A : Args.slice(ArgIx)) 4959 CheckArrayAccess(A); 4960 } 4961 return Invalid; 4962 } 4963 4964 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4965 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4966 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4967 TL = DTL.getOriginalLoc(); 4968 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4969 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4970 << ATL.getLocalSourceRange(); 4971 } 4972 4973 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4974 /// array parameter, check that it is non-null, and that if it is formed by 4975 /// array-to-pointer decay, the underlying array is sufficiently large. 4976 /// 4977 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4978 /// array type derivation, then for each call to the function, the value of the 4979 /// corresponding actual argument shall provide access to the first element of 4980 /// an array with at least as many elements as specified by the size expression. 4981 void 4982 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4983 ParmVarDecl *Param, 4984 const Expr *ArgExpr) { 4985 // Static array parameters are not supported in C++. 4986 if (!Param || getLangOpts().CPlusPlus) 4987 return; 4988 4989 QualType OrigTy = Param->getOriginalType(); 4990 4991 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4992 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4993 return; 4994 4995 if (ArgExpr->isNullPointerConstant(Context, 4996 Expr::NPC_NeverValueDependent)) { 4997 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4998 DiagnoseCalleeStaticArrayParam(*this, Param); 4999 return; 5000 } 5001 5002 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5003 if (!CAT) 5004 return; 5005 5006 const ConstantArrayType *ArgCAT = 5007 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5008 if (!ArgCAT) 5009 return; 5010 5011 if (ArgCAT->getSize().ult(CAT->getSize())) { 5012 Diag(CallLoc, diag::warn_static_array_too_small) 5013 << ArgExpr->getSourceRange() 5014 << (unsigned) ArgCAT->getSize().getZExtValue() 5015 << (unsigned) CAT->getSize().getZExtValue(); 5016 DiagnoseCalleeStaticArrayParam(*this, Param); 5017 } 5018 } 5019 5020 /// Given a function expression of unknown-any type, try to rebuild it 5021 /// to have a function type. 5022 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5023 5024 /// Is the given type a placeholder that we need to lower out 5025 /// immediately during argument processing? 5026 static bool isPlaceholderToRemoveAsArg(QualType type) { 5027 // Placeholders are never sugared. 5028 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5029 if (!placeholder) return false; 5030 5031 switch (placeholder->getKind()) { 5032 // Ignore all the non-placeholder types. 5033 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5034 case BuiltinType::Id: 5035 #include "clang/Basic/OpenCLImageTypes.def" 5036 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5037 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5038 #include "clang/AST/BuiltinTypes.def" 5039 return false; 5040 5041 // We cannot lower out overload sets; they might validly be resolved 5042 // by the call machinery. 5043 case BuiltinType::Overload: 5044 return false; 5045 5046 // Unbridged casts in ARC can be handled in some call positions and 5047 // should be left in place. 5048 case BuiltinType::ARCUnbridgedCast: 5049 return false; 5050 5051 // Pseudo-objects should be converted as soon as possible. 5052 case BuiltinType::PseudoObject: 5053 return true; 5054 5055 // The debugger mode could theoretically but currently does not try 5056 // to resolve unknown-typed arguments based on known parameter types. 5057 case BuiltinType::UnknownAny: 5058 return true; 5059 5060 // These are always invalid as call arguments and should be reported. 5061 case BuiltinType::BoundMember: 5062 case BuiltinType::BuiltinFn: 5063 case BuiltinType::OMPArraySection: 5064 return true; 5065 5066 } 5067 llvm_unreachable("bad builtin type kind"); 5068 } 5069 5070 /// Check an argument list for placeholders that we won't try to 5071 /// handle later. 5072 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5073 // Apply this processing to all the arguments at once instead of 5074 // dying at the first failure. 5075 bool hasInvalid = false; 5076 for (size_t i = 0, e = args.size(); i != e; i++) { 5077 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5078 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5079 if (result.isInvalid()) hasInvalid = true; 5080 else args[i] = result.get(); 5081 } else if (hasInvalid) { 5082 (void)S.CorrectDelayedTyposInExpr(args[i]); 5083 } 5084 } 5085 return hasInvalid; 5086 } 5087 5088 /// If a builtin function has a pointer argument with no explicit address 5089 /// space, then it should be able to accept a pointer to any address 5090 /// space as input. In order to do this, we need to replace the 5091 /// standard builtin declaration with one that uses the same address space 5092 /// as the call. 5093 /// 5094 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5095 /// it does not contain any pointer arguments without 5096 /// an address space qualifer. Otherwise the rewritten 5097 /// FunctionDecl is returned. 5098 /// TODO: Handle pointer return types. 5099 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5100 const FunctionDecl *FDecl, 5101 MultiExprArg ArgExprs) { 5102 5103 QualType DeclType = FDecl->getType(); 5104 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5105 5106 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5107 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5108 return nullptr; 5109 5110 bool NeedsNewDecl = false; 5111 unsigned i = 0; 5112 SmallVector<QualType, 8> OverloadParams; 5113 5114 for (QualType ParamType : FT->param_types()) { 5115 5116 // Convert array arguments to pointer to simplify type lookup. 5117 ExprResult ArgRes = 5118 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5119 if (ArgRes.isInvalid()) 5120 return nullptr; 5121 Expr *Arg = ArgRes.get(); 5122 QualType ArgType = Arg->getType(); 5123 if (!ParamType->isPointerType() || 5124 ParamType.getQualifiers().hasAddressSpace() || 5125 !ArgType->isPointerType() || 5126 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5127 OverloadParams.push_back(ParamType); 5128 continue; 5129 } 5130 5131 NeedsNewDecl = true; 5132 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 5133 5134 QualType PointeeType = ParamType->getPointeeType(); 5135 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5136 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5137 } 5138 5139 if (!NeedsNewDecl) 5140 return nullptr; 5141 5142 FunctionProtoType::ExtProtoInfo EPI; 5143 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5144 OverloadParams, EPI); 5145 DeclContext *Parent = Context.getTranslationUnitDecl(); 5146 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5147 FDecl->getLocation(), 5148 FDecl->getLocation(), 5149 FDecl->getIdentifier(), 5150 OverloadTy, 5151 /*TInfo=*/nullptr, 5152 SC_Extern, false, 5153 /*hasPrototype=*/true); 5154 SmallVector<ParmVarDecl*, 16> Params; 5155 FT = cast<FunctionProtoType>(OverloadTy); 5156 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5157 QualType ParamType = FT->getParamType(i); 5158 ParmVarDecl *Parm = 5159 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5160 SourceLocation(), nullptr, ParamType, 5161 /*TInfo=*/nullptr, SC_None, nullptr); 5162 Parm->setScopeInfo(0, i); 5163 Params.push_back(Parm); 5164 } 5165 OverloadDecl->setParams(Params); 5166 return OverloadDecl; 5167 } 5168 5169 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5170 FunctionDecl *Callee, 5171 MultiExprArg ArgExprs) { 5172 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5173 // similar attributes) really don't like it when functions are called with an 5174 // invalid number of args. 5175 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5176 /*PartialOverloading=*/false) && 5177 !Callee->isVariadic()) 5178 return; 5179 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5180 return; 5181 5182 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5183 S.Diag(Fn->getLocStart(), 5184 isa<CXXMethodDecl>(Callee) 5185 ? diag::err_ovl_no_viable_member_function_in_call 5186 : diag::err_ovl_no_viable_function_in_call) 5187 << Callee << Callee->getSourceRange(); 5188 S.Diag(Callee->getLocation(), 5189 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5190 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5191 return; 5192 } 5193 5194 SmallVector<DiagnoseIfAttr *, 4> Nonfatal; 5195 if (const DiagnoseIfAttr *Attr = S.checkArgDependentDiagnoseIf( 5196 Callee, ArgExprs, Nonfatal, /*MissingImplicitThis=*/true)) { 5197 S.emitDiagnoseIfDiagnostic(Fn->getLocStart(), Attr); 5198 return; 5199 } 5200 5201 for (const auto *W : Nonfatal) 5202 S.emitDiagnoseIfDiagnostic(Fn->getLocStart(), W); 5203 } 5204 5205 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5206 /// This provides the location of the left/right parens and a list of comma 5207 /// locations. 5208 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5209 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5210 Expr *ExecConfig, bool IsExecConfig) { 5211 // Since this might be a postfix expression, get rid of ParenListExprs. 5212 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5213 if (Result.isInvalid()) return ExprError(); 5214 Fn = Result.get(); 5215 5216 if (checkArgsForPlaceholders(*this, ArgExprs)) 5217 return ExprError(); 5218 5219 if (getLangOpts().CPlusPlus) { 5220 // If this is a pseudo-destructor expression, build the call immediately. 5221 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5222 if (!ArgExprs.empty()) { 5223 // Pseudo-destructor calls should not have any arguments. 5224 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5225 << FixItHint::CreateRemoval( 5226 SourceRange(ArgExprs.front()->getLocStart(), 5227 ArgExprs.back()->getLocEnd())); 5228 } 5229 5230 return new (Context) 5231 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5232 } 5233 if (Fn->getType() == Context.PseudoObjectTy) { 5234 ExprResult result = CheckPlaceholderExpr(Fn); 5235 if (result.isInvalid()) return ExprError(); 5236 Fn = result.get(); 5237 } 5238 5239 // Determine whether this is a dependent call inside a C++ template, 5240 // in which case we won't do any semantic analysis now. 5241 bool Dependent = false; 5242 if (Fn->isTypeDependent()) 5243 Dependent = true; 5244 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5245 Dependent = true; 5246 5247 if (Dependent) { 5248 if (ExecConfig) { 5249 return new (Context) CUDAKernelCallExpr( 5250 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5251 Context.DependentTy, VK_RValue, RParenLoc); 5252 } else { 5253 return new (Context) CallExpr( 5254 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5255 } 5256 } 5257 5258 // Determine whether this is a call to an object (C++ [over.call.object]). 5259 if (Fn->getType()->isRecordType()) 5260 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5261 RParenLoc); 5262 5263 if (Fn->getType() == Context.UnknownAnyTy) { 5264 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5265 if (result.isInvalid()) return ExprError(); 5266 Fn = result.get(); 5267 } 5268 5269 if (Fn->getType() == Context.BoundMemberTy) { 5270 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5271 RParenLoc); 5272 } 5273 } 5274 5275 // Check for overloaded calls. This can happen even in C due to extensions. 5276 if (Fn->getType() == Context.OverloadTy) { 5277 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5278 5279 // We aren't supposed to apply this logic for if there'Scope an '&' 5280 // involved. 5281 if (!find.HasFormOfMemberPointer) { 5282 OverloadExpr *ovl = find.Expression; 5283 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5284 return BuildOverloadedCallExpr( 5285 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5286 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5287 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5288 RParenLoc); 5289 } 5290 } 5291 5292 // If we're directly calling a function, get the appropriate declaration. 5293 if (Fn->getType() == Context.UnknownAnyTy) { 5294 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5295 if (result.isInvalid()) return ExprError(); 5296 Fn = result.get(); 5297 } 5298 5299 Expr *NakedFn = Fn->IgnoreParens(); 5300 5301 bool CallingNDeclIndirectly = false; 5302 NamedDecl *NDecl = nullptr; 5303 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5304 if (UnOp->getOpcode() == UO_AddrOf) { 5305 CallingNDeclIndirectly = true; 5306 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5307 } 5308 } 5309 5310 if (isa<DeclRefExpr>(NakedFn)) { 5311 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5312 5313 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5314 if (FDecl && FDecl->getBuiltinID()) { 5315 // Rewrite the function decl for this builtin by replacing parameters 5316 // with no explicit address space with the address space of the arguments 5317 // in ArgExprs. 5318 if ((FDecl = 5319 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5320 NDecl = FDecl; 5321 Fn = DeclRefExpr::Create( 5322 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5323 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5324 } 5325 } 5326 } else if (isa<MemberExpr>(NakedFn)) 5327 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5328 5329 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5330 if (CallingNDeclIndirectly && 5331 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5332 Fn->getLocStart())) 5333 return ExprError(); 5334 5335 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5336 return ExprError(); 5337 5338 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5339 } 5340 5341 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5342 ExecConfig, IsExecConfig); 5343 } 5344 5345 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5346 /// 5347 /// __builtin_astype( value, dst type ) 5348 /// 5349 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5350 SourceLocation BuiltinLoc, 5351 SourceLocation RParenLoc) { 5352 ExprValueKind VK = VK_RValue; 5353 ExprObjectKind OK = OK_Ordinary; 5354 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5355 QualType SrcTy = E->getType(); 5356 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5357 return ExprError(Diag(BuiltinLoc, 5358 diag::err_invalid_astype_of_different_size) 5359 << DstTy 5360 << SrcTy 5361 << E->getSourceRange()); 5362 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5363 } 5364 5365 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5366 /// provided arguments. 5367 /// 5368 /// __builtin_convertvector( value, dst type ) 5369 /// 5370 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5371 SourceLocation BuiltinLoc, 5372 SourceLocation RParenLoc) { 5373 TypeSourceInfo *TInfo; 5374 GetTypeFromParser(ParsedDestTy, &TInfo); 5375 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5376 } 5377 5378 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5379 /// i.e. an expression not of \p OverloadTy. The expression should 5380 /// unary-convert to an expression of function-pointer or 5381 /// block-pointer type. 5382 /// 5383 /// \param NDecl the declaration being called, if available 5384 ExprResult 5385 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5386 SourceLocation LParenLoc, 5387 ArrayRef<Expr *> Args, 5388 SourceLocation RParenLoc, 5389 Expr *Config, bool IsExecConfig) { 5390 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5391 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5392 5393 // Functions with 'interrupt' attribute cannot be called directly. 5394 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5395 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5396 return ExprError(); 5397 } 5398 5399 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5400 // so there's some risk when calling out to non-interrupt handler functions 5401 // that the callee might not preserve them. This is easy to diagnose here, 5402 // but can be very challenging to debug. 5403 if (auto *Caller = getCurFunctionDecl()) 5404 if (Caller->hasAttr<ARMInterruptAttr>()) 5405 if (!FDecl->hasAttr<ARMInterruptAttr>()) 5406 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5407 5408 // Promote the function operand. 5409 // We special-case function promotion here because we only allow promoting 5410 // builtin functions to function pointers in the callee of a call. 5411 ExprResult Result; 5412 if (BuiltinID && 5413 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5414 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5415 CK_BuiltinFnToFnPtr).get(); 5416 } else { 5417 Result = CallExprUnaryConversions(Fn); 5418 } 5419 if (Result.isInvalid()) 5420 return ExprError(); 5421 Fn = Result.get(); 5422 5423 // Make the call expr early, before semantic checks. This guarantees cleanup 5424 // of arguments and function on error. 5425 CallExpr *TheCall; 5426 if (Config) 5427 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5428 cast<CallExpr>(Config), Args, 5429 Context.BoolTy, VK_RValue, 5430 RParenLoc); 5431 else 5432 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5433 VK_RValue, RParenLoc); 5434 5435 if (!getLangOpts().CPlusPlus) { 5436 // C cannot always handle TypoExpr nodes in builtin calls and direct 5437 // function calls as their argument checking don't necessarily handle 5438 // dependent types properly, so make sure any TypoExprs have been 5439 // dealt with. 5440 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5441 if (!Result.isUsable()) return ExprError(); 5442 TheCall = dyn_cast<CallExpr>(Result.get()); 5443 if (!TheCall) return Result; 5444 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5445 } 5446 5447 // Bail out early if calling a builtin with custom typechecking. 5448 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5449 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5450 5451 retry: 5452 const FunctionType *FuncT; 5453 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5454 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5455 // have type pointer to function". 5456 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5457 if (!FuncT) 5458 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5459 << Fn->getType() << Fn->getSourceRange()); 5460 } else if (const BlockPointerType *BPT = 5461 Fn->getType()->getAs<BlockPointerType>()) { 5462 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5463 } else { 5464 // Handle calls to expressions of unknown-any type. 5465 if (Fn->getType() == Context.UnknownAnyTy) { 5466 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5467 if (rewrite.isInvalid()) return ExprError(); 5468 Fn = rewrite.get(); 5469 TheCall->setCallee(Fn); 5470 goto retry; 5471 } 5472 5473 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5474 << Fn->getType() << Fn->getSourceRange()); 5475 } 5476 5477 if (getLangOpts().CUDA) { 5478 if (Config) { 5479 // CUDA: Kernel calls must be to global functions 5480 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5481 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5482 << FDecl->getName() << Fn->getSourceRange()); 5483 5484 // CUDA: Kernel function must have 'void' return type 5485 if (!FuncT->getReturnType()->isVoidType()) 5486 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5487 << Fn->getType() << Fn->getSourceRange()); 5488 } else { 5489 // CUDA: Calls to global functions must be configured 5490 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5491 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5492 << FDecl->getName() << Fn->getSourceRange()); 5493 } 5494 } 5495 5496 // Check for a valid return type 5497 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5498 FDecl)) 5499 return ExprError(); 5500 5501 // We know the result type of the call, set it. 5502 TheCall->setType(FuncT->getCallResultType(Context)); 5503 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5504 5505 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5506 if (Proto) { 5507 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5508 IsExecConfig)) 5509 return ExprError(); 5510 } else { 5511 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5512 5513 if (FDecl) { 5514 // Check if we have too few/too many template arguments, based 5515 // on our knowledge of the function definition. 5516 const FunctionDecl *Def = nullptr; 5517 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5518 Proto = Def->getType()->getAs<FunctionProtoType>(); 5519 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5520 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5521 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5522 } 5523 5524 // If the function we're calling isn't a function prototype, but we have 5525 // a function prototype from a prior declaratiom, use that prototype. 5526 if (!FDecl->hasPrototype()) 5527 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5528 } 5529 5530 // Promote the arguments (C99 6.5.2.2p6). 5531 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5532 Expr *Arg = Args[i]; 5533 5534 if (Proto && i < Proto->getNumParams()) { 5535 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5536 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5537 ExprResult ArgE = 5538 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5539 if (ArgE.isInvalid()) 5540 return true; 5541 5542 Arg = ArgE.getAs<Expr>(); 5543 5544 } else { 5545 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5546 5547 if (ArgE.isInvalid()) 5548 return true; 5549 5550 Arg = ArgE.getAs<Expr>(); 5551 } 5552 5553 if (RequireCompleteType(Arg->getLocStart(), 5554 Arg->getType(), 5555 diag::err_call_incomplete_argument, Arg)) 5556 return ExprError(); 5557 5558 TheCall->setArg(i, Arg); 5559 } 5560 } 5561 5562 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5563 if (!Method->isStatic()) 5564 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5565 << Fn->getSourceRange()); 5566 5567 // Check for sentinels 5568 if (NDecl) 5569 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5570 5571 // Do special checking on direct calls to functions. 5572 if (FDecl) { 5573 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5574 return ExprError(); 5575 5576 if (BuiltinID) 5577 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5578 } else if (NDecl) { 5579 if (CheckPointerCall(NDecl, TheCall, Proto)) 5580 return ExprError(); 5581 } else { 5582 if (CheckOtherCall(TheCall, Proto)) 5583 return ExprError(); 5584 } 5585 5586 return MaybeBindToTemporary(TheCall); 5587 } 5588 5589 ExprResult 5590 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5591 SourceLocation RParenLoc, Expr *InitExpr) { 5592 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5593 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5594 5595 TypeSourceInfo *TInfo; 5596 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5597 if (!TInfo) 5598 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5599 5600 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5601 } 5602 5603 ExprResult 5604 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5605 SourceLocation RParenLoc, Expr *LiteralExpr) { 5606 QualType literalType = TInfo->getType(); 5607 5608 if (literalType->isArrayType()) { 5609 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5610 diag::err_illegal_decl_array_incomplete_type, 5611 SourceRange(LParenLoc, 5612 LiteralExpr->getSourceRange().getEnd()))) 5613 return ExprError(); 5614 if (literalType->isVariableArrayType()) 5615 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5616 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5617 } else if (!literalType->isDependentType() && 5618 RequireCompleteType(LParenLoc, literalType, 5619 diag::err_typecheck_decl_incomplete_type, 5620 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5621 return ExprError(); 5622 5623 InitializedEntity Entity 5624 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5625 InitializationKind Kind 5626 = InitializationKind::CreateCStyleCast(LParenLoc, 5627 SourceRange(LParenLoc, RParenLoc), 5628 /*InitList=*/true); 5629 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5630 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5631 &literalType); 5632 if (Result.isInvalid()) 5633 return ExprError(); 5634 LiteralExpr = Result.get(); 5635 5636 bool isFileScope = !CurContext->isFunctionOrMethod(); 5637 if (isFileScope && 5638 !LiteralExpr->isTypeDependent() && 5639 !LiteralExpr->isValueDependent() && 5640 !literalType->isDependentType()) { // 6.5.2.5p3 5641 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5642 return ExprError(); 5643 } 5644 5645 // In C, compound literals are l-values for some reason. 5646 // For GCC compatibility, in C++, file-scope array compound literals with 5647 // constant initializers are also l-values, and compound literals are 5648 // otherwise prvalues. 5649 // 5650 // (GCC also treats C++ list-initialized file-scope array prvalues with 5651 // constant initializers as l-values, but that's non-conforming, so we don't 5652 // follow it there.) 5653 // 5654 // FIXME: It would be better to handle the lvalue cases as materializing and 5655 // lifetime-extending a temporary object, but our materialized temporaries 5656 // representation only supports lifetime extension from a variable, not "out 5657 // of thin air". 5658 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5659 // is bound to the result of applying array-to-pointer decay to the compound 5660 // literal. 5661 // FIXME: GCC supports compound literals of reference type, which should 5662 // obviously have a value kind derived from the kind of reference involved. 5663 ExprValueKind VK = 5664 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5665 ? VK_RValue 5666 : VK_LValue; 5667 5668 return MaybeBindToTemporary( 5669 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5670 VK, LiteralExpr, isFileScope)); 5671 } 5672 5673 ExprResult 5674 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5675 SourceLocation RBraceLoc) { 5676 // Immediately handle non-overload placeholders. Overloads can be 5677 // resolved contextually, but everything else here can't. 5678 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5679 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5680 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5681 5682 // Ignore failures; dropping the entire initializer list because 5683 // of one failure would be terrible for indexing/etc. 5684 if (result.isInvalid()) continue; 5685 5686 InitArgList[I] = result.get(); 5687 } 5688 } 5689 5690 // Semantic analysis for initializers is done by ActOnDeclarator() and 5691 // CheckInitializer() - it requires knowledge of the object being intialized. 5692 5693 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5694 RBraceLoc); 5695 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5696 return E; 5697 } 5698 5699 /// Do an explicit extend of the given block pointer if we're in ARC. 5700 void Sema::maybeExtendBlockObject(ExprResult &E) { 5701 assert(E.get()->getType()->isBlockPointerType()); 5702 assert(E.get()->isRValue()); 5703 5704 // Only do this in an r-value context. 5705 if (!getLangOpts().ObjCAutoRefCount) return; 5706 5707 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5708 CK_ARCExtendBlockObject, E.get(), 5709 /*base path*/ nullptr, VK_RValue); 5710 Cleanup.setExprNeedsCleanups(true); 5711 } 5712 5713 /// Prepare a conversion of the given expression to an ObjC object 5714 /// pointer type. 5715 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5716 QualType type = E.get()->getType(); 5717 if (type->isObjCObjectPointerType()) { 5718 return CK_BitCast; 5719 } else if (type->isBlockPointerType()) { 5720 maybeExtendBlockObject(E); 5721 return CK_BlockPointerToObjCPointerCast; 5722 } else { 5723 assert(type->isPointerType()); 5724 return CK_CPointerToObjCPointerCast; 5725 } 5726 } 5727 5728 /// Prepares for a scalar cast, performing all the necessary stages 5729 /// except the final cast and returning the kind required. 5730 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5731 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5732 // Also, callers should have filtered out the invalid cases with 5733 // pointers. Everything else should be possible. 5734 5735 QualType SrcTy = Src.get()->getType(); 5736 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5737 return CK_NoOp; 5738 5739 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5740 case Type::STK_MemberPointer: 5741 llvm_unreachable("member pointer type in C"); 5742 5743 case Type::STK_CPointer: 5744 case Type::STK_BlockPointer: 5745 case Type::STK_ObjCObjectPointer: 5746 switch (DestTy->getScalarTypeKind()) { 5747 case Type::STK_CPointer: { 5748 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5749 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5750 if (SrcAS != DestAS) 5751 return CK_AddressSpaceConversion; 5752 return CK_BitCast; 5753 } 5754 case Type::STK_BlockPointer: 5755 return (SrcKind == Type::STK_BlockPointer 5756 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5757 case Type::STK_ObjCObjectPointer: 5758 if (SrcKind == Type::STK_ObjCObjectPointer) 5759 return CK_BitCast; 5760 if (SrcKind == Type::STK_CPointer) 5761 return CK_CPointerToObjCPointerCast; 5762 maybeExtendBlockObject(Src); 5763 return CK_BlockPointerToObjCPointerCast; 5764 case Type::STK_Bool: 5765 return CK_PointerToBoolean; 5766 case Type::STK_Integral: 5767 return CK_PointerToIntegral; 5768 case Type::STK_Floating: 5769 case Type::STK_FloatingComplex: 5770 case Type::STK_IntegralComplex: 5771 case Type::STK_MemberPointer: 5772 llvm_unreachable("illegal cast from pointer"); 5773 } 5774 llvm_unreachable("Should have returned before this"); 5775 5776 case Type::STK_Bool: // casting from bool is like casting from an integer 5777 case Type::STK_Integral: 5778 switch (DestTy->getScalarTypeKind()) { 5779 case Type::STK_CPointer: 5780 case Type::STK_ObjCObjectPointer: 5781 case Type::STK_BlockPointer: 5782 if (Src.get()->isNullPointerConstant(Context, 5783 Expr::NPC_ValueDependentIsNull)) 5784 return CK_NullToPointer; 5785 return CK_IntegralToPointer; 5786 case Type::STK_Bool: 5787 return CK_IntegralToBoolean; 5788 case Type::STK_Integral: 5789 return CK_IntegralCast; 5790 case Type::STK_Floating: 5791 return CK_IntegralToFloating; 5792 case Type::STK_IntegralComplex: 5793 Src = ImpCastExprToType(Src.get(), 5794 DestTy->castAs<ComplexType>()->getElementType(), 5795 CK_IntegralCast); 5796 return CK_IntegralRealToComplex; 5797 case Type::STK_FloatingComplex: 5798 Src = ImpCastExprToType(Src.get(), 5799 DestTy->castAs<ComplexType>()->getElementType(), 5800 CK_IntegralToFloating); 5801 return CK_FloatingRealToComplex; 5802 case Type::STK_MemberPointer: 5803 llvm_unreachable("member pointer type in C"); 5804 } 5805 llvm_unreachable("Should have returned before this"); 5806 5807 case Type::STK_Floating: 5808 switch (DestTy->getScalarTypeKind()) { 5809 case Type::STK_Floating: 5810 return CK_FloatingCast; 5811 case Type::STK_Bool: 5812 return CK_FloatingToBoolean; 5813 case Type::STK_Integral: 5814 return CK_FloatingToIntegral; 5815 case Type::STK_FloatingComplex: 5816 Src = ImpCastExprToType(Src.get(), 5817 DestTy->castAs<ComplexType>()->getElementType(), 5818 CK_FloatingCast); 5819 return CK_FloatingRealToComplex; 5820 case Type::STK_IntegralComplex: 5821 Src = ImpCastExprToType(Src.get(), 5822 DestTy->castAs<ComplexType>()->getElementType(), 5823 CK_FloatingToIntegral); 5824 return CK_IntegralRealToComplex; 5825 case Type::STK_CPointer: 5826 case Type::STK_ObjCObjectPointer: 5827 case Type::STK_BlockPointer: 5828 llvm_unreachable("valid float->pointer cast?"); 5829 case Type::STK_MemberPointer: 5830 llvm_unreachable("member pointer type in C"); 5831 } 5832 llvm_unreachable("Should have returned before this"); 5833 5834 case Type::STK_FloatingComplex: 5835 switch (DestTy->getScalarTypeKind()) { 5836 case Type::STK_FloatingComplex: 5837 return CK_FloatingComplexCast; 5838 case Type::STK_IntegralComplex: 5839 return CK_FloatingComplexToIntegralComplex; 5840 case Type::STK_Floating: { 5841 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5842 if (Context.hasSameType(ET, DestTy)) 5843 return CK_FloatingComplexToReal; 5844 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5845 return CK_FloatingCast; 5846 } 5847 case Type::STK_Bool: 5848 return CK_FloatingComplexToBoolean; 5849 case Type::STK_Integral: 5850 Src = ImpCastExprToType(Src.get(), 5851 SrcTy->castAs<ComplexType>()->getElementType(), 5852 CK_FloatingComplexToReal); 5853 return CK_FloatingToIntegral; 5854 case Type::STK_CPointer: 5855 case Type::STK_ObjCObjectPointer: 5856 case Type::STK_BlockPointer: 5857 llvm_unreachable("valid complex float->pointer cast?"); 5858 case Type::STK_MemberPointer: 5859 llvm_unreachable("member pointer type in C"); 5860 } 5861 llvm_unreachable("Should have returned before this"); 5862 5863 case Type::STK_IntegralComplex: 5864 switch (DestTy->getScalarTypeKind()) { 5865 case Type::STK_FloatingComplex: 5866 return CK_IntegralComplexToFloatingComplex; 5867 case Type::STK_IntegralComplex: 5868 return CK_IntegralComplexCast; 5869 case Type::STK_Integral: { 5870 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5871 if (Context.hasSameType(ET, DestTy)) 5872 return CK_IntegralComplexToReal; 5873 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5874 return CK_IntegralCast; 5875 } 5876 case Type::STK_Bool: 5877 return CK_IntegralComplexToBoolean; 5878 case Type::STK_Floating: 5879 Src = ImpCastExprToType(Src.get(), 5880 SrcTy->castAs<ComplexType>()->getElementType(), 5881 CK_IntegralComplexToReal); 5882 return CK_IntegralToFloating; 5883 case Type::STK_CPointer: 5884 case Type::STK_ObjCObjectPointer: 5885 case Type::STK_BlockPointer: 5886 llvm_unreachable("valid complex int->pointer cast?"); 5887 case Type::STK_MemberPointer: 5888 llvm_unreachable("member pointer type in C"); 5889 } 5890 llvm_unreachable("Should have returned before this"); 5891 } 5892 5893 llvm_unreachable("Unhandled scalar cast"); 5894 } 5895 5896 static bool breakDownVectorType(QualType type, uint64_t &len, 5897 QualType &eltType) { 5898 // Vectors are simple. 5899 if (const VectorType *vecType = type->getAs<VectorType>()) { 5900 len = vecType->getNumElements(); 5901 eltType = vecType->getElementType(); 5902 assert(eltType->isScalarType()); 5903 return true; 5904 } 5905 5906 // We allow lax conversion to and from non-vector types, but only if 5907 // they're real types (i.e. non-complex, non-pointer scalar types). 5908 if (!type->isRealType()) return false; 5909 5910 len = 1; 5911 eltType = type; 5912 return true; 5913 } 5914 5915 /// Are the two types lax-compatible vector types? That is, given 5916 /// that one of them is a vector, do they have equal storage sizes, 5917 /// where the storage size is the number of elements times the element 5918 /// size? 5919 /// 5920 /// This will also return false if either of the types is neither a 5921 /// vector nor a real type. 5922 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5923 assert(destTy->isVectorType() || srcTy->isVectorType()); 5924 5925 // Disallow lax conversions between scalars and ExtVectors (these 5926 // conversions are allowed for other vector types because common headers 5927 // depend on them). Most scalar OP ExtVector cases are handled by the 5928 // splat path anyway, which does what we want (convert, not bitcast). 5929 // What this rules out for ExtVectors is crazy things like char4*float. 5930 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5931 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5932 5933 uint64_t srcLen, destLen; 5934 QualType srcEltTy, destEltTy; 5935 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5936 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5937 5938 // ASTContext::getTypeSize will return the size rounded up to a 5939 // power of 2, so instead of using that, we need to use the raw 5940 // element size multiplied by the element count. 5941 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5942 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5943 5944 return (srcLen * srcEltSize == destLen * destEltSize); 5945 } 5946 5947 /// Is this a legal conversion between two types, one of which is 5948 /// known to be a vector type? 5949 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5950 assert(destTy->isVectorType() || srcTy->isVectorType()); 5951 5952 if (!Context.getLangOpts().LaxVectorConversions) 5953 return false; 5954 return areLaxCompatibleVectorTypes(srcTy, destTy); 5955 } 5956 5957 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5958 CastKind &Kind) { 5959 assert(VectorTy->isVectorType() && "Not a vector type!"); 5960 5961 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5962 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5963 return Diag(R.getBegin(), 5964 Ty->isVectorType() ? 5965 diag::err_invalid_conversion_between_vectors : 5966 diag::err_invalid_conversion_between_vector_and_integer) 5967 << VectorTy << Ty << R; 5968 } else 5969 return Diag(R.getBegin(), 5970 diag::err_invalid_conversion_between_vector_and_scalar) 5971 << VectorTy << Ty << R; 5972 5973 Kind = CK_BitCast; 5974 return false; 5975 } 5976 5977 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5978 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5979 5980 if (DestElemTy == SplattedExpr->getType()) 5981 return SplattedExpr; 5982 5983 assert(DestElemTy->isFloatingType() || 5984 DestElemTy->isIntegralOrEnumerationType()); 5985 5986 CastKind CK; 5987 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5988 // OpenCL requires that we convert `true` boolean expressions to -1, but 5989 // only when splatting vectors. 5990 if (DestElemTy->isFloatingType()) { 5991 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5992 // in two steps: boolean to signed integral, then to floating. 5993 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5994 CK_BooleanToSignedIntegral); 5995 SplattedExpr = CastExprRes.get(); 5996 CK = CK_IntegralToFloating; 5997 } else { 5998 CK = CK_BooleanToSignedIntegral; 5999 } 6000 } else { 6001 ExprResult CastExprRes = SplattedExpr; 6002 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6003 if (CastExprRes.isInvalid()) 6004 return ExprError(); 6005 SplattedExpr = CastExprRes.get(); 6006 } 6007 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6008 } 6009 6010 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6011 Expr *CastExpr, CastKind &Kind) { 6012 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6013 6014 QualType SrcTy = CastExpr->getType(); 6015 6016 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6017 // an ExtVectorType. 6018 // In OpenCL, casts between vectors of different types are not allowed. 6019 // (See OpenCL 6.2). 6020 if (SrcTy->isVectorType()) { 6021 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 6022 || (getLangOpts().OpenCL && 6023 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 6024 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6025 << DestTy << SrcTy << R; 6026 return ExprError(); 6027 } 6028 Kind = CK_BitCast; 6029 return CastExpr; 6030 } 6031 6032 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6033 // conversion will take place first from scalar to elt type, and then 6034 // splat from elt type to vector. 6035 if (SrcTy->isPointerType()) 6036 return Diag(R.getBegin(), 6037 diag::err_invalid_conversion_between_vector_and_scalar) 6038 << DestTy << SrcTy << R; 6039 6040 Kind = CK_VectorSplat; 6041 return prepareVectorSplat(DestTy, CastExpr); 6042 } 6043 6044 ExprResult 6045 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6046 Declarator &D, ParsedType &Ty, 6047 SourceLocation RParenLoc, Expr *CastExpr) { 6048 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6049 "ActOnCastExpr(): missing type or expr"); 6050 6051 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6052 if (D.isInvalidType()) 6053 return ExprError(); 6054 6055 if (getLangOpts().CPlusPlus) { 6056 // Check that there are no default arguments (C++ only). 6057 CheckExtraCXXDefaultArguments(D); 6058 } else { 6059 // Make sure any TypoExprs have been dealt with. 6060 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6061 if (!Res.isUsable()) 6062 return ExprError(); 6063 CastExpr = Res.get(); 6064 } 6065 6066 checkUnusedDeclAttributes(D); 6067 6068 QualType castType = castTInfo->getType(); 6069 Ty = CreateParsedType(castType, castTInfo); 6070 6071 bool isVectorLiteral = false; 6072 6073 // Check for an altivec or OpenCL literal, 6074 // i.e. all the elements are integer constants. 6075 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6076 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6077 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6078 && castType->isVectorType() && (PE || PLE)) { 6079 if (PLE && PLE->getNumExprs() == 0) { 6080 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6081 return ExprError(); 6082 } 6083 if (PE || PLE->getNumExprs() == 1) { 6084 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6085 if (!E->getType()->isVectorType()) 6086 isVectorLiteral = true; 6087 } 6088 else 6089 isVectorLiteral = true; 6090 } 6091 6092 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6093 // then handle it as such. 6094 if (isVectorLiteral) 6095 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6096 6097 // If the Expr being casted is a ParenListExpr, handle it specially. 6098 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6099 // sequence of BinOp comma operators. 6100 if (isa<ParenListExpr>(CastExpr)) { 6101 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6102 if (Result.isInvalid()) return ExprError(); 6103 CastExpr = Result.get(); 6104 } 6105 6106 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6107 !getSourceManager().isInSystemMacro(LParenLoc)) 6108 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6109 6110 CheckTollFreeBridgeCast(castType, CastExpr); 6111 6112 CheckObjCBridgeRelatedCast(castType, CastExpr); 6113 6114 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6115 6116 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6117 } 6118 6119 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6120 SourceLocation RParenLoc, Expr *E, 6121 TypeSourceInfo *TInfo) { 6122 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6123 "Expected paren or paren list expression"); 6124 6125 Expr **exprs; 6126 unsigned numExprs; 6127 Expr *subExpr; 6128 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6129 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6130 LiteralLParenLoc = PE->getLParenLoc(); 6131 LiteralRParenLoc = PE->getRParenLoc(); 6132 exprs = PE->getExprs(); 6133 numExprs = PE->getNumExprs(); 6134 } else { // isa<ParenExpr> by assertion at function entrance 6135 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6136 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6137 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6138 exprs = &subExpr; 6139 numExprs = 1; 6140 } 6141 6142 QualType Ty = TInfo->getType(); 6143 assert(Ty->isVectorType() && "Expected vector type"); 6144 6145 SmallVector<Expr *, 8> initExprs; 6146 const VectorType *VTy = Ty->getAs<VectorType>(); 6147 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6148 6149 // '(...)' form of vector initialization in AltiVec: the number of 6150 // initializers must be one or must match the size of the vector. 6151 // If a single value is specified in the initializer then it will be 6152 // replicated to all the components of the vector 6153 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6154 // The number of initializers must be one or must match the size of the 6155 // vector. If a single value is specified in the initializer then it will 6156 // be replicated to all the components of the vector 6157 if (numExprs == 1) { 6158 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6159 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6160 if (Literal.isInvalid()) 6161 return ExprError(); 6162 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6163 PrepareScalarCast(Literal, ElemTy)); 6164 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6165 } 6166 else if (numExprs < numElems) { 6167 Diag(E->getExprLoc(), 6168 diag::err_incorrect_number_of_vector_initializers); 6169 return ExprError(); 6170 } 6171 else 6172 initExprs.append(exprs, exprs + numExprs); 6173 } 6174 else { 6175 // For OpenCL, when the number of initializers is a single value, 6176 // it will be replicated to all components of the vector. 6177 if (getLangOpts().OpenCL && 6178 VTy->getVectorKind() == VectorType::GenericVector && 6179 numExprs == 1) { 6180 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6181 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6182 if (Literal.isInvalid()) 6183 return ExprError(); 6184 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6185 PrepareScalarCast(Literal, ElemTy)); 6186 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6187 } 6188 6189 initExprs.append(exprs, exprs + numExprs); 6190 } 6191 // FIXME: This means that pretty-printing the final AST will produce curly 6192 // braces instead of the original commas. 6193 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6194 initExprs, LiteralRParenLoc); 6195 initE->setType(Ty); 6196 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6197 } 6198 6199 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6200 /// the ParenListExpr into a sequence of comma binary operators. 6201 ExprResult 6202 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6203 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6204 if (!E) 6205 return OrigExpr; 6206 6207 ExprResult Result(E->getExpr(0)); 6208 6209 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6210 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6211 E->getExpr(i)); 6212 6213 if (Result.isInvalid()) return ExprError(); 6214 6215 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6216 } 6217 6218 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6219 SourceLocation R, 6220 MultiExprArg Val) { 6221 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6222 return expr; 6223 } 6224 6225 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6226 /// constant and the other is not a pointer. Returns true if a diagnostic is 6227 /// emitted. 6228 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6229 SourceLocation QuestionLoc) { 6230 Expr *NullExpr = LHSExpr; 6231 Expr *NonPointerExpr = RHSExpr; 6232 Expr::NullPointerConstantKind NullKind = 6233 NullExpr->isNullPointerConstant(Context, 6234 Expr::NPC_ValueDependentIsNotNull); 6235 6236 if (NullKind == Expr::NPCK_NotNull) { 6237 NullExpr = RHSExpr; 6238 NonPointerExpr = LHSExpr; 6239 NullKind = 6240 NullExpr->isNullPointerConstant(Context, 6241 Expr::NPC_ValueDependentIsNotNull); 6242 } 6243 6244 if (NullKind == Expr::NPCK_NotNull) 6245 return false; 6246 6247 if (NullKind == Expr::NPCK_ZeroExpression) 6248 return false; 6249 6250 if (NullKind == Expr::NPCK_ZeroLiteral) { 6251 // In this case, check to make sure that we got here from a "NULL" 6252 // string in the source code. 6253 NullExpr = NullExpr->IgnoreParenImpCasts(); 6254 SourceLocation loc = NullExpr->getExprLoc(); 6255 if (!findMacroSpelling(loc, "NULL")) 6256 return false; 6257 } 6258 6259 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6260 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6261 << NonPointerExpr->getType() << DiagType 6262 << NonPointerExpr->getSourceRange(); 6263 return true; 6264 } 6265 6266 /// \brief Return false if the condition expression is valid, true otherwise. 6267 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6268 QualType CondTy = Cond->getType(); 6269 6270 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6271 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6272 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6273 << CondTy << Cond->getSourceRange(); 6274 return true; 6275 } 6276 6277 // C99 6.5.15p2 6278 if (CondTy->isScalarType()) return false; 6279 6280 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6281 << CondTy << Cond->getSourceRange(); 6282 return true; 6283 } 6284 6285 /// \brief Handle when one or both operands are void type. 6286 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6287 ExprResult &RHS) { 6288 Expr *LHSExpr = LHS.get(); 6289 Expr *RHSExpr = RHS.get(); 6290 6291 if (!LHSExpr->getType()->isVoidType()) 6292 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6293 << RHSExpr->getSourceRange(); 6294 if (!RHSExpr->getType()->isVoidType()) 6295 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6296 << LHSExpr->getSourceRange(); 6297 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6298 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6299 return S.Context.VoidTy; 6300 } 6301 6302 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6303 /// true otherwise. 6304 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6305 QualType PointerTy) { 6306 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6307 !NullExpr.get()->isNullPointerConstant(S.Context, 6308 Expr::NPC_ValueDependentIsNull)) 6309 return true; 6310 6311 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6312 return false; 6313 } 6314 6315 /// \brief Checks compatibility between two pointers and return the resulting 6316 /// type. 6317 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6318 ExprResult &RHS, 6319 SourceLocation Loc) { 6320 QualType LHSTy = LHS.get()->getType(); 6321 QualType RHSTy = RHS.get()->getType(); 6322 6323 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6324 // Two identical pointers types are always compatible. 6325 return LHSTy; 6326 } 6327 6328 QualType lhptee, rhptee; 6329 6330 // Get the pointee types. 6331 bool IsBlockPointer = false; 6332 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6333 lhptee = LHSBTy->getPointeeType(); 6334 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6335 IsBlockPointer = true; 6336 } else { 6337 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6338 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6339 } 6340 6341 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6342 // differently qualified versions of compatible types, the result type is 6343 // a pointer to an appropriately qualified version of the composite 6344 // type. 6345 6346 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6347 // clause doesn't make sense for our extensions. E.g. address space 2 should 6348 // be incompatible with address space 3: they may live on different devices or 6349 // anything. 6350 Qualifiers lhQual = lhptee.getQualifiers(); 6351 Qualifiers rhQual = rhptee.getQualifiers(); 6352 6353 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6354 lhQual.removeCVRQualifiers(); 6355 rhQual.removeCVRQualifiers(); 6356 6357 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6358 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6359 6360 // For OpenCL: 6361 // 1. If LHS and RHS types match exactly and: 6362 // (a) AS match => use standard C rules, no bitcast or addrspacecast 6363 // (b) AS overlap => generate addrspacecast 6364 // (c) AS don't overlap => give an error 6365 // 2. if LHS and RHS types don't match: 6366 // (a) AS match => use standard C rules, generate bitcast 6367 // (b) AS overlap => generate addrspacecast instead of bitcast 6368 // (c) AS don't overlap => give an error 6369 6370 // For OpenCL, non-null composite type is returned only for cases 1a and 1b. 6371 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6372 6373 // OpenCL cases 1c, 2a, 2b, and 2c. 6374 if (CompositeTy.isNull()) { 6375 // In this situation, we assume void* type. No especially good 6376 // reason, but this is what gcc does, and we do have to pick 6377 // to get a consistent AST. 6378 QualType incompatTy; 6379 if (S.getLangOpts().OpenCL) { 6380 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6381 // spaces is disallowed. 6382 unsigned ResultAddrSpace; 6383 if (lhQual.isAddressSpaceSupersetOf(rhQual)) { 6384 // Cases 2a and 2b. 6385 ResultAddrSpace = lhQual.getAddressSpace(); 6386 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) { 6387 // Cases 2a and 2b. 6388 ResultAddrSpace = rhQual.getAddressSpace(); 6389 } else { 6390 // Cases 1c and 2c. 6391 S.Diag(Loc, 6392 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6393 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6394 << RHS.get()->getSourceRange(); 6395 return QualType(); 6396 } 6397 6398 // Continue handling cases 2a and 2b. 6399 incompatTy = S.Context.getPointerType( 6400 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6401 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, 6402 (lhQual.getAddressSpace() != ResultAddrSpace) 6403 ? CK_AddressSpaceConversion /* 2b */ 6404 : CK_BitCast /* 2a */); 6405 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, 6406 (rhQual.getAddressSpace() != ResultAddrSpace) 6407 ? CK_AddressSpaceConversion /* 2b */ 6408 : CK_BitCast /* 2a */); 6409 } else { 6410 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6411 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6412 << RHS.get()->getSourceRange(); 6413 incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6414 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6415 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6416 } 6417 return incompatTy; 6418 } 6419 6420 // The pointer types are compatible. 6421 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6422 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6423 if (IsBlockPointer) 6424 ResultTy = S.Context.getBlockPointerType(ResultTy); 6425 else { 6426 // Cases 1a and 1b for OpenCL. 6427 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace(); 6428 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace 6429 ? CK_BitCast /* 1a */ 6430 : CK_AddressSpaceConversion /* 1b */; 6431 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace 6432 ? CK_BitCast /* 1a */ 6433 : CK_AddressSpaceConversion /* 1b */; 6434 ResultTy = S.Context.getPointerType(ResultTy); 6435 } 6436 6437 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast 6438 // if the target type does not change. 6439 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6440 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6441 return ResultTy; 6442 } 6443 6444 /// \brief Return the resulting type when the operands are both block pointers. 6445 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6446 ExprResult &LHS, 6447 ExprResult &RHS, 6448 SourceLocation Loc) { 6449 QualType LHSTy = LHS.get()->getType(); 6450 QualType RHSTy = RHS.get()->getType(); 6451 6452 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6453 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6454 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6455 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6456 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6457 return destType; 6458 } 6459 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6460 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6461 << RHS.get()->getSourceRange(); 6462 return QualType(); 6463 } 6464 6465 // We have 2 block pointer types. 6466 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6467 } 6468 6469 /// \brief Return the resulting type when the operands are both pointers. 6470 static QualType 6471 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6472 ExprResult &RHS, 6473 SourceLocation Loc) { 6474 // get the pointer types 6475 QualType LHSTy = LHS.get()->getType(); 6476 QualType RHSTy = RHS.get()->getType(); 6477 6478 // get the "pointed to" types 6479 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6480 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6481 6482 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6483 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6484 // Figure out necessary qualifiers (C99 6.5.15p6) 6485 QualType destPointee 6486 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6487 QualType destType = S.Context.getPointerType(destPointee); 6488 // Add qualifiers if necessary. 6489 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6490 // Promote to void*. 6491 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6492 return destType; 6493 } 6494 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6495 QualType destPointee 6496 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6497 QualType destType = S.Context.getPointerType(destPointee); 6498 // Add qualifiers if necessary. 6499 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6500 // Promote to void*. 6501 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6502 return destType; 6503 } 6504 6505 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6506 } 6507 6508 /// \brief Return false if the first expression is not an integer and the second 6509 /// expression is not a pointer, true otherwise. 6510 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6511 Expr* PointerExpr, SourceLocation Loc, 6512 bool IsIntFirstExpr) { 6513 if (!PointerExpr->getType()->isPointerType() || 6514 !Int.get()->getType()->isIntegerType()) 6515 return false; 6516 6517 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6518 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6519 6520 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6521 << Expr1->getType() << Expr2->getType() 6522 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6523 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6524 CK_IntegralToPointer); 6525 return true; 6526 } 6527 6528 /// \brief Simple conversion between integer and floating point types. 6529 /// 6530 /// Used when handling the OpenCL conditional operator where the 6531 /// condition is a vector while the other operands are scalar. 6532 /// 6533 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6534 /// types are either integer or floating type. Between the two 6535 /// operands, the type with the higher rank is defined as the "result 6536 /// type". The other operand needs to be promoted to the same type. No 6537 /// other type promotion is allowed. We cannot use 6538 /// UsualArithmeticConversions() for this purpose, since it always 6539 /// promotes promotable types. 6540 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6541 ExprResult &RHS, 6542 SourceLocation QuestionLoc) { 6543 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6544 if (LHS.isInvalid()) 6545 return QualType(); 6546 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6547 if (RHS.isInvalid()) 6548 return QualType(); 6549 6550 // For conversion purposes, we ignore any qualifiers. 6551 // For example, "const float" and "float" are equivalent. 6552 QualType LHSType = 6553 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6554 QualType RHSType = 6555 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6556 6557 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6558 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6559 << LHSType << LHS.get()->getSourceRange(); 6560 return QualType(); 6561 } 6562 6563 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6564 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6565 << RHSType << RHS.get()->getSourceRange(); 6566 return QualType(); 6567 } 6568 6569 // If both types are identical, no conversion is needed. 6570 if (LHSType == RHSType) 6571 return LHSType; 6572 6573 // Now handle "real" floating types (i.e. float, double, long double). 6574 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6575 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6576 /*IsCompAssign = */ false); 6577 6578 // Finally, we have two differing integer types. 6579 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6580 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6581 } 6582 6583 /// \brief Convert scalar operands to a vector that matches the 6584 /// condition in length. 6585 /// 6586 /// Used when handling the OpenCL conditional operator where the 6587 /// condition is a vector while the other operands are scalar. 6588 /// 6589 /// We first compute the "result type" for the scalar operands 6590 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6591 /// into a vector of that type where the length matches the condition 6592 /// vector type. s6.11.6 requires that the element types of the result 6593 /// and the condition must have the same number of bits. 6594 static QualType 6595 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6596 QualType CondTy, SourceLocation QuestionLoc) { 6597 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6598 if (ResTy.isNull()) return QualType(); 6599 6600 const VectorType *CV = CondTy->getAs<VectorType>(); 6601 assert(CV); 6602 6603 // Determine the vector result type 6604 unsigned NumElements = CV->getNumElements(); 6605 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6606 6607 // Ensure that all types have the same number of bits 6608 if (S.Context.getTypeSize(CV->getElementType()) 6609 != S.Context.getTypeSize(ResTy)) { 6610 // Since VectorTy is created internally, it does not pretty print 6611 // with an OpenCL name. Instead, we just print a description. 6612 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6613 SmallString<64> Str; 6614 llvm::raw_svector_ostream OS(Str); 6615 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6616 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6617 << CondTy << OS.str(); 6618 return QualType(); 6619 } 6620 6621 // Convert operands to the vector result type 6622 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6623 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6624 6625 return VectorTy; 6626 } 6627 6628 /// \brief Return false if this is a valid OpenCL condition vector 6629 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6630 SourceLocation QuestionLoc) { 6631 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6632 // integral type. 6633 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6634 assert(CondTy); 6635 QualType EleTy = CondTy->getElementType(); 6636 if (EleTy->isIntegerType()) return false; 6637 6638 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6639 << Cond->getType() << Cond->getSourceRange(); 6640 return true; 6641 } 6642 6643 /// \brief Return false if the vector condition type and the vector 6644 /// result type are compatible. 6645 /// 6646 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6647 /// number of elements, and their element types have the same number 6648 /// of bits. 6649 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6650 SourceLocation QuestionLoc) { 6651 const VectorType *CV = CondTy->getAs<VectorType>(); 6652 const VectorType *RV = VecResTy->getAs<VectorType>(); 6653 assert(CV && RV); 6654 6655 if (CV->getNumElements() != RV->getNumElements()) { 6656 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6657 << CondTy << VecResTy; 6658 return true; 6659 } 6660 6661 QualType CVE = CV->getElementType(); 6662 QualType RVE = RV->getElementType(); 6663 6664 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6665 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6666 << CondTy << VecResTy; 6667 return true; 6668 } 6669 6670 return false; 6671 } 6672 6673 /// \brief Return the resulting type for the conditional operator in 6674 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6675 /// s6.3.i) when the condition is a vector type. 6676 static QualType 6677 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6678 ExprResult &LHS, ExprResult &RHS, 6679 SourceLocation QuestionLoc) { 6680 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6681 if (Cond.isInvalid()) 6682 return QualType(); 6683 QualType CondTy = Cond.get()->getType(); 6684 6685 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6686 return QualType(); 6687 6688 // If either operand is a vector then find the vector type of the 6689 // result as specified in OpenCL v1.1 s6.3.i. 6690 if (LHS.get()->getType()->isVectorType() || 6691 RHS.get()->getType()->isVectorType()) { 6692 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6693 /*isCompAssign*/false, 6694 /*AllowBothBool*/true, 6695 /*AllowBoolConversions*/false); 6696 if (VecResTy.isNull()) return QualType(); 6697 // The result type must match the condition type as specified in 6698 // OpenCL v1.1 s6.11.6. 6699 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6700 return QualType(); 6701 return VecResTy; 6702 } 6703 6704 // Both operands are scalar. 6705 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6706 } 6707 6708 /// \brief Return true if the Expr is block type 6709 static bool checkBlockType(Sema &S, const Expr *E) { 6710 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6711 QualType Ty = CE->getCallee()->getType(); 6712 if (Ty->isBlockPointerType()) { 6713 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6714 return true; 6715 } 6716 } 6717 return false; 6718 } 6719 6720 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6721 /// In that case, LHS = cond. 6722 /// C99 6.5.15 6723 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6724 ExprResult &RHS, ExprValueKind &VK, 6725 ExprObjectKind &OK, 6726 SourceLocation QuestionLoc) { 6727 6728 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6729 if (!LHSResult.isUsable()) return QualType(); 6730 LHS = LHSResult; 6731 6732 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6733 if (!RHSResult.isUsable()) return QualType(); 6734 RHS = RHSResult; 6735 6736 // C++ is sufficiently different to merit its own checker. 6737 if (getLangOpts().CPlusPlus) 6738 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6739 6740 VK = VK_RValue; 6741 OK = OK_Ordinary; 6742 6743 // The OpenCL operator with a vector condition is sufficiently 6744 // different to merit its own checker. 6745 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6746 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6747 6748 // First, check the condition. 6749 Cond = UsualUnaryConversions(Cond.get()); 6750 if (Cond.isInvalid()) 6751 return QualType(); 6752 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6753 return QualType(); 6754 6755 // Now check the two expressions. 6756 if (LHS.get()->getType()->isVectorType() || 6757 RHS.get()->getType()->isVectorType()) 6758 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6759 /*AllowBothBool*/true, 6760 /*AllowBoolConversions*/false); 6761 6762 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6763 if (LHS.isInvalid() || RHS.isInvalid()) 6764 return QualType(); 6765 6766 QualType LHSTy = LHS.get()->getType(); 6767 QualType RHSTy = RHS.get()->getType(); 6768 6769 // Diagnose attempts to convert between __float128 and long double where 6770 // such conversions currently can't be handled. 6771 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6772 Diag(QuestionLoc, 6773 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6774 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6775 return QualType(); 6776 } 6777 6778 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6779 // selection operator (?:). 6780 if (getLangOpts().OpenCL && 6781 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6782 return QualType(); 6783 } 6784 6785 // If both operands have arithmetic type, do the usual arithmetic conversions 6786 // to find a common type: C99 6.5.15p3,5. 6787 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6788 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6789 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6790 6791 return ResTy; 6792 } 6793 6794 // If both operands are the same structure or union type, the result is that 6795 // type. 6796 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6797 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6798 if (LHSRT->getDecl() == RHSRT->getDecl()) 6799 // "If both the operands have structure or union type, the result has 6800 // that type." This implies that CV qualifiers are dropped. 6801 return LHSTy.getUnqualifiedType(); 6802 // FIXME: Type of conditional expression must be complete in C mode. 6803 } 6804 6805 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6806 // The following || allows only one side to be void (a GCC-ism). 6807 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6808 return checkConditionalVoidType(*this, LHS, RHS); 6809 } 6810 6811 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6812 // the type of the other operand." 6813 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6814 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6815 6816 // All objective-c pointer type analysis is done here. 6817 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6818 QuestionLoc); 6819 if (LHS.isInvalid() || RHS.isInvalid()) 6820 return QualType(); 6821 if (!compositeType.isNull()) 6822 return compositeType; 6823 6824 6825 // Handle block pointer types. 6826 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6827 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6828 QuestionLoc); 6829 6830 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6831 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6832 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6833 QuestionLoc); 6834 6835 // GCC compatibility: soften pointer/integer mismatch. Note that 6836 // null pointers have been filtered out by this point. 6837 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6838 /*isIntFirstExpr=*/true)) 6839 return RHSTy; 6840 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6841 /*isIntFirstExpr=*/false)) 6842 return LHSTy; 6843 6844 // Emit a better diagnostic if one of the expressions is a null pointer 6845 // constant and the other is not a pointer type. In this case, the user most 6846 // likely forgot to take the address of the other expression. 6847 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6848 return QualType(); 6849 6850 // Otherwise, the operands are not compatible. 6851 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6852 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6853 << RHS.get()->getSourceRange(); 6854 return QualType(); 6855 } 6856 6857 /// FindCompositeObjCPointerType - Helper method to find composite type of 6858 /// two objective-c pointer types of the two input expressions. 6859 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6860 SourceLocation QuestionLoc) { 6861 QualType LHSTy = LHS.get()->getType(); 6862 QualType RHSTy = RHS.get()->getType(); 6863 6864 // Handle things like Class and struct objc_class*. Here we case the result 6865 // to the pseudo-builtin, because that will be implicitly cast back to the 6866 // redefinition type if an attempt is made to access its fields. 6867 if (LHSTy->isObjCClassType() && 6868 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6869 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6870 return LHSTy; 6871 } 6872 if (RHSTy->isObjCClassType() && 6873 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6874 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6875 return RHSTy; 6876 } 6877 // And the same for struct objc_object* / id 6878 if (LHSTy->isObjCIdType() && 6879 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6880 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6881 return LHSTy; 6882 } 6883 if (RHSTy->isObjCIdType() && 6884 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6885 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6886 return RHSTy; 6887 } 6888 // And the same for struct objc_selector* / SEL 6889 if (Context.isObjCSelType(LHSTy) && 6890 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6891 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6892 return LHSTy; 6893 } 6894 if (Context.isObjCSelType(RHSTy) && 6895 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6896 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6897 return RHSTy; 6898 } 6899 // Check constraints for Objective-C object pointers types. 6900 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6901 6902 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6903 // Two identical object pointer types are always compatible. 6904 return LHSTy; 6905 } 6906 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6907 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6908 QualType compositeType = LHSTy; 6909 6910 // If both operands are interfaces and either operand can be 6911 // assigned to the other, use that type as the composite 6912 // type. This allows 6913 // xxx ? (A*) a : (B*) b 6914 // where B is a subclass of A. 6915 // 6916 // Additionally, as for assignment, if either type is 'id' 6917 // allow silent coercion. Finally, if the types are 6918 // incompatible then make sure to use 'id' as the composite 6919 // type so the result is acceptable for sending messages to. 6920 6921 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6922 // It could return the composite type. 6923 if (!(compositeType = 6924 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6925 // Nothing more to do. 6926 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6927 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6928 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6929 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6930 } else if ((LHSTy->isObjCQualifiedIdType() || 6931 RHSTy->isObjCQualifiedIdType()) && 6932 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6933 // Need to handle "id<xx>" explicitly. 6934 // GCC allows qualified id and any Objective-C type to devolve to 6935 // id. Currently localizing to here until clear this should be 6936 // part of ObjCQualifiedIdTypesAreCompatible. 6937 compositeType = Context.getObjCIdType(); 6938 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6939 compositeType = Context.getObjCIdType(); 6940 } else { 6941 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6942 << LHSTy << RHSTy 6943 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6944 QualType incompatTy = Context.getObjCIdType(); 6945 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6946 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6947 return incompatTy; 6948 } 6949 // The object pointer types are compatible. 6950 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6951 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6952 return compositeType; 6953 } 6954 // Check Objective-C object pointer types and 'void *' 6955 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6956 if (getLangOpts().ObjCAutoRefCount) { 6957 // ARC forbids the implicit conversion of object pointers to 'void *', 6958 // so these types are not compatible. 6959 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6960 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6961 LHS = RHS = true; 6962 return QualType(); 6963 } 6964 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6965 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6966 QualType destPointee 6967 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6968 QualType destType = Context.getPointerType(destPointee); 6969 // Add qualifiers if necessary. 6970 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6971 // Promote to void*. 6972 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6973 return destType; 6974 } 6975 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6976 if (getLangOpts().ObjCAutoRefCount) { 6977 // ARC forbids the implicit conversion of object pointers to 'void *', 6978 // so these types are not compatible. 6979 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6980 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6981 LHS = RHS = true; 6982 return QualType(); 6983 } 6984 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6985 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6986 QualType destPointee 6987 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6988 QualType destType = Context.getPointerType(destPointee); 6989 // Add qualifiers if necessary. 6990 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6991 // Promote to void*. 6992 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6993 return destType; 6994 } 6995 return QualType(); 6996 } 6997 6998 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6999 /// ParenRange in parentheses. 7000 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7001 const PartialDiagnostic &Note, 7002 SourceRange ParenRange) { 7003 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7004 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7005 EndLoc.isValid()) { 7006 Self.Diag(Loc, Note) 7007 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7008 << FixItHint::CreateInsertion(EndLoc, ")"); 7009 } else { 7010 // We can't display the parentheses, so just show the bare note. 7011 Self.Diag(Loc, Note) << ParenRange; 7012 } 7013 } 7014 7015 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7016 return BinaryOperator::isAdditiveOp(Opc) || 7017 BinaryOperator::isMultiplicativeOp(Opc) || 7018 BinaryOperator::isShiftOp(Opc); 7019 } 7020 7021 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7022 /// expression, either using a built-in or overloaded operator, 7023 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7024 /// expression. 7025 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7026 Expr **RHSExprs) { 7027 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7028 E = E->IgnoreImpCasts(); 7029 E = E->IgnoreConversionOperator(); 7030 E = E->IgnoreImpCasts(); 7031 7032 // Built-in binary operator. 7033 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7034 if (IsArithmeticOp(OP->getOpcode())) { 7035 *Opcode = OP->getOpcode(); 7036 *RHSExprs = OP->getRHS(); 7037 return true; 7038 } 7039 } 7040 7041 // Overloaded operator. 7042 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7043 if (Call->getNumArgs() != 2) 7044 return false; 7045 7046 // Make sure this is really a binary operator that is safe to pass into 7047 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7048 OverloadedOperatorKind OO = Call->getOperator(); 7049 if (OO < OO_Plus || OO > OO_Arrow || 7050 OO == OO_PlusPlus || OO == OO_MinusMinus) 7051 return false; 7052 7053 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7054 if (IsArithmeticOp(OpKind)) { 7055 *Opcode = OpKind; 7056 *RHSExprs = Call->getArg(1); 7057 return true; 7058 } 7059 } 7060 7061 return false; 7062 } 7063 7064 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7065 /// or is a logical expression such as (x==y) which has int type, but is 7066 /// commonly interpreted as boolean. 7067 static bool ExprLooksBoolean(Expr *E) { 7068 E = E->IgnoreParenImpCasts(); 7069 7070 if (E->getType()->isBooleanType()) 7071 return true; 7072 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7073 return OP->isComparisonOp() || OP->isLogicalOp(); 7074 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7075 return OP->getOpcode() == UO_LNot; 7076 if (E->getType()->isPointerType()) 7077 return true; 7078 7079 return false; 7080 } 7081 7082 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7083 /// and binary operator are mixed in a way that suggests the programmer assumed 7084 /// the conditional operator has higher precedence, for example: 7085 /// "int x = a + someBinaryCondition ? 1 : 2". 7086 static void DiagnoseConditionalPrecedence(Sema &Self, 7087 SourceLocation OpLoc, 7088 Expr *Condition, 7089 Expr *LHSExpr, 7090 Expr *RHSExpr) { 7091 BinaryOperatorKind CondOpcode; 7092 Expr *CondRHS; 7093 7094 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7095 return; 7096 if (!ExprLooksBoolean(CondRHS)) 7097 return; 7098 7099 // The condition is an arithmetic binary expression, with a right- 7100 // hand side that looks boolean, so warn. 7101 7102 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7103 << Condition->getSourceRange() 7104 << BinaryOperator::getOpcodeStr(CondOpcode); 7105 7106 SuggestParentheses(Self, OpLoc, 7107 Self.PDiag(diag::note_precedence_silence) 7108 << BinaryOperator::getOpcodeStr(CondOpcode), 7109 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7110 7111 SuggestParentheses(Self, OpLoc, 7112 Self.PDiag(diag::note_precedence_conditional_first), 7113 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7114 } 7115 7116 /// Compute the nullability of a conditional expression. 7117 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7118 QualType LHSTy, QualType RHSTy, 7119 ASTContext &Ctx) { 7120 if (!ResTy->isAnyPointerType()) 7121 return ResTy; 7122 7123 auto GetNullability = [&Ctx](QualType Ty) { 7124 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7125 if (Kind) 7126 return *Kind; 7127 return NullabilityKind::Unspecified; 7128 }; 7129 7130 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7131 NullabilityKind MergedKind; 7132 7133 // Compute nullability of a binary conditional expression. 7134 if (IsBin) { 7135 if (LHSKind == NullabilityKind::NonNull) 7136 MergedKind = NullabilityKind::NonNull; 7137 else 7138 MergedKind = RHSKind; 7139 // Compute nullability of a normal conditional expression. 7140 } else { 7141 if (LHSKind == NullabilityKind::Nullable || 7142 RHSKind == NullabilityKind::Nullable) 7143 MergedKind = NullabilityKind::Nullable; 7144 else if (LHSKind == NullabilityKind::NonNull) 7145 MergedKind = RHSKind; 7146 else if (RHSKind == NullabilityKind::NonNull) 7147 MergedKind = LHSKind; 7148 else 7149 MergedKind = NullabilityKind::Unspecified; 7150 } 7151 7152 // Return if ResTy already has the correct nullability. 7153 if (GetNullability(ResTy) == MergedKind) 7154 return ResTy; 7155 7156 // Strip all nullability from ResTy. 7157 while (ResTy->getNullability(Ctx)) 7158 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7159 7160 // Create a new AttributedType with the new nullability kind. 7161 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7162 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7163 } 7164 7165 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7166 /// in the case of a the GNU conditional expr extension. 7167 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7168 SourceLocation ColonLoc, 7169 Expr *CondExpr, Expr *LHSExpr, 7170 Expr *RHSExpr) { 7171 if (!getLangOpts().CPlusPlus) { 7172 // C cannot handle TypoExpr nodes in the condition because it 7173 // doesn't handle dependent types properly, so make sure any TypoExprs have 7174 // been dealt with before checking the operands. 7175 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7176 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7177 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7178 7179 if (!CondResult.isUsable()) 7180 return ExprError(); 7181 7182 if (LHSExpr) { 7183 if (!LHSResult.isUsable()) 7184 return ExprError(); 7185 } 7186 7187 if (!RHSResult.isUsable()) 7188 return ExprError(); 7189 7190 CondExpr = CondResult.get(); 7191 LHSExpr = LHSResult.get(); 7192 RHSExpr = RHSResult.get(); 7193 } 7194 7195 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7196 // was the condition. 7197 OpaqueValueExpr *opaqueValue = nullptr; 7198 Expr *commonExpr = nullptr; 7199 if (!LHSExpr) { 7200 commonExpr = CondExpr; 7201 // Lower out placeholder types first. This is important so that we don't 7202 // try to capture a placeholder. This happens in few cases in C++; such 7203 // as Objective-C++'s dictionary subscripting syntax. 7204 if (commonExpr->hasPlaceholderType()) { 7205 ExprResult result = CheckPlaceholderExpr(commonExpr); 7206 if (!result.isUsable()) return ExprError(); 7207 commonExpr = result.get(); 7208 } 7209 // We usually want to apply unary conversions *before* saving, except 7210 // in the special case of a C++ l-value conditional. 7211 if (!(getLangOpts().CPlusPlus 7212 && !commonExpr->isTypeDependent() 7213 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7214 && commonExpr->isGLValue() 7215 && commonExpr->isOrdinaryOrBitFieldObject() 7216 && RHSExpr->isOrdinaryOrBitFieldObject() 7217 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7218 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7219 if (commonRes.isInvalid()) 7220 return ExprError(); 7221 commonExpr = commonRes.get(); 7222 } 7223 7224 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7225 commonExpr->getType(), 7226 commonExpr->getValueKind(), 7227 commonExpr->getObjectKind(), 7228 commonExpr); 7229 LHSExpr = CondExpr = opaqueValue; 7230 } 7231 7232 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7233 ExprValueKind VK = VK_RValue; 7234 ExprObjectKind OK = OK_Ordinary; 7235 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7236 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7237 VK, OK, QuestionLoc); 7238 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7239 RHS.isInvalid()) 7240 return ExprError(); 7241 7242 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7243 RHS.get()); 7244 7245 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7246 7247 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7248 Context); 7249 7250 if (!commonExpr) 7251 return new (Context) 7252 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7253 RHS.get(), result, VK, OK); 7254 7255 return new (Context) BinaryConditionalOperator( 7256 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7257 ColonLoc, result, VK, OK); 7258 } 7259 7260 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7261 // being closely modeled after the C99 spec:-). The odd characteristic of this 7262 // routine is it effectively iqnores the qualifiers on the top level pointee. 7263 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7264 // FIXME: add a couple examples in this comment. 7265 static Sema::AssignConvertType 7266 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7267 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7268 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7269 7270 // get the "pointed to" type (ignoring qualifiers at the top level) 7271 const Type *lhptee, *rhptee; 7272 Qualifiers lhq, rhq; 7273 std::tie(lhptee, lhq) = 7274 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7275 std::tie(rhptee, rhq) = 7276 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7277 7278 Sema::AssignConvertType ConvTy = Sema::Compatible; 7279 7280 // C99 6.5.16.1p1: This following citation is common to constraints 7281 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7282 // qualifiers of the type *pointed to* by the right; 7283 7284 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7285 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7286 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7287 // Ignore lifetime for further calculation. 7288 lhq.removeObjCLifetime(); 7289 rhq.removeObjCLifetime(); 7290 } 7291 7292 if (!lhq.compatiblyIncludes(rhq)) { 7293 // Treat address-space mismatches as fatal. TODO: address subspaces 7294 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7295 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7296 7297 // It's okay to add or remove GC or lifetime qualifiers when converting to 7298 // and from void*. 7299 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7300 .compatiblyIncludes( 7301 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7302 && (lhptee->isVoidType() || rhptee->isVoidType())) 7303 ; // keep old 7304 7305 // Treat lifetime mismatches as fatal. 7306 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7307 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7308 7309 // For GCC/MS compatibility, other qualifier mismatches are treated 7310 // as still compatible in C. 7311 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7312 } 7313 7314 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7315 // incomplete type and the other is a pointer to a qualified or unqualified 7316 // version of void... 7317 if (lhptee->isVoidType()) { 7318 if (rhptee->isIncompleteOrObjectType()) 7319 return ConvTy; 7320 7321 // As an extension, we allow cast to/from void* to function pointer. 7322 assert(rhptee->isFunctionType()); 7323 return Sema::FunctionVoidPointer; 7324 } 7325 7326 if (rhptee->isVoidType()) { 7327 if (lhptee->isIncompleteOrObjectType()) 7328 return ConvTy; 7329 7330 // As an extension, we allow cast to/from void* to function pointer. 7331 assert(lhptee->isFunctionType()); 7332 return Sema::FunctionVoidPointer; 7333 } 7334 7335 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7336 // unqualified versions of compatible types, ... 7337 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7338 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7339 // Check if the pointee types are compatible ignoring the sign. 7340 // We explicitly check for char so that we catch "char" vs 7341 // "unsigned char" on systems where "char" is unsigned. 7342 if (lhptee->isCharType()) 7343 ltrans = S.Context.UnsignedCharTy; 7344 else if (lhptee->hasSignedIntegerRepresentation()) 7345 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7346 7347 if (rhptee->isCharType()) 7348 rtrans = S.Context.UnsignedCharTy; 7349 else if (rhptee->hasSignedIntegerRepresentation()) 7350 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7351 7352 if (ltrans == rtrans) { 7353 // Types are compatible ignoring the sign. Qualifier incompatibility 7354 // takes priority over sign incompatibility because the sign 7355 // warning can be disabled. 7356 if (ConvTy != Sema::Compatible) 7357 return ConvTy; 7358 7359 return Sema::IncompatiblePointerSign; 7360 } 7361 7362 // If we are a multi-level pointer, it's possible that our issue is simply 7363 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7364 // the eventual target type is the same and the pointers have the same 7365 // level of indirection, this must be the issue. 7366 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7367 do { 7368 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7369 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7370 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7371 7372 if (lhptee == rhptee) 7373 return Sema::IncompatibleNestedPointerQualifiers; 7374 } 7375 7376 // General pointer incompatibility takes priority over qualifiers. 7377 return Sema::IncompatiblePointer; 7378 } 7379 if (!S.getLangOpts().CPlusPlus && 7380 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7381 return Sema::IncompatiblePointer; 7382 return ConvTy; 7383 } 7384 7385 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7386 /// block pointer types are compatible or whether a block and normal pointer 7387 /// are compatible. It is more restrict than comparing two function pointer 7388 // types. 7389 static Sema::AssignConvertType 7390 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7391 QualType RHSType) { 7392 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7393 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7394 7395 QualType lhptee, rhptee; 7396 7397 // get the "pointed to" type (ignoring qualifiers at the top level) 7398 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7399 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7400 7401 // In C++, the types have to match exactly. 7402 if (S.getLangOpts().CPlusPlus) 7403 return Sema::IncompatibleBlockPointer; 7404 7405 Sema::AssignConvertType ConvTy = Sema::Compatible; 7406 7407 // For blocks we enforce that qualifiers are identical. 7408 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7409 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7410 7411 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7412 return Sema::IncompatibleBlockPointer; 7413 7414 return ConvTy; 7415 } 7416 7417 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7418 /// for assignment compatibility. 7419 static Sema::AssignConvertType 7420 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7421 QualType RHSType) { 7422 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7423 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7424 7425 if (LHSType->isObjCBuiltinType()) { 7426 // Class is not compatible with ObjC object pointers. 7427 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7428 !RHSType->isObjCQualifiedClassType()) 7429 return Sema::IncompatiblePointer; 7430 return Sema::Compatible; 7431 } 7432 if (RHSType->isObjCBuiltinType()) { 7433 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7434 !LHSType->isObjCQualifiedClassType()) 7435 return Sema::IncompatiblePointer; 7436 return Sema::Compatible; 7437 } 7438 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7439 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7440 7441 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7442 // make an exception for id<P> 7443 !LHSType->isObjCQualifiedIdType()) 7444 return Sema::CompatiblePointerDiscardsQualifiers; 7445 7446 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7447 return Sema::Compatible; 7448 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7449 return Sema::IncompatibleObjCQualifiedId; 7450 return Sema::IncompatiblePointer; 7451 } 7452 7453 Sema::AssignConvertType 7454 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7455 QualType LHSType, QualType RHSType) { 7456 // Fake up an opaque expression. We don't actually care about what 7457 // cast operations are required, so if CheckAssignmentConstraints 7458 // adds casts to this they'll be wasted, but fortunately that doesn't 7459 // usually happen on valid code. 7460 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7461 ExprResult RHSPtr = &RHSExpr; 7462 CastKind K = CK_Invalid; 7463 7464 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7465 } 7466 7467 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7468 /// has code to accommodate several GCC extensions when type checking 7469 /// pointers. Here are some objectionable examples that GCC considers warnings: 7470 /// 7471 /// int a, *pint; 7472 /// short *pshort; 7473 /// struct foo *pfoo; 7474 /// 7475 /// pint = pshort; // warning: assignment from incompatible pointer type 7476 /// a = pint; // warning: assignment makes integer from pointer without a cast 7477 /// pint = a; // warning: assignment makes pointer from integer without a cast 7478 /// pint = pfoo; // warning: assignment from incompatible pointer type 7479 /// 7480 /// As a result, the code for dealing with pointers is more complex than the 7481 /// C99 spec dictates. 7482 /// 7483 /// Sets 'Kind' for any result kind except Incompatible. 7484 Sema::AssignConvertType 7485 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7486 CastKind &Kind, bool ConvertRHS) { 7487 QualType RHSType = RHS.get()->getType(); 7488 QualType OrigLHSType = LHSType; 7489 7490 // Get canonical types. We're not formatting these types, just comparing 7491 // them. 7492 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7493 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7494 7495 // Common case: no conversion required. 7496 if (LHSType == RHSType) { 7497 Kind = CK_NoOp; 7498 return Compatible; 7499 } 7500 7501 // If we have an atomic type, try a non-atomic assignment, then just add an 7502 // atomic qualification step. 7503 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7504 Sema::AssignConvertType result = 7505 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7506 if (result != Compatible) 7507 return result; 7508 if (Kind != CK_NoOp && ConvertRHS) 7509 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7510 Kind = CK_NonAtomicToAtomic; 7511 return Compatible; 7512 } 7513 7514 // If the left-hand side is a reference type, then we are in a 7515 // (rare!) case where we've allowed the use of references in C, 7516 // e.g., as a parameter type in a built-in function. In this case, 7517 // just make sure that the type referenced is compatible with the 7518 // right-hand side type. The caller is responsible for adjusting 7519 // LHSType so that the resulting expression does not have reference 7520 // type. 7521 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7522 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7523 Kind = CK_LValueBitCast; 7524 return Compatible; 7525 } 7526 return Incompatible; 7527 } 7528 7529 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7530 // to the same ExtVector type. 7531 if (LHSType->isExtVectorType()) { 7532 if (RHSType->isExtVectorType()) 7533 return Incompatible; 7534 if (RHSType->isArithmeticType()) { 7535 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7536 if (ConvertRHS) 7537 RHS = prepareVectorSplat(LHSType, RHS.get()); 7538 Kind = CK_VectorSplat; 7539 return Compatible; 7540 } 7541 } 7542 7543 // Conversions to or from vector type. 7544 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7545 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7546 // Allow assignments of an AltiVec vector type to an equivalent GCC 7547 // vector type and vice versa 7548 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7549 Kind = CK_BitCast; 7550 return Compatible; 7551 } 7552 7553 // If we are allowing lax vector conversions, and LHS and RHS are both 7554 // vectors, the total size only needs to be the same. This is a bitcast; 7555 // no bits are changed but the result type is different. 7556 if (isLaxVectorConversion(RHSType, LHSType)) { 7557 Kind = CK_BitCast; 7558 return IncompatibleVectors; 7559 } 7560 } 7561 7562 // When the RHS comes from another lax conversion (e.g. binops between 7563 // scalars and vectors) the result is canonicalized as a vector. When the 7564 // LHS is also a vector, the lax is allowed by the condition above. Handle 7565 // the case where LHS is a scalar. 7566 if (LHSType->isScalarType()) { 7567 const VectorType *VecType = RHSType->getAs<VectorType>(); 7568 if (VecType && VecType->getNumElements() == 1 && 7569 isLaxVectorConversion(RHSType, LHSType)) { 7570 ExprResult *VecExpr = &RHS; 7571 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7572 Kind = CK_BitCast; 7573 return Compatible; 7574 } 7575 } 7576 7577 return Incompatible; 7578 } 7579 7580 // Diagnose attempts to convert between __float128 and long double where 7581 // such conversions currently can't be handled. 7582 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7583 return Incompatible; 7584 7585 // Arithmetic conversions. 7586 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7587 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7588 if (ConvertRHS) 7589 Kind = PrepareScalarCast(RHS, LHSType); 7590 return Compatible; 7591 } 7592 7593 // Conversions to normal pointers. 7594 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7595 // U* -> T* 7596 if (isa<PointerType>(RHSType)) { 7597 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7598 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7599 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7600 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7601 } 7602 7603 // int -> T* 7604 if (RHSType->isIntegerType()) { 7605 Kind = CK_IntegralToPointer; // FIXME: null? 7606 return IntToPointer; 7607 } 7608 7609 // C pointers are not compatible with ObjC object pointers, 7610 // with two exceptions: 7611 if (isa<ObjCObjectPointerType>(RHSType)) { 7612 // - conversions to void* 7613 if (LHSPointer->getPointeeType()->isVoidType()) { 7614 Kind = CK_BitCast; 7615 return Compatible; 7616 } 7617 7618 // - conversions from 'Class' to the redefinition type 7619 if (RHSType->isObjCClassType() && 7620 Context.hasSameType(LHSType, 7621 Context.getObjCClassRedefinitionType())) { 7622 Kind = CK_BitCast; 7623 return Compatible; 7624 } 7625 7626 Kind = CK_BitCast; 7627 return IncompatiblePointer; 7628 } 7629 7630 // U^ -> void* 7631 if (RHSType->getAs<BlockPointerType>()) { 7632 if (LHSPointer->getPointeeType()->isVoidType()) { 7633 Kind = CK_BitCast; 7634 return Compatible; 7635 } 7636 } 7637 7638 return Incompatible; 7639 } 7640 7641 // Conversions to block pointers. 7642 if (isa<BlockPointerType>(LHSType)) { 7643 // U^ -> T^ 7644 if (RHSType->isBlockPointerType()) { 7645 Kind = CK_BitCast; 7646 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7647 } 7648 7649 // int or null -> T^ 7650 if (RHSType->isIntegerType()) { 7651 Kind = CK_IntegralToPointer; // FIXME: null 7652 return IntToBlockPointer; 7653 } 7654 7655 // id -> T^ 7656 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7657 Kind = CK_AnyPointerToBlockPointerCast; 7658 return Compatible; 7659 } 7660 7661 // void* -> T^ 7662 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7663 if (RHSPT->getPointeeType()->isVoidType()) { 7664 Kind = CK_AnyPointerToBlockPointerCast; 7665 return Compatible; 7666 } 7667 7668 return Incompatible; 7669 } 7670 7671 // Conversions to Objective-C pointers. 7672 if (isa<ObjCObjectPointerType>(LHSType)) { 7673 // A* -> B* 7674 if (RHSType->isObjCObjectPointerType()) { 7675 Kind = CK_BitCast; 7676 Sema::AssignConvertType result = 7677 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7678 if (getLangOpts().ObjCAutoRefCount && 7679 result == Compatible && 7680 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7681 result = IncompatibleObjCWeakRef; 7682 return result; 7683 } 7684 7685 // int or null -> A* 7686 if (RHSType->isIntegerType()) { 7687 Kind = CK_IntegralToPointer; // FIXME: null 7688 return IntToPointer; 7689 } 7690 7691 // In general, C pointers are not compatible with ObjC object pointers, 7692 // with two exceptions: 7693 if (isa<PointerType>(RHSType)) { 7694 Kind = CK_CPointerToObjCPointerCast; 7695 7696 // - conversions from 'void*' 7697 if (RHSType->isVoidPointerType()) { 7698 return Compatible; 7699 } 7700 7701 // - conversions to 'Class' from its redefinition type 7702 if (LHSType->isObjCClassType() && 7703 Context.hasSameType(RHSType, 7704 Context.getObjCClassRedefinitionType())) { 7705 return Compatible; 7706 } 7707 7708 return IncompatiblePointer; 7709 } 7710 7711 // Only under strict condition T^ is compatible with an Objective-C pointer. 7712 if (RHSType->isBlockPointerType() && 7713 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7714 if (ConvertRHS) 7715 maybeExtendBlockObject(RHS); 7716 Kind = CK_BlockPointerToObjCPointerCast; 7717 return Compatible; 7718 } 7719 7720 return Incompatible; 7721 } 7722 7723 // Conversions from pointers that are not covered by the above. 7724 if (isa<PointerType>(RHSType)) { 7725 // T* -> _Bool 7726 if (LHSType == Context.BoolTy) { 7727 Kind = CK_PointerToBoolean; 7728 return Compatible; 7729 } 7730 7731 // T* -> int 7732 if (LHSType->isIntegerType()) { 7733 Kind = CK_PointerToIntegral; 7734 return PointerToInt; 7735 } 7736 7737 return Incompatible; 7738 } 7739 7740 // Conversions from Objective-C pointers that are not covered by the above. 7741 if (isa<ObjCObjectPointerType>(RHSType)) { 7742 // T* -> _Bool 7743 if (LHSType == Context.BoolTy) { 7744 Kind = CK_PointerToBoolean; 7745 return Compatible; 7746 } 7747 7748 // T* -> int 7749 if (LHSType->isIntegerType()) { 7750 Kind = CK_PointerToIntegral; 7751 return PointerToInt; 7752 } 7753 7754 return Incompatible; 7755 } 7756 7757 // struct A -> struct B 7758 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7759 if (Context.typesAreCompatible(LHSType, RHSType)) { 7760 Kind = CK_NoOp; 7761 return Compatible; 7762 } 7763 } 7764 7765 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7766 Kind = CK_IntToOCLSampler; 7767 return Compatible; 7768 } 7769 7770 return Incompatible; 7771 } 7772 7773 /// \brief Constructs a transparent union from an expression that is 7774 /// used to initialize the transparent union. 7775 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7776 ExprResult &EResult, QualType UnionType, 7777 FieldDecl *Field) { 7778 // Build an initializer list that designates the appropriate member 7779 // of the transparent union. 7780 Expr *E = EResult.get(); 7781 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7782 E, SourceLocation()); 7783 Initializer->setType(UnionType); 7784 Initializer->setInitializedFieldInUnion(Field); 7785 7786 // Build a compound literal constructing a value of the transparent 7787 // union type from this initializer list. 7788 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7789 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7790 VK_RValue, Initializer, false); 7791 } 7792 7793 Sema::AssignConvertType 7794 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7795 ExprResult &RHS) { 7796 QualType RHSType = RHS.get()->getType(); 7797 7798 // If the ArgType is a Union type, we want to handle a potential 7799 // transparent_union GCC extension. 7800 const RecordType *UT = ArgType->getAsUnionType(); 7801 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7802 return Incompatible; 7803 7804 // The field to initialize within the transparent union. 7805 RecordDecl *UD = UT->getDecl(); 7806 FieldDecl *InitField = nullptr; 7807 // It's compatible if the expression matches any of the fields. 7808 for (auto *it : UD->fields()) { 7809 if (it->getType()->isPointerType()) { 7810 // If the transparent union contains a pointer type, we allow: 7811 // 1) void pointer 7812 // 2) null pointer constant 7813 if (RHSType->isPointerType()) 7814 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7815 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7816 InitField = it; 7817 break; 7818 } 7819 7820 if (RHS.get()->isNullPointerConstant(Context, 7821 Expr::NPC_ValueDependentIsNull)) { 7822 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7823 CK_NullToPointer); 7824 InitField = it; 7825 break; 7826 } 7827 } 7828 7829 CastKind Kind = CK_Invalid; 7830 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7831 == Compatible) { 7832 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7833 InitField = it; 7834 break; 7835 } 7836 } 7837 7838 if (!InitField) 7839 return Incompatible; 7840 7841 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7842 return Compatible; 7843 } 7844 7845 Sema::AssignConvertType 7846 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7847 bool Diagnose, 7848 bool DiagnoseCFAudited, 7849 bool ConvertRHS) { 7850 // We need to be able to tell the caller whether we diagnosed a problem, if 7851 // they ask us to issue diagnostics. 7852 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7853 7854 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7855 // we can't avoid *all* modifications at the moment, so we need some somewhere 7856 // to put the updated value. 7857 ExprResult LocalRHS = CallerRHS; 7858 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7859 7860 if (getLangOpts().CPlusPlus) { 7861 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7862 // C++ 5.17p3: If the left operand is not of class type, the 7863 // expression is implicitly converted (C++ 4) to the 7864 // cv-unqualified type of the left operand. 7865 QualType RHSType = RHS.get()->getType(); 7866 if (Diagnose) { 7867 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7868 AA_Assigning); 7869 } else { 7870 ImplicitConversionSequence ICS = 7871 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7872 /*SuppressUserConversions=*/false, 7873 /*AllowExplicit=*/false, 7874 /*InOverloadResolution=*/false, 7875 /*CStyle=*/false, 7876 /*AllowObjCWritebackConversion=*/false); 7877 if (ICS.isFailure()) 7878 return Incompatible; 7879 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7880 ICS, AA_Assigning); 7881 } 7882 if (RHS.isInvalid()) 7883 return Incompatible; 7884 Sema::AssignConvertType result = Compatible; 7885 if (getLangOpts().ObjCAutoRefCount && 7886 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7887 result = IncompatibleObjCWeakRef; 7888 return result; 7889 } 7890 7891 // FIXME: Currently, we fall through and treat C++ classes like C 7892 // structures. 7893 // FIXME: We also fall through for atomics; not sure what should 7894 // happen there, though. 7895 } else if (RHS.get()->getType() == Context.OverloadTy) { 7896 // As a set of extensions to C, we support overloading on functions. These 7897 // functions need to be resolved here. 7898 DeclAccessPair DAP; 7899 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7900 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7901 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7902 else 7903 return Incompatible; 7904 } 7905 7906 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7907 // a null pointer constant. 7908 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7909 LHSType->isBlockPointerType()) && 7910 RHS.get()->isNullPointerConstant(Context, 7911 Expr::NPC_ValueDependentIsNull)) { 7912 if (Diagnose || ConvertRHS) { 7913 CastKind Kind; 7914 CXXCastPath Path; 7915 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7916 /*IgnoreBaseAccess=*/false, Diagnose); 7917 if (ConvertRHS) 7918 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7919 } 7920 return Compatible; 7921 } 7922 7923 // This check seems unnatural, however it is necessary to ensure the proper 7924 // conversion of functions/arrays. If the conversion were done for all 7925 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7926 // expressions that suppress this implicit conversion (&, sizeof). 7927 // 7928 // Suppress this for references: C++ 8.5.3p5. 7929 if (!LHSType->isReferenceType()) { 7930 // FIXME: We potentially allocate here even if ConvertRHS is false. 7931 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7932 if (RHS.isInvalid()) 7933 return Incompatible; 7934 } 7935 7936 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7937 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7938 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7939 if (PDecl && !PDecl->hasDefinition()) { 7940 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7941 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7942 } 7943 } 7944 7945 CastKind Kind = CK_Invalid; 7946 Sema::AssignConvertType result = 7947 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7948 7949 // C99 6.5.16.1p2: The value of the right operand is converted to the 7950 // type of the assignment expression. 7951 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7952 // so that we can use references in built-in functions even in C. 7953 // The getNonReferenceType() call makes sure that the resulting expression 7954 // does not have reference type. 7955 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7956 QualType Ty = LHSType.getNonLValueExprType(Context); 7957 Expr *E = RHS.get(); 7958 7959 // Check for various Objective-C errors. If we are not reporting 7960 // diagnostics and just checking for errors, e.g., during overload 7961 // resolution, return Incompatible to indicate the failure. 7962 if (getLangOpts().ObjCAutoRefCount && 7963 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7964 Diagnose, DiagnoseCFAudited) != ACR_okay) { 7965 if (!Diagnose) 7966 return Incompatible; 7967 } 7968 if (getLangOpts().ObjC1 && 7969 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7970 E->getType(), E, Diagnose) || 7971 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7972 if (!Diagnose) 7973 return Incompatible; 7974 // Replace the expression with a corrected version and continue so we 7975 // can find further errors. 7976 RHS = E; 7977 return Compatible; 7978 } 7979 7980 if (ConvertRHS) 7981 RHS = ImpCastExprToType(E, Ty, Kind); 7982 } 7983 return result; 7984 } 7985 7986 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7987 ExprResult &RHS) { 7988 Diag(Loc, diag::err_typecheck_invalid_operands) 7989 << LHS.get()->getType() << RHS.get()->getType() 7990 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7991 return QualType(); 7992 } 7993 7994 /// Try to convert a value of non-vector type to a vector type by converting 7995 /// the type to the element type of the vector and then performing a splat. 7996 /// If the language is OpenCL, we only use conversions that promote scalar 7997 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7998 /// for float->int. 7999 /// 8000 /// \param scalar - if non-null, actually perform the conversions 8001 /// \return true if the operation fails (but without diagnosing the failure) 8002 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8003 QualType scalarTy, 8004 QualType vectorEltTy, 8005 QualType vectorTy) { 8006 // The conversion to apply to the scalar before splatting it, 8007 // if necessary. 8008 CastKind scalarCast = CK_Invalid; 8009 8010 if (vectorEltTy->isIntegralType(S.Context)) { 8011 if (!scalarTy->isIntegralType(S.Context)) 8012 return true; 8013 if (S.getLangOpts().OpenCL && 8014 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 8015 return true; 8016 scalarCast = CK_IntegralCast; 8017 } else if (vectorEltTy->isRealFloatingType()) { 8018 if (scalarTy->isRealFloatingType()) { 8019 if (S.getLangOpts().OpenCL && 8020 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 8021 return true; 8022 scalarCast = CK_FloatingCast; 8023 } 8024 else if (scalarTy->isIntegralType(S.Context)) 8025 scalarCast = CK_IntegralToFloating; 8026 else 8027 return true; 8028 } else { 8029 return true; 8030 } 8031 8032 // Adjust scalar if desired. 8033 if (scalar) { 8034 if (scalarCast != CK_Invalid) 8035 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8036 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8037 } 8038 return false; 8039 } 8040 8041 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8042 SourceLocation Loc, bool IsCompAssign, 8043 bool AllowBothBool, 8044 bool AllowBoolConversions) { 8045 if (!IsCompAssign) { 8046 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8047 if (LHS.isInvalid()) 8048 return QualType(); 8049 } 8050 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8051 if (RHS.isInvalid()) 8052 return QualType(); 8053 8054 // For conversion purposes, we ignore any qualifiers. 8055 // For example, "const float" and "float" are equivalent. 8056 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8057 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8058 8059 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8060 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8061 assert(LHSVecType || RHSVecType); 8062 8063 // AltiVec-style "vector bool op vector bool" combinations are allowed 8064 // for some operators but not others. 8065 if (!AllowBothBool && 8066 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8067 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8068 return InvalidOperands(Loc, LHS, RHS); 8069 8070 // If the vector types are identical, return. 8071 if (Context.hasSameType(LHSType, RHSType)) 8072 return LHSType; 8073 8074 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8075 if (LHSVecType && RHSVecType && 8076 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8077 if (isa<ExtVectorType>(LHSVecType)) { 8078 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8079 return LHSType; 8080 } 8081 8082 if (!IsCompAssign) 8083 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8084 return RHSType; 8085 } 8086 8087 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8088 // can be mixed, with the result being the non-bool type. The non-bool 8089 // operand must have integer element type. 8090 if (AllowBoolConversions && LHSVecType && RHSVecType && 8091 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8092 (Context.getTypeSize(LHSVecType->getElementType()) == 8093 Context.getTypeSize(RHSVecType->getElementType()))) { 8094 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8095 LHSVecType->getElementType()->isIntegerType() && 8096 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8097 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8098 return LHSType; 8099 } 8100 if (!IsCompAssign && 8101 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8102 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8103 RHSVecType->getElementType()->isIntegerType()) { 8104 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8105 return RHSType; 8106 } 8107 } 8108 8109 // If there's an ext-vector type and a scalar, try to convert the scalar to 8110 // the vector element type and splat. 8111 // FIXME: this should also work for regular vector types as supported in GCC. 8112 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 8113 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8114 LHSVecType->getElementType(), LHSType)) 8115 return LHSType; 8116 } 8117 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 8118 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8119 LHSType, RHSVecType->getElementType(), 8120 RHSType)) 8121 return RHSType; 8122 } 8123 8124 // FIXME: The code below also handles convertion between vectors and 8125 // non-scalars, we should break this down into fine grained specific checks 8126 // and emit proper diagnostics. 8127 QualType VecType = LHSVecType ? LHSType : RHSType; 8128 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8129 QualType OtherType = LHSVecType ? RHSType : LHSType; 8130 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8131 if (isLaxVectorConversion(OtherType, VecType)) { 8132 // If we're allowing lax vector conversions, only the total (data) size 8133 // needs to be the same. For non compound assignment, if one of the types is 8134 // scalar, the result is always the vector type. 8135 if (!IsCompAssign) { 8136 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8137 return VecType; 8138 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8139 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8140 // type. Note that this is already done by non-compound assignments in 8141 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8142 // <1 x T> -> T. The result is also a vector type. 8143 } else if (OtherType->isExtVectorType() || 8144 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8145 ExprResult *RHSExpr = &RHS; 8146 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8147 return VecType; 8148 } 8149 } 8150 8151 // Okay, the expression is invalid. 8152 8153 // If there's a non-vector, non-real operand, diagnose that. 8154 if ((!RHSVecType && !RHSType->isRealType()) || 8155 (!LHSVecType && !LHSType->isRealType())) { 8156 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8157 << LHSType << RHSType 8158 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8159 return QualType(); 8160 } 8161 8162 // OpenCL V1.1 6.2.6.p1: 8163 // If the operands are of more than one vector type, then an error shall 8164 // occur. Implicit conversions between vector types are not permitted, per 8165 // section 6.2.1. 8166 if (getLangOpts().OpenCL && 8167 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8168 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8169 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8170 << RHSType; 8171 return QualType(); 8172 } 8173 8174 // Otherwise, use the generic diagnostic. 8175 Diag(Loc, diag::err_typecheck_vector_not_convertable) 8176 << LHSType << RHSType 8177 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8178 return QualType(); 8179 } 8180 8181 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8182 // expression. These are mainly cases where the null pointer is used as an 8183 // integer instead of a pointer. 8184 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8185 SourceLocation Loc, bool IsCompare) { 8186 // The canonical way to check for a GNU null is with isNullPointerConstant, 8187 // but we use a bit of a hack here for speed; this is a relatively 8188 // hot path, and isNullPointerConstant is slow. 8189 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8190 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8191 8192 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8193 8194 // Avoid analyzing cases where the result will either be invalid (and 8195 // diagnosed as such) or entirely valid and not something to warn about. 8196 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8197 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8198 return; 8199 8200 // Comparison operations would not make sense with a null pointer no matter 8201 // what the other expression is. 8202 if (!IsCompare) { 8203 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8204 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8205 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8206 return; 8207 } 8208 8209 // The rest of the operations only make sense with a null pointer 8210 // if the other expression is a pointer. 8211 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8212 NonNullType->canDecayToPointerType()) 8213 return; 8214 8215 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8216 << LHSNull /* LHS is NULL */ << NonNullType 8217 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8218 } 8219 8220 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8221 ExprResult &RHS, 8222 SourceLocation Loc, bool IsDiv) { 8223 // Check for division/remainder by zero. 8224 llvm::APSInt RHSValue; 8225 if (!RHS.get()->isValueDependent() && 8226 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8227 S.DiagRuntimeBehavior(Loc, RHS.get(), 8228 S.PDiag(diag::warn_remainder_division_by_zero) 8229 << IsDiv << RHS.get()->getSourceRange()); 8230 } 8231 8232 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8233 SourceLocation Loc, 8234 bool IsCompAssign, bool IsDiv) { 8235 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8236 8237 if (LHS.get()->getType()->isVectorType() || 8238 RHS.get()->getType()->isVectorType()) 8239 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8240 /*AllowBothBool*/getLangOpts().AltiVec, 8241 /*AllowBoolConversions*/false); 8242 8243 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8244 if (LHS.isInvalid() || RHS.isInvalid()) 8245 return QualType(); 8246 8247 8248 if (compType.isNull() || !compType->isArithmeticType()) 8249 return InvalidOperands(Loc, LHS, RHS); 8250 if (IsDiv) 8251 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8252 return compType; 8253 } 8254 8255 QualType Sema::CheckRemainderOperands( 8256 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8257 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8258 8259 if (LHS.get()->getType()->isVectorType() || 8260 RHS.get()->getType()->isVectorType()) { 8261 if (LHS.get()->getType()->hasIntegerRepresentation() && 8262 RHS.get()->getType()->hasIntegerRepresentation()) 8263 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8264 /*AllowBothBool*/getLangOpts().AltiVec, 8265 /*AllowBoolConversions*/false); 8266 return InvalidOperands(Loc, LHS, RHS); 8267 } 8268 8269 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8270 if (LHS.isInvalid() || RHS.isInvalid()) 8271 return QualType(); 8272 8273 if (compType.isNull() || !compType->isIntegerType()) 8274 return InvalidOperands(Loc, LHS, RHS); 8275 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8276 return compType; 8277 } 8278 8279 /// \brief Diagnose invalid arithmetic on two void pointers. 8280 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8281 Expr *LHSExpr, Expr *RHSExpr) { 8282 S.Diag(Loc, S.getLangOpts().CPlusPlus 8283 ? diag::err_typecheck_pointer_arith_void_type 8284 : diag::ext_gnu_void_ptr) 8285 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8286 << RHSExpr->getSourceRange(); 8287 } 8288 8289 /// \brief Diagnose invalid arithmetic on a void pointer. 8290 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8291 Expr *Pointer) { 8292 S.Diag(Loc, S.getLangOpts().CPlusPlus 8293 ? diag::err_typecheck_pointer_arith_void_type 8294 : diag::ext_gnu_void_ptr) 8295 << 0 /* one pointer */ << Pointer->getSourceRange(); 8296 } 8297 8298 /// \brief Diagnose invalid arithmetic on two function pointers. 8299 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8300 Expr *LHS, Expr *RHS) { 8301 assert(LHS->getType()->isAnyPointerType()); 8302 assert(RHS->getType()->isAnyPointerType()); 8303 S.Diag(Loc, S.getLangOpts().CPlusPlus 8304 ? diag::err_typecheck_pointer_arith_function_type 8305 : diag::ext_gnu_ptr_func_arith) 8306 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8307 // We only show the second type if it differs from the first. 8308 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8309 RHS->getType()) 8310 << RHS->getType()->getPointeeType() 8311 << LHS->getSourceRange() << RHS->getSourceRange(); 8312 } 8313 8314 /// \brief Diagnose invalid arithmetic on a function pointer. 8315 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8316 Expr *Pointer) { 8317 assert(Pointer->getType()->isAnyPointerType()); 8318 S.Diag(Loc, S.getLangOpts().CPlusPlus 8319 ? diag::err_typecheck_pointer_arith_function_type 8320 : diag::ext_gnu_ptr_func_arith) 8321 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8322 << 0 /* one pointer, so only one type */ 8323 << Pointer->getSourceRange(); 8324 } 8325 8326 /// \brief Emit error if Operand is incomplete pointer type 8327 /// 8328 /// \returns True if pointer has incomplete type 8329 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8330 Expr *Operand) { 8331 QualType ResType = Operand->getType(); 8332 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8333 ResType = ResAtomicType->getValueType(); 8334 8335 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8336 QualType PointeeTy = ResType->getPointeeType(); 8337 return S.RequireCompleteType(Loc, PointeeTy, 8338 diag::err_typecheck_arithmetic_incomplete_type, 8339 PointeeTy, Operand->getSourceRange()); 8340 } 8341 8342 /// \brief Check the validity of an arithmetic pointer operand. 8343 /// 8344 /// If the operand has pointer type, this code will check for pointer types 8345 /// which are invalid in arithmetic operations. These will be diagnosed 8346 /// appropriately, including whether or not the use is supported as an 8347 /// extension. 8348 /// 8349 /// \returns True when the operand is valid to use (even if as an extension). 8350 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8351 Expr *Operand) { 8352 QualType ResType = Operand->getType(); 8353 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8354 ResType = ResAtomicType->getValueType(); 8355 8356 if (!ResType->isAnyPointerType()) return true; 8357 8358 QualType PointeeTy = ResType->getPointeeType(); 8359 if (PointeeTy->isVoidType()) { 8360 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8361 return !S.getLangOpts().CPlusPlus; 8362 } 8363 if (PointeeTy->isFunctionType()) { 8364 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8365 return !S.getLangOpts().CPlusPlus; 8366 } 8367 8368 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8369 8370 return true; 8371 } 8372 8373 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8374 /// operands. 8375 /// 8376 /// This routine will diagnose any invalid arithmetic on pointer operands much 8377 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8378 /// for emitting a single diagnostic even for operations where both LHS and RHS 8379 /// are (potentially problematic) pointers. 8380 /// 8381 /// \returns True when the operand is valid to use (even if as an extension). 8382 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8383 Expr *LHSExpr, Expr *RHSExpr) { 8384 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8385 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8386 if (!isLHSPointer && !isRHSPointer) return true; 8387 8388 QualType LHSPointeeTy, RHSPointeeTy; 8389 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8390 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8391 8392 // if both are pointers check if operation is valid wrt address spaces 8393 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8394 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8395 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8396 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8397 S.Diag(Loc, 8398 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8399 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8400 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8401 return false; 8402 } 8403 } 8404 8405 // Check for arithmetic on pointers to incomplete types. 8406 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8407 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8408 if (isLHSVoidPtr || isRHSVoidPtr) { 8409 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8410 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8411 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8412 8413 return !S.getLangOpts().CPlusPlus; 8414 } 8415 8416 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8417 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8418 if (isLHSFuncPtr || isRHSFuncPtr) { 8419 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8420 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8421 RHSExpr); 8422 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8423 8424 return !S.getLangOpts().CPlusPlus; 8425 } 8426 8427 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8428 return false; 8429 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8430 return false; 8431 8432 return true; 8433 } 8434 8435 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8436 /// literal. 8437 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8438 Expr *LHSExpr, Expr *RHSExpr) { 8439 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8440 Expr* IndexExpr = RHSExpr; 8441 if (!StrExpr) { 8442 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8443 IndexExpr = LHSExpr; 8444 } 8445 8446 bool IsStringPlusInt = StrExpr && 8447 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8448 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8449 return; 8450 8451 llvm::APSInt index; 8452 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8453 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8454 if (index.isNonNegative() && 8455 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8456 index.isUnsigned())) 8457 return; 8458 } 8459 8460 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8461 Self.Diag(OpLoc, diag::warn_string_plus_int) 8462 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8463 8464 // Only print a fixit for "str" + int, not for int + "str". 8465 if (IndexExpr == RHSExpr) { 8466 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8467 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8468 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8469 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8470 << FixItHint::CreateInsertion(EndLoc, "]"); 8471 } else 8472 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8473 } 8474 8475 /// \brief Emit a warning when adding a char literal to a string. 8476 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8477 Expr *LHSExpr, Expr *RHSExpr) { 8478 const Expr *StringRefExpr = LHSExpr; 8479 const CharacterLiteral *CharExpr = 8480 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8481 8482 if (!CharExpr) { 8483 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8484 StringRefExpr = RHSExpr; 8485 } 8486 8487 if (!CharExpr || !StringRefExpr) 8488 return; 8489 8490 const QualType StringType = StringRefExpr->getType(); 8491 8492 // Return if not a PointerType. 8493 if (!StringType->isAnyPointerType()) 8494 return; 8495 8496 // Return if not a CharacterType. 8497 if (!StringType->getPointeeType()->isAnyCharacterType()) 8498 return; 8499 8500 ASTContext &Ctx = Self.getASTContext(); 8501 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8502 8503 const QualType CharType = CharExpr->getType(); 8504 if (!CharType->isAnyCharacterType() && 8505 CharType->isIntegerType() && 8506 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8507 Self.Diag(OpLoc, diag::warn_string_plus_char) 8508 << DiagRange << Ctx.CharTy; 8509 } else { 8510 Self.Diag(OpLoc, diag::warn_string_plus_char) 8511 << DiagRange << CharExpr->getType(); 8512 } 8513 8514 // Only print a fixit for str + char, not for char + str. 8515 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8516 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8517 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8518 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8519 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8520 << FixItHint::CreateInsertion(EndLoc, "]"); 8521 } else { 8522 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8523 } 8524 } 8525 8526 /// \brief Emit error when two pointers are incompatible. 8527 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8528 Expr *LHSExpr, Expr *RHSExpr) { 8529 assert(LHSExpr->getType()->isAnyPointerType()); 8530 assert(RHSExpr->getType()->isAnyPointerType()); 8531 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8532 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8533 << RHSExpr->getSourceRange(); 8534 } 8535 8536 // C99 6.5.6 8537 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8538 SourceLocation Loc, BinaryOperatorKind Opc, 8539 QualType* CompLHSTy) { 8540 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8541 8542 if (LHS.get()->getType()->isVectorType() || 8543 RHS.get()->getType()->isVectorType()) { 8544 QualType compType = CheckVectorOperands( 8545 LHS, RHS, Loc, CompLHSTy, 8546 /*AllowBothBool*/getLangOpts().AltiVec, 8547 /*AllowBoolConversions*/getLangOpts().ZVector); 8548 if (CompLHSTy) *CompLHSTy = compType; 8549 return compType; 8550 } 8551 8552 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8553 if (LHS.isInvalid() || RHS.isInvalid()) 8554 return QualType(); 8555 8556 // Diagnose "string literal" '+' int and string '+' "char literal". 8557 if (Opc == BO_Add) { 8558 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8559 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8560 } 8561 8562 // handle the common case first (both operands are arithmetic). 8563 if (!compType.isNull() && compType->isArithmeticType()) { 8564 if (CompLHSTy) *CompLHSTy = compType; 8565 return compType; 8566 } 8567 8568 // Type-checking. Ultimately the pointer's going to be in PExp; 8569 // note that we bias towards the LHS being the pointer. 8570 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8571 8572 bool isObjCPointer; 8573 if (PExp->getType()->isPointerType()) { 8574 isObjCPointer = false; 8575 } else if (PExp->getType()->isObjCObjectPointerType()) { 8576 isObjCPointer = true; 8577 } else { 8578 std::swap(PExp, IExp); 8579 if (PExp->getType()->isPointerType()) { 8580 isObjCPointer = false; 8581 } else if (PExp->getType()->isObjCObjectPointerType()) { 8582 isObjCPointer = true; 8583 } else { 8584 return InvalidOperands(Loc, LHS, RHS); 8585 } 8586 } 8587 assert(PExp->getType()->isAnyPointerType()); 8588 8589 if (!IExp->getType()->isIntegerType()) 8590 return InvalidOperands(Loc, LHS, RHS); 8591 8592 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8593 return QualType(); 8594 8595 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8596 return QualType(); 8597 8598 // Check array bounds for pointer arithemtic 8599 CheckArrayAccess(PExp, IExp); 8600 8601 if (CompLHSTy) { 8602 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8603 if (LHSTy.isNull()) { 8604 LHSTy = LHS.get()->getType(); 8605 if (LHSTy->isPromotableIntegerType()) 8606 LHSTy = Context.getPromotedIntegerType(LHSTy); 8607 } 8608 *CompLHSTy = LHSTy; 8609 } 8610 8611 return PExp->getType(); 8612 } 8613 8614 // C99 6.5.6 8615 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8616 SourceLocation Loc, 8617 QualType* CompLHSTy) { 8618 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8619 8620 if (LHS.get()->getType()->isVectorType() || 8621 RHS.get()->getType()->isVectorType()) { 8622 QualType compType = CheckVectorOperands( 8623 LHS, RHS, Loc, CompLHSTy, 8624 /*AllowBothBool*/getLangOpts().AltiVec, 8625 /*AllowBoolConversions*/getLangOpts().ZVector); 8626 if (CompLHSTy) *CompLHSTy = compType; 8627 return compType; 8628 } 8629 8630 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8631 if (LHS.isInvalid() || RHS.isInvalid()) 8632 return QualType(); 8633 8634 // Enforce type constraints: C99 6.5.6p3. 8635 8636 // Handle the common case first (both operands are arithmetic). 8637 if (!compType.isNull() && compType->isArithmeticType()) { 8638 if (CompLHSTy) *CompLHSTy = compType; 8639 return compType; 8640 } 8641 8642 // Either ptr - int or ptr - ptr. 8643 if (LHS.get()->getType()->isAnyPointerType()) { 8644 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8645 8646 // Diagnose bad cases where we step over interface counts. 8647 if (LHS.get()->getType()->isObjCObjectPointerType() && 8648 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8649 return QualType(); 8650 8651 // The result type of a pointer-int computation is the pointer type. 8652 if (RHS.get()->getType()->isIntegerType()) { 8653 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8654 return QualType(); 8655 8656 // Check array bounds for pointer arithemtic 8657 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8658 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8659 8660 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8661 return LHS.get()->getType(); 8662 } 8663 8664 // Handle pointer-pointer subtractions. 8665 if (const PointerType *RHSPTy 8666 = RHS.get()->getType()->getAs<PointerType>()) { 8667 QualType rpointee = RHSPTy->getPointeeType(); 8668 8669 if (getLangOpts().CPlusPlus) { 8670 // Pointee types must be the same: C++ [expr.add] 8671 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8672 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8673 } 8674 } else { 8675 // Pointee types must be compatible C99 6.5.6p3 8676 if (!Context.typesAreCompatible( 8677 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8678 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8679 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8680 return QualType(); 8681 } 8682 } 8683 8684 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8685 LHS.get(), RHS.get())) 8686 return QualType(); 8687 8688 // The pointee type may have zero size. As an extension, a structure or 8689 // union may have zero size or an array may have zero length. In this 8690 // case subtraction does not make sense. 8691 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8692 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8693 if (ElementSize.isZero()) { 8694 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8695 << rpointee.getUnqualifiedType() 8696 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8697 } 8698 } 8699 8700 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8701 return Context.getPointerDiffType(); 8702 } 8703 } 8704 8705 return InvalidOperands(Loc, LHS, RHS); 8706 } 8707 8708 static bool isScopedEnumerationType(QualType T) { 8709 if (const EnumType *ET = T->getAs<EnumType>()) 8710 return ET->getDecl()->isScoped(); 8711 return false; 8712 } 8713 8714 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8715 SourceLocation Loc, BinaryOperatorKind Opc, 8716 QualType LHSType) { 8717 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8718 // so skip remaining warnings as we don't want to modify values within Sema. 8719 if (S.getLangOpts().OpenCL) 8720 return; 8721 8722 llvm::APSInt Right; 8723 // Check right/shifter operand 8724 if (RHS.get()->isValueDependent() || 8725 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8726 return; 8727 8728 if (Right.isNegative()) { 8729 S.DiagRuntimeBehavior(Loc, RHS.get(), 8730 S.PDiag(diag::warn_shift_negative) 8731 << RHS.get()->getSourceRange()); 8732 return; 8733 } 8734 llvm::APInt LeftBits(Right.getBitWidth(), 8735 S.Context.getTypeSize(LHS.get()->getType())); 8736 if (Right.uge(LeftBits)) { 8737 S.DiagRuntimeBehavior(Loc, RHS.get(), 8738 S.PDiag(diag::warn_shift_gt_typewidth) 8739 << RHS.get()->getSourceRange()); 8740 return; 8741 } 8742 if (Opc != BO_Shl) 8743 return; 8744 8745 // When left shifting an ICE which is signed, we can check for overflow which 8746 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8747 // integers have defined behavior modulo one more than the maximum value 8748 // representable in the result type, so never warn for those. 8749 llvm::APSInt Left; 8750 if (LHS.get()->isValueDependent() || 8751 LHSType->hasUnsignedIntegerRepresentation() || 8752 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8753 return; 8754 8755 // If LHS does not have a signed type and non-negative value 8756 // then, the behavior is undefined. Warn about it. 8757 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 8758 S.DiagRuntimeBehavior(Loc, LHS.get(), 8759 S.PDiag(diag::warn_shift_lhs_negative) 8760 << LHS.get()->getSourceRange()); 8761 return; 8762 } 8763 8764 llvm::APInt ResultBits = 8765 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8766 if (LeftBits.uge(ResultBits)) 8767 return; 8768 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8769 Result = Result.shl(Right); 8770 8771 // Print the bit representation of the signed integer as an unsigned 8772 // hexadecimal number. 8773 SmallString<40> HexResult; 8774 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8775 8776 // If we are only missing a sign bit, this is less likely to result in actual 8777 // bugs -- if the result is cast back to an unsigned type, it will have the 8778 // expected value. Thus we place this behind a different warning that can be 8779 // turned off separately if needed. 8780 if (LeftBits == ResultBits - 1) { 8781 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8782 << HexResult << LHSType 8783 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8784 return; 8785 } 8786 8787 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8788 << HexResult.str() << Result.getMinSignedBits() << LHSType 8789 << Left.getBitWidth() << LHS.get()->getSourceRange() 8790 << RHS.get()->getSourceRange(); 8791 } 8792 8793 /// \brief Return the resulting type when a vector is shifted 8794 /// by a scalar or vector shift amount. 8795 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 8796 SourceLocation Loc, bool IsCompAssign) { 8797 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8798 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 8799 !LHS.get()->getType()->isVectorType()) { 8800 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8801 << RHS.get()->getType() << LHS.get()->getType() 8802 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8803 return QualType(); 8804 } 8805 8806 if (!IsCompAssign) { 8807 LHS = S.UsualUnaryConversions(LHS.get()); 8808 if (LHS.isInvalid()) return QualType(); 8809 } 8810 8811 RHS = S.UsualUnaryConversions(RHS.get()); 8812 if (RHS.isInvalid()) return QualType(); 8813 8814 QualType LHSType = LHS.get()->getType(); 8815 // Note that LHS might be a scalar because the routine calls not only in 8816 // OpenCL case. 8817 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8818 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 8819 8820 // Note that RHS might not be a vector. 8821 QualType RHSType = RHS.get()->getType(); 8822 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8823 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8824 8825 // The operands need to be integers. 8826 if (!LHSEleType->isIntegerType()) { 8827 S.Diag(Loc, diag::err_typecheck_expect_int) 8828 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8829 return QualType(); 8830 } 8831 8832 if (!RHSEleType->isIntegerType()) { 8833 S.Diag(Loc, diag::err_typecheck_expect_int) 8834 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8835 return QualType(); 8836 } 8837 8838 if (!LHSVecTy) { 8839 assert(RHSVecTy); 8840 if (IsCompAssign) 8841 return RHSType; 8842 if (LHSEleType != RHSEleType) { 8843 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 8844 LHSEleType = RHSEleType; 8845 } 8846 QualType VecTy = 8847 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 8848 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 8849 LHSType = VecTy; 8850 } else if (RHSVecTy) { 8851 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8852 // are applied component-wise. So if RHS is a vector, then ensure 8853 // that the number of elements is the same as LHS... 8854 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8855 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8856 << LHS.get()->getType() << RHS.get()->getType() 8857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8858 return QualType(); 8859 } 8860 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 8861 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 8862 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 8863 if (LHSBT != RHSBT && 8864 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 8865 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 8866 << LHS.get()->getType() << RHS.get()->getType() 8867 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8868 } 8869 } 8870 } else { 8871 // ...else expand RHS to match the number of elements in LHS. 8872 QualType VecTy = 8873 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8874 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8875 } 8876 8877 return LHSType; 8878 } 8879 8880 // C99 6.5.7 8881 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8882 SourceLocation Loc, BinaryOperatorKind Opc, 8883 bool IsCompAssign) { 8884 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8885 8886 // Vector shifts promote their scalar inputs to vector type. 8887 if (LHS.get()->getType()->isVectorType() || 8888 RHS.get()->getType()->isVectorType()) { 8889 if (LangOpts.ZVector) { 8890 // The shift operators for the z vector extensions work basically 8891 // like general shifts, except that neither the LHS nor the RHS is 8892 // allowed to be a "vector bool". 8893 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8894 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8895 return InvalidOperands(Loc, LHS, RHS); 8896 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8897 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8898 return InvalidOperands(Loc, LHS, RHS); 8899 } 8900 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8901 } 8902 8903 // Shifts don't perform usual arithmetic conversions, they just do integer 8904 // promotions on each operand. C99 6.5.7p3 8905 8906 // For the LHS, do usual unary conversions, but then reset them away 8907 // if this is a compound assignment. 8908 ExprResult OldLHS = LHS; 8909 LHS = UsualUnaryConversions(LHS.get()); 8910 if (LHS.isInvalid()) 8911 return QualType(); 8912 QualType LHSType = LHS.get()->getType(); 8913 if (IsCompAssign) LHS = OldLHS; 8914 8915 // The RHS is simpler. 8916 RHS = UsualUnaryConversions(RHS.get()); 8917 if (RHS.isInvalid()) 8918 return QualType(); 8919 QualType RHSType = RHS.get()->getType(); 8920 8921 // C99 6.5.7p2: Each of the operands shall have integer type. 8922 if (!LHSType->hasIntegerRepresentation() || 8923 !RHSType->hasIntegerRepresentation()) 8924 return InvalidOperands(Loc, LHS, RHS); 8925 8926 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8927 // hasIntegerRepresentation() above instead of this. 8928 if (isScopedEnumerationType(LHSType) || 8929 isScopedEnumerationType(RHSType)) { 8930 return InvalidOperands(Loc, LHS, RHS); 8931 } 8932 // Sanity-check shift operands 8933 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8934 8935 // "The type of the result is that of the promoted left operand." 8936 return LHSType; 8937 } 8938 8939 static bool IsWithinTemplateSpecialization(Decl *D) { 8940 if (DeclContext *DC = D->getDeclContext()) { 8941 if (isa<ClassTemplateSpecializationDecl>(DC)) 8942 return true; 8943 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8944 return FD->isFunctionTemplateSpecialization(); 8945 } 8946 return false; 8947 } 8948 8949 /// If two different enums are compared, raise a warning. 8950 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8951 Expr *RHS) { 8952 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8953 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8954 8955 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8956 if (!LHSEnumType) 8957 return; 8958 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8959 if (!RHSEnumType) 8960 return; 8961 8962 // Ignore anonymous enums. 8963 if (!LHSEnumType->getDecl()->getIdentifier()) 8964 return; 8965 if (!RHSEnumType->getDecl()->getIdentifier()) 8966 return; 8967 8968 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8969 return; 8970 8971 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8972 << LHSStrippedType << RHSStrippedType 8973 << LHS->getSourceRange() << RHS->getSourceRange(); 8974 } 8975 8976 /// \brief Diagnose bad pointer comparisons. 8977 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8978 ExprResult &LHS, ExprResult &RHS, 8979 bool IsError) { 8980 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8981 : diag::ext_typecheck_comparison_of_distinct_pointers) 8982 << LHS.get()->getType() << RHS.get()->getType() 8983 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8984 } 8985 8986 /// \brief Returns false if the pointers are converted to a composite type, 8987 /// true otherwise. 8988 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8989 ExprResult &LHS, ExprResult &RHS) { 8990 // C++ [expr.rel]p2: 8991 // [...] Pointer conversions (4.10) and qualification 8992 // conversions (4.4) are performed on pointer operands (or on 8993 // a pointer operand and a null pointer constant) to bring 8994 // them to their composite pointer type. [...] 8995 // 8996 // C++ [expr.eq]p1 uses the same notion for (in)equality 8997 // comparisons of pointers. 8998 8999 QualType LHSType = LHS.get()->getType(); 9000 QualType RHSType = RHS.get()->getType(); 9001 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9002 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9003 9004 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9005 if (T.isNull()) { 9006 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9007 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9008 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9009 else 9010 S.InvalidOperands(Loc, LHS, RHS); 9011 return true; 9012 } 9013 9014 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9015 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9016 return false; 9017 } 9018 9019 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9020 ExprResult &LHS, 9021 ExprResult &RHS, 9022 bool IsError) { 9023 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9024 : diag::ext_typecheck_comparison_of_fptr_to_void) 9025 << LHS.get()->getType() << RHS.get()->getType() 9026 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9027 } 9028 9029 static bool isObjCObjectLiteral(ExprResult &E) { 9030 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9031 case Stmt::ObjCArrayLiteralClass: 9032 case Stmt::ObjCDictionaryLiteralClass: 9033 case Stmt::ObjCStringLiteralClass: 9034 case Stmt::ObjCBoxedExprClass: 9035 return true; 9036 default: 9037 // Note that ObjCBoolLiteral is NOT an object literal! 9038 return false; 9039 } 9040 } 9041 9042 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9043 const ObjCObjectPointerType *Type = 9044 LHS->getType()->getAs<ObjCObjectPointerType>(); 9045 9046 // If this is not actually an Objective-C object, bail out. 9047 if (!Type) 9048 return false; 9049 9050 // Get the LHS object's interface type. 9051 QualType InterfaceType = Type->getPointeeType(); 9052 9053 // If the RHS isn't an Objective-C object, bail out. 9054 if (!RHS->getType()->isObjCObjectPointerType()) 9055 return false; 9056 9057 // Try to find the -isEqual: method. 9058 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9059 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9060 InterfaceType, 9061 /*instance=*/true); 9062 if (!Method) { 9063 if (Type->isObjCIdType()) { 9064 // For 'id', just check the global pool. 9065 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9066 /*receiverId=*/true); 9067 } else { 9068 // Check protocols. 9069 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9070 /*instance=*/true); 9071 } 9072 } 9073 9074 if (!Method) 9075 return false; 9076 9077 QualType T = Method->parameters()[0]->getType(); 9078 if (!T->isObjCObjectPointerType()) 9079 return false; 9080 9081 QualType R = Method->getReturnType(); 9082 if (!R->isScalarType()) 9083 return false; 9084 9085 return true; 9086 } 9087 9088 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9089 FromE = FromE->IgnoreParenImpCasts(); 9090 switch (FromE->getStmtClass()) { 9091 default: 9092 break; 9093 case Stmt::ObjCStringLiteralClass: 9094 // "string literal" 9095 return LK_String; 9096 case Stmt::ObjCArrayLiteralClass: 9097 // "array literal" 9098 return LK_Array; 9099 case Stmt::ObjCDictionaryLiteralClass: 9100 // "dictionary literal" 9101 return LK_Dictionary; 9102 case Stmt::BlockExprClass: 9103 return LK_Block; 9104 case Stmt::ObjCBoxedExprClass: { 9105 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9106 switch (Inner->getStmtClass()) { 9107 case Stmt::IntegerLiteralClass: 9108 case Stmt::FloatingLiteralClass: 9109 case Stmt::CharacterLiteralClass: 9110 case Stmt::ObjCBoolLiteralExprClass: 9111 case Stmt::CXXBoolLiteralExprClass: 9112 // "numeric literal" 9113 return LK_Numeric; 9114 case Stmt::ImplicitCastExprClass: { 9115 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9116 // Boolean literals can be represented by implicit casts. 9117 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9118 return LK_Numeric; 9119 break; 9120 } 9121 default: 9122 break; 9123 } 9124 return LK_Boxed; 9125 } 9126 } 9127 return LK_None; 9128 } 9129 9130 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9131 ExprResult &LHS, ExprResult &RHS, 9132 BinaryOperator::Opcode Opc){ 9133 Expr *Literal; 9134 Expr *Other; 9135 if (isObjCObjectLiteral(LHS)) { 9136 Literal = LHS.get(); 9137 Other = RHS.get(); 9138 } else { 9139 Literal = RHS.get(); 9140 Other = LHS.get(); 9141 } 9142 9143 // Don't warn on comparisons against nil. 9144 Other = Other->IgnoreParenCasts(); 9145 if (Other->isNullPointerConstant(S.getASTContext(), 9146 Expr::NPC_ValueDependentIsNotNull)) 9147 return; 9148 9149 // This should be kept in sync with warn_objc_literal_comparison. 9150 // LK_String should always be after the other literals, since it has its own 9151 // warning flag. 9152 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9153 assert(LiteralKind != Sema::LK_Block); 9154 if (LiteralKind == Sema::LK_None) { 9155 llvm_unreachable("Unknown Objective-C object literal kind"); 9156 } 9157 9158 if (LiteralKind == Sema::LK_String) 9159 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9160 << Literal->getSourceRange(); 9161 else 9162 S.Diag(Loc, diag::warn_objc_literal_comparison) 9163 << LiteralKind << Literal->getSourceRange(); 9164 9165 if (BinaryOperator::isEqualityOp(Opc) && 9166 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9167 SourceLocation Start = LHS.get()->getLocStart(); 9168 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9169 CharSourceRange OpRange = 9170 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9171 9172 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9173 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9174 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9175 << FixItHint::CreateInsertion(End, "]"); 9176 } 9177 } 9178 9179 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9180 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9181 ExprResult &RHS, SourceLocation Loc, 9182 BinaryOperatorKind Opc) { 9183 // Check that left hand side is !something. 9184 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9185 if (!UO || UO->getOpcode() != UO_LNot) return; 9186 9187 // Only check if the right hand side is non-bool arithmetic type. 9188 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9189 9190 // Make sure that the something in !something is not bool. 9191 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9192 if (SubExpr->isKnownToHaveBooleanValue()) return; 9193 9194 // Emit warning. 9195 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9196 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9197 << Loc << IsBitwiseOp; 9198 9199 // First note suggest !(x < y) 9200 SourceLocation FirstOpen = SubExpr->getLocStart(); 9201 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9202 FirstClose = S.getLocForEndOfToken(FirstClose); 9203 if (FirstClose.isInvalid()) 9204 FirstOpen = SourceLocation(); 9205 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9206 << IsBitwiseOp 9207 << FixItHint::CreateInsertion(FirstOpen, "(") 9208 << FixItHint::CreateInsertion(FirstClose, ")"); 9209 9210 // Second note suggests (!x) < y 9211 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9212 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9213 SecondClose = S.getLocForEndOfToken(SecondClose); 9214 if (SecondClose.isInvalid()) 9215 SecondOpen = SourceLocation(); 9216 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9217 << FixItHint::CreateInsertion(SecondOpen, "(") 9218 << FixItHint::CreateInsertion(SecondClose, ")"); 9219 } 9220 9221 // Get the decl for a simple expression: a reference to a variable, 9222 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9223 static ValueDecl *getCompareDecl(Expr *E) { 9224 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 9225 return DR->getDecl(); 9226 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9227 if (Ivar->isFreeIvar()) 9228 return Ivar->getDecl(); 9229 } 9230 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 9231 if (Mem->isImplicitAccess()) 9232 return Mem->getMemberDecl(); 9233 } 9234 return nullptr; 9235 } 9236 9237 // C99 6.5.8, C++ [expr.rel] 9238 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9239 SourceLocation Loc, BinaryOperatorKind Opc, 9240 bool IsRelational) { 9241 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9242 9243 // Handle vector comparisons separately. 9244 if (LHS.get()->getType()->isVectorType() || 9245 RHS.get()->getType()->isVectorType()) 9246 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 9247 9248 QualType LHSType = LHS.get()->getType(); 9249 QualType RHSType = RHS.get()->getType(); 9250 9251 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9252 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9253 9254 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 9255 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9256 9257 if (!LHSType->hasFloatingRepresentation() && 9258 !(LHSType->isBlockPointerType() && IsRelational) && 9259 !LHS.get()->getLocStart().isMacroID() && 9260 !RHS.get()->getLocStart().isMacroID() && 9261 ActiveTemplateInstantiations.empty()) { 9262 // For non-floating point types, check for self-comparisons of the form 9263 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9264 // often indicate logic errors in the program. 9265 // 9266 // NOTE: Don't warn about comparison expressions resulting from macro 9267 // expansion. Also don't warn about comparisons which are only self 9268 // comparisons within a template specialization. The warnings should catch 9269 // obvious cases in the definition of the template anyways. The idea is to 9270 // warn when the typed comparison operator will always evaluate to the same 9271 // result. 9272 ValueDecl *DL = getCompareDecl(LHSStripped); 9273 ValueDecl *DR = getCompareDecl(RHSStripped); 9274 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 9275 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9276 << 0 // self- 9277 << (Opc == BO_EQ 9278 || Opc == BO_LE 9279 || Opc == BO_GE)); 9280 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 9281 !DL->getType()->isReferenceType() && 9282 !DR->getType()->isReferenceType()) { 9283 // what is it always going to eval to? 9284 char always_evals_to; 9285 switch(Opc) { 9286 case BO_EQ: // e.g. array1 == array2 9287 always_evals_to = 0; // false 9288 break; 9289 case BO_NE: // e.g. array1 != array2 9290 always_evals_to = 1; // true 9291 break; 9292 default: 9293 // best we can say is 'a constant' 9294 always_evals_to = 2; // e.g. array1 <= array2 9295 break; 9296 } 9297 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 9298 << 1 // array 9299 << always_evals_to); 9300 } 9301 9302 if (isa<CastExpr>(LHSStripped)) 9303 LHSStripped = LHSStripped->IgnoreParenCasts(); 9304 if (isa<CastExpr>(RHSStripped)) 9305 RHSStripped = RHSStripped->IgnoreParenCasts(); 9306 9307 // Warn about comparisons against a string constant (unless the other 9308 // operand is null), the user probably wants strcmp. 9309 Expr *literalString = nullptr; 9310 Expr *literalStringStripped = nullptr; 9311 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9312 !RHSStripped->isNullPointerConstant(Context, 9313 Expr::NPC_ValueDependentIsNull)) { 9314 literalString = LHS.get(); 9315 literalStringStripped = LHSStripped; 9316 } else if ((isa<StringLiteral>(RHSStripped) || 9317 isa<ObjCEncodeExpr>(RHSStripped)) && 9318 !LHSStripped->isNullPointerConstant(Context, 9319 Expr::NPC_ValueDependentIsNull)) { 9320 literalString = RHS.get(); 9321 literalStringStripped = RHSStripped; 9322 } 9323 9324 if (literalString) { 9325 DiagRuntimeBehavior(Loc, nullptr, 9326 PDiag(diag::warn_stringcompare) 9327 << isa<ObjCEncodeExpr>(literalStringStripped) 9328 << literalString->getSourceRange()); 9329 } 9330 } 9331 9332 // C99 6.5.8p3 / C99 6.5.9p4 9333 UsualArithmeticConversions(LHS, RHS); 9334 if (LHS.isInvalid() || RHS.isInvalid()) 9335 return QualType(); 9336 9337 LHSType = LHS.get()->getType(); 9338 RHSType = RHS.get()->getType(); 9339 9340 // The result of comparisons is 'bool' in C++, 'int' in C. 9341 QualType ResultTy = Context.getLogicalOperationType(); 9342 9343 if (IsRelational) { 9344 if (LHSType->isRealType() && RHSType->isRealType()) 9345 return ResultTy; 9346 } else { 9347 // Check for comparisons of floating point operands using != and ==. 9348 if (LHSType->hasFloatingRepresentation()) 9349 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9350 9351 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 9352 return ResultTy; 9353 } 9354 9355 const Expr::NullPointerConstantKind LHSNullKind = 9356 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9357 const Expr::NullPointerConstantKind RHSNullKind = 9358 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9359 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9360 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9361 9362 if (!IsRelational && LHSIsNull != RHSIsNull) { 9363 bool IsEquality = Opc == BO_EQ; 9364 if (RHSIsNull) 9365 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9366 RHS.get()->getSourceRange()); 9367 else 9368 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9369 LHS.get()->getSourceRange()); 9370 } 9371 9372 if ((LHSType->isIntegerType() && !LHSIsNull) || 9373 (RHSType->isIntegerType() && !RHSIsNull)) { 9374 // Skip normal pointer conversion checks in this case; we have better 9375 // diagnostics for this below. 9376 } else if (getLangOpts().CPlusPlus) { 9377 // Equality comparison of a function pointer to a void pointer is invalid, 9378 // but we allow it as an extension. 9379 // FIXME: If we really want to allow this, should it be part of composite 9380 // pointer type computation so it works in conditionals too? 9381 if (!IsRelational && 9382 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9383 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9384 // This is a gcc extension compatibility comparison. 9385 // In a SFINAE context, we treat this as a hard error to maintain 9386 // conformance with the C++ standard. 9387 diagnoseFunctionPointerToVoidComparison( 9388 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9389 9390 if (isSFINAEContext()) 9391 return QualType(); 9392 9393 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9394 return ResultTy; 9395 } 9396 9397 // C++ [expr.eq]p2: 9398 // If at least one operand is a pointer [...] bring them to their 9399 // composite pointer type. 9400 // C++ [expr.rel]p2: 9401 // If both operands are pointers, [...] bring them to their composite 9402 // pointer type. 9403 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9404 (IsRelational ? 2 : 1)) { 9405 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9406 return QualType(); 9407 else 9408 return ResultTy; 9409 } 9410 } else if (LHSType->isPointerType() && 9411 RHSType->isPointerType()) { // C99 6.5.8p2 9412 // All of the following pointer-related warnings are GCC extensions, except 9413 // when handling null pointer constants. 9414 QualType LCanPointeeTy = 9415 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9416 QualType RCanPointeeTy = 9417 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9418 9419 // C99 6.5.9p2 and C99 6.5.8p2 9420 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9421 RCanPointeeTy.getUnqualifiedType())) { 9422 // Valid unless a relational comparison of function pointers 9423 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9424 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9425 << LHSType << RHSType << LHS.get()->getSourceRange() 9426 << RHS.get()->getSourceRange(); 9427 } 9428 } else if (!IsRelational && 9429 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9430 // Valid unless comparison between non-null pointer and function pointer 9431 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9432 && !LHSIsNull && !RHSIsNull) 9433 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9434 /*isError*/false); 9435 } else { 9436 // Invalid 9437 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9438 } 9439 if (LCanPointeeTy != RCanPointeeTy) { 9440 // Treat NULL constant as a special case in OpenCL. 9441 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9442 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9443 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9444 Diag(Loc, 9445 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9446 << LHSType << RHSType << 0 /* comparison */ 9447 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9448 } 9449 } 9450 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9451 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9452 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9453 : CK_BitCast; 9454 if (LHSIsNull && !RHSIsNull) 9455 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9456 else 9457 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9458 } 9459 return ResultTy; 9460 } 9461 9462 if (getLangOpts().CPlusPlus) { 9463 // C++ [expr.eq]p4: 9464 // Two operands of type std::nullptr_t or one operand of type 9465 // std::nullptr_t and the other a null pointer constant compare equal. 9466 if (!IsRelational && LHSIsNull && RHSIsNull) { 9467 if (LHSType->isNullPtrType()) { 9468 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9469 return ResultTy; 9470 } 9471 if (RHSType->isNullPtrType()) { 9472 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9473 return ResultTy; 9474 } 9475 } 9476 9477 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9478 // These aren't covered by the composite pointer type rules. 9479 if (!IsRelational && RHSType->isNullPtrType() && 9480 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9481 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9482 return ResultTy; 9483 } 9484 if (!IsRelational && LHSType->isNullPtrType() && 9485 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9486 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9487 return ResultTy; 9488 } 9489 9490 if (IsRelational && 9491 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9492 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9493 // HACK: Relational comparison of nullptr_t against a pointer type is 9494 // invalid per DR583, but we allow it within std::less<> and friends, 9495 // since otherwise common uses of it break. 9496 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9497 // friends to have std::nullptr_t overload candidates. 9498 DeclContext *DC = CurContext; 9499 if (isa<FunctionDecl>(DC)) 9500 DC = DC->getParent(); 9501 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9502 if (CTSD->isInStdNamespace() && 9503 llvm::StringSwitch<bool>(CTSD->getName()) 9504 .Cases("less", "less_equal", "greater", "greater_equal", true) 9505 .Default(false)) { 9506 if (RHSType->isNullPtrType()) 9507 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9508 else 9509 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9510 return ResultTy; 9511 } 9512 } 9513 } 9514 9515 // C++ [expr.eq]p2: 9516 // If at least one operand is a pointer to member, [...] bring them to 9517 // their composite pointer type. 9518 if (!IsRelational && 9519 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9520 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9521 return QualType(); 9522 else 9523 return ResultTy; 9524 } 9525 9526 // Handle scoped enumeration types specifically, since they don't promote 9527 // to integers. 9528 if (LHS.get()->getType()->isEnumeralType() && 9529 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9530 RHS.get()->getType())) 9531 return ResultTy; 9532 } 9533 9534 // Handle block pointer types. 9535 if (!IsRelational && LHSType->isBlockPointerType() && 9536 RHSType->isBlockPointerType()) { 9537 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9538 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9539 9540 if (!LHSIsNull && !RHSIsNull && 9541 !Context.typesAreCompatible(lpointee, rpointee)) { 9542 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9543 << LHSType << RHSType << LHS.get()->getSourceRange() 9544 << RHS.get()->getSourceRange(); 9545 } 9546 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9547 return ResultTy; 9548 } 9549 9550 // Allow block pointers to be compared with null pointer constants. 9551 if (!IsRelational 9552 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9553 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9554 if (!LHSIsNull && !RHSIsNull) { 9555 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9556 ->getPointeeType()->isVoidType()) 9557 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9558 ->getPointeeType()->isVoidType()))) 9559 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9560 << LHSType << RHSType << LHS.get()->getSourceRange() 9561 << RHS.get()->getSourceRange(); 9562 } 9563 if (LHSIsNull && !RHSIsNull) 9564 LHS = ImpCastExprToType(LHS.get(), RHSType, 9565 RHSType->isPointerType() ? CK_BitCast 9566 : CK_AnyPointerToBlockPointerCast); 9567 else 9568 RHS = ImpCastExprToType(RHS.get(), LHSType, 9569 LHSType->isPointerType() ? CK_BitCast 9570 : CK_AnyPointerToBlockPointerCast); 9571 return ResultTy; 9572 } 9573 9574 if (LHSType->isObjCObjectPointerType() || 9575 RHSType->isObjCObjectPointerType()) { 9576 const PointerType *LPT = LHSType->getAs<PointerType>(); 9577 const PointerType *RPT = RHSType->getAs<PointerType>(); 9578 if (LPT || RPT) { 9579 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9580 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9581 9582 if (!LPtrToVoid && !RPtrToVoid && 9583 !Context.typesAreCompatible(LHSType, RHSType)) { 9584 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9585 /*isError*/false); 9586 } 9587 if (LHSIsNull && !RHSIsNull) { 9588 Expr *E = LHS.get(); 9589 if (getLangOpts().ObjCAutoRefCount) 9590 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9591 LHS = ImpCastExprToType(E, RHSType, 9592 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9593 } 9594 else { 9595 Expr *E = RHS.get(); 9596 if (getLangOpts().ObjCAutoRefCount) 9597 CheckObjCARCConversion(SourceRange(), LHSType, E, 9598 CCK_ImplicitConversion, /*Diagnose=*/true, 9599 /*DiagnoseCFAudited=*/false, Opc); 9600 RHS = ImpCastExprToType(E, LHSType, 9601 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9602 } 9603 return ResultTy; 9604 } 9605 if (LHSType->isObjCObjectPointerType() && 9606 RHSType->isObjCObjectPointerType()) { 9607 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9608 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9609 /*isError*/false); 9610 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9611 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9612 9613 if (LHSIsNull && !RHSIsNull) 9614 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9615 else 9616 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9617 return ResultTy; 9618 } 9619 } 9620 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9621 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9622 unsigned DiagID = 0; 9623 bool isError = false; 9624 if (LangOpts.DebuggerSupport) { 9625 // Under a debugger, allow the comparison of pointers to integers, 9626 // since users tend to want to compare addresses. 9627 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9628 (RHSIsNull && RHSType->isIntegerType())) { 9629 if (IsRelational) { 9630 isError = getLangOpts().CPlusPlus; 9631 DiagID = 9632 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 9633 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9634 } 9635 } else if (getLangOpts().CPlusPlus) { 9636 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9637 isError = true; 9638 } else if (IsRelational) 9639 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9640 else 9641 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9642 9643 if (DiagID) { 9644 Diag(Loc, DiagID) 9645 << LHSType << RHSType << LHS.get()->getSourceRange() 9646 << RHS.get()->getSourceRange(); 9647 if (isError) 9648 return QualType(); 9649 } 9650 9651 if (LHSType->isIntegerType()) 9652 LHS = ImpCastExprToType(LHS.get(), RHSType, 9653 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9654 else 9655 RHS = ImpCastExprToType(RHS.get(), LHSType, 9656 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9657 return ResultTy; 9658 } 9659 9660 // Handle block pointers. 9661 if (!IsRelational && RHSIsNull 9662 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9663 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9664 return ResultTy; 9665 } 9666 if (!IsRelational && LHSIsNull 9667 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9668 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9669 return ResultTy; 9670 } 9671 9672 if (getLangOpts().OpenCLVersion >= 200) { 9673 if (LHSIsNull && RHSType->isQueueT()) { 9674 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9675 return ResultTy; 9676 } 9677 9678 if (LHSType->isQueueT() && RHSIsNull) { 9679 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9680 return ResultTy; 9681 } 9682 } 9683 9684 return InvalidOperands(Loc, LHS, RHS); 9685 } 9686 9687 9688 // Return a signed type that is of identical size and number of elements. 9689 // For floating point vectors, return an integer type of identical size 9690 // and number of elements. 9691 QualType Sema::GetSignedVectorType(QualType V) { 9692 const VectorType *VTy = V->getAs<VectorType>(); 9693 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9694 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9695 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9696 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9697 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9698 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9699 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9700 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9701 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9702 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9703 "Unhandled vector element size in vector compare"); 9704 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9705 } 9706 9707 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9708 /// operates on extended vector types. Instead of producing an IntTy result, 9709 /// like a scalar comparison, a vector comparison produces a vector of integer 9710 /// types. 9711 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9712 SourceLocation Loc, 9713 bool IsRelational) { 9714 // Check to make sure we're operating on vectors of the same type and width, 9715 // Allowing one side to be a scalar of element type. 9716 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9717 /*AllowBothBool*/true, 9718 /*AllowBoolConversions*/getLangOpts().ZVector); 9719 if (vType.isNull()) 9720 return vType; 9721 9722 QualType LHSType = LHS.get()->getType(); 9723 9724 // If AltiVec, the comparison results in a numeric type, i.e. 9725 // bool for C++, int for C 9726 if (getLangOpts().AltiVec && 9727 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9728 return Context.getLogicalOperationType(); 9729 9730 // For non-floating point types, check for self-comparisons of the form 9731 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9732 // often indicate logic errors in the program. 9733 if (!LHSType->hasFloatingRepresentation() && 9734 ActiveTemplateInstantiations.empty()) { 9735 if (DeclRefExpr* DRL 9736 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9737 if (DeclRefExpr* DRR 9738 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9739 if (DRL->getDecl() == DRR->getDecl()) 9740 DiagRuntimeBehavior(Loc, nullptr, 9741 PDiag(diag::warn_comparison_always) 9742 << 0 // self- 9743 << 2 // "a constant" 9744 ); 9745 } 9746 9747 // Check for comparisons of floating point operands using != and ==. 9748 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9749 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9750 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9751 } 9752 9753 // Return a signed type for the vector. 9754 return GetSignedVectorType(vType); 9755 } 9756 9757 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9758 SourceLocation Loc) { 9759 // Ensure that either both operands are of the same vector type, or 9760 // one operand is of a vector type and the other is of its element type. 9761 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9762 /*AllowBothBool*/true, 9763 /*AllowBoolConversions*/false); 9764 if (vType.isNull()) 9765 return InvalidOperands(Loc, LHS, RHS); 9766 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9767 vType->hasFloatingRepresentation()) 9768 return InvalidOperands(Loc, LHS, RHS); 9769 9770 return GetSignedVectorType(LHS.get()->getType()); 9771 } 9772 9773 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 9774 SourceLocation Loc, 9775 BinaryOperatorKind Opc) { 9776 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9777 9778 bool IsCompAssign = 9779 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 9780 9781 if (LHS.get()->getType()->isVectorType() || 9782 RHS.get()->getType()->isVectorType()) { 9783 if (LHS.get()->getType()->hasIntegerRepresentation() && 9784 RHS.get()->getType()->hasIntegerRepresentation()) 9785 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9786 /*AllowBothBool*/true, 9787 /*AllowBoolConversions*/getLangOpts().ZVector); 9788 return InvalidOperands(Loc, LHS, RHS); 9789 } 9790 9791 if (Opc == BO_And) 9792 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9793 9794 ExprResult LHSResult = LHS, RHSResult = RHS; 9795 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9796 IsCompAssign); 9797 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9798 return QualType(); 9799 LHS = LHSResult.get(); 9800 RHS = RHSResult.get(); 9801 9802 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9803 return compType; 9804 return InvalidOperands(Loc, LHS, RHS); 9805 } 9806 9807 // C99 6.5.[13,14] 9808 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9809 SourceLocation Loc, 9810 BinaryOperatorKind Opc) { 9811 // Check vector operands differently. 9812 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9813 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9814 9815 // Diagnose cases where the user write a logical and/or but probably meant a 9816 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9817 // is a constant. 9818 if (LHS.get()->getType()->isIntegerType() && 9819 !LHS.get()->getType()->isBooleanType() && 9820 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9821 // Don't warn in macros or template instantiations. 9822 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9823 // If the RHS can be constant folded, and if it constant folds to something 9824 // that isn't 0 or 1 (which indicate a potential logical operation that 9825 // happened to fold to true/false) then warn. 9826 // Parens on the RHS are ignored. 9827 llvm::APSInt Result; 9828 if (RHS.get()->EvaluateAsInt(Result, Context)) 9829 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9830 !RHS.get()->getExprLoc().isMacroID()) || 9831 (Result != 0 && Result != 1)) { 9832 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9833 << RHS.get()->getSourceRange() 9834 << (Opc == BO_LAnd ? "&&" : "||"); 9835 // Suggest replacing the logical operator with the bitwise version 9836 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9837 << (Opc == BO_LAnd ? "&" : "|") 9838 << FixItHint::CreateReplacement(SourceRange( 9839 Loc, getLocForEndOfToken(Loc)), 9840 Opc == BO_LAnd ? "&" : "|"); 9841 if (Opc == BO_LAnd) 9842 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9843 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9844 << FixItHint::CreateRemoval( 9845 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9846 RHS.get()->getLocEnd())); 9847 } 9848 } 9849 9850 if (!Context.getLangOpts().CPlusPlus) { 9851 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9852 // not operate on the built-in scalar and vector float types. 9853 if (Context.getLangOpts().OpenCL && 9854 Context.getLangOpts().OpenCLVersion < 120) { 9855 if (LHS.get()->getType()->isFloatingType() || 9856 RHS.get()->getType()->isFloatingType()) 9857 return InvalidOperands(Loc, LHS, RHS); 9858 } 9859 9860 LHS = UsualUnaryConversions(LHS.get()); 9861 if (LHS.isInvalid()) 9862 return QualType(); 9863 9864 RHS = UsualUnaryConversions(RHS.get()); 9865 if (RHS.isInvalid()) 9866 return QualType(); 9867 9868 if (!LHS.get()->getType()->isScalarType() || 9869 !RHS.get()->getType()->isScalarType()) 9870 return InvalidOperands(Loc, LHS, RHS); 9871 9872 return Context.IntTy; 9873 } 9874 9875 // The following is safe because we only use this method for 9876 // non-overloadable operands. 9877 9878 // C++ [expr.log.and]p1 9879 // C++ [expr.log.or]p1 9880 // The operands are both contextually converted to type bool. 9881 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9882 if (LHSRes.isInvalid()) 9883 return InvalidOperands(Loc, LHS, RHS); 9884 LHS = LHSRes; 9885 9886 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9887 if (RHSRes.isInvalid()) 9888 return InvalidOperands(Loc, LHS, RHS); 9889 RHS = RHSRes; 9890 9891 // C++ [expr.log.and]p2 9892 // C++ [expr.log.or]p2 9893 // The result is a bool. 9894 return Context.BoolTy; 9895 } 9896 9897 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9898 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9899 if (!ME) return false; 9900 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9901 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 9902 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 9903 if (!Base) return false; 9904 return Base->getMethodDecl() != nullptr; 9905 } 9906 9907 /// Is the given expression (which must be 'const') a reference to a 9908 /// variable which was originally non-const, but which has become 9909 /// 'const' due to being captured within a block? 9910 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9911 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9912 assert(E->isLValue() && E->getType().isConstQualified()); 9913 E = E->IgnoreParens(); 9914 9915 // Must be a reference to a declaration from an enclosing scope. 9916 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9917 if (!DRE) return NCCK_None; 9918 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9919 9920 // The declaration must be a variable which is not declared 'const'. 9921 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9922 if (!var) return NCCK_None; 9923 if (var->getType().isConstQualified()) return NCCK_None; 9924 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9925 9926 // Decide whether the first capture was for a block or a lambda. 9927 DeclContext *DC = S.CurContext, *Prev = nullptr; 9928 // Decide whether the first capture was for a block or a lambda. 9929 while (DC) { 9930 // For init-capture, it is possible that the variable belongs to the 9931 // template pattern of the current context. 9932 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 9933 if (var->isInitCapture() && 9934 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 9935 break; 9936 if (DC == var->getDeclContext()) 9937 break; 9938 Prev = DC; 9939 DC = DC->getParent(); 9940 } 9941 // Unless we have an init-capture, we've gone one step too far. 9942 if (!var->isInitCapture()) 9943 DC = Prev; 9944 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9945 } 9946 9947 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9948 Ty = Ty.getNonReferenceType(); 9949 if (IsDereference && Ty->isPointerType()) 9950 Ty = Ty->getPointeeType(); 9951 return !Ty.isConstQualified(); 9952 } 9953 9954 /// Emit the "read-only variable not assignable" error and print notes to give 9955 /// more information about why the variable is not assignable, such as pointing 9956 /// to the declaration of a const variable, showing that a method is const, or 9957 /// that the function is returning a const reference. 9958 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9959 SourceLocation Loc) { 9960 // Update err_typecheck_assign_const and note_typecheck_assign_const 9961 // when this enum is changed. 9962 enum { 9963 ConstFunction, 9964 ConstVariable, 9965 ConstMember, 9966 ConstMethod, 9967 ConstUnknown, // Keep as last element 9968 }; 9969 9970 SourceRange ExprRange = E->getSourceRange(); 9971 9972 // Only emit one error on the first const found. All other consts will emit 9973 // a note to the error. 9974 bool DiagnosticEmitted = false; 9975 9976 // Track if the current expression is the result of a dereference, and if the 9977 // next checked expression is the result of a dereference. 9978 bool IsDereference = false; 9979 bool NextIsDereference = false; 9980 9981 // Loop to process MemberExpr chains. 9982 while (true) { 9983 IsDereference = NextIsDereference; 9984 9985 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 9986 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9987 NextIsDereference = ME->isArrow(); 9988 const ValueDecl *VD = ME->getMemberDecl(); 9989 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9990 // Mutable fields can be modified even if the class is const. 9991 if (Field->isMutable()) { 9992 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9993 break; 9994 } 9995 9996 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9997 if (!DiagnosticEmitted) { 9998 S.Diag(Loc, diag::err_typecheck_assign_const) 9999 << ExprRange << ConstMember << false /*static*/ << Field 10000 << Field->getType(); 10001 DiagnosticEmitted = true; 10002 } 10003 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10004 << ConstMember << false /*static*/ << Field << Field->getType() 10005 << Field->getSourceRange(); 10006 } 10007 E = ME->getBase(); 10008 continue; 10009 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10010 if (VDecl->getType().isConstQualified()) { 10011 if (!DiagnosticEmitted) { 10012 S.Diag(Loc, diag::err_typecheck_assign_const) 10013 << ExprRange << ConstMember << true /*static*/ << VDecl 10014 << VDecl->getType(); 10015 DiagnosticEmitted = true; 10016 } 10017 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10018 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10019 << VDecl->getSourceRange(); 10020 } 10021 // Static fields do not inherit constness from parents. 10022 break; 10023 } 10024 break; 10025 } // End MemberExpr 10026 break; 10027 } 10028 10029 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10030 // Function calls 10031 const FunctionDecl *FD = CE->getDirectCallee(); 10032 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10033 if (!DiagnosticEmitted) { 10034 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10035 << ConstFunction << FD; 10036 DiagnosticEmitted = true; 10037 } 10038 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10039 diag::note_typecheck_assign_const) 10040 << ConstFunction << FD << FD->getReturnType() 10041 << FD->getReturnTypeSourceRange(); 10042 } 10043 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10044 // Point to variable declaration. 10045 if (const ValueDecl *VD = DRE->getDecl()) { 10046 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10047 if (!DiagnosticEmitted) { 10048 S.Diag(Loc, diag::err_typecheck_assign_const) 10049 << ExprRange << ConstVariable << VD << VD->getType(); 10050 DiagnosticEmitted = true; 10051 } 10052 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10053 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10054 } 10055 } 10056 } else if (isa<CXXThisExpr>(E)) { 10057 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10058 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10059 if (MD->isConst()) { 10060 if (!DiagnosticEmitted) { 10061 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10062 << ConstMethod << MD; 10063 DiagnosticEmitted = true; 10064 } 10065 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10066 << ConstMethod << MD << MD->getSourceRange(); 10067 } 10068 } 10069 } 10070 } 10071 10072 if (DiagnosticEmitted) 10073 return; 10074 10075 // Can't determine a more specific message, so display the generic error. 10076 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10077 } 10078 10079 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10080 /// emit an error and return true. If so, return false. 10081 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10082 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10083 10084 S.CheckShadowingDeclModification(E, Loc); 10085 10086 SourceLocation OrigLoc = Loc; 10087 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10088 &Loc); 10089 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10090 IsLV = Expr::MLV_InvalidMessageExpression; 10091 if (IsLV == Expr::MLV_Valid) 10092 return false; 10093 10094 unsigned DiagID = 0; 10095 bool NeedType = false; 10096 switch (IsLV) { // C99 6.5.16p2 10097 case Expr::MLV_ConstQualified: 10098 // Use a specialized diagnostic when we're assigning to an object 10099 // from an enclosing function or block. 10100 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10101 if (NCCK == NCCK_Block) 10102 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10103 else 10104 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10105 break; 10106 } 10107 10108 // In ARC, use some specialized diagnostics for occasions where we 10109 // infer 'const'. These are always pseudo-strong variables. 10110 if (S.getLangOpts().ObjCAutoRefCount) { 10111 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10112 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10113 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10114 10115 // Use the normal diagnostic if it's pseudo-__strong but the 10116 // user actually wrote 'const'. 10117 if (var->isARCPseudoStrong() && 10118 (!var->getTypeSourceInfo() || 10119 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10120 // There are two pseudo-strong cases: 10121 // - self 10122 ObjCMethodDecl *method = S.getCurMethodDecl(); 10123 if (method && var == method->getSelfDecl()) 10124 DiagID = method->isClassMethod() 10125 ? diag::err_typecheck_arc_assign_self_class_method 10126 : diag::err_typecheck_arc_assign_self; 10127 10128 // - fast enumeration variables 10129 else 10130 DiagID = diag::err_typecheck_arr_assign_enumeration; 10131 10132 SourceRange Assign; 10133 if (Loc != OrigLoc) 10134 Assign = SourceRange(OrigLoc, OrigLoc); 10135 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10136 // We need to preserve the AST regardless, so migration tool 10137 // can do its job. 10138 return false; 10139 } 10140 } 10141 } 10142 10143 // If none of the special cases above are triggered, then this is a 10144 // simple const assignment. 10145 if (DiagID == 0) { 10146 DiagnoseConstAssignment(S, E, Loc); 10147 return true; 10148 } 10149 10150 break; 10151 case Expr::MLV_ConstAddrSpace: 10152 DiagnoseConstAssignment(S, E, Loc); 10153 return true; 10154 case Expr::MLV_ArrayType: 10155 case Expr::MLV_ArrayTemporary: 10156 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10157 NeedType = true; 10158 break; 10159 case Expr::MLV_NotObjectType: 10160 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10161 NeedType = true; 10162 break; 10163 case Expr::MLV_LValueCast: 10164 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10165 break; 10166 case Expr::MLV_Valid: 10167 llvm_unreachable("did not take early return for MLV_Valid"); 10168 case Expr::MLV_InvalidExpression: 10169 case Expr::MLV_MemberFunction: 10170 case Expr::MLV_ClassTemporary: 10171 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10172 break; 10173 case Expr::MLV_IncompleteType: 10174 case Expr::MLV_IncompleteVoidType: 10175 return S.RequireCompleteType(Loc, E->getType(), 10176 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10177 case Expr::MLV_DuplicateVectorComponents: 10178 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10179 break; 10180 case Expr::MLV_NoSetterProperty: 10181 llvm_unreachable("readonly properties should be processed differently"); 10182 case Expr::MLV_InvalidMessageExpression: 10183 DiagID = diag::err_readonly_message_assignment; 10184 break; 10185 case Expr::MLV_SubObjCPropertySetting: 10186 DiagID = diag::err_no_subobject_property_setting; 10187 break; 10188 } 10189 10190 SourceRange Assign; 10191 if (Loc != OrigLoc) 10192 Assign = SourceRange(OrigLoc, OrigLoc); 10193 if (NeedType) 10194 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10195 else 10196 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10197 return true; 10198 } 10199 10200 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10201 SourceLocation Loc, 10202 Sema &Sema) { 10203 // C / C++ fields 10204 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10205 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10206 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10207 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10208 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10209 } 10210 10211 // Objective-C instance variables 10212 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10213 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10214 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10215 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10216 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10217 if (RL && RR && RL->getDecl() == RR->getDecl()) 10218 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10219 } 10220 } 10221 10222 // C99 6.5.16.1 10223 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10224 SourceLocation Loc, 10225 QualType CompoundType) { 10226 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10227 10228 // Verify that LHS is a modifiable lvalue, and emit error if not. 10229 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10230 return QualType(); 10231 10232 QualType LHSType = LHSExpr->getType(); 10233 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10234 CompoundType; 10235 // OpenCL v1.2 s6.1.1.1 p2: 10236 // The half data type can only be used to declare a pointer to a buffer that 10237 // contains half values 10238 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10239 LHSType->isHalfType()) { 10240 Diag(Loc, diag::err_opencl_half_load_store) << 1 10241 << LHSType.getUnqualifiedType(); 10242 return QualType(); 10243 } 10244 10245 AssignConvertType ConvTy; 10246 if (CompoundType.isNull()) { 10247 Expr *RHSCheck = RHS.get(); 10248 10249 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10250 10251 QualType LHSTy(LHSType); 10252 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10253 if (RHS.isInvalid()) 10254 return QualType(); 10255 // Special case of NSObject attributes on c-style pointer types. 10256 if (ConvTy == IncompatiblePointer && 10257 ((Context.isObjCNSObjectType(LHSType) && 10258 RHSType->isObjCObjectPointerType()) || 10259 (Context.isObjCNSObjectType(RHSType) && 10260 LHSType->isObjCObjectPointerType()))) 10261 ConvTy = Compatible; 10262 10263 if (ConvTy == Compatible && 10264 LHSType->isObjCObjectType()) 10265 Diag(Loc, diag::err_objc_object_assignment) 10266 << LHSType; 10267 10268 // If the RHS is a unary plus or minus, check to see if they = and + are 10269 // right next to each other. If so, the user may have typo'd "x =+ 4" 10270 // instead of "x += 4". 10271 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10272 RHSCheck = ICE->getSubExpr(); 10273 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10274 if ((UO->getOpcode() == UO_Plus || 10275 UO->getOpcode() == UO_Minus) && 10276 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10277 // Only if the two operators are exactly adjacent. 10278 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10279 // And there is a space or other character before the subexpr of the 10280 // unary +/-. We don't want to warn on "x=-1". 10281 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10282 UO->getSubExpr()->getLocStart().isFileID()) { 10283 Diag(Loc, diag::warn_not_compound_assign) 10284 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10285 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10286 } 10287 } 10288 10289 if (ConvTy == Compatible) { 10290 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10291 // Warn about retain cycles where a block captures the LHS, but 10292 // not if the LHS is a simple variable into which the block is 10293 // being stored...unless that variable can be captured by reference! 10294 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10295 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10296 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10297 checkRetainCycles(LHSExpr, RHS.get()); 10298 10299 // It is safe to assign a weak reference into a strong variable. 10300 // Although this code can still have problems: 10301 // id x = self.weakProp; 10302 // id y = self.weakProp; 10303 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10304 // paths through the function. This should be revisited if 10305 // -Wrepeated-use-of-weak is made flow-sensitive. 10306 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10307 RHS.get()->getLocStart())) 10308 getCurFunction()->markSafeWeakUse(RHS.get()); 10309 10310 } else if (getLangOpts().ObjCAutoRefCount) { 10311 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10312 } 10313 } 10314 } else { 10315 // Compound assignment "x += y" 10316 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10317 } 10318 10319 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10320 RHS.get(), AA_Assigning)) 10321 return QualType(); 10322 10323 CheckForNullPointerDereference(*this, LHSExpr); 10324 10325 // C99 6.5.16p3: The type of an assignment expression is the type of the 10326 // left operand unless the left operand has qualified type, in which case 10327 // it is the unqualified version of the type of the left operand. 10328 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10329 // is converted to the type of the assignment expression (above). 10330 // C++ 5.17p1: the type of the assignment expression is that of its left 10331 // operand. 10332 return (getLangOpts().CPlusPlus 10333 ? LHSType : LHSType.getUnqualifiedType()); 10334 } 10335 10336 // Only ignore explicit casts to void. 10337 static bool IgnoreCommaOperand(const Expr *E) { 10338 E = E->IgnoreParens(); 10339 10340 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10341 if (CE->getCastKind() == CK_ToVoid) { 10342 return true; 10343 } 10344 } 10345 10346 return false; 10347 } 10348 10349 // Look for instances where it is likely the comma operator is confused with 10350 // another operator. There is a whitelist of acceptable expressions for the 10351 // left hand side of the comma operator, otherwise emit a warning. 10352 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10353 // No warnings in macros 10354 if (Loc.isMacroID()) 10355 return; 10356 10357 // Don't warn in template instantiations. 10358 if (!ActiveTemplateInstantiations.empty()) 10359 return; 10360 10361 // Scope isn't fine-grained enough to whitelist the specific cases, so 10362 // instead, skip more than needed, then call back into here with the 10363 // CommaVisitor in SemaStmt.cpp. 10364 // The whitelisted locations are the initialization and increment portions 10365 // of a for loop. The additional checks are on the condition of 10366 // if statements, do/while loops, and for loops. 10367 const unsigned ForIncrementFlags = 10368 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10369 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10370 const unsigned ScopeFlags = getCurScope()->getFlags(); 10371 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10372 (ScopeFlags & ForInitFlags) == ForInitFlags) 10373 return; 10374 10375 // If there are multiple comma operators used together, get the RHS of the 10376 // of the comma operator as the LHS. 10377 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10378 if (BO->getOpcode() != BO_Comma) 10379 break; 10380 LHS = BO->getRHS(); 10381 } 10382 10383 // Only allow some expressions on LHS to not warn. 10384 if (IgnoreCommaOperand(LHS)) 10385 return; 10386 10387 Diag(Loc, diag::warn_comma_operator); 10388 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10389 << LHS->getSourceRange() 10390 << FixItHint::CreateInsertion(LHS->getLocStart(), 10391 LangOpts.CPlusPlus ? "static_cast<void>(" 10392 : "(void)(") 10393 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10394 ")"); 10395 } 10396 10397 // C99 6.5.17 10398 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10399 SourceLocation Loc) { 10400 LHS = S.CheckPlaceholderExpr(LHS.get()); 10401 RHS = S.CheckPlaceholderExpr(RHS.get()); 10402 if (LHS.isInvalid() || RHS.isInvalid()) 10403 return QualType(); 10404 10405 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10406 // operands, but not unary promotions. 10407 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10408 10409 // So we treat the LHS as a ignored value, and in C++ we allow the 10410 // containing site to determine what should be done with the RHS. 10411 LHS = S.IgnoredValueConversions(LHS.get()); 10412 if (LHS.isInvalid()) 10413 return QualType(); 10414 10415 S.DiagnoseUnusedExprResult(LHS.get()); 10416 10417 if (!S.getLangOpts().CPlusPlus) { 10418 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10419 if (RHS.isInvalid()) 10420 return QualType(); 10421 if (!RHS.get()->getType()->isVoidType()) 10422 S.RequireCompleteType(Loc, RHS.get()->getType(), 10423 diag::err_incomplete_type); 10424 } 10425 10426 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10427 S.DiagnoseCommaOperator(LHS.get(), Loc); 10428 10429 return RHS.get()->getType(); 10430 } 10431 10432 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10433 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10434 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10435 ExprValueKind &VK, 10436 ExprObjectKind &OK, 10437 SourceLocation OpLoc, 10438 bool IsInc, bool IsPrefix) { 10439 if (Op->isTypeDependent()) 10440 return S.Context.DependentTy; 10441 10442 QualType ResType = Op->getType(); 10443 // Atomic types can be used for increment / decrement where the non-atomic 10444 // versions can, so ignore the _Atomic() specifier for the purpose of 10445 // checking. 10446 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10447 ResType = ResAtomicType->getValueType(); 10448 10449 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10450 10451 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10452 // Decrement of bool is not allowed. 10453 if (!IsInc) { 10454 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10455 return QualType(); 10456 } 10457 // Increment of bool sets it to true, but is deprecated. 10458 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 10459 : diag::warn_increment_bool) 10460 << Op->getSourceRange(); 10461 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10462 // Error on enum increments and decrements in C++ mode 10463 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10464 return QualType(); 10465 } else if (ResType->isRealType()) { 10466 // OK! 10467 } else if (ResType->isPointerType()) { 10468 // C99 6.5.2.4p2, 6.5.6p2 10469 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10470 return QualType(); 10471 } else if (ResType->isObjCObjectPointerType()) { 10472 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10473 // Otherwise, we just need a complete type. 10474 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10475 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10476 return QualType(); 10477 } else if (ResType->isAnyComplexType()) { 10478 // C99 does not support ++/-- on complex types, we allow as an extension. 10479 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10480 << ResType << Op->getSourceRange(); 10481 } else if (ResType->isPlaceholderType()) { 10482 ExprResult PR = S.CheckPlaceholderExpr(Op); 10483 if (PR.isInvalid()) return QualType(); 10484 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10485 IsInc, IsPrefix); 10486 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10487 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10488 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10489 (ResType->getAs<VectorType>()->getVectorKind() != 10490 VectorType::AltiVecBool)) { 10491 // The z vector extensions allow ++ and -- for non-bool vectors. 10492 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10493 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 10494 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 10495 } else { 10496 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 10497 << ResType << int(IsInc) << Op->getSourceRange(); 10498 return QualType(); 10499 } 10500 // At this point, we know we have a real, complex or pointer type. 10501 // Now make sure the operand is a modifiable lvalue. 10502 if (CheckForModifiableLvalue(Op, OpLoc, S)) 10503 return QualType(); 10504 // In C++, a prefix increment is the same type as the operand. Otherwise 10505 // (in C or with postfix), the increment is the unqualified type of the 10506 // operand. 10507 if (IsPrefix && S.getLangOpts().CPlusPlus) { 10508 VK = VK_LValue; 10509 OK = Op->getObjectKind(); 10510 return ResType; 10511 } else { 10512 VK = VK_RValue; 10513 return ResType.getUnqualifiedType(); 10514 } 10515 } 10516 10517 10518 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 10519 /// This routine allows us to typecheck complex/recursive expressions 10520 /// where the declaration is needed for type checking. We only need to 10521 /// handle cases when the expression references a function designator 10522 /// or is an lvalue. Here are some examples: 10523 /// - &(x) => x 10524 /// - &*****f => f for f a function designator. 10525 /// - &s.xx => s 10526 /// - &s.zz[1].yy -> s, if zz is an array 10527 /// - *(x + 1) -> x, if x is an array 10528 /// - &"123"[2] -> 0 10529 /// - & __real__ x -> x 10530 static ValueDecl *getPrimaryDecl(Expr *E) { 10531 switch (E->getStmtClass()) { 10532 case Stmt::DeclRefExprClass: 10533 return cast<DeclRefExpr>(E)->getDecl(); 10534 case Stmt::MemberExprClass: 10535 // If this is an arrow operator, the address is an offset from 10536 // the base's value, so the object the base refers to is 10537 // irrelevant. 10538 if (cast<MemberExpr>(E)->isArrow()) 10539 return nullptr; 10540 // Otherwise, the expression refers to a part of the base 10541 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 10542 case Stmt::ArraySubscriptExprClass: { 10543 // FIXME: This code shouldn't be necessary! We should catch the implicit 10544 // promotion of register arrays earlier. 10545 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 10546 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 10547 if (ICE->getSubExpr()->getType()->isArrayType()) 10548 return getPrimaryDecl(ICE->getSubExpr()); 10549 } 10550 return nullptr; 10551 } 10552 case Stmt::UnaryOperatorClass: { 10553 UnaryOperator *UO = cast<UnaryOperator>(E); 10554 10555 switch(UO->getOpcode()) { 10556 case UO_Real: 10557 case UO_Imag: 10558 case UO_Extension: 10559 return getPrimaryDecl(UO->getSubExpr()); 10560 default: 10561 return nullptr; 10562 } 10563 } 10564 case Stmt::ParenExprClass: 10565 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 10566 case Stmt::ImplicitCastExprClass: 10567 // If the result of an implicit cast is an l-value, we care about 10568 // the sub-expression; otherwise, the result here doesn't matter. 10569 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 10570 default: 10571 return nullptr; 10572 } 10573 } 10574 10575 namespace { 10576 enum { 10577 AO_Bit_Field = 0, 10578 AO_Vector_Element = 1, 10579 AO_Property_Expansion = 2, 10580 AO_Register_Variable = 3, 10581 AO_No_Error = 4 10582 }; 10583 } 10584 /// \brief Diagnose invalid operand for address of operations. 10585 /// 10586 /// \param Type The type of operand which cannot have its address taken. 10587 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10588 Expr *E, unsigned Type) { 10589 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10590 } 10591 10592 /// CheckAddressOfOperand - The operand of & must be either a function 10593 /// designator or an lvalue designating an object. If it is an lvalue, the 10594 /// object cannot be declared with storage class register or be a bit field. 10595 /// Note: The usual conversions are *not* applied to the operand of the & 10596 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10597 /// In C++, the operand might be an overloaded function name, in which case 10598 /// we allow the '&' but retain the overloaded-function type. 10599 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10600 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10601 if (PTy->getKind() == BuiltinType::Overload) { 10602 Expr *E = OrigOp.get()->IgnoreParens(); 10603 if (!isa<OverloadExpr>(E)) { 10604 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10605 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10606 << OrigOp.get()->getSourceRange(); 10607 return QualType(); 10608 } 10609 10610 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10611 if (isa<UnresolvedMemberExpr>(Ovl)) 10612 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10613 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10614 << OrigOp.get()->getSourceRange(); 10615 return QualType(); 10616 } 10617 10618 return Context.OverloadTy; 10619 } 10620 10621 if (PTy->getKind() == BuiltinType::UnknownAny) 10622 return Context.UnknownAnyTy; 10623 10624 if (PTy->getKind() == BuiltinType::BoundMember) { 10625 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10626 << OrigOp.get()->getSourceRange(); 10627 return QualType(); 10628 } 10629 10630 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10631 if (OrigOp.isInvalid()) return QualType(); 10632 } 10633 10634 if (OrigOp.get()->isTypeDependent()) 10635 return Context.DependentTy; 10636 10637 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10638 10639 // Make sure to ignore parentheses in subsequent checks 10640 Expr *op = OrigOp.get()->IgnoreParens(); 10641 10642 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10643 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10644 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10645 return QualType(); 10646 } 10647 10648 if (getLangOpts().C99) { 10649 // Implement C99-only parts of addressof rules. 10650 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10651 if (uOp->getOpcode() == UO_Deref) 10652 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10653 // (assuming the deref expression is valid). 10654 return uOp->getSubExpr()->getType(); 10655 } 10656 // Technically, there should be a check for array subscript 10657 // expressions here, but the result of one is always an lvalue anyway. 10658 } 10659 ValueDecl *dcl = getPrimaryDecl(op); 10660 10661 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10662 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10663 op->getLocStart())) 10664 return QualType(); 10665 10666 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10667 unsigned AddressOfError = AO_No_Error; 10668 10669 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10670 bool sfinae = (bool)isSFINAEContext(); 10671 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10672 : diag::ext_typecheck_addrof_temporary) 10673 << op->getType() << op->getSourceRange(); 10674 if (sfinae) 10675 return QualType(); 10676 // Materialize the temporary as an lvalue so that we can take its address. 10677 OrigOp = op = 10678 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10679 } else if (isa<ObjCSelectorExpr>(op)) { 10680 return Context.getPointerType(op->getType()); 10681 } else if (lval == Expr::LV_MemberFunction) { 10682 // If it's an instance method, make a member pointer. 10683 // The expression must have exactly the form &A::foo. 10684 10685 // If the underlying expression isn't a decl ref, give up. 10686 if (!isa<DeclRefExpr>(op)) { 10687 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10688 << OrigOp.get()->getSourceRange(); 10689 return QualType(); 10690 } 10691 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10692 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10693 10694 // The id-expression was parenthesized. 10695 if (OrigOp.get() != DRE) { 10696 Diag(OpLoc, diag::err_parens_pointer_member_function) 10697 << OrigOp.get()->getSourceRange(); 10698 10699 // The method was named without a qualifier. 10700 } else if (!DRE->getQualifier()) { 10701 if (MD->getParent()->getName().empty()) 10702 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10703 << op->getSourceRange(); 10704 else { 10705 SmallString<32> Str; 10706 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10707 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10708 << op->getSourceRange() 10709 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10710 } 10711 } 10712 10713 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10714 if (isa<CXXDestructorDecl>(MD)) 10715 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10716 10717 QualType MPTy = Context.getMemberPointerType( 10718 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10719 // Under the MS ABI, lock down the inheritance model now. 10720 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10721 (void)isCompleteType(OpLoc, MPTy); 10722 return MPTy; 10723 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10724 // C99 6.5.3.2p1 10725 // The operand must be either an l-value or a function designator 10726 if (!op->getType()->isFunctionType()) { 10727 // Use a special diagnostic for loads from property references. 10728 if (isa<PseudoObjectExpr>(op)) { 10729 AddressOfError = AO_Property_Expansion; 10730 } else { 10731 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10732 << op->getType() << op->getSourceRange(); 10733 return QualType(); 10734 } 10735 } 10736 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10737 // The operand cannot be a bit-field 10738 AddressOfError = AO_Bit_Field; 10739 } else if (op->getObjectKind() == OK_VectorComponent) { 10740 // The operand cannot be an element of a vector 10741 AddressOfError = AO_Vector_Element; 10742 } else if (dcl) { // C99 6.5.3.2p1 10743 // We have an lvalue with a decl. Make sure the decl is not declared 10744 // with the register storage-class specifier. 10745 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10746 // in C++ it is not error to take address of a register 10747 // variable (c++03 7.1.1P3) 10748 if (vd->getStorageClass() == SC_Register && 10749 !getLangOpts().CPlusPlus) { 10750 AddressOfError = AO_Register_Variable; 10751 } 10752 } else if (isa<MSPropertyDecl>(dcl)) { 10753 AddressOfError = AO_Property_Expansion; 10754 } else if (isa<FunctionTemplateDecl>(dcl)) { 10755 return Context.OverloadTy; 10756 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10757 // Okay: we can take the address of a field. 10758 // Could be a pointer to member, though, if there is an explicit 10759 // scope qualifier for the class. 10760 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10761 DeclContext *Ctx = dcl->getDeclContext(); 10762 if (Ctx && Ctx->isRecord()) { 10763 if (dcl->getType()->isReferenceType()) { 10764 Diag(OpLoc, 10765 diag::err_cannot_form_pointer_to_member_of_reference_type) 10766 << dcl->getDeclName() << dcl->getType(); 10767 return QualType(); 10768 } 10769 10770 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10771 Ctx = Ctx->getParent(); 10772 10773 QualType MPTy = Context.getMemberPointerType( 10774 op->getType(), 10775 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10776 // Under the MS ABI, lock down the inheritance model now. 10777 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10778 (void)isCompleteType(OpLoc, MPTy); 10779 return MPTy; 10780 } 10781 } 10782 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 10783 !isa<BindingDecl>(dcl)) 10784 llvm_unreachable("Unknown/unexpected decl type"); 10785 } 10786 10787 if (AddressOfError != AO_No_Error) { 10788 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10789 return QualType(); 10790 } 10791 10792 if (lval == Expr::LV_IncompleteVoidType) { 10793 // Taking the address of a void variable is technically illegal, but we 10794 // allow it in cases which are otherwise valid. 10795 // Example: "extern void x; void* y = &x;". 10796 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10797 } 10798 10799 // If the operand has type "type", the result has type "pointer to type". 10800 if (op->getType()->isObjCObjectType()) 10801 return Context.getObjCObjectPointerType(op->getType()); 10802 10803 CheckAddressOfPackedMember(op); 10804 10805 return Context.getPointerType(op->getType()); 10806 } 10807 10808 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10809 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10810 if (!DRE) 10811 return; 10812 const Decl *D = DRE->getDecl(); 10813 if (!D) 10814 return; 10815 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10816 if (!Param) 10817 return; 10818 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10819 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10820 return; 10821 if (FunctionScopeInfo *FD = S.getCurFunction()) 10822 if (!FD->ModifiedNonNullParams.count(Param)) 10823 FD->ModifiedNonNullParams.insert(Param); 10824 } 10825 10826 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10827 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10828 SourceLocation OpLoc) { 10829 if (Op->isTypeDependent()) 10830 return S.Context.DependentTy; 10831 10832 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10833 if (ConvResult.isInvalid()) 10834 return QualType(); 10835 Op = ConvResult.get(); 10836 QualType OpTy = Op->getType(); 10837 QualType Result; 10838 10839 if (isa<CXXReinterpretCastExpr>(Op)) { 10840 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10841 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10842 Op->getSourceRange()); 10843 } 10844 10845 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10846 { 10847 Result = PT->getPointeeType(); 10848 } 10849 else if (const ObjCObjectPointerType *OPT = 10850 OpTy->getAs<ObjCObjectPointerType>()) 10851 Result = OPT->getPointeeType(); 10852 else { 10853 ExprResult PR = S.CheckPlaceholderExpr(Op); 10854 if (PR.isInvalid()) return QualType(); 10855 if (PR.get() != Op) 10856 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10857 } 10858 10859 if (Result.isNull()) { 10860 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10861 << OpTy << Op->getSourceRange(); 10862 return QualType(); 10863 } 10864 10865 // Note that per both C89 and C99, indirection is always legal, even if Result 10866 // is an incomplete type or void. It would be possible to warn about 10867 // dereferencing a void pointer, but it's completely well-defined, and such a 10868 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10869 // for pointers to 'void' but is fine for any other pointer type: 10870 // 10871 // C++ [expr.unary.op]p1: 10872 // [...] the expression to which [the unary * operator] is applied shall 10873 // be a pointer to an object type, or a pointer to a function type 10874 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10875 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10876 << OpTy << Op->getSourceRange(); 10877 10878 // Dereferences are usually l-values... 10879 VK = VK_LValue; 10880 10881 // ...except that certain expressions are never l-values in C. 10882 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10883 VK = VK_RValue; 10884 10885 return Result; 10886 } 10887 10888 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10889 BinaryOperatorKind Opc; 10890 switch (Kind) { 10891 default: llvm_unreachable("Unknown binop!"); 10892 case tok::periodstar: Opc = BO_PtrMemD; break; 10893 case tok::arrowstar: Opc = BO_PtrMemI; break; 10894 case tok::star: Opc = BO_Mul; break; 10895 case tok::slash: Opc = BO_Div; break; 10896 case tok::percent: Opc = BO_Rem; break; 10897 case tok::plus: Opc = BO_Add; break; 10898 case tok::minus: Opc = BO_Sub; break; 10899 case tok::lessless: Opc = BO_Shl; break; 10900 case tok::greatergreater: Opc = BO_Shr; break; 10901 case tok::lessequal: Opc = BO_LE; break; 10902 case tok::less: Opc = BO_LT; break; 10903 case tok::greaterequal: Opc = BO_GE; break; 10904 case tok::greater: Opc = BO_GT; break; 10905 case tok::exclaimequal: Opc = BO_NE; break; 10906 case tok::equalequal: Opc = BO_EQ; break; 10907 case tok::amp: Opc = BO_And; break; 10908 case tok::caret: Opc = BO_Xor; break; 10909 case tok::pipe: Opc = BO_Or; break; 10910 case tok::ampamp: Opc = BO_LAnd; break; 10911 case tok::pipepipe: Opc = BO_LOr; break; 10912 case tok::equal: Opc = BO_Assign; break; 10913 case tok::starequal: Opc = BO_MulAssign; break; 10914 case tok::slashequal: Opc = BO_DivAssign; break; 10915 case tok::percentequal: Opc = BO_RemAssign; break; 10916 case tok::plusequal: Opc = BO_AddAssign; break; 10917 case tok::minusequal: Opc = BO_SubAssign; break; 10918 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10919 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10920 case tok::ampequal: Opc = BO_AndAssign; break; 10921 case tok::caretequal: Opc = BO_XorAssign; break; 10922 case tok::pipeequal: Opc = BO_OrAssign; break; 10923 case tok::comma: Opc = BO_Comma; break; 10924 } 10925 return Opc; 10926 } 10927 10928 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10929 tok::TokenKind Kind) { 10930 UnaryOperatorKind Opc; 10931 switch (Kind) { 10932 default: llvm_unreachable("Unknown unary op!"); 10933 case tok::plusplus: Opc = UO_PreInc; break; 10934 case tok::minusminus: Opc = UO_PreDec; break; 10935 case tok::amp: Opc = UO_AddrOf; break; 10936 case tok::star: Opc = UO_Deref; break; 10937 case tok::plus: Opc = UO_Plus; break; 10938 case tok::minus: Opc = UO_Minus; break; 10939 case tok::tilde: Opc = UO_Not; break; 10940 case tok::exclaim: Opc = UO_LNot; break; 10941 case tok::kw___real: Opc = UO_Real; break; 10942 case tok::kw___imag: Opc = UO_Imag; break; 10943 case tok::kw___extension__: Opc = UO_Extension; break; 10944 } 10945 return Opc; 10946 } 10947 10948 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10949 /// This warning is only emitted for builtin assignment operations. It is also 10950 /// suppressed in the event of macro expansions. 10951 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10952 SourceLocation OpLoc) { 10953 if (!S.ActiveTemplateInstantiations.empty()) 10954 return; 10955 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10956 return; 10957 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10958 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10959 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10960 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10961 if (!LHSDeclRef || !RHSDeclRef || 10962 LHSDeclRef->getLocation().isMacroID() || 10963 RHSDeclRef->getLocation().isMacroID()) 10964 return; 10965 const ValueDecl *LHSDecl = 10966 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10967 const ValueDecl *RHSDecl = 10968 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10969 if (LHSDecl != RHSDecl) 10970 return; 10971 if (LHSDecl->getType().isVolatileQualified()) 10972 return; 10973 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10974 if (RefTy->getPointeeType().isVolatileQualified()) 10975 return; 10976 10977 S.Diag(OpLoc, diag::warn_self_assignment) 10978 << LHSDeclRef->getType() 10979 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10980 } 10981 10982 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10983 /// is usually indicative of introspection within the Objective-C pointer. 10984 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10985 SourceLocation OpLoc) { 10986 if (!S.getLangOpts().ObjC1) 10987 return; 10988 10989 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10990 const Expr *LHS = L.get(); 10991 const Expr *RHS = R.get(); 10992 10993 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10994 ObjCPointerExpr = LHS; 10995 OtherExpr = RHS; 10996 } 10997 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10998 ObjCPointerExpr = RHS; 10999 OtherExpr = LHS; 11000 } 11001 11002 // This warning is deliberately made very specific to reduce false 11003 // positives with logic that uses '&' for hashing. This logic mainly 11004 // looks for code trying to introspect into tagged pointers, which 11005 // code should generally never do. 11006 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11007 unsigned Diag = diag::warn_objc_pointer_masking; 11008 // Determine if we are introspecting the result of performSelectorXXX. 11009 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11010 // Special case messages to -performSelector and friends, which 11011 // can return non-pointer values boxed in a pointer value. 11012 // Some clients may wish to silence warnings in this subcase. 11013 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11014 Selector S = ME->getSelector(); 11015 StringRef SelArg0 = S.getNameForSlot(0); 11016 if (SelArg0.startswith("performSelector")) 11017 Diag = diag::warn_objc_pointer_masking_performSelector; 11018 } 11019 11020 S.Diag(OpLoc, Diag) 11021 << ObjCPointerExpr->getSourceRange(); 11022 } 11023 } 11024 11025 static NamedDecl *getDeclFromExpr(Expr *E) { 11026 if (!E) 11027 return nullptr; 11028 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11029 return DRE->getDecl(); 11030 if (auto *ME = dyn_cast<MemberExpr>(E)) 11031 return ME->getMemberDecl(); 11032 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11033 return IRE->getDecl(); 11034 return nullptr; 11035 } 11036 11037 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11038 /// operator @p Opc at location @c TokLoc. This routine only supports 11039 /// built-in operations; ActOnBinOp handles overloaded operators. 11040 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11041 BinaryOperatorKind Opc, 11042 Expr *LHSExpr, Expr *RHSExpr) { 11043 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11044 // The syntax only allows initializer lists on the RHS of assignment, 11045 // so we don't need to worry about accepting invalid code for 11046 // non-assignment operators. 11047 // C++11 5.17p9: 11048 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11049 // of x = {} is x = T(). 11050 InitializationKind Kind = 11051 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 11052 InitializedEntity Entity = 11053 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11054 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11055 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11056 if (Init.isInvalid()) 11057 return Init; 11058 RHSExpr = Init.get(); 11059 } 11060 11061 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11062 QualType ResultTy; // Result type of the binary operator. 11063 // The following two variables are used for compound assignment operators 11064 QualType CompLHSTy; // Type of LHS after promotions for computation 11065 QualType CompResultTy; // Type of computation result 11066 ExprValueKind VK = VK_RValue; 11067 ExprObjectKind OK = OK_Ordinary; 11068 11069 if (!getLangOpts().CPlusPlus) { 11070 // C cannot handle TypoExpr nodes on either side of a binop because it 11071 // doesn't handle dependent types properly, so make sure any TypoExprs have 11072 // been dealt with before checking the operands. 11073 LHS = CorrectDelayedTyposInExpr(LHSExpr); 11074 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 11075 if (Opc != BO_Assign) 11076 return ExprResult(E); 11077 // Avoid correcting the RHS to the same Expr as the LHS. 11078 Decl *D = getDeclFromExpr(E); 11079 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11080 }); 11081 if (!LHS.isUsable() || !RHS.isUsable()) 11082 return ExprError(); 11083 } 11084 11085 if (getLangOpts().OpenCL) { 11086 QualType LHSTy = LHSExpr->getType(); 11087 QualType RHSTy = RHSExpr->getType(); 11088 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11089 // the ATOMIC_VAR_INIT macro. 11090 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11091 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11092 if (BO_Assign == Opc) 11093 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 11094 else 11095 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11096 return ExprError(); 11097 } 11098 11099 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11100 // only with a builtin functions and therefore should be disallowed here. 11101 if (LHSTy->isImageType() || RHSTy->isImageType() || 11102 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11103 LHSTy->isPipeType() || RHSTy->isPipeType() || 11104 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11105 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11106 return ExprError(); 11107 } 11108 } 11109 11110 switch (Opc) { 11111 case BO_Assign: 11112 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11113 if (getLangOpts().CPlusPlus && 11114 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11115 VK = LHS.get()->getValueKind(); 11116 OK = LHS.get()->getObjectKind(); 11117 } 11118 if (!ResultTy.isNull()) { 11119 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11120 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11121 } 11122 RecordModifiableNonNullParam(*this, LHS.get()); 11123 break; 11124 case BO_PtrMemD: 11125 case BO_PtrMemI: 11126 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11127 Opc == BO_PtrMemI); 11128 break; 11129 case BO_Mul: 11130 case BO_Div: 11131 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11132 Opc == BO_Div); 11133 break; 11134 case BO_Rem: 11135 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11136 break; 11137 case BO_Add: 11138 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11139 break; 11140 case BO_Sub: 11141 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11142 break; 11143 case BO_Shl: 11144 case BO_Shr: 11145 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11146 break; 11147 case BO_LE: 11148 case BO_LT: 11149 case BO_GE: 11150 case BO_GT: 11151 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11152 break; 11153 case BO_EQ: 11154 case BO_NE: 11155 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11156 break; 11157 case BO_And: 11158 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11159 case BO_Xor: 11160 case BO_Or: 11161 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11162 break; 11163 case BO_LAnd: 11164 case BO_LOr: 11165 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11166 break; 11167 case BO_MulAssign: 11168 case BO_DivAssign: 11169 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11170 Opc == BO_DivAssign); 11171 CompLHSTy = CompResultTy; 11172 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11173 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11174 break; 11175 case BO_RemAssign: 11176 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11177 CompLHSTy = CompResultTy; 11178 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11179 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11180 break; 11181 case BO_AddAssign: 11182 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11183 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11184 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11185 break; 11186 case BO_SubAssign: 11187 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11188 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11189 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11190 break; 11191 case BO_ShlAssign: 11192 case BO_ShrAssign: 11193 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11194 CompLHSTy = CompResultTy; 11195 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11196 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11197 break; 11198 case BO_AndAssign: 11199 case BO_OrAssign: // fallthrough 11200 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11201 case BO_XorAssign: 11202 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11203 CompLHSTy = CompResultTy; 11204 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11205 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11206 break; 11207 case BO_Comma: 11208 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11209 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11210 VK = RHS.get()->getValueKind(); 11211 OK = RHS.get()->getObjectKind(); 11212 } 11213 break; 11214 } 11215 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11216 return ExprError(); 11217 11218 // Check for array bounds violations for both sides of the BinaryOperator 11219 CheckArrayAccess(LHS.get()); 11220 CheckArrayAccess(RHS.get()); 11221 11222 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11223 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11224 &Context.Idents.get("object_setClass"), 11225 SourceLocation(), LookupOrdinaryName); 11226 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11227 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11228 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11229 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11230 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11231 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11232 } 11233 else 11234 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11235 } 11236 else if (const ObjCIvarRefExpr *OIRE = 11237 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11238 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11239 11240 if (CompResultTy.isNull()) 11241 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11242 OK, OpLoc, FPFeatures.fp_contract); 11243 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11244 OK_ObjCProperty) { 11245 VK = VK_LValue; 11246 OK = LHS.get()->getObjectKind(); 11247 } 11248 return new (Context) CompoundAssignOperator( 11249 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11250 OpLoc, FPFeatures.fp_contract); 11251 } 11252 11253 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11254 /// operators are mixed in a way that suggests that the programmer forgot that 11255 /// comparison operators have higher precedence. The most typical example of 11256 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11257 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11258 SourceLocation OpLoc, Expr *LHSExpr, 11259 Expr *RHSExpr) { 11260 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11261 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11262 11263 // Check that one of the sides is a comparison operator and the other isn't. 11264 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11265 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11266 if (isLeftComp == isRightComp) 11267 return; 11268 11269 // Bitwise operations are sometimes used as eager logical ops. 11270 // Don't diagnose this. 11271 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11272 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11273 if (isLeftBitwise || isRightBitwise) 11274 return; 11275 11276 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11277 OpLoc) 11278 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11279 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11280 SourceRange ParensRange = isLeftComp ? 11281 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11282 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11283 11284 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11285 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11286 SuggestParentheses(Self, OpLoc, 11287 Self.PDiag(diag::note_precedence_silence) << OpStr, 11288 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11289 SuggestParentheses(Self, OpLoc, 11290 Self.PDiag(diag::note_precedence_bitwise_first) 11291 << BinaryOperator::getOpcodeStr(Opc), 11292 ParensRange); 11293 } 11294 11295 /// \brief It accepts a '&&' expr that is inside a '||' one. 11296 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11297 /// in parentheses. 11298 static void 11299 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11300 BinaryOperator *Bop) { 11301 assert(Bop->getOpcode() == BO_LAnd); 11302 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11303 << Bop->getSourceRange() << OpLoc; 11304 SuggestParentheses(Self, Bop->getOperatorLoc(), 11305 Self.PDiag(diag::note_precedence_silence) 11306 << Bop->getOpcodeStr(), 11307 Bop->getSourceRange()); 11308 } 11309 11310 /// \brief Returns true if the given expression can be evaluated as a constant 11311 /// 'true'. 11312 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11313 bool Res; 11314 return !E->isValueDependent() && 11315 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11316 } 11317 11318 /// \brief Returns true if the given expression can be evaluated as a constant 11319 /// 'false'. 11320 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11321 bool Res; 11322 return !E->isValueDependent() && 11323 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11324 } 11325 11326 /// \brief Look for '&&' in the left hand of a '||' expr. 11327 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11328 Expr *LHSExpr, Expr *RHSExpr) { 11329 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11330 if (Bop->getOpcode() == BO_LAnd) { 11331 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11332 if (EvaluatesAsFalse(S, RHSExpr)) 11333 return; 11334 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11335 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11336 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11337 } else if (Bop->getOpcode() == BO_LOr) { 11338 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11339 // If it's "a || b && 1 || c" we didn't warn earlier for 11340 // "a || b && 1", but warn now. 11341 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11342 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11343 } 11344 } 11345 } 11346 } 11347 11348 /// \brief Look for '&&' in the right hand of a '||' expr. 11349 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11350 Expr *LHSExpr, Expr *RHSExpr) { 11351 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11352 if (Bop->getOpcode() == BO_LAnd) { 11353 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11354 if (EvaluatesAsFalse(S, LHSExpr)) 11355 return; 11356 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11357 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11358 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11359 } 11360 } 11361 } 11362 11363 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11364 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11365 /// the '&' expression in parentheses. 11366 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11367 SourceLocation OpLoc, Expr *SubExpr) { 11368 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11369 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11370 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11371 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11372 << Bop->getSourceRange() << OpLoc; 11373 SuggestParentheses(S, Bop->getOperatorLoc(), 11374 S.PDiag(diag::note_precedence_silence) 11375 << Bop->getOpcodeStr(), 11376 Bop->getSourceRange()); 11377 } 11378 } 11379 } 11380 11381 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11382 Expr *SubExpr, StringRef Shift) { 11383 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11384 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11385 StringRef Op = Bop->getOpcodeStr(); 11386 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11387 << Bop->getSourceRange() << OpLoc << Shift << Op; 11388 SuggestParentheses(S, Bop->getOperatorLoc(), 11389 S.PDiag(diag::note_precedence_silence) << Op, 11390 Bop->getSourceRange()); 11391 } 11392 } 11393 } 11394 11395 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 11396 Expr *LHSExpr, Expr *RHSExpr) { 11397 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 11398 if (!OCE) 11399 return; 11400 11401 FunctionDecl *FD = OCE->getDirectCallee(); 11402 if (!FD || !FD->isOverloadedOperator()) 11403 return; 11404 11405 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 11406 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 11407 return; 11408 11409 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 11410 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 11411 << (Kind == OO_LessLess); 11412 SuggestParentheses(S, OCE->getOperatorLoc(), 11413 S.PDiag(diag::note_precedence_silence) 11414 << (Kind == OO_LessLess ? "<<" : ">>"), 11415 OCE->getSourceRange()); 11416 SuggestParentheses(S, OpLoc, 11417 S.PDiag(diag::note_evaluate_comparison_first), 11418 SourceRange(OCE->getArg(1)->getLocStart(), 11419 RHSExpr->getLocEnd())); 11420 } 11421 11422 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 11423 /// precedence. 11424 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 11425 SourceLocation OpLoc, Expr *LHSExpr, 11426 Expr *RHSExpr){ 11427 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 11428 if (BinaryOperator::isBitwiseOp(Opc)) 11429 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 11430 11431 // Diagnose "arg1 & arg2 | arg3" 11432 if ((Opc == BO_Or || Opc == BO_Xor) && 11433 !OpLoc.isMacroID()/* Don't warn in macros. */) { 11434 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 11435 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 11436 } 11437 11438 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 11439 // We don't warn for 'assert(a || b && "bad")' since this is safe. 11440 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 11441 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 11442 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 11443 } 11444 11445 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 11446 || Opc == BO_Shr) { 11447 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 11448 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 11449 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 11450 } 11451 11452 // Warn on overloaded shift operators and comparisons, such as: 11453 // cout << 5 == 4; 11454 if (BinaryOperator::isComparisonOp(Opc)) 11455 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 11456 } 11457 11458 // Binary Operators. 'Tok' is the token for the operator. 11459 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 11460 tok::TokenKind Kind, 11461 Expr *LHSExpr, Expr *RHSExpr) { 11462 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 11463 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 11464 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 11465 11466 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 11467 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 11468 11469 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 11470 } 11471 11472 /// Build an overloaded binary operator expression in the given scope. 11473 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 11474 BinaryOperatorKind Opc, 11475 Expr *LHS, Expr *RHS) { 11476 // Find all of the overloaded operators visible from this 11477 // point. We perform both an operator-name lookup from the local 11478 // scope and an argument-dependent lookup based on the types of 11479 // the arguments. 11480 UnresolvedSet<16> Functions; 11481 OverloadedOperatorKind OverOp 11482 = BinaryOperator::getOverloadedOperator(Opc); 11483 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 11484 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 11485 RHS->getType(), Functions); 11486 11487 // Build the (potentially-overloaded, potentially-dependent) 11488 // binary operation. 11489 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 11490 } 11491 11492 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 11493 BinaryOperatorKind Opc, 11494 Expr *LHSExpr, Expr *RHSExpr) { 11495 // We want to end up calling one of checkPseudoObjectAssignment 11496 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 11497 // both expressions are overloadable or either is type-dependent), 11498 // or CreateBuiltinBinOp (in any other case). We also want to get 11499 // any placeholder types out of the way. 11500 11501 // Handle pseudo-objects in the LHS. 11502 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 11503 // Assignments with a pseudo-object l-value need special analysis. 11504 if (pty->getKind() == BuiltinType::PseudoObject && 11505 BinaryOperator::isAssignmentOp(Opc)) 11506 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 11507 11508 // Don't resolve overloads if the other type is overloadable. 11509 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 11510 // We can't actually test that if we still have a placeholder, 11511 // though. Fortunately, none of the exceptions we see in that 11512 // code below are valid when the LHS is an overload set. Note 11513 // that an overload set can be dependently-typed, but it never 11514 // instantiates to having an overloadable type. 11515 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11516 if (resolvedRHS.isInvalid()) return ExprError(); 11517 RHSExpr = resolvedRHS.get(); 11518 11519 if (RHSExpr->isTypeDependent() || 11520 RHSExpr->getType()->isOverloadableType()) 11521 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11522 } 11523 11524 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 11525 if (LHS.isInvalid()) return ExprError(); 11526 LHSExpr = LHS.get(); 11527 } 11528 11529 // Handle pseudo-objects in the RHS. 11530 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 11531 // An overload in the RHS can potentially be resolved by the type 11532 // being assigned to. 11533 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 11534 if (getLangOpts().CPlusPlus && 11535 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 11536 LHSExpr->getType()->isOverloadableType())) 11537 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11538 11539 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11540 } 11541 11542 // Don't resolve overloads if the other type is overloadable. 11543 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 11544 LHSExpr->getType()->isOverloadableType()) 11545 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11546 11547 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 11548 if (!resolvedRHS.isUsable()) return ExprError(); 11549 RHSExpr = resolvedRHS.get(); 11550 } 11551 11552 if (getLangOpts().CPlusPlus) { 11553 // If either expression is type-dependent, always build an 11554 // overloaded op. 11555 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 11556 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11557 11558 // Otherwise, build an overloaded op if either expression has an 11559 // overloadable type. 11560 if (LHSExpr->getType()->isOverloadableType() || 11561 RHSExpr->getType()->isOverloadableType()) 11562 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 11563 } 11564 11565 // Build a built-in binary operation. 11566 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 11567 } 11568 11569 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 11570 UnaryOperatorKind Opc, 11571 Expr *InputExpr) { 11572 ExprResult Input = InputExpr; 11573 ExprValueKind VK = VK_RValue; 11574 ExprObjectKind OK = OK_Ordinary; 11575 QualType resultType; 11576 if (getLangOpts().OpenCL) { 11577 QualType Ty = InputExpr->getType(); 11578 // The only legal unary operation for atomics is '&'. 11579 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 11580 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11581 // only with a builtin functions and therefore should be disallowed here. 11582 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 11583 || Ty->isBlockPointerType())) { 11584 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11585 << InputExpr->getType() 11586 << Input.get()->getSourceRange()); 11587 } 11588 } 11589 switch (Opc) { 11590 case UO_PreInc: 11591 case UO_PreDec: 11592 case UO_PostInc: 11593 case UO_PostDec: 11594 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 11595 OpLoc, 11596 Opc == UO_PreInc || 11597 Opc == UO_PostInc, 11598 Opc == UO_PreInc || 11599 Opc == UO_PreDec); 11600 break; 11601 case UO_AddrOf: 11602 resultType = CheckAddressOfOperand(Input, OpLoc); 11603 RecordModifiableNonNullParam(*this, InputExpr); 11604 break; 11605 case UO_Deref: { 11606 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11607 if (Input.isInvalid()) return ExprError(); 11608 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11609 break; 11610 } 11611 case UO_Plus: 11612 case UO_Minus: 11613 Input = UsualUnaryConversions(Input.get()); 11614 if (Input.isInvalid()) return ExprError(); 11615 resultType = Input.get()->getType(); 11616 if (resultType->isDependentType()) 11617 break; 11618 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11619 break; 11620 else if (resultType->isVectorType() && 11621 // The z vector extensions don't allow + or - with bool vectors. 11622 (!Context.getLangOpts().ZVector || 11623 resultType->getAs<VectorType>()->getVectorKind() != 11624 VectorType::AltiVecBool)) 11625 break; 11626 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11627 Opc == UO_Plus && 11628 resultType->isPointerType()) 11629 break; 11630 11631 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11632 << resultType << Input.get()->getSourceRange()); 11633 11634 case UO_Not: // bitwise complement 11635 Input = UsualUnaryConversions(Input.get()); 11636 if (Input.isInvalid()) 11637 return ExprError(); 11638 resultType = Input.get()->getType(); 11639 if (resultType->isDependentType()) 11640 break; 11641 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11642 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11643 // C99 does not support '~' for complex conjugation. 11644 Diag(OpLoc, diag::ext_integer_complement_complex) 11645 << resultType << Input.get()->getSourceRange(); 11646 else if (resultType->hasIntegerRepresentation()) 11647 break; 11648 else if (resultType->isExtVectorType()) { 11649 if (Context.getLangOpts().OpenCL) { 11650 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11651 // on vector float types. 11652 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11653 if (!T->isIntegerType()) 11654 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11655 << resultType << Input.get()->getSourceRange()); 11656 } 11657 break; 11658 } else { 11659 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11660 << resultType << Input.get()->getSourceRange()); 11661 } 11662 break; 11663 11664 case UO_LNot: // logical negation 11665 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11666 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11667 if (Input.isInvalid()) return ExprError(); 11668 resultType = Input.get()->getType(); 11669 11670 // Though we still have to promote half FP to float... 11671 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11672 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11673 resultType = Context.FloatTy; 11674 } 11675 11676 if (resultType->isDependentType()) 11677 break; 11678 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11679 // C99 6.5.3.3p1: ok, fallthrough; 11680 if (Context.getLangOpts().CPlusPlus) { 11681 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11682 // operand contextually converted to bool. 11683 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11684 ScalarTypeToBooleanCastKind(resultType)); 11685 } else if (Context.getLangOpts().OpenCL && 11686 Context.getLangOpts().OpenCLVersion < 120) { 11687 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11688 // operate on scalar float types. 11689 if (!resultType->isIntegerType()) 11690 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11691 << resultType << Input.get()->getSourceRange()); 11692 } 11693 } else if (resultType->isExtVectorType()) { 11694 if (Context.getLangOpts().OpenCL && 11695 Context.getLangOpts().OpenCLVersion < 120) { 11696 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11697 // operate on vector float types. 11698 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11699 if (!T->isIntegerType()) 11700 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11701 << resultType << Input.get()->getSourceRange()); 11702 } 11703 // Vector logical not returns the signed variant of the operand type. 11704 resultType = GetSignedVectorType(resultType); 11705 break; 11706 } else { 11707 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11708 << resultType << Input.get()->getSourceRange()); 11709 } 11710 11711 // LNot always has type int. C99 6.5.3.3p5. 11712 // In C++, it's bool. C++ 5.3.1p8 11713 resultType = Context.getLogicalOperationType(); 11714 break; 11715 case UO_Real: 11716 case UO_Imag: 11717 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11718 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11719 // complex l-values to ordinary l-values and all other values to r-values. 11720 if (Input.isInvalid()) return ExprError(); 11721 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11722 if (Input.get()->getValueKind() != VK_RValue && 11723 Input.get()->getObjectKind() == OK_Ordinary) 11724 VK = Input.get()->getValueKind(); 11725 } else if (!getLangOpts().CPlusPlus) { 11726 // In C, a volatile scalar is read by __imag. In C++, it is not. 11727 Input = DefaultLvalueConversion(Input.get()); 11728 } 11729 break; 11730 case UO_Extension: 11731 case UO_Coawait: 11732 resultType = Input.get()->getType(); 11733 VK = Input.get()->getValueKind(); 11734 OK = Input.get()->getObjectKind(); 11735 break; 11736 } 11737 if (resultType.isNull() || Input.isInvalid()) 11738 return ExprError(); 11739 11740 // Check for array bounds violations in the operand of the UnaryOperator, 11741 // except for the '*' and '&' operators that have to be handled specially 11742 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11743 // that are explicitly defined as valid by the standard). 11744 if (Opc != UO_AddrOf && Opc != UO_Deref) 11745 CheckArrayAccess(Input.get()); 11746 11747 return new (Context) 11748 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11749 } 11750 11751 /// \brief Determine whether the given expression is a qualified member 11752 /// access expression, of a form that could be turned into a pointer to member 11753 /// with the address-of operator. 11754 static bool isQualifiedMemberAccess(Expr *E) { 11755 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11756 if (!DRE->getQualifier()) 11757 return false; 11758 11759 ValueDecl *VD = DRE->getDecl(); 11760 if (!VD->isCXXClassMember()) 11761 return false; 11762 11763 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11764 return true; 11765 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11766 return Method->isInstance(); 11767 11768 return false; 11769 } 11770 11771 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11772 if (!ULE->getQualifier()) 11773 return false; 11774 11775 for (NamedDecl *D : ULE->decls()) { 11776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11777 if (Method->isInstance()) 11778 return true; 11779 } else { 11780 // Overload set does not contain methods. 11781 break; 11782 } 11783 } 11784 11785 return false; 11786 } 11787 11788 return false; 11789 } 11790 11791 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11792 UnaryOperatorKind Opc, Expr *Input) { 11793 // First things first: handle placeholders so that the 11794 // overloaded-operator check considers the right type. 11795 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11796 // Increment and decrement of pseudo-object references. 11797 if (pty->getKind() == BuiltinType::PseudoObject && 11798 UnaryOperator::isIncrementDecrementOp(Opc)) 11799 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11800 11801 // extension is always a builtin operator. 11802 if (Opc == UO_Extension) 11803 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11804 11805 // & gets special logic for several kinds of placeholder. 11806 // The builtin code knows what to do. 11807 if (Opc == UO_AddrOf && 11808 (pty->getKind() == BuiltinType::Overload || 11809 pty->getKind() == BuiltinType::UnknownAny || 11810 pty->getKind() == BuiltinType::BoundMember)) 11811 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11812 11813 // Anything else needs to be handled now. 11814 ExprResult Result = CheckPlaceholderExpr(Input); 11815 if (Result.isInvalid()) return ExprError(); 11816 Input = Result.get(); 11817 } 11818 11819 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11820 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11821 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11822 // Find all of the overloaded operators visible from this 11823 // point. We perform both an operator-name lookup from the local 11824 // scope and an argument-dependent lookup based on the types of 11825 // the arguments. 11826 UnresolvedSet<16> Functions; 11827 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11828 if (S && OverOp != OO_None) 11829 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11830 Functions); 11831 11832 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11833 } 11834 11835 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11836 } 11837 11838 // Unary Operators. 'Tok' is the token for the operator. 11839 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11840 tok::TokenKind Op, Expr *Input) { 11841 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11842 } 11843 11844 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11845 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11846 LabelDecl *TheDecl) { 11847 TheDecl->markUsed(Context); 11848 // Create the AST node. The address of a label always has type 'void*'. 11849 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11850 Context.getPointerType(Context.VoidTy)); 11851 } 11852 11853 /// Given the last statement in a statement-expression, check whether 11854 /// the result is a producing expression (like a call to an 11855 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11856 /// release out of the full-expression. Otherwise, return null. 11857 /// Cannot fail. 11858 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11859 // Should always be wrapped with one of these. 11860 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11861 if (!cleanups) return nullptr; 11862 11863 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11864 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11865 return nullptr; 11866 11867 // Splice out the cast. This shouldn't modify any interesting 11868 // features of the statement. 11869 Expr *producer = cast->getSubExpr(); 11870 assert(producer->getType() == cast->getType()); 11871 assert(producer->getValueKind() == cast->getValueKind()); 11872 cleanups->setSubExpr(producer); 11873 return cleanups; 11874 } 11875 11876 void Sema::ActOnStartStmtExpr() { 11877 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11878 } 11879 11880 void Sema::ActOnStmtExprError() { 11881 // Note that function is also called by TreeTransform when leaving a 11882 // StmtExpr scope without rebuilding anything. 11883 11884 DiscardCleanupsInEvaluationContext(); 11885 PopExpressionEvaluationContext(); 11886 } 11887 11888 ExprResult 11889 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11890 SourceLocation RPLoc) { // "({..})" 11891 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11892 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11893 11894 if (hasAnyUnrecoverableErrorsInThisFunction()) 11895 DiscardCleanupsInEvaluationContext(); 11896 assert(!Cleanup.exprNeedsCleanups() && 11897 "cleanups within StmtExpr not correctly bound!"); 11898 PopExpressionEvaluationContext(); 11899 11900 // FIXME: there are a variety of strange constraints to enforce here, for 11901 // example, it is not possible to goto into a stmt expression apparently. 11902 // More semantic analysis is needed. 11903 11904 // If there are sub-stmts in the compound stmt, take the type of the last one 11905 // as the type of the stmtexpr. 11906 QualType Ty = Context.VoidTy; 11907 bool StmtExprMayBindToTemp = false; 11908 if (!Compound->body_empty()) { 11909 Stmt *LastStmt = Compound->body_back(); 11910 LabelStmt *LastLabelStmt = nullptr; 11911 // If LastStmt is a label, skip down through into the body. 11912 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11913 LastLabelStmt = Label; 11914 LastStmt = Label->getSubStmt(); 11915 } 11916 11917 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11918 // Do function/array conversion on the last expression, but not 11919 // lvalue-to-rvalue. However, initialize an unqualified type. 11920 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11921 if (LastExpr.isInvalid()) 11922 return ExprError(); 11923 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11924 11925 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11926 // In ARC, if the final expression ends in a consume, splice 11927 // the consume out and bind it later. In the alternate case 11928 // (when dealing with a retainable type), the result 11929 // initialization will create a produce. In both cases the 11930 // result will be +1, and we'll need to balance that out with 11931 // a bind. 11932 if (Expr *rebuiltLastStmt 11933 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11934 LastExpr = rebuiltLastStmt; 11935 } else { 11936 LastExpr = PerformCopyInitialization( 11937 InitializedEntity::InitializeResult(LPLoc, 11938 Ty, 11939 false), 11940 SourceLocation(), 11941 LastExpr); 11942 } 11943 11944 if (LastExpr.isInvalid()) 11945 return ExprError(); 11946 if (LastExpr.get() != nullptr) { 11947 if (!LastLabelStmt) 11948 Compound->setLastStmt(LastExpr.get()); 11949 else 11950 LastLabelStmt->setSubStmt(LastExpr.get()); 11951 StmtExprMayBindToTemp = true; 11952 } 11953 } 11954 } 11955 } 11956 11957 // FIXME: Check that expression type is complete/non-abstract; statement 11958 // expressions are not lvalues. 11959 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11960 if (StmtExprMayBindToTemp) 11961 return MaybeBindToTemporary(ResStmtExpr); 11962 return ResStmtExpr; 11963 } 11964 11965 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11966 TypeSourceInfo *TInfo, 11967 ArrayRef<OffsetOfComponent> Components, 11968 SourceLocation RParenLoc) { 11969 QualType ArgTy = TInfo->getType(); 11970 bool Dependent = ArgTy->isDependentType(); 11971 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11972 11973 // We must have at least one component that refers to the type, and the first 11974 // one is known to be a field designator. Verify that the ArgTy represents 11975 // a struct/union/class. 11976 if (!Dependent && !ArgTy->isRecordType()) 11977 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11978 << ArgTy << TypeRange); 11979 11980 // Type must be complete per C99 7.17p3 because a declaring a variable 11981 // with an incomplete type would be ill-formed. 11982 if (!Dependent 11983 && RequireCompleteType(BuiltinLoc, ArgTy, 11984 diag::err_offsetof_incomplete_type, TypeRange)) 11985 return ExprError(); 11986 11987 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11988 // GCC extension, diagnose them. 11989 // FIXME: This diagnostic isn't actually visible because the location is in 11990 // a system header! 11991 if (Components.size() != 1) 11992 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11993 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11994 11995 bool DidWarnAboutNonPOD = false; 11996 QualType CurrentType = ArgTy; 11997 SmallVector<OffsetOfNode, 4> Comps; 11998 SmallVector<Expr*, 4> Exprs; 11999 for (const OffsetOfComponent &OC : Components) { 12000 if (OC.isBrackets) { 12001 // Offset of an array sub-field. TODO: Should we allow vector elements? 12002 if (!CurrentType->isDependentType()) { 12003 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12004 if(!AT) 12005 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12006 << CurrentType); 12007 CurrentType = AT->getElementType(); 12008 } else 12009 CurrentType = Context.DependentTy; 12010 12011 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12012 if (IdxRval.isInvalid()) 12013 return ExprError(); 12014 Expr *Idx = IdxRval.get(); 12015 12016 // The expression must be an integral expression. 12017 // FIXME: An integral constant expression? 12018 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12019 !Idx->getType()->isIntegerType()) 12020 return ExprError(Diag(Idx->getLocStart(), 12021 diag::err_typecheck_subscript_not_integer) 12022 << Idx->getSourceRange()); 12023 12024 // Record this array index. 12025 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12026 Exprs.push_back(Idx); 12027 continue; 12028 } 12029 12030 // Offset of a field. 12031 if (CurrentType->isDependentType()) { 12032 // We have the offset of a field, but we can't look into the dependent 12033 // type. Just record the identifier of the field. 12034 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12035 CurrentType = Context.DependentTy; 12036 continue; 12037 } 12038 12039 // We need to have a complete type to look into. 12040 if (RequireCompleteType(OC.LocStart, CurrentType, 12041 diag::err_offsetof_incomplete_type)) 12042 return ExprError(); 12043 12044 // Look for the designated field. 12045 const RecordType *RC = CurrentType->getAs<RecordType>(); 12046 if (!RC) 12047 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12048 << CurrentType); 12049 RecordDecl *RD = RC->getDecl(); 12050 12051 // C++ [lib.support.types]p5: 12052 // The macro offsetof accepts a restricted set of type arguments in this 12053 // International Standard. type shall be a POD structure or a POD union 12054 // (clause 9). 12055 // C++11 [support.types]p4: 12056 // If type is not a standard-layout class (Clause 9), the results are 12057 // undefined. 12058 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12059 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12060 unsigned DiagID = 12061 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12062 : diag::ext_offsetof_non_pod_type; 12063 12064 if (!IsSafe && !DidWarnAboutNonPOD && 12065 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12066 PDiag(DiagID) 12067 << SourceRange(Components[0].LocStart, OC.LocEnd) 12068 << CurrentType)) 12069 DidWarnAboutNonPOD = true; 12070 } 12071 12072 // Look for the field. 12073 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12074 LookupQualifiedName(R, RD); 12075 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12076 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12077 if (!MemberDecl) { 12078 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12079 MemberDecl = IndirectMemberDecl->getAnonField(); 12080 } 12081 12082 if (!MemberDecl) 12083 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12084 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12085 OC.LocEnd)); 12086 12087 // C99 7.17p3: 12088 // (If the specified member is a bit-field, the behavior is undefined.) 12089 // 12090 // We diagnose this as an error. 12091 if (MemberDecl->isBitField()) { 12092 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12093 << MemberDecl->getDeclName() 12094 << SourceRange(BuiltinLoc, RParenLoc); 12095 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12096 return ExprError(); 12097 } 12098 12099 RecordDecl *Parent = MemberDecl->getParent(); 12100 if (IndirectMemberDecl) 12101 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12102 12103 // If the member was found in a base class, introduce OffsetOfNodes for 12104 // the base class indirections. 12105 CXXBasePaths Paths; 12106 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12107 Paths)) { 12108 if (Paths.getDetectedVirtual()) { 12109 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12110 << MemberDecl->getDeclName() 12111 << SourceRange(BuiltinLoc, RParenLoc); 12112 return ExprError(); 12113 } 12114 12115 CXXBasePath &Path = Paths.front(); 12116 for (const CXXBasePathElement &B : Path) 12117 Comps.push_back(OffsetOfNode(B.Base)); 12118 } 12119 12120 if (IndirectMemberDecl) { 12121 for (auto *FI : IndirectMemberDecl->chain()) { 12122 assert(isa<FieldDecl>(FI)); 12123 Comps.push_back(OffsetOfNode(OC.LocStart, 12124 cast<FieldDecl>(FI), OC.LocEnd)); 12125 } 12126 } else 12127 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12128 12129 CurrentType = MemberDecl->getType().getNonReferenceType(); 12130 } 12131 12132 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12133 Comps, Exprs, RParenLoc); 12134 } 12135 12136 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12137 SourceLocation BuiltinLoc, 12138 SourceLocation TypeLoc, 12139 ParsedType ParsedArgTy, 12140 ArrayRef<OffsetOfComponent> Components, 12141 SourceLocation RParenLoc) { 12142 12143 TypeSourceInfo *ArgTInfo; 12144 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12145 if (ArgTy.isNull()) 12146 return ExprError(); 12147 12148 if (!ArgTInfo) 12149 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12150 12151 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12152 } 12153 12154 12155 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12156 Expr *CondExpr, 12157 Expr *LHSExpr, Expr *RHSExpr, 12158 SourceLocation RPLoc) { 12159 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12160 12161 ExprValueKind VK = VK_RValue; 12162 ExprObjectKind OK = OK_Ordinary; 12163 QualType resType; 12164 bool ValueDependent = false; 12165 bool CondIsTrue = false; 12166 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12167 resType = Context.DependentTy; 12168 ValueDependent = true; 12169 } else { 12170 // The conditional expression is required to be a constant expression. 12171 llvm::APSInt condEval(32); 12172 ExprResult CondICE 12173 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12174 diag::err_typecheck_choose_expr_requires_constant, false); 12175 if (CondICE.isInvalid()) 12176 return ExprError(); 12177 CondExpr = CondICE.get(); 12178 CondIsTrue = condEval.getZExtValue(); 12179 12180 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12181 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12182 12183 resType = ActiveExpr->getType(); 12184 ValueDependent = ActiveExpr->isValueDependent(); 12185 VK = ActiveExpr->getValueKind(); 12186 OK = ActiveExpr->getObjectKind(); 12187 } 12188 12189 return new (Context) 12190 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12191 CondIsTrue, resType->isDependentType(), ValueDependent); 12192 } 12193 12194 //===----------------------------------------------------------------------===// 12195 // Clang Extensions. 12196 //===----------------------------------------------------------------------===// 12197 12198 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12199 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12200 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12201 12202 if (LangOpts.CPlusPlus) { 12203 Decl *ManglingContextDecl; 12204 if (MangleNumberingContext *MCtx = 12205 getCurrentMangleNumberContext(Block->getDeclContext(), 12206 ManglingContextDecl)) { 12207 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12208 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12209 } 12210 } 12211 12212 PushBlockScope(CurScope, Block); 12213 CurContext->addDecl(Block); 12214 if (CurScope) 12215 PushDeclContext(CurScope, Block); 12216 else 12217 CurContext = Block; 12218 12219 getCurBlock()->HasImplicitReturnType = true; 12220 12221 // Enter a new evaluation context to insulate the block from any 12222 // cleanups from the enclosing full-expression. 12223 PushExpressionEvaluationContext(PotentiallyEvaluated); 12224 } 12225 12226 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12227 Scope *CurScope) { 12228 assert(ParamInfo.getIdentifier() == nullptr && 12229 "block-id should have no identifier!"); 12230 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 12231 BlockScopeInfo *CurBlock = getCurBlock(); 12232 12233 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12234 QualType T = Sig->getType(); 12235 12236 // FIXME: We should allow unexpanded parameter packs here, but that would, 12237 // in turn, make the block expression contain unexpanded parameter packs. 12238 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12239 // Drop the parameters. 12240 FunctionProtoType::ExtProtoInfo EPI; 12241 EPI.HasTrailingReturn = false; 12242 EPI.TypeQuals |= DeclSpec::TQ_const; 12243 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12244 Sig = Context.getTrivialTypeSourceInfo(T); 12245 } 12246 12247 // GetTypeForDeclarator always produces a function type for a block 12248 // literal signature. Furthermore, it is always a FunctionProtoType 12249 // unless the function was written with a typedef. 12250 assert(T->isFunctionType() && 12251 "GetTypeForDeclarator made a non-function block signature"); 12252 12253 // Look for an explicit signature in that function type. 12254 FunctionProtoTypeLoc ExplicitSignature; 12255 12256 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 12257 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 12258 12259 // Check whether that explicit signature was synthesized by 12260 // GetTypeForDeclarator. If so, don't save that as part of the 12261 // written signature. 12262 if (ExplicitSignature.getLocalRangeBegin() == 12263 ExplicitSignature.getLocalRangeEnd()) { 12264 // This would be much cheaper if we stored TypeLocs instead of 12265 // TypeSourceInfos. 12266 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12267 unsigned Size = Result.getFullDataSize(); 12268 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12269 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12270 12271 ExplicitSignature = FunctionProtoTypeLoc(); 12272 } 12273 } 12274 12275 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12276 CurBlock->FunctionType = T; 12277 12278 const FunctionType *Fn = T->getAs<FunctionType>(); 12279 QualType RetTy = Fn->getReturnType(); 12280 bool isVariadic = 12281 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12282 12283 CurBlock->TheDecl->setIsVariadic(isVariadic); 12284 12285 // Context.DependentTy is used as a placeholder for a missing block 12286 // return type. TODO: what should we do with declarators like: 12287 // ^ * { ... } 12288 // If the answer is "apply template argument deduction".... 12289 if (RetTy != Context.DependentTy) { 12290 CurBlock->ReturnType = RetTy; 12291 CurBlock->TheDecl->setBlockMissingReturnType(false); 12292 CurBlock->HasImplicitReturnType = false; 12293 } 12294 12295 // Push block parameters from the declarator if we had them. 12296 SmallVector<ParmVarDecl*, 8> Params; 12297 if (ExplicitSignature) { 12298 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12299 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12300 if (Param->getIdentifier() == nullptr && 12301 !Param->isImplicit() && 12302 !Param->isInvalidDecl() && 12303 !getLangOpts().CPlusPlus) 12304 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12305 Params.push_back(Param); 12306 } 12307 12308 // Fake up parameter variables if we have a typedef, like 12309 // ^ fntype { ... } 12310 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12311 for (const auto &I : Fn->param_types()) { 12312 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12313 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12314 Params.push_back(Param); 12315 } 12316 } 12317 12318 // Set the parameters on the block decl. 12319 if (!Params.empty()) { 12320 CurBlock->TheDecl->setParams(Params); 12321 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12322 /*CheckParameterNames=*/false); 12323 } 12324 12325 // Finally we can process decl attributes. 12326 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12327 12328 // Put the parameter variables in scope. 12329 for (auto AI : CurBlock->TheDecl->parameters()) { 12330 AI->setOwningFunction(CurBlock->TheDecl); 12331 12332 // If this has an identifier, add it to the scope stack. 12333 if (AI->getIdentifier()) { 12334 CheckShadow(CurBlock->TheScope, AI); 12335 12336 PushOnScopeChains(AI, CurBlock->TheScope); 12337 } 12338 } 12339 } 12340 12341 /// ActOnBlockError - If there is an error parsing a block, this callback 12342 /// is invoked to pop the information about the block from the action impl. 12343 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 12344 // Leave the expression-evaluation context. 12345 DiscardCleanupsInEvaluationContext(); 12346 PopExpressionEvaluationContext(); 12347 12348 // Pop off CurBlock, handle nested blocks. 12349 PopDeclContext(); 12350 PopFunctionScopeInfo(); 12351 } 12352 12353 /// ActOnBlockStmtExpr - This is called when the body of a block statement 12354 /// literal was successfully completed. ^(int x){...} 12355 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 12356 Stmt *Body, Scope *CurScope) { 12357 // If blocks are disabled, emit an error. 12358 if (!LangOpts.Blocks) 12359 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 12360 12361 // Leave the expression-evaluation context. 12362 if (hasAnyUnrecoverableErrorsInThisFunction()) 12363 DiscardCleanupsInEvaluationContext(); 12364 assert(!Cleanup.exprNeedsCleanups() && 12365 "cleanups within block not correctly bound!"); 12366 PopExpressionEvaluationContext(); 12367 12368 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 12369 12370 if (BSI->HasImplicitReturnType) 12371 deduceClosureReturnType(*BSI); 12372 12373 PopDeclContext(); 12374 12375 QualType RetTy = Context.VoidTy; 12376 if (!BSI->ReturnType.isNull()) 12377 RetTy = BSI->ReturnType; 12378 12379 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 12380 QualType BlockTy; 12381 12382 // Set the captured variables on the block. 12383 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 12384 SmallVector<BlockDecl::Capture, 4> Captures; 12385 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 12386 if (Cap.isThisCapture()) 12387 continue; 12388 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 12389 Cap.isNested(), Cap.getInitExpr()); 12390 Captures.push_back(NewCap); 12391 } 12392 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 12393 12394 // If the user wrote a function type in some form, try to use that. 12395 if (!BSI->FunctionType.isNull()) { 12396 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 12397 12398 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 12399 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 12400 12401 // Turn protoless block types into nullary block types. 12402 if (isa<FunctionNoProtoType>(FTy)) { 12403 FunctionProtoType::ExtProtoInfo EPI; 12404 EPI.ExtInfo = Ext; 12405 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12406 12407 // Otherwise, if we don't need to change anything about the function type, 12408 // preserve its sugar structure. 12409 } else if (FTy->getReturnType() == RetTy && 12410 (!NoReturn || FTy->getNoReturnAttr())) { 12411 BlockTy = BSI->FunctionType; 12412 12413 // Otherwise, make the minimal modifications to the function type. 12414 } else { 12415 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 12416 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12417 EPI.TypeQuals = 0; // FIXME: silently? 12418 EPI.ExtInfo = Ext; 12419 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 12420 } 12421 12422 // If we don't have a function type, just build one from nothing. 12423 } else { 12424 FunctionProtoType::ExtProtoInfo EPI; 12425 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 12426 BlockTy = Context.getFunctionType(RetTy, None, EPI); 12427 } 12428 12429 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 12430 BlockTy = Context.getBlockPointerType(BlockTy); 12431 12432 // If needed, diagnose invalid gotos and switches in the block. 12433 if (getCurFunction()->NeedsScopeChecking() && 12434 !PP.isCodeCompletionEnabled()) 12435 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 12436 12437 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 12438 12439 // Try to apply the named return value optimization. We have to check again 12440 // if we can do this, though, because blocks keep return statements around 12441 // to deduce an implicit return type. 12442 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 12443 !BSI->TheDecl->isDependentContext()) 12444 computeNRVO(Body, BSI); 12445 12446 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 12447 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12448 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 12449 12450 // If the block isn't obviously global, i.e. it captures anything at 12451 // all, then we need to do a few things in the surrounding context: 12452 if (Result->getBlockDecl()->hasCaptures()) { 12453 // First, this expression has a new cleanup object. 12454 ExprCleanupObjects.push_back(Result->getBlockDecl()); 12455 Cleanup.setExprNeedsCleanups(true); 12456 12457 // It also gets a branch-protected scope if any of the captured 12458 // variables needs destruction. 12459 for (const auto &CI : Result->getBlockDecl()->captures()) { 12460 const VarDecl *var = CI.getVariable(); 12461 if (var->getType().isDestructedType() != QualType::DK_none) { 12462 getCurFunction()->setHasBranchProtectedScope(); 12463 break; 12464 } 12465 } 12466 } 12467 12468 return Result; 12469 } 12470 12471 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 12472 SourceLocation RPLoc) { 12473 TypeSourceInfo *TInfo; 12474 GetTypeFromParser(Ty, &TInfo); 12475 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 12476 } 12477 12478 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 12479 Expr *E, TypeSourceInfo *TInfo, 12480 SourceLocation RPLoc) { 12481 Expr *OrigExpr = E; 12482 bool IsMS = false; 12483 12484 // CUDA device code does not support varargs. 12485 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 12486 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 12487 CUDAFunctionTarget T = IdentifyCUDATarget(F); 12488 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 12489 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 12490 } 12491 } 12492 12493 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 12494 // as Microsoft ABI on an actual Microsoft platform, where 12495 // __builtin_ms_va_list and __builtin_va_list are the same.) 12496 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 12497 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 12498 QualType MSVaListType = Context.getBuiltinMSVaListType(); 12499 if (Context.hasSameType(MSVaListType, E->getType())) { 12500 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12501 return ExprError(); 12502 IsMS = true; 12503 } 12504 } 12505 12506 // Get the va_list type 12507 QualType VaListType = Context.getBuiltinVaListType(); 12508 if (!IsMS) { 12509 if (VaListType->isArrayType()) { 12510 // Deal with implicit array decay; for example, on x86-64, 12511 // va_list is an array, but it's supposed to decay to 12512 // a pointer for va_arg. 12513 VaListType = Context.getArrayDecayedType(VaListType); 12514 // Make sure the input expression also decays appropriately. 12515 ExprResult Result = UsualUnaryConversions(E); 12516 if (Result.isInvalid()) 12517 return ExprError(); 12518 E = Result.get(); 12519 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 12520 // If va_list is a record type and we are compiling in C++ mode, 12521 // check the argument using reference binding. 12522 InitializedEntity Entity = InitializedEntity::InitializeParameter( 12523 Context, Context.getLValueReferenceType(VaListType), false); 12524 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 12525 if (Init.isInvalid()) 12526 return ExprError(); 12527 E = Init.getAs<Expr>(); 12528 } else { 12529 // Otherwise, the va_list argument must be an l-value because 12530 // it is modified by va_arg. 12531 if (!E->isTypeDependent() && 12532 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 12533 return ExprError(); 12534 } 12535 } 12536 12537 if (!IsMS && !E->isTypeDependent() && 12538 !Context.hasSameType(VaListType, E->getType())) 12539 return ExprError(Diag(E->getLocStart(), 12540 diag::err_first_argument_to_va_arg_not_of_type_va_list) 12541 << OrigExpr->getType() << E->getSourceRange()); 12542 12543 if (!TInfo->getType()->isDependentType()) { 12544 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 12545 diag::err_second_parameter_to_va_arg_incomplete, 12546 TInfo->getTypeLoc())) 12547 return ExprError(); 12548 12549 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 12550 TInfo->getType(), 12551 diag::err_second_parameter_to_va_arg_abstract, 12552 TInfo->getTypeLoc())) 12553 return ExprError(); 12554 12555 if (!TInfo->getType().isPODType(Context)) { 12556 Diag(TInfo->getTypeLoc().getBeginLoc(), 12557 TInfo->getType()->isObjCLifetimeType() 12558 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 12559 : diag::warn_second_parameter_to_va_arg_not_pod) 12560 << TInfo->getType() 12561 << TInfo->getTypeLoc().getSourceRange(); 12562 } 12563 12564 // Check for va_arg where arguments of the given type will be promoted 12565 // (i.e. this va_arg is guaranteed to have undefined behavior). 12566 QualType PromoteType; 12567 if (TInfo->getType()->isPromotableIntegerType()) { 12568 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 12569 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 12570 PromoteType = QualType(); 12571 } 12572 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 12573 PromoteType = Context.DoubleTy; 12574 if (!PromoteType.isNull()) 12575 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 12576 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 12577 << TInfo->getType() 12578 << PromoteType 12579 << TInfo->getTypeLoc().getSourceRange()); 12580 } 12581 12582 QualType T = TInfo->getType().getNonLValueExprType(Context); 12583 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 12584 } 12585 12586 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 12587 // The type of __null will be int or long, depending on the size of 12588 // pointers on the target. 12589 QualType Ty; 12590 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 12591 if (pw == Context.getTargetInfo().getIntWidth()) 12592 Ty = Context.IntTy; 12593 else if (pw == Context.getTargetInfo().getLongWidth()) 12594 Ty = Context.LongTy; 12595 else if (pw == Context.getTargetInfo().getLongLongWidth()) 12596 Ty = Context.LongLongTy; 12597 else { 12598 llvm_unreachable("I don't know size of pointer!"); 12599 } 12600 12601 return new (Context) GNUNullExpr(Ty, TokenLoc); 12602 } 12603 12604 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 12605 bool Diagnose) { 12606 if (!getLangOpts().ObjC1) 12607 return false; 12608 12609 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12610 if (!PT) 12611 return false; 12612 12613 if (!PT->isObjCIdType()) { 12614 // Check if the destination is the 'NSString' interface. 12615 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12616 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12617 return false; 12618 } 12619 12620 // Ignore any parens, implicit casts (should only be 12621 // array-to-pointer decays), and not-so-opaque values. The last is 12622 // important for making this trigger for property assignments. 12623 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12624 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12625 if (OV->getSourceExpr()) 12626 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12627 12628 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12629 if (!SL || !SL->isAscii()) 12630 return false; 12631 if (Diagnose) { 12632 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12633 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12634 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12635 } 12636 return true; 12637 } 12638 12639 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12640 const Expr *SrcExpr) { 12641 if (!DstType->isFunctionPointerType() || 12642 !SrcExpr->getType()->isFunctionType()) 12643 return false; 12644 12645 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12646 if (!DRE) 12647 return false; 12648 12649 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12650 if (!FD) 12651 return false; 12652 12653 return !S.checkAddressOfFunctionIsAvailable(FD, 12654 /*Complain=*/true, 12655 SrcExpr->getLocStart()); 12656 } 12657 12658 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12659 SourceLocation Loc, 12660 QualType DstType, QualType SrcType, 12661 Expr *SrcExpr, AssignmentAction Action, 12662 bool *Complained) { 12663 if (Complained) 12664 *Complained = false; 12665 12666 // Decode the result (notice that AST's are still created for extensions). 12667 bool CheckInferredResultType = false; 12668 bool isInvalid = false; 12669 unsigned DiagKind = 0; 12670 FixItHint Hint; 12671 ConversionFixItGenerator ConvHints; 12672 bool MayHaveConvFixit = false; 12673 bool MayHaveFunctionDiff = false; 12674 const ObjCInterfaceDecl *IFace = nullptr; 12675 const ObjCProtocolDecl *PDecl = nullptr; 12676 12677 switch (ConvTy) { 12678 case Compatible: 12679 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12680 return false; 12681 12682 case PointerToInt: 12683 DiagKind = diag::ext_typecheck_convert_pointer_int; 12684 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12685 MayHaveConvFixit = true; 12686 break; 12687 case IntToPointer: 12688 DiagKind = diag::ext_typecheck_convert_int_pointer; 12689 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12690 MayHaveConvFixit = true; 12691 break; 12692 case IncompatiblePointer: 12693 if (Action == AA_Passing_CFAudited) 12694 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 12695 else if (SrcType->isFunctionPointerType() && 12696 DstType->isFunctionPointerType()) 12697 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 12698 else 12699 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 12700 12701 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12702 SrcType->isObjCObjectPointerType(); 12703 if (Hint.isNull() && !CheckInferredResultType) { 12704 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12705 } 12706 else if (CheckInferredResultType) { 12707 SrcType = SrcType.getUnqualifiedType(); 12708 DstType = DstType.getUnqualifiedType(); 12709 } 12710 MayHaveConvFixit = true; 12711 break; 12712 case IncompatiblePointerSign: 12713 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12714 break; 12715 case FunctionVoidPointer: 12716 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12717 break; 12718 case IncompatiblePointerDiscardsQualifiers: { 12719 // Perform array-to-pointer decay if necessary. 12720 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12721 12722 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12723 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12724 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12725 DiagKind = diag::err_typecheck_incompatible_address_space; 12726 break; 12727 12728 12729 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12730 DiagKind = diag::err_typecheck_incompatible_ownership; 12731 break; 12732 } 12733 12734 llvm_unreachable("unknown error case for discarding qualifiers!"); 12735 // fallthrough 12736 } 12737 case CompatiblePointerDiscardsQualifiers: 12738 // If the qualifiers lost were because we were applying the 12739 // (deprecated) C++ conversion from a string literal to a char* 12740 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12741 // Ideally, this check would be performed in 12742 // checkPointerTypesForAssignment. However, that would require a 12743 // bit of refactoring (so that the second argument is an 12744 // expression, rather than a type), which should be done as part 12745 // of a larger effort to fix checkPointerTypesForAssignment for 12746 // C++ semantics. 12747 if (getLangOpts().CPlusPlus && 12748 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12749 return false; 12750 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12751 break; 12752 case IncompatibleNestedPointerQualifiers: 12753 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12754 break; 12755 case IntToBlockPointer: 12756 DiagKind = diag::err_int_to_block_pointer; 12757 break; 12758 case IncompatibleBlockPointer: 12759 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12760 break; 12761 case IncompatibleObjCQualifiedId: { 12762 if (SrcType->isObjCQualifiedIdType()) { 12763 const ObjCObjectPointerType *srcOPT = 12764 SrcType->getAs<ObjCObjectPointerType>(); 12765 for (auto *srcProto : srcOPT->quals()) { 12766 PDecl = srcProto; 12767 break; 12768 } 12769 if (const ObjCInterfaceType *IFaceT = 12770 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12771 IFace = IFaceT->getDecl(); 12772 } 12773 else if (DstType->isObjCQualifiedIdType()) { 12774 const ObjCObjectPointerType *dstOPT = 12775 DstType->getAs<ObjCObjectPointerType>(); 12776 for (auto *dstProto : dstOPT->quals()) { 12777 PDecl = dstProto; 12778 break; 12779 } 12780 if (const ObjCInterfaceType *IFaceT = 12781 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12782 IFace = IFaceT->getDecl(); 12783 } 12784 DiagKind = diag::warn_incompatible_qualified_id; 12785 break; 12786 } 12787 case IncompatibleVectors: 12788 DiagKind = diag::warn_incompatible_vectors; 12789 break; 12790 case IncompatibleObjCWeakRef: 12791 DiagKind = diag::err_arc_weak_unavailable_assign; 12792 break; 12793 case Incompatible: 12794 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12795 if (Complained) 12796 *Complained = true; 12797 return true; 12798 } 12799 12800 DiagKind = diag::err_typecheck_convert_incompatible; 12801 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12802 MayHaveConvFixit = true; 12803 isInvalid = true; 12804 MayHaveFunctionDiff = true; 12805 break; 12806 } 12807 12808 QualType FirstType, SecondType; 12809 switch (Action) { 12810 case AA_Assigning: 12811 case AA_Initializing: 12812 // The destination type comes first. 12813 FirstType = DstType; 12814 SecondType = SrcType; 12815 break; 12816 12817 case AA_Returning: 12818 case AA_Passing: 12819 case AA_Passing_CFAudited: 12820 case AA_Converting: 12821 case AA_Sending: 12822 case AA_Casting: 12823 // The source type comes first. 12824 FirstType = SrcType; 12825 SecondType = DstType; 12826 break; 12827 } 12828 12829 PartialDiagnostic FDiag = PDiag(DiagKind); 12830 if (Action == AA_Passing_CFAudited) 12831 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12832 else 12833 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12834 12835 // If we can fix the conversion, suggest the FixIts. 12836 assert(ConvHints.isNull() || Hint.isNull()); 12837 if (!ConvHints.isNull()) { 12838 for (FixItHint &H : ConvHints.Hints) 12839 FDiag << H; 12840 } else { 12841 FDiag << Hint; 12842 } 12843 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12844 12845 if (MayHaveFunctionDiff) 12846 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12847 12848 Diag(Loc, FDiag); 12849 if (DiagKind == diag::warn_incompatible_qualified_id && 12850 PDecl && IFace && !IFace->hasDefinition()) 12851 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 12852 << IFace->getName() << PDecl->getName(); 12853 12854 if (SecondType == Context.OverloadTy) 12855 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12856 FirstType, /*TakingAddress=*/true); 12857 12858 if (CheckInferredResultType) 12859 EmitRelatedResultTypeNote(SrcExpr); 12860 12861 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12862 EmitRelatedResultTypeNoteForReturn(DstType); 12863 12864 if (Complained) 12865 *Complained = true; 12866 return isInvalid; 12867 } 12868 12869 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12870 llvm::APSInt *Result) { 12871 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12872 public: 12873 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12874 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12875 } 12876 } Diagnoser; 12877 12878 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12879 } 12880 12881 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12882 llvm::APSInt *Result, 12883 unsigned DiagID, 12884 bool AllowFold) { 12885 class IDDiagnoser : public VerifyICEDiagnoser { 12886 unsigned DiagID; 12887 12888 public: 12889 IDDiagnoser(unsigned DiagID) 12890 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12891 12892 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12893 S.Diag(Loc, DiagID) << SR; 12894 } 12895 } Diagnoser(DiagID); 12896 12897 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12898 } 12899 12900 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12901 SourceRange SR) { 12902 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12903 } 12904 12905 ExprResult 12906 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12907 VerifyICEDiagnoser &Diagnoser, 12908 bool AllowFold) { 12909 SourceLocation DiagLoc = E->getLocStart(); 12910 12911 if (getLangOpts().CPlusPlus11) { 12912 // C++11 [expr.const]p5: 12913 // If an expression of literal class type is used in a context where an 12914 // integral constant expression is required, then that class type shall 12915 // have a single non-explicit conversion function to an integral or 12916 // unscoped enumeration type 12917 ExprResult Converted; 12918 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12919 public: 12920 CXX11ConvertDiagnoser(bool Silent) 12921 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12922 Silent, true) {} 12923 12924 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12925 QualType T) override { 12926 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12927 } 12928 12929 SemaDiagnosticBuilder diagnoseIncomplete( 12930 Sema &S, SourceLocation Loc, QualType T) override { 12931 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12932 } 12933 12934 SemaDiagnosticBuilder diagnoseExplicitConv( 12935 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12936 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12937 } 12938 12939 SemaDiagnosticBuilder noteExplicitConv( 12940 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12941 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12942 << ConvTy->isEnumeralType() << ConvTy; 12943 } 12944 12945 SemaDiagnosticBuilder diagnoseAmbiguous( 12946 Sema &S, SourceLocation Loc, QualType T) override { 12947 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12948 } 12949 12950 SemaDiagnosticBuilder noteAmbiguous( 12951 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12952 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12953 << ConvTy->isEnumeralType() << ConvTy; 12954 } 12955 12956 SemaDiagnosticBuilder diagnoseConversion( 12957 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12958 llvm_unreachable("conversion functions are permitted"); 12959 } 12960 } ConvertDiagnoser(Diagnoser.Suppress); 12961 12962 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12963 ConvertDiagnoser); 12964 if (Converted.isInvalid()) 12965 return Converted; 12966 E = Converted.get(); 12967 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12968 return ExprError(); 12969 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12970 // An ICE must be of integral or unscoped enumeration type. 12971 if (!Diagnoser.Suppress) 12972 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12973 return ExprError(); 12974 } 12975 12976 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12977 // in the non-ICE case. 12978 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12979 if (Result) 12980 *Result = E->EvaluateKnownConstInt(Context); 12981 return E; 12982 } 12983 12984 Expr::EvalResult EvalResult; 12985 SmallVector<PartialDiagnosticAt, 8> Notes; 12986 EvalResult.Diag = &Notes; 12987 12988 // Try to evaluate the expression, and produce diagnostics explaining why it's 12989 // not a constant expression as a side-effect. 12990 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12991 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12992 12993 // In C++11, we can rely on diagnostics being produced for any expression 12994 // which is not a constant expression. If no diagnostics were produced, then 12995 // this is a constant expression. 12996 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12997 if (Result) 12998 *Result = EvalResult.Val.getInt(); 12999 return E; 13000 } 13001 13002 // If our only note is the usual "invalid subexpression" note, just point 13003 // the caret at its location rather than producing an essentially 13004 // redundant note. 13005 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13006 diag::note_invalid_subexpr_in_const_expr) { 13007 DiagLoc = Notes[0].first; 13008 Notes.clear(); 13009 } 13010 13011 if (!Folded || !AllowFold) { 13012 if (!Diagnoser.Suppress) { 13013 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13014 for (const PartialDiagnosticAt &Note : Notes) 13015 Diag(Note.first, Note.second); 13016 } 13017 13018 return ExprError(); 13019 } 13020 13021 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13022 for (const PartialDiagnosticAt &Note : Notes) 13023 Diag(Note.first, Note.second); 13024 13025 if (Result) 13026 *Result = EvalResult.Val.getInt(); 13027 return E; 13028 } 13029 13030 namespace { 13031 // Handle the case where we conclude a expression which we speculatively 13032 // considered to be unevaluated is actually evaluated. 13033 class TransformToPE : public TreeTransform<TransformToPE> { 13034 typedef TreeTransform<TransformToPE> BaseTransform; 13035 13036 public: 13037 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13038 13039 // Make sure we redo semantic analysis 13040 bool AlwaysRebuild() { return true; } 13041 13042 // Make sure we handle LabelStmts correctly. 13043 // FIXME: This does the right thing, but maybe we need a more general 13044 // fix to TreeTransform? 13045 StmtResult TransformLabelStmt(LabelStmt *S) { 13046 S->getDecl()->setStmt(nullptr); 13047 return BaseTransform::TransformLabelStmt(S); 13048 } 13049 13050 // We need to special-case DeclRefExprs referring to FieldDecls which 13051 // are not part of a member pointer formation; normal TreeTransforming 13052 // doesn't catch this case because of the way we represent them in the AST. 13053 // FIXME: This is a bit ugly; is it really the best way to handle this 13054 // case? 13055 // 13056 // Error on DeclRefExprs referring to FieldDecls. 13057 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13058 if (isa<FieldDecl>(E->getDecl()) && 13059 !SemaRef.isUnevaluatedContext()) 13060 return SemaRef.Diag(E->getLocation(), 13061 diag::err_invalid_non_static_member_use) 13062 << E->getDecl() << E->getSourceRange(); 13063 13064 return BaseTransform::TransformDeclRefExpr(E); 13065 } 13066 13067 // Exception: filter out member pointer formation 13068 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13069 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13070 return E; 13071 13072 return BaseTransform::TransformUnaryOperator(E); 13073 } 13074 13075 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13076 // Lambdas never need to be transformed. 13077 return E; 13078 } 13079 }; 13080 } 13081 13082 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13083 assert(isUnevaluatedContext() && 13084 "Should only transform unevaluated expressions"); 13085 ExprEvalContexts.back().Context = 13086 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13087 if (isUnevaluatedContext()) 13088 return E; 13089 return TransformToPE(*this).TransformExpr(E); 13090 } 13091 13092 void 13093 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13094 Decl *LambdaContextDecl, 13095 bool IsDecltype) { 13096 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13097 LambdaContextDecl, IsDecltype); 13098 Cleanup.reset(); 13099 if (!MaybeODRUseExprs.empty()) 13100 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13101 } 13102 13103 void 13104 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13105 ReuseLambdaContextDecl_t, 13106 bool IsDecltype) { 13107 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13108 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13109 } 13110 13111 void Sema::PopExpressionEvaluationContext() { 13112 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13113 unsigned NumTypos = Rec.NumTypos; 13114 13115 if (!Rec.Lambdas.empty()) { 13116 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13117 unsigned D; 13118 if (Rec.isUnevaluated()) { 13119 // C++11 [expr.prim.lambda]p2: 13120 // A lambda-expression shall not appear in an unevaluated operand 13121 // (Clause 5). 13122 D = diag::err_lambda_unevaluated_operand; 13123 } else { 13124 // C++1y [expr.const]p2: 13125 // A conditional-expression e is a core constant expression unless the 13126 // evaluation of e, following the rules of the abstract machine, would 13127 // evaluate [...] a lambda-expression. 13128 D = diag::err_lambda_in_constant_expression; 13129 } 13130 13131 // C++1z allows lambda expressions as core constant expressions. 13132 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13133 // 1607) from appearing within template-arguments and array-bounds that 13134 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13135 // unevaluated contexts) might lift some of these restrictions in a 13136 // future version. 13137 if (Rec.Context != ConstantEvaluated || !getLangOpts().CPlusPlus1z) 13138 for (const auto *L : Rec.Lambdas) 13139 Diag(L->getLocStart(), D); 13140 } else { 13141 // Mark the capture expressions odr-used. This was deferred 13142 // during lambda expression creation. 13143 for (auto *Lambda : Rec.Lambdas) { 13144 for (auto *C : Lambda->capture_inits()) 13145 MarkDeclarationsReferencedInExpr(C); 13146 } 13147 } 13148 } 13149 13150 // When are coming out of an unevaluated context, clear out any 13151 // temporaries that we may have created as part of the evaluation of 13152 // the expression in that context: they aren't relevant because they 13153 // will never be constructed. 13154 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 13155 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13156 ExprCleanupObjects.end()); 13157 Cleanup = Rec.ParentCleanup; 13158 CleanupVarDeclMarking(); 13159 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13160 // Otherwise, merge the contexts together. 13161 } else { 13162 Cleanup.mergeFrom(Rec.ParentCleanup); 13163 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13164 Rec.SavedMaybeODRUseExprs.end()); 13165 } 13166 13167 // Pop the current expression evaluation context off the stack. 13168 ExprEvalContexts.pop_back(); 13169 13170 if (!ExprEvalContexts.empty()) 13171 ExprEvalContexts.back().NumTypos += NumTypos; 13172 else 13173 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13174 "last ExpressionEvaluationContextRecord"); 13175 } 13176 13177 void Sema::DiscardCleanupsInEvaluationContext() { 13178 ExprCleanupObjects.erase( 13179 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13180 ExprCleanupObjects.end()); 13181 Cleanup.reset(); 13182 MaybeODRUseExprs.clear(); 13183 } 13184 13185 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13186 if (!E->getType()->isVariablyModifiedType()) 13187 return E; 13188 return TransformToPotentiallyEvaluated(E); 13189 } 13190 13191 /// Are we within a context in which some evaluation could be performed (be it 13192 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13193 /// captured by C++'s idea of an "unevaluated context". 13194 static bool isEvaluatableContext(Sema &SemaRef) { 13195 switch (SemaRef.ExprEvalContexts.back().Context) { 13196 case Sema::Unevaluated: 13197 case Sema::UnevaluatedAbstract: 13198 case Sema::DiscardedStatement: 13199 // Expressions in this context are never evaluated. 13200 return false; 13201 13202 case Sema::UnevaluatedList: 13203 case Sema::ConstantEvaluated: 13204 case Sema::PotentiallyEvaluated: 13205 // Expressions in this context could be evaluated. 13206 return true; 13207 13208 case Sema::PotentiallyEvaluatedIfUsed: 13209 // Referenced declarations will only be used if the construct in the 13210 // containing expression is used, at which point we'll be given another 13211 // turn to mark them. 13212 return false; 13213 } 13214 llvm_unreachable("Invalid context"); 13215 } 13216 13217 /// Are we within a context in which references to resolved functions or to 13218 /// variables result in odr-use? 13219 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13220 // An expression in a template is not really an expression until it's been 13221 // instantiated, so it doesn't trigger odr-use. 13222 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13223 return false; 13224 13225 switch (SemaRef.ExprEvalContexts.back().Context) { 13226 case Sema::Unevaluated: 13227 case Sema::UnevaluatedList: 13228 case Sema::UnevaluatedAbstract: 13229 case Sema::DiscardedStatement: 13230 return false; 13231 13232 case Sema::ConstantEvaluated: 13233 case Sema::PotentiallyEvaluated: 13234 return true; 13235 13236 case Sema::PotentiallyEvaluatedIfUsed: 13237 return false; 13238 } 13239 llvm_unreachable("Invalid context"); 13240 } 13241 13242 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13243 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13244 return Func->isConstexpr() && 13245 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13246 } 13247 13248 /// \brief Mark a function referenced, and check whether it is odr-used 13249 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13250 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13251 bool MightBeOdrUse) { 13252 assert(Func && "No function?"); 13253 13254 Func->setReferenced(); 13255 13256 // C++11 [basic.def.odr]p3: 13257 // A function whose name appears as a potentially-evaluated expression is 13258 // odr-used if it is the unique lookup result or the selected member of a 13259 // set of overloaded functions [...]. 13260 // 13261 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13262 // can just check that here. 13263 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13264 13265 // Determine whether we require a function definition to exist, per 13266 // C++11 [temp.inst]p3: 13267 // Unless a function template specialization has been explicitly 13268 // instantiated or explicitly specialized, the function template 13269 // specialization is implicitly instantiated when the specialization is 13270 // referenced in a context that requires a function definition to exist. 13271 // 13272 // That is either when this is an odr-use, or when a usage of a constexpr 13273 // function occurs within an evaluatable context. 13274 bool NeedDefinition = 13275 OdrUse || (isEvaluatableContext(*this) && 13276 isImplicitlyDefinableConstexprFunction(Func)); 13277 13278 // C++14 [temp.expl.spec]p6: 13279 // If a template [...] is explicitly specialized then that specialization 13280 // shall be declared before the first use of that specialization that would 13281 // cause an implicit instantiation to take place, in every translation unit 13282 // in which such a use occurs 13283 if (NeedDefinition && 13284 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13285 Func->getMemberSpecializationInfo())) 13286 checkSpecializationVisibility(Loc, Func); 13287 13288 // C++14 [except.spec]p17: 13289 // An exception-specification is considered to be needed when: 13290 // - the function is odr-used or, if it appears in an unevaluated operand, 13291 // would be odr-used if the expression were potentially-evaluated; 13292 // 13293 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13294 // function is a pure virtual function we're calling, and in that case the 13295 // function was selected by overload resolution and we need to resolve its 13296 // exception specification for a different reason. 13297 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13298 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13299 ResolveExceptionSpec(Loc, FPT); 13300 13301 // If we don't need to mark the function as used, and we don't need to 13302 // try to provide a definition, there's nothing more to do. 13303 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13304 (!NeedDefinition || Func->getBody())) 13305 return; 13306 13307 // Note that this declaration has been used. 13308 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13309 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13310 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13311 if (Constructor->isDefaultConstructor()) { 13312 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13313 return; 13314 DefineImplicitDefaultConstructor(Loc, Constructor); 13315 } else if (Constructor->isCopyConstructor()) { 13316 DefineImplicitCopyConstructor(Loc, Constructor); 13317 } else if (Constructor->isMoveConstructor()) { 13318 DefineImplicitMoveConstructor(Loc, Constructor); 13319 } 13320 } else if (Constructor->getInheritedConstructor()) { 13321 DefineInheritingConstructor(Loc, Constructor); 13322 } 13323 } else if (CXXDestructorDecl *Destructor = 13324 dyn_cast<CXXDestructorDecl>(Func)) { 13325 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13326 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13327 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13328 return; 13329 DefineImplicitDestructor(Loc, Destructor); 13330 } 13331 if (Destructor->isVirtual() && getLangOpts().AppleKext) 13332 MarkVTableUsed(Loc, Destructor->getParent()); 13333 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 13334 if (MethodDecl->isOverloadedOperator() && 13335 MethodDecl->getOverloadedOperator() == OO_Equal) { 13336 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 13337 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 13338 if (MethodDecl->isCopyAssignmentOperator()) 13339 DefineImplicitCopyAssignment(Loc, MethodDecl); 13340 else if (MethodDecl->isMoveAssignmentOperator()) 13341 DefineImplicitMoveAssignment(Loc, MethodDecl); 13342 } 13343 } else if (isa<CXXConversionDecl>(MethodDecl) && 13344 MethodDecl->getParent()->isLambda()) { 13345 CXXConversionDecl *Conversion = 13346 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 13347 if (Conversion->isLambdaToBlockPointerConversion()) 13348 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 13349 else 13350 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 13351 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 13352 MarkVTableUsed(Loc, MethodDecl->getParent()); 13353 } 13354 13355 // Recursive functions should be marked when used from another function. 13356 // FIXME: Is this really right? 13357 if (CurContext == Func) return; 13358 13359 // Implicit instantiation of function templates and member functions of 13360 // class templates. 13361 if (Func->isImplicitlyInstantiable()) { 13362 bool AlreadyInstantiated = false; 13363 SourceLocation PointOfInstantiation = Loc; 13364 if (FunctionTemplateSpecializationInfo *SpecInfo 13365 = Func->getTemplateSpecializationInfo()) { 13366 if (SpecInfo->getPointOfInstantiation().isInvalid()) 13367 SpecInfo->setPointOfInstantiation(Loc); 13368 else if (SpecInfo->getTemplateSpecializationKind() 13369 == TSK_ImplicitInstantiation) { 13370 AlreadyInstantiated = true; 13371 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 13372 } 13373 } else if (MemberSpecializationInfo *MSInfo 13374 = Func->getMemberSpecializationInfo()) { 13375 if (MSInfo->getPointOfInstantiation().isInvalid()) 13376 MSInfo->setPointOfInstantiation(Loc); 13377 else if (MSInfo->getTemplateSpecializationKind() 13378 == TSK_ImplicitInstantiation) { 13379 AlreadyInstantiated = true; 13380 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 13381 } 13382 } 13383 13384 if (!AlreadyInstantiated || Func->isConstexpr()) { 13385 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 13386 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 13387 ActiveTemplateInstantiations.size()) 13388 PendingLocalImplicitInstantiations.push_back( 13389 std::make_pair(Func, PointOfInstantiation)); 13390 else if (Func->isConstexpr()) 13391 // Do not defer instantiations of constexpr functions, to avoid the 13392 // expression evaluator needing to call back into Sema if it sees a 13393 // call to such a function. 13394 InstantiateFunctionDefinition(PointOfInstantiation, Func); 13395 else { 13396 PendingInstantiations.push_back(std::make_pair(Func, 13397 PointOfInstantiation)); 13398 // Notify the consumer that a function was implicitly instantiated. 13399 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 13400 } 13401 } 13402 } else { 13403 // Walk redefinitions, as some of them may be instantiable. 13404 for (auto i : Func->redecls()) { 13405 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 13406 MarkFunctionReferenced(Loc, i, OdrUse); 13407 } 13408 } 13409 13410 if (!OdrUse) return; 13411 13412 // Keep track of used but undefined functions. 13413 if (!Func->isDefined()) { 13414 if (mightHaveNonExternalLinkage(Func)) 13415 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13416 else if (Func->getMostRecentDecl()->isInlined() && 13417 !LangOpts.GNUInline && 13418 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 13419 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 13420 } 13421 13422 Func->markUsed(Context); 13423 } 13424 13425 static void 13426 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 13427 ValueDecl *var, DeclContext *DC) { 13428 DeclContext *VarDC = var->getDeclContext(); 13429 13430 // If the parameter still belongs to the translation unit, then 13431 // we're actually just using one parameter in the declaration of 13432 // the next. 13433 if (isa<ParmVarDecl>(var) && 13434 isa<TranslationUnitDecl>(VarDC)) 13435 return; 13436 13437 // For C code, don't diagnose about capture if we're not actually in code 13438 // right now; it's impossible to write a non-constant expression outside of 13439 // function context, so we'll get other (more useful) diagnostics later. 13440 // 13441 // For C++, things get a bit more nasty... it would be nice to suppress this 13442 // diagnostic for certain cases like using a local variable in an array bound 13443 // for a member of a local class, but the correct predicate is not obvious. 13444 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 13445 return; 13446 13447 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 13448 unsigned ContextKind = 3; // unknown 13449 if (isa<CXXMethodDecl>(VarDC) && 13450 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 13451 ContextKind = 2; 13452 } else if (isa<FunctionDecl>(VarDC)) { 13453 ContextKind = 0; 13454 } else if (isa<BlockDecl>(VarDC)) { 13455 ContextKind = 1; 13456 } 13457 13458 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 13459 << var << ValueKind << ContextKind << VarDC; 13460 S.Diag(var->getLocation(), diag::note_entity_declared_at) 13461 << var; 13462 13463 // FIXME: Add additional diagnostic info about class etc. which prevents 13464 // capture. 13465 } 13466 13467 13468 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 13469 bool &SubCapturesAreNested, 13470 QualType &CaptureType, 13471 QualType &DeclRefType) { 13472 // Check whether we've already captured it. 13473 if (CSI->CaptureMap.count(Var)) { 13474 // If we found a capture, any subcaptures are nested. 13475 SubCapturesAreNested = true; 13476 13477 // Retrieve the capture type for this variable. 13478 CaptureType = CSI->getCapture(Var).getCaptureType(); 13479 13480 // Compute the type of an expression that refers to this variable. 13481 DeclRefType = CaptureType.getNonReferenceType(); 13482 13483 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 13484 // are mutable in the sense that user can change their value - they are 13485 // private instances of the captured declarations. 13486 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 13487 if (Cap.isCopyCapture() && 13488 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 13489 !(isa<CapturedRegionScopeInfo>(CSI) && 13490 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 13491 DeclRefType.addConst(); 13492 return true; 13493 } 13494 return false; 13495 } 13496 13497 // Only block literals, captured statements, and lambda expressions can 13498 // capture; other scopes don't work. 13499 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 13500 SourceLocation Loc, 13501 const bool Diagnose, Sema &S) { 13502 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 13503 return getLambdaAwareParentOfDeclContext(DC); 13504 else if (Var->hasLocalStorage()) { 13505 if (Diagnose) 13506 diagnoseUncapturableValueReference(S, Loc, Var, DC); 13507 } 13508 return nullptr; 13509 } 13510 13511 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13512 // certain types of variables (unnamed, variably modified types etc.) 13513 // so check for eligibility. 13514 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 13515 SourceLocation Loc, 13516 const bool Diagnose, Sema &S) { 13517 13518 bool IsBlock = isa<BlockScopeInfo>(CSI); 13519 bool IsLambda = isa<LambdaScopeInfo>(CSI); 13520 13521 // Lambdas are not allowed to capture unnamed variables 13522 // (e.g. anonymous unions). 13523 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 13524 // assuming that's the intent. 13525 if (IsLambda && !Var->getDeclName()) { 13526 if (Diagnose) { 13527 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 13528 S.Diag(Var->getLocation(), diag::note_declared_at); 13529 } 13530 return false; 13531 } 13532 13533 // Prohibit variably-modified types in blocks; they're difficult to deal with. 13534 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 13535 if (Diagnose) { 13536 S.Diag(Loc, diag::err_ref_vm_type); 13537 S.Diag(Var->getLocation(), diag::note_previous_decl) 13538 << Var->getDeclName(); 13539 } 13540 return false; 13541 } 13542 // Prohibit structs with flexible array members too. 13543 // We cannot capture what is in the tail end of the struct. 13544 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 13545 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 13546 if (Diagnose) { 13547 if (IsBlock) 13548 S.Diag(Loc, diag::err_ref_flexarray_type); 13549 else 13550 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 13551 << Var->getDeclName(); 13552 S.Diag(Var->getLocation(), diag::note_previous_decl) 13553 << Var->getDeclName(); 13554 } 13555 return false; 13556 } 13557 } 13558 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13559 // Lambdas and captured statements are not allowed to capture __block 13560 // variables; they don't support the expected semantics. 13561 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 13562 if (Diagnose) { 13563 S.Diag(Loc, diag::err_capture_block_variable) 13564 << Var->getDeclName() << !IsLambda; 13565 S.Diag(Var->getLocation(), diag::note_previous_decl) 13566 << Var->getDeclName(); 13567 } 13568 return false; 13569 } 13570 13571 return true; 13572 } 13573 13574 // Returns true if the capture by block was successful. 13575 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 13576 SourceLocation Loc, 13577 const bool BuildAndDiagnose, 13578 QualType &CaptureType, 13579 QualType &DeclRefType, 13580 const bool Nested, 13581 Sema &S) { 13582 Expr *CopyExpr = nullptr; 13583 bool ByRef = false; 13584 13585 // Blocks are not allowed to capture arrays. 13586 if (CaptureType->isArrayType()) { 13587 if (BuildAndDiagnose) { 13588 S.Diag(Loc, diag::err_ref_array_type); 13589 S.Diag(Var->getLocation(), diag::note_previous_decl) 13590 << Var->getDeclName(); 13591 } 13592 return false; 13593 } 13594 13595 // Forbid the block-capture of autoreleasing variables. 13596 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13597 if (BuildAndDiagnose) { 13598 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 13599 << /*block*/ 0; 13600 S.Diag(Var->getLocation(), diag::note_previous_decl) 13601 << Var->getDeclName(); 13602 } 13603 return false; 13604 } 13605 13606 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 13607 if (const auto *PT = CaptureType->getAs<PointerType>()) { 13608 // This function finds out whether there is an AttributedType of kind 13609 // attr_objc_ownership in Ty. The existence of AttributedType of kind 13610 // attr_objc_ownership implies __autoreleasing was explicitly specified 13611 // rather than being added implicitly by the compiler. 13612 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 13613 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 13614 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 13615 return true; 13616 13617 // Peel off AttributedTypes that are not of kind objc_ownership. 13618 Ty = AttrTy->getModifiedType(); 13619 } 13620 13621 return false; 13622 }; 13623 13624 QualType PointeeTy = PT->getPointeeType(); 13625 13626 if (PointeeTy->getAs<ObjCObjectPointerType>() && 13627 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 13628 !IsObjCOwnershipAttributedType(PointeeTy)) { 13629 if (BuildAndDiagnose) { 13630 SourceLocation VarLoc = Var->getLocation(); 13631 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 13632 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) << 13633 FixItHint::CreateInsertion(VarLoc, "__autoreleasing"); 13634 S.Diag(VarLoc, diag::note_declare_parameter_strong); 13635 } 13636 } 13637 } 13638 13639 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 13640 if (HasBlocksAttr || CaptureType->isReferenceType() || 13641 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 13642 // Block capture by reference does not change the capture or 13643 // declaration reference types. 13644 ByRef = true; 13645 } else { 13646 // Block capture by copy introduces 'const'. 13647 CaptureType = CaptureType.getNonReferenceType().withConst(); 13648 DeclRefType = CaptureType; 13649 13650 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 13651 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 13652 // The capture logic needs the destructor, so make sure we mark it. 13653 // Usually this is unnecessary because most local variables have 13654 // their destructors marked at declaration time, but parameters are 13655 // an exception because it's technically only the call site that 13656 // actually requires the destructor. 13657 if (isa<ParmVarDecl>(Var)) 13658 S.FinalizeVarWithDestructor(Var, Record); 13659 13660 // Enter a new evaluation context to insulate the copy 13661 // full-expression. 13662 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 13663 13664 // According to the blocks spec, the capture of a variable from 13665 // the stack requires a const copy constructor. This is not true 13666 // of the copy/move done to move a __block variable to the heap. 13667 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 13668 DeclRefType.withConst(), 13669 VK_LValue, Loc); 13670 13671 ExprResult Result 13672 = S.PerformCopyInitialization( 13673 InitializedEntity::InitializeBlock(Var->getLocation(), 13674 CaptureType, false), 13675 Loc, DeclRef); 13676 13677 // Build a full-expression copy expression if initialization 13678 // succeeded and used a non-trivial constructor. Recover from 13679 // errors by pretending that the copy isn't necessary. 13680 if (!Result.isInvalid() && 13681 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13682 ->isTrivial()) { 13683 Result = S.MaybeCreateExprWithCleanups(Result); 13684 CopyExpr = Result.get(); 13685 } 13686 } 13687 } 13688 } 13689 13690 // Actually capture the variable. 13691 if (BuildAndDiagnose) 13692 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13693 SourceLocation(), CaptureType, CopyExpr); 13694 13695 return true; 13696 13697 } 13698 13699 13700 /// \brief Capture the given variable in the captured region. 13701 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13702 VarDecl *Var, 13703 SourceLocation Loc, 13704 const bool BuildAndDiagnose, 13705 QualType &CaptureType, 13706 QualType &DeclRefType, 13707 const bool RefersToCapturedVariable, 13708 Sema &S) { 13709 // By default, capture variables by reference. 13710 bool ByRef = true; 13711 // Using an LValue reference type is consistent with Lambdas (see below). 13712 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 13713 if (S.IsOpenMPCapturedDecl(Var)) 13714 DeclRefType = DeclRefType.getUnqualifiedType(); 13715 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 13716 } 13717 13718 if (ByRef) 13719 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13720 else 13721 CaptureType = DeclRefType; 13722 13723 Expr *CopyExpr = nullptr; 13724 if (BuildAndDiagnose) { 13725 // The current implementation assumes that all variables are captured 13726 // by references. Since there is no capture by copy, no expression 13727 // evaluation will be needed. 13728 RecordDecl *RD = RSI->TheRecordDecl; 13729 13730 FieldDecl *Field 13731 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13732 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13733 nullptr, false, ICIS_NoInit); 13734 Field->setImplicit(true); 13735 Field->setAccess(AS_private); 13736 RD->addDecl(Field); 13737 13738 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13739 DeclRefType, VK_LValue, Loc); 13740 Var->setReferenced(true); 13741 Var->markUsed(S.Context); 13742 } 13743 13744 // Actually capture the variable. 13745 if (BuildAndDiagnose) 13746 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13747 SourceLocation(), CaptureType, CopyExpr); 13748 13749 13750 return true; 13751 } 13752 13753 /// \brief Create a field within the lambda class for the variable 13754 /// being captured. 13755 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 13756 QualType FieldType, QualType DeclRefType, 13757 SourceLocation Loc, 13758 bool RefersToCapturedVariable) { 13759 CXXRecordDecl *Lambda = LSI->Lambda; 13760 13761 // Build the non-static data member. 13762 FieldDecl *Field 13763 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13764 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13765 nullptr, false, ICIS_NoInit); 13766 Field->setImplicit(true); 13767 Field->setAccess(AS_private); 13768 Lambda->addDecl(Field); 13769 } 13770 13771 /// \brief Capture the given variable in the lambda. 13772 static bool captureInLambda(LambdaScopeInfo *LSI, 13773 VarDecl *Var, 13774 SourceLocation Loc, 13775 const bool BuildAndDiagnose, 13776 QualType &CaptureType, 13777 QualType &DeclRefType, 13778 const bool RefersToCapturedVariable, 13779 const Sema::TryCaptureKind Kind, 13780 SourceLocation EllipsisLoc, 13781 const bool IsTopScope, 13782 Sema &S) { 13783 13784 // Determine whether we are capturing by reference or by value. 13785 bool ByRef = false; 13786 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13787 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13788 } else { 13789 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13790 } 13791 13792 // Compute the type of the field that will capture this variable. 13793 if (ByRef) { 13794 // C++11 [expr.prim.lambda]p15: 13795 // An entity is captured by reference if it is implicitly or 13796 // explicitly captured but not captured by copy. It is 13797 // unspecified whether additional unnamed non-static data 13798 // members are declared in the closure type for entities 13799 // captured by reference. 13800 // 13801 // FIXME: It is not clear whether we want to build an lvalue reference 13802 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13803 // to do the former, while EDG does the latter. Core issue 1249 will 13804 // clarify, but for now we follow GCC because it's a more permissive and 13805 // easily defensible position. 13806 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13807 } else { 13808 // C++11 [expr.prim.lambda]p14: 13809 // For each entity captured by copy, an unnamed non-static 13810 // data member is declared in the closure type. The 13811 // declaration order of these members is unspecified. The type 13812 // of such a data member is the type of the corresponding 13813 // captured entity if the entity is not a reference to an 13814 // object, or the referenced type otherwise. [Note: If the 13815 // captured entity is a reference to a function, the 13816 // corresponding data member is also a reference to a 13817 // function. - end note ] 13818 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13819 if (!RefType->getPointeeType()->isFunctionType()) 13820 CaptureType = RefType->getPointeeType(); 13821 } 13822 13823 // Forbid the lambda copy-capture of autoreleasing variables. 13824 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13825 if (BuildAndDiagnose) { 13826 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13827 S.Diag(Var->getLocation(), diag::note_previous_decl) 13828 << Var->getDeclName(); 13829 } 13830 return false; 13831 } 13832 13833 // Make sure that by-copy captures are of a complete and non-abstract type. 13834 if (BuildAndDiagnose) { 13835 if (!CaptureType->isDependentType() && 13836 S.RequireCompleteType(Loc, CaptureType, 13837 diag::err_capture_of_incomplete_type, 13838 Var->getDeclName())) 13839 return false; 13840 13841 if (S.RequireNonAbstractType(Loc, CaptureType, 13842 diag::err_capture_of_abstract_type)) 13843 return false; 13844 } 13845 } 13846 13847 // Capture this variable in the lambda. 13848 if (BuildAndDiagnose) 13849 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 13850 RefersToCapturedVariable); 13851 13852 // Compute the type of a reference to this captured variable. 13853 if (ByRef) 13854 DeclRefType = CaptureType.getNonReferenceType(); 13855 else { 13856 // C++ [expr.prim.lambda]p5: 13857 // The closure type for a lambda-expression has a public inline 13858 // function call operator [...]. This function call operator is 13859 // declared const (9.3.1) if and only if the lambda-expression's 13860 // parameter-declaration-clause is not followed by mutable. 13861 DeclRefType = CaptureType.getNonReferenceType(); 13862 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13863 DeclRefType.addConst(); 13864 } 13865 13866 // Add the capture. 13867 if (BuildAndDiagnose) 13868 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13869 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13870 13871 return true; 13872 } 13873 13874 bool Sema::tryCaptureVariable( 13875 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13876 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13877 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13878 // An init-capture is notionally from the context surrounding its 13879 // declaration, but its parent DC is the lambda class. 13880 DeclContext *VarDC = Var->getDeclContext(); 13881 if (Var->isInitCapture()) 13882 VarDC = VarDC->getParent(); 13883 13884 DeclContext *DC = CurContext; 13885 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13886 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13887 // We need to sync up the Declaration Context with the 13888 // FunctionScopeIndexToStopAt 13889 if (FunctionScopeIndexToStopAt) { 13890 unsigned FSIndex = FunctionScopes.size() - 1; 13891 while (FSIndex != MaxFunctionScopesIndex) { 13892 DC = getLambdaAwareParentOfDeclContext(DC); 13893 --FSIndex; 13894 } 13895 } 13896 13897 13898 // If the variable is declared in the current context, there is no need to 13899 // capture it. 13900 if (VarDC == DC) return true; 13901 13902 // Capture global variables if it is required to use private copy of this 13903 // variable. 13904 bool IsGlobal = !Var->hasLocalStorage(); 13905 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13906 return true; 13907 13908 // Walk up the stack to determine whether we can capture the variable, 13909 // performing the "simple" checks that don't depend on type. We stop when 13910 // we've either hit the declared scope of the variable or find an existing 13911 // capture of that variable. We start from the innermost capturing-entity 13912 // (the DC) and ensure that all intervening capturing-entities 13913 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13914 // declcontext can either capture the variable or have already captured 13915 // the variable. 13916 CaptureType = Var->getType(); 13917 DeclRefType = CaptureType.getNonReferenceType(); 13918 bool Nested = false; 13919 bool Explicit = (Kind != TryCapture_Implicit); 13920 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13921 do { 13922 // Only block literals, captured statements, and lambda expressions can 13923 // capture; other scopes don't work. 13924 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13925 ExprLoc, 13926 BuildAndDiagnose, 13927 *this); 13928 // We need to check for the parent *first* because, if we *have* 13929 // private-captured a global variable, we need to recursively capture it in 13930 // intermediate blocks, lambdas, etc. 13931 if (!ParentDC) { 13932 if (IsGlobal) { 13933 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13934 break; 13935 } 13936 return true; 13937 } 13938 13939 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13940 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13941 13942 13943 // Check whether we've already captured it. 13944 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13945 DeclRefType)) { 13946 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 13947 break; 13948 } 13949 // If we are instantiating a generic lambda call operator body, 13950 // we do not want to capture new variables. What was captured 13951 // during either a lambdas transformation or initial parsing 13952 // should be used. 13953 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13954 if (BuildAndDiagnose) { 13955 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13956 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13957 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13958 Diag(Var->getLocation(), diag::note_previous_decl) 13959 << Var->getDeclName(); 13960 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13961 } else 13962 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13963 } 13964 return true; 13965 } 13966 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13967 // certain types of variables (unnamed, variably modified types etc.) 13968 // so check for eligibility. 13969 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13970 return true; 13971 13972 // Try to capture variable-length arrays types. 13973 if (Var->getType()->isVariablyModifiedType()) { 13974 // We're going to walk down into the type and look for VLA 13975 // expressions. 13976 QualType QTy = Var->getType(); 13977 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13978 QTy = PVD->getOriginalType(); 13979 captureVariablyModifiedType(Context, QTy, CSI); 13980 } 13981 13982 if (getLangOpts().OpenMP) { 13983 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13984 // OpenMP private variables should not be captured in outer scope, so 13985 // just break here. Similarly, global variables that are captured in a 13986 // target region should not be captured outside the scope of the region. 13987 if (RSI->CapRegionKind == CR_OpenMP) { 13988 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 13989 // When we detect target captures we are looking from inside the 13990 // target region, therefore we need to propagate the capture from the 13991 // enclosing region. Therefore, the capture is not initially nested. 13992 if (IsTargetCap) 13993 FunctionScopesIndex--; 13994 13995 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) { 13996 Nested = !IsTargetCap; 13997 DeclRefType = DeclRefType.getUnqualifiedType(); 13998 CaptureType = Context.getLValueReferenceType(DeclRefType); 13999 break; 14000 } 14001 } 14002 } 14003 } 14004 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14005 // No capture-default, and this is not an explicit capture 14006 // so cannot capture this variable. 14007 if (BuildAndDiagnose) { 14008 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14009 Diag(Var->getLocation(), diag::note_previous_decl) 14010 << Var->getDeclName(); 14011 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14012 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14013 diag::note_lambda_decl); 14014 // FIXME: If we error out because an outer lambda can not implicitly 14015 // capture a variable that an inner lambda explicitly captures, we 14016 // should have the inner lambda do the explicit capture - because 14017 // it makes for cleaner diagnostics later. This would purely be done 14018 // so that the diagnostic does not misleadingly claim that a variable 14019 // can not be captured by a lambda implicitly even though it is captured 14020 // explicitly. Suggestion: 14021 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14022 // at the function head 14023 // - cache the StartingDeclContext - this must be a lambda 14024 // - captureInLambda in the innermost lambda the variable. 14025 } 14026 return true; 14027 } 14028 14029 FunctionScopesIndex--; 14030 DC = ParentDC; 14031 Explicit = false; 14032 } while (!VarDC->Equals(DC)); 14033 14034 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14035 // computing the type of the capture at each step, checking type-specific 14036 // requirements, and adding captures if requested. 14037 // If the variable had already been captured previously, we start capturing 14038 // at the lambda nested within that one. 14039 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14040 ++I) { 14041 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14042 14043 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14044 if (!captureInBlock(BSI, Var, ExprLoc, 14045 BuildAndDiagnose, CaptureType, 14046 DeclRefType, Nested, *this)) 14047 return true; 14048 Nested = true; 14049 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14050 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14051 BuildAndDiagnose, CaptureType, 14052 DeclRefType, Nested, *this)) 14053 return true; 14054 Nested = true; 14055 } else { 14056 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14057 if (!captureInLambda(LSI, Var, ExprLoc, 14058 BuildAndDiagnose, CaptureType, 14059 DeclRefType, Nested, Kind, EllipsisLoc, 14060 /*IsTopScope*/I == N - 1, *this)) 14061 return true; 14062 Nested = true; 14063 } 14064 } 14065 return false; 14066 } 14067 14068 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14069 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14070 QualType CaptureType; 14071 QualType DeclRefType; 14072 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14073 /*BuildAndDiagnose=*/true, CaptureType, 14074 DeclRefType, nullptr); 14075 } 14076 14077 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14078 QualType CaptureType; 14079 QualType DeclRefType; 14080 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14081 /*BuildAndDiagnose=*/false, CaptureType, 14082 DeclRefType, nullptr); 14083 } 14084 14085 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14086 QualType CaptureType; 14087 QualType DeclRefType; 14088 14089 // Determine whether we can capture this variable. 14090 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14091 /*BuildAndDiagnose=*/false, CaptureType, 14092 DeclRefType, nullptr)) 14093 return QualType(); 14094 14095 return DeclRefType; 14096 } 14097 14098 14099 14100 // If either the type of the variable or the initializer is dependent, 14101 // return false. Otherwise, determine whether the variable is a constant 14102 // expression. Use this if you need to know if a variable that might or 14103 // might not be dependent is truly a constant expression. 14104 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14105 ASTContext &Context) { 14106 14107 if (Var->getType()->isDependentType()) 14108 return false; 14109 const VarDecl *DefVD = nullptr; 14110 Var->getAnyInitializer(DefVD); 14111 if (!DefVD) 14112 return false; 14113 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14114 Expr *Init = cast<Expr>(Eval->Value); 14115 if (Init->isValueDependent()) 14116 return false; 14117 return IsVariableAConstantExpression(Var, Context); 14118 } 14119 14120 14121 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14122 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14123 // an object that satisfies the requirements for appearing in a 14124 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14125 // is immediately applied." This function handles the lvalue-to-rvalue 14126 // conversion part. 14127 MaybeODRUseExprs.erase(E->IgnoreParens()); 14128 14129 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14130 // to a variable that is a constant expression, and if so, identify it as 14131 // a reference to a variable that does not involve an odr-use of that 14132 // variable. 14133 if (LambdaScopeInfo *LSI = getCurLambda()) { 14134 Expr *SansParensExpr = E->IgnoreParens(); 14135 VarDecl *Var = nullptr; 14136 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14137 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14138 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14139 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14140 14141 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14142 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14143 } 14144 } 14145 14146 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14147 Res = CorrectDelayedTyposInExpr(Res); 14148 14149 if (!Res.isUsable()) 14150 return Res; 14151 14152 // If a constant-expression is a reference to a variable where we delay 14153 // deciding whether it is an odr-use, just assume we will apply the 14154 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14155 // (a non-type template argument), we have special handling anyway. 14156 UpdateMarkingForLValueToRValue(Res.get()); 14157 return Res; 14158 } 14159 14160 void Sema::CleanupVarDeclMarking() { 14161 for (Expr *E : MaybeODRUseExprs) { 14162 VarDecl *Var; 14163 SourceLocation Loc; 14164 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14165 Var = cast<VarDecl>(DRE->getDecl()); 14166 Loc = DRE->getLocation(); 14167 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14168 Var = cast<VarDecl>(ME->getMemberDecl()); 14169 Loc = ME->getMemberLoc(); 14170 } else { 14171 llvm_unreachable("Unexpected expression"); 14172 } 14173 14174 MarkVarDeclODRUsed(Var, Loc, *this, 14175 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14176 } 14177 14178 MaybeODRUseExprs.clear(); 14179 } 14180 14181 14182 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14183 VarDecl *Var, Expr *E) { 14184 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14185 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14186 Var->setReferenced(); 14187 14188 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14189 14190 bool OdrUseContext = isOdrUseContext(SemaRef); 14191 bool NeedDefinition = 14192 OdrUseContext || (isEvaluatableContext(SemaRef) && 14193 Var->isUsableInConstantExpressions(SemaRef.Context)); 14194 14195 VarTemplateSpecializationDecl *VarSpec = 14196 dyn_cast<VarTemplateSpecializationDecl>(Var); 14197 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14198 "Can't instantiate a partial template specialization."); 14199 14200 // If this might be a member specialization of a static data member, check 14201 // the specialization is visible. We already did the checks for variable 14202 // template specializations when we created them. 14203 if (NeedDefinition && TSK != TSK_Undeclared && 14204 !isa<VarTemplateSpecializationDecl>(Var)) 14205 SemaRef.checkSpecializationVisibility(Loc, Var); 14206 14207 // Perform implicit instantiation of static data members, static data member 14208 // templates of class templates, and variable template specializations. Delay 14209 // instantiations of variable templates, except for those that could be used 14210 // in a constant expression. 14211 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14212 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 14213 14214 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 14215 if (Var->getPointOfInstantiation().isInvalid()) { 14216 // This is a modification of an existing AST node. Notify listeners. 14217 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 14218 L->StaticDataMemberInstantiated(Var); 14219 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 14220 // Don't bother trying to instantiate it again, unless we might need 14221 // its initializer before we get to the end of the TU. 14222 TryInstantiating = false; 14223 } 14224 14225 if (Var->getPointOfInstantiation().isInvalid()) 14226 Var->setTemplateSpecializationKind(TSK, Loc); 14227 14228 if (TryInstantiating) { 14229 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14230 bool InstantiationDependent = false; 14231 bool IsNonDependent = 14232 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14233 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14234 : true; 14235 14236 // Do not instantiate specializations that are still type-dependent. 14237 if (IsNonDependent) { 14238 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 14239 // Do not defer instantiations of variables which could be used in a 14240 // constant expression. 14241 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14242 } else { 14243 SemaRef.PendingInstantiations 14244 .push_back(std::make_pair(Var, PointOfInstantiation)); 14245 } 14246 } 14247 } 14248 } 14249 14250 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14251 // the requirements for appearing in a constant expression (5.19) and, if 14252 // it is an object, the lvalue-to-rvalue conversion (4.1) 14253 // is immediately applied." We check the first part here, and 14254 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14255 // Note that we use the C++11 definition everywhere because nothing in 14256 // C++03 depends on whether we get the C++03 version correct. The second 14257 // part does not apply to references, since they are not objects. 14258 if (OdrUseContext && E && 14259 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14260 // A reference initialized by a constant expression can never be 14261 // odr-used, so simply ignore it. 14262 if (!Var->getType()->isReferenceType()) 14263 SemaRef.MaybeODRUseExprs.insert(E); 14264 } else if (OdrUseContext) { 14265 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14266 /*MaxFunctionScopeIndex ptr*/ nullptr); 14267 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14268 // If this is a dependent context, we don't need to mark variables as 14269 // odr-used, but we may still need to track them for lambda capture. 14270 // FIXME: Do we also need to do this inside dependent typeid expressions 14271 // (which are modeled as unevaluated at this point)? 14272 const bool RefersToEnclosingScope = 14273 (SemaRef.CurContext != Var->getDeclContext() && 14274 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14275 if (RefersToEnclosingScope) { 14276 if (LambdaScopeInfo *const LSI = 14277 SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) { 14278 // If a variable could potentially be odr-used, defer marking it so 14279 // until we finish analyzing the full expression for any 14280 // lvalue-to-rvalue 14281 // or discarded value conversions that would obviate odr-use. 14282 // Add it to the list of potential captures that will be analyzed 14283 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14284 // unless the variable is a reference that was initialized by a constant 14285 // expression (this will never need to be captured or odr-used). 14286 assert(E && "Capture variable should be used in an expression."); 14287 if (!Var->getType()->isReferenceType() || 14288 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14289 LSI->addPotentialCapture(E->IgnoreParens()); 14290 } 14291 } 14292 } 14293 } 14294 14295 /// \brief Mark a variable referenced, and check whether it is odr-used 14296 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 14297 /// used directly for normal expressions referring to VarDecl. 14298 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 14299 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 14300 } 14301 14302 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 14303 Decl *D, Expr *E, bool MightBeOdrUse) { 14304 if (SemaRef.isInOpenMPDeclareTargetContext()) 14305 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 14306 14307 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 14308 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 14309 return; 14310 } 14311 14312 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 14313 14314 // If this is a call to a method via a cast, also mark the method in the 14315 // derived class used in case codegen can devirtualize the call. 14316 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 14317 if (!ME) 14318 return; 14319 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 14320 if (!MD) 14321 return; 14322 // Only attempt to devirtualize if this is truly a virtual call. 14323 bool IsVirtualCall = MD->isVirtual() && 14324 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 14325 if (!IsVirtualCall) 14326 return; 14327 const Expr *Base = ME->getBase(); 14328 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 14329 if (!MostDerivedClassDecl) 14330 return; 14331 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 14332 if (!DM || DM->isPure()) 14333 return; 14334 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 14335 } 14336 14337 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 14338 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 14339 // TODO: update this with DR# once a defect report is filed. 14340 // C++11 defect. The address of a pure member should not be an ODR use, even 14341 // if it's a qualified reference. 14342 bool OdrUse = true; 14343 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 14344 if (Method->isVirtual()) 14345 OdrUse = false; 14346 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 14347 } 14348 14349 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 14350 void Sema::MarkMemberReferenced(MemberExpr *E) { 14351 // C++11 [basic.def.odr]p2: 14352 // A non-overloaded function whose name appears as a potentially-evaluated 14353 // expression or a member of a set of candidate functions, if selected by 14354 // overload resolution when referred to from a potentially-evaluated 14355 // expression, is odr-used, unless it is a pure virtual function and its 14356 // name is not explicitly qualified. 14357 bool MightBeOdrUse = true; 14358 if (E->performsVirtualDispatch(getLangOpts())) { 14359 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 14360 if (Method->isPure()) 14361 MightBeOdrUse = false; 14362 } 14363 SourceLocation Loc = E->getMemberLoc().isValid() ? 14364 E->getMemberLoc() : E->getLocStart(); 14365 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 14366 } 14367 14368 /// \brief Perform marking for a reference to an arbitrary declaration. It 14369 /// marks the declaration referenced, and performs odr-use checking for 14370 /// functions and variables. This method should not be used when building a 14371 /// normal expression which refers to a variable. 14372 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 14373 bool MightBeOdrUse) { 14374 if (MightBeOdrUse) { 14375 if (auto *VD = dyn_cast<VarDecl>(D)) { 14376 MarkVariableReferenced(Loc, VD); 14377 return; 14378 } 14379 } 14380 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 14381 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 14382 return; 14383 } 14384 D->setReferenced(); 14385 } 14386 14387 namespace { 14388 // Mark all of the declarations used by a type as referenced. 14389 // FIXME: Not fully implemented yet! We need to have a better understanding 14390 // of when we're entering a context we should not recurse into. 14391 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 14392 // TreeTransforms rebuilding the type in a new context. Rather than 14393 // duplicating the TreeTransform logic, we should consider reusing it here. 14394 // Currently that causes problems when rebuilding LambdaExprs. 14395 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 14396 Sema &S; 14397 SourceLocation Loc; 14398 14399 public: 14400 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 14401 14402 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 14403 14404 bool TraverseTemplateArgument(const TemplateArgument &Arg); 14405 }; 14406 } 14407 14408 bool MarkReferencedDecls::TraverseTemplateArgument( 14409 const TemplateArgument &Arg) { 14410 { 14411 // A non-type template argument is a constant-evaluated context. 14412 EnterExpressionEvaluationContext Evaluated(S, Sema::ConstantEvaluated); 14413 if (Arg.getKind() == TemplateArgument::Declaration) { 14414 if (Decl *D = Arg.getAsDecl()) 14415 S.MarkAnyDeclReferenced(Loc, D, true); 14416 } else if (Arg.getKind() == TemplateArgument::Expression) { 14417 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 14418 } 14419 } 14420 14421 return Inherited::TraverseTemplateArgument(Arg); 14422 } 14423 14424 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 14425 MarkReferencedDecls Marker(*this, Loc); 14426 Marker.TraverseType(T); 14427 } 14428 14429 namespace { 14430 /// \brief Helper class that marks all of the declarations referenced by 14431 /// potentially-evaluated subexpressions as "referenced". 14432 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 14433 Sema &S; 14434 bool SkipLocalVariables; 14435 14436 public: 14437 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 14438 14439 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 14440 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 14441 14442 void VisitDeclRefExpr(DeclRefExpr *E) { 14443 // If we were asked not to visit local variables, don't. 14444 if (SkipLocalVariables) { 14445 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 14446 if (VD->hasLocalStorage()) 14447 return; 14448 } 14449 14450 S.MarkDeclRefReferenced(E); 14451 } 14452 14453 void VisitMemberExpr(MemberExpr *E) { 14454 S.MarkMemberReferenced(E); 14455 Inherited::VisitMemberExpr(E); 14456 } 14457 14458 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 14459 S.MarkFunctionReferenced(E->getLocStart(), 14460 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 14461 Visit(E->getSubExpr()); 14462 } 14463 14464 void VisitCXXNewExpr(CXXNewExpr *E) { 14465 if (E->getOperatorNew()) 14466 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 14467 if (E->getOperatorDelete()) 14468 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14469 Inherited::VisitCXXNewExpr(E); 14470 } 14471 14472 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 14473 if (E->getOperatorDelete()) 14474 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 14475 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 14476 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 14477 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 14478 S.MarkFunctionReferenced(E->getLocStart(), 14479 S.LookupDestructor(Record)); 14480 } 14481 14482 Inherited::VisitCXXDeleteExpr(E); 14483 } 14484 14485 void VisitCXXConstructExpr(CXXConstructExpr *E) { 14486 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 14487 Inherited::VisitCXXConstructExpr(E); 14488 } 14489 14490 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 14491 Visit(E->getExpr()); 14492 } 14493 14494 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 14495 Inherited::VisitImplicitCastExpr(E); 14496 14497 if (E->getCastKind() == CK_LValueToRValue) 14498 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 14499 } 14500 }; 14501 } 14502 14503 /// \brief Mark any declarations that appear within this expression or any 14504 /// potentially-evaluated subexpressions as "referenced". 14505 /// 14506 /// \param SkipLocalVariables If true, don't mark local variables as 14507 /// 'referenced'. 14508 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 14509 bool SkipLocalVariables) { 14510 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 14511 } 14512 14513 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 14514 /// of the program being compiled. 14515 /// 14516 /// This routine emits the given diagnostic when the code currently being 14517 /// type-checked is "potentially evaluated", meaning that there is a 14518 /// possibility that the code will actually be executable. Code in sizeof() 14519 /// expressions, code used only during overload resolution, etc., are not 14520 /// potentially evaluated. This routine will suppress such diagnostics or, 14521 /// in the absolutely nutty case of potentially potentially evaluated 14522 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 14523 /// later. 14524 /// 14525 /// This routine should be used for all diagnostics that describe the run-time 14526 /// behavior of a program, such as passing a non-POD value through an ellipsis. 14527 /// Failure to do so will likely result in spurious diagnostics or failures 14528 /// during overload resolution or within sizeof/alignof/typeof/typeid. 14529 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 14530 const PartialDiagnostic &PD) { 14531 switch (ExprEvalContexts.back().Context) { 14532 case Unevaluated: 14533 case UnevaluatedList: 14534 case UnevaluatedAbstract: 14535 case DiscardedStatement: 14536 // The argument will never be evaluated, so don't complain. 14537 break; 14538 14539 case ConstantEvaluated: 14540 // Relevant diagnostics should be produced by constant evaluation. 14541 break; 14542 14543 case PotentiallyEvaluated: 14544 case PotentiallyEvaluatedIfUsed: 14545 if (Statement && getCurFunctionOrMethodDecl()) { 14546 FunctionScopes.back()->PossiblyUnreachableDiags. 14547 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 14548 } 14549 else 14550 Diag(Loc, PD); 14551 14552 return true; 14553 } 14554 14555 return false; 14556 } 14557 14558 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 14559 CallExpr *CE, FunctionDecl *FD) { 14560 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 14561 return false; 14562 14563 // If we're inside a decltype's expression, don't check for a valid return 14564 // type or construct temporaries until we know whether this is the last call. 14565 if (ExprEvalContexts.back().IsDecltype) { 14566 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 14567 return false; 14568 } 14569 14570 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 14571 FunctionDecl *FD; 14572 CallExpr *CE; 14573 14574 public: 14575 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 14576 : FD(FD), CE(CE) { } 14577 14578 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 14579 if (!FD) { 14580 S.Diag(Loc, diag::err_call_incomplete_return) 14581 << T << CE->getSourceRange(); 14582 return; 14583 } 14584 14585 S.Diag(Loc, diag::err_call_function_incomplete_return) 14586 << CE->getSourceRange() << FD->getDeclName() << T; 14587 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 14588 << FD->getDeclName(); 14589 } 14590 } Diagnoser(FD, CE); 14591 14592 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 14593 return true; 14594 14595 return false; 14596 } 14597 14598 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 14599 // will prevent this condition from triggering, which is what we want. 14600 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 14601 SourceLocation Loc; 14602 14603 unsigned diagnostic = diag::warn_condition_is_assignment; 14604 bool IsOrAssign = false; 14605 14606 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 14607 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 14608 return; 14609 14610 IsOrAssign = Op->getOpcode() == BO_OrAssign; 14611 14612 // Greylist some idioms by putting them into a warning subcategory. 14613 if (ObjCMessageExpr *ME 14614 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 14615 Selector Sel = ME->getSelector(); 14616 14617 // self = [<foo> init...] 14618 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 14619 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14620 14621 // <foo> = [<bar> nextObject] 14622 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 14623 diagnostic = diag::warn_condition_is_idiomatic_assignment; 14624 } 14625 14626 Loc = Op->getOperatorLoc(); 14627 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 14628 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 14629 return; 14630 14631 IsOrAssign = Op->getOperator() == OO_PipeEqual; 14632 Loc = Op->getOperatorLoc(); 14633 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 14634 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 14635 else { 14636 // Not an assignment. 14637 return; 14638 } 14639 14640 Diag(Loc, diagnostic) << E->getSourceRange(); 14641 14642 SourceLocation Open = E->getLocStart(); 14643 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 14644 Diag(Loc, diag::note_condition_assign_silence) 14645 << FixItHint::CreateInsertion(Open, "(") 14646 << FixItHint::CreateInsertion(Close, ")"); 14647 14648 if (IsOrAssign) 14649 Diag(Loc, diag::note_condition_or_assign_to_comparison) 14650 << FixItHint::CreateReplacement(Loc, "!="); 14651 else 14652 Diag(Loc, diag::note_condition_assign_to_comparison) 14653 << FixItHint::CreateReplacement(Loc, "=="); 14654 } 14655 14656 /// \brief Redundant parentheses over an equality comparison can indicate 14657 /// that the user intended an assignment used as condition. 14658 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 14659 // Don't warn if the parens came from a macro. 14660 SourceLocation parenLoc = ParenE->getLocStart(); 14661 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 14662 return; 14663 // Don't warn for dependent expressions. 14664 if (ParenE->isTypeDependent()) 14665 return; 14666 14667 Expr *E = ParenE->IgnoreParens(); 14668 14669 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 14670 if (opE->getOpcode() == BO_EQ && 14671 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 14672 == Expr::MLV_Valid) { 14673 SourceLocation Loc = opE->getOperatorLoc(); 14674 14675 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14676 SourceRange ParenERange = ParenE->getSourceRange(); 14677 Diag(Loc, diag::note_equality_comparison_silence) 14678 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14679 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14680 Diag(Loc, diag::note_equality_comparison_to_assign) 14681 << FixItHint::CreateReplacement(Loc, "="); 14682 } 14683 } 14684 14685 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 14686 bool IsConstexpr) { 14687 DiagnoseAssignmentAsCondition(E); 14688 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14689 DiagnoseEqualityWithExtraParens(parenE); 14690 14691 ExprResult result = CheckPlaceholderExpr(E); 14692 if (result.isInvalid()) return ExprError(); 14693 E = result.get(); 14694 14695 if (!E->isTypeDependent()) { 14696 if (getLangOpts().CPlusPlus) 14697 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 14698 14699 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14700 if (ERes.isInvalid()) 14701 return ExprError(); 14702 E = ERes.get(); 14703 14704 QualType T = E->getType(); 14705 if (!T->isScalarType()) { // C99 6.8.4.1p1 14706 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14707 << T << E->getSourceRange(); 14708 return ExprError(); 14709 } 14710 CheckBoolLikeConversion(E, Loc); 14711 } 14712 14713 return E; 14714 } 14715 14716 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 14717 Expr *SubExpr, ConditionKind CK) { 14718 // Empty conditions are valid in for-statements. 14719 if (!SubExpr) 14720 return ConditionResult(); 14721 14722 ExprResult Cond; 14723 switch (CK) { 14724 case ConditionKind::Boolean: 14725 Cond = CheckBooleanCondition(Loc, SubExpr); 14726 break; 14727 14728 case ConditionKind::ConstexprIf: 14729 Cond = CheckBooleanCondition(Loc, SubExpr, true); 14730 break; 14731 14732 case ConditionKind::Switch: 14733 Cond = CheckSwitchCondition(Loc, SubExpr); 14734 break; 14735 } 14736 if (Cond.isInvalid()) 14737 return ConditionError(); 14738 14739 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 14740 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 14741 if (!FullExpr.get()) 14742 return ConditionError(); 14743 14744 return ConditionResult(*this, nullptr, FullExpr, 14745 CK == ConditionKind::ConstexprIf); 14746 } 14747 14748 namespace { 14749 /// A visitor for rebuilding a call to an __unknown_any expression 14750 /// to have an appropriate type. 14751 struct RebuildUnknownAnyFunction 14752 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14753 14754 Sema &S; 14755 14756 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14757 14758 ExprResult VisitStmt(Stmt *S) { 14759 llvm_unreachable("unexpected statement!"); 14760 } 14761 14762 ExprResult VisitExpr(Expr *E) { 14763 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14764 << E->getSourceRange(); 14765 return ExprError(); 14766 } 14767 14768 /// Rebuild an expression which simply semantically wraps another 14769 /// expression which it shares the type and value kind of. 14770 template <class T> ExprResult rebuildSugarExpr(T *E) { 14771 ExprResult SubResult = Visit(E->getSubExpr()); 14772 if (SubResult.isInvalid()) return ExprError(); 14773 14774 Expr *SubExpr = SubResult.get(); 14775 E->setSubExpr(SubExpr); 14776 E->setType(SubExpr->getType()); 14777 E->setValueKind(SubExpr->getValueKind()); 14778 assert(E->getObjectKind() == OK_Ordinary); 14779 return E; 14780 } 14781 14782 ExprResult VisitParenExpr(ParenExpr *E) { 14783 return rebuildSugarExpr(E); 14784 } 14785 14786 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14787 return rebuildSugarExpr(E); 14788 } 14789 14790 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14791 ExprResult SubResult = Visit(E->getSubExpr()); 14792 if (SubResult.isInvalid()) return ExprError(); 14793 14794 Expr *SubExpr = SubResult.get(); 14795 E->setSubExpr(SubExpr); 14796 E->setType(S.Context.getPointerType(SubExpr->getType())); 14797 assert(E->getValueKind() == VK_RValue); 14798 assert(E->getObjectKind() == OK_Ordinary); 14799 return E; 14800 } 14801 14802 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14803 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14804 14805 E->setType(VD->getType()); 14806 14807 assert(E->getValueKind() == VK_RValue); 14808 if (S.getLangOpts().CPlusPlus && 14809 !(isa<CXXMethodDecl>(VD) && 14810 cast<CXXMethodDecl>(VD)->isInstance())) 14811 E->setValueKind(VK_LValue); 14812 14813 return E; 14814 } 14815 14816 ExprResult VisitMemberExpr(MemberExpr *E) { 14817 return resolveDecl(E, E->getMemberDecl()); 14818 } 14819 14820 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14821 return resolveDecl(E, E->getDecl()); 14822 } 14823 }; 14824 } 14825 14826 /// Given a function expression of unknown-any type, try to rebuild it 14827 /// to have a function type. 14828 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14829 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14830 if (Result.isInvalid()) return ExprError(); 14831 return S.DefaultFunctionArrayConversion(Result.get()); 14832 } 14833 14834 namespace { 14835 /// A visitor for rebuilding an expression of type __unknown_anytype 14836 /// into one which resolves the type directly on the referring 14837 /// expression. Strict preservation of the original source 14838 /// structure is not a goal. 14839 struct RebuildUnknownAnyExpr 14840 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14841 14842 Sema &S; 14843 14844 /// The current destination type. 14845 QualType DestType; 14846 14847 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14848 : S(S), DestType(CastType) {} 14849 14850 ExprResult VisitStmt(Stmt *S) { 14851 llvm_unreachable("unexpected statement!"); 14852 } 14853 14854 ExprResult VisitExpr(Expr *E) { 14855 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14856 << E->getSourceRange(); 14857 return ExprError(); 14858 } 14859 14860 ExprResult VisitCallExpr(CallExpr *E); 14861 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14862 14863 /// Rebuild an expression which simply semantically wraps another 14864 /// expression which it shares the type and value kind of. 14865 template <class T> ExprResult rebuildSugarExpr(T *E) { 14866 ExprResult SubResult = Visit(E->getSubExpr()); 14867 if (SubResult.isInvalid()) return ExprError(); 14868 Expr *SubExpr = SubResult.get(); 14869 E->setSubExpr(SubExpr); 14870 E->setType(SubExpr->getType()); 14871 E->setValueKind(SubExpr->getValueKind()); 14872 assert(E->getObjectKind() == OK_Ordinary); 14873 return E; 14874 } 14875 14876 ExprResult VisitParenExpr(ParenExpr *E) { 14877 return rebuildSugarExpr(E); 14878 } 14879 14880 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14881 return rebuildSugarExpr(E); 14882 } 14883 14884 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14885 const PointerType *Ptr = DestType->getAs<PointerType>(); 14886 if (!Ptr) { 14887 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14888 << E->getSourceRange(); 14889 return ExprError(); 14890 } 14891 14892 if (isa<CallExpr>(E->getSubExpr())) { 14893 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 14894 << E->getSourceRange(); 14895 return ExprError(); 14896 } 14897 14898 assert(E->getValueKind() == VK_RValue); 14899 assert(E->getObjectKind() == OK_Ordinary); 14900 E->setType(DestType); 14901 14902 // Build the sub-expression as if it were an object of the pointee type. 14903 DestType = Ptr->getPointeeType(); 14904 ExprResult SubResult = Visit(E->getSubExpr()); 14905 if (SubResult.isInvalid()) return ExprError(); 14906 E->setSubExpr(SubResult.get()); 14907 return E; 14908 } 14909 14910 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14911 14912 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14913 14914 ExprResult VisitMemberExpr(MemberExpr *E) { 14915 return resolveDecl(E, E->getMemberDecl()); 14916 } 14917 14918 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14919 return resolveDecl(E, E->getDecl()); 14920 } 14921 }; 14922 } 14923 14924 /// Rebuilds a call expression which yielded __unknown_anytype. 14925 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14926 Expr *CalleeExpr = E->getCallee(); 14927 14928 enum FnKind { 14929 FK_MemberFunction, 14930 FK_FunctionPointer, 14931 FK_BlockPointer 14932 }; 14933 14934 FnKind Kind; 14935 QualType CalleeType = CalleeExpr->getType(); 14936 if (CalleeType == S.Context.BoundMemberTy) { 14937 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14938 Kind = FK_MemberFunction; 14939 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14940 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14941 CalleeType = Ptr->getPointeeType(); 14942 Kind = FK_FunctionPointer; 14943 } else { 14944 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14945 Kind = FK_BlockPointer; 14946 } 14947 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14948 14949 // Verify that this is a legal result type of a function. 14950 if (DestType->isArrayType() || DestType->isFunctionType()) { 14951 unsigned diagID = diag::err_func_returning_array_function; 14952 if (Kind == FK_BlockPointer) 14953 diagID = diag::err_block_returning_array_function; 14954 14955 S.Diag(E->getExprLoc(), diagID) 14956 << DestType->isFunctionType() << DestType; 14957 return ExprError(); 14958 } 14959 14960 // Otherwise, go ahead and set DestType as the call's result. 14961 E->setType(DestType.getNonLValueExprType(S.Context)); 14962 E->setValueKind(Expr::getValueKindForType(DestType)); 14963 assert(E->getObjectKind() == OK_Ordinary); 14964 14965 // Rebuild the function type, replacing the result type with DestType. 14966 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14967 if (Proto) { 14968 // __unknown_anytype(...) is a special case used by the debugger when 14969 // it has no idea what a function's signature is. 14970 // 14971 // We want to build this call essentially under the K&R 14972 // unprototyped rules, but making a FunctionNoProtoType in C++ 14973 // would foul up all sorts of assumptions. However, we cannot 14974 // simply pass all arguments as variadic arguments, nor can we 14975 // portably just call the function under a non-variadic type; see 14976 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14977 // However, it turns out that in practice it is generally safe to 14978 // call a function declared as "A foo(B,C,D);" under the prototype 14979 // "A foo(B,C,D,...);". The only known exception is with the 14980 // Windows ABI, where any variadic function is implicitly cdecl 14981 // regardless of its normal CC. Therefore we change the parameter 14982 // types to match the types of the arguments. 14983 // 14984 // This is a hack, but it is far superior to moving the 14985 // corresponding target-specific code from IR-gen to Sema/AST. 14986 14987 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14988 SmallVector<QualType, 8> ArgTypes; 14989 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14990 ArgTypes.reserve(E->getNumArgs()); 14991 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14992 Expr *Arg = E->getArg(i); 14993 QualType ArgType = Arg->getType(); 14994 if (E->isLValue()) { 14995 ArgType = S.Context.getLValueReferenceType(ArgType); 14996 } else if (E->isXValue()) { 14997 ArgType = S.Context.getRValueReferenceType(ArgType); 14998 } 14999 ArgTypes.push_back(ArgType); 15000 } 15001 ParamTypes = ArgTypes; 15002 } 15003 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15004 Proto->getExtProtoInfo()); 15005 } else { 15006 DestType = S.Context.getFunctionNoProtoType(DestType, 15007 FnType->getExtInfo()); 15008 } 15009 15010 // Rebuild the appropriate pointer-to-function type. 15011 switch (Kind) { 15012 case FK_MemberFunction: 15013 // Nothing to do. 15014 break; 15015 15016 case FK_FunctionPointer: 15017 DestType = S.Context.getPointerType(DestType); 15018 break; 15019 15020 case FK_BlockPointer: 15021 DestType = S.Context.getBlockPointerType(DestType); 15022 break; 15023 } 15024 15025 // Finally, we can recurse. 15026 ExprResult CalleeResult = Visit(CalleeExpr); 15027 if (!CalleeResult.isUsable()) return ExprError(); 15028 E->setCallee(CalleeResult.get()); 15029 15030 // Bind a temporary if necessary. 15031 return S.MaybeBindToTemporary(E); 15032 } 15033 15034 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15035 // Verify that this is a legal result type of a call. 15036 if (DestType->isArrayType() || DestType->isFunctionType()) { 15037 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15038 << DestType->isFunctionType() << DestType; 15039 return ExprError(); 15040 } 15041 15042 // Rewrite the method result type if available. 15043 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15044 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15045 Method->setReturnType(DestType); 15046 } 15047 15048 // Change the type of the message. 15049 E->setType(DestType.getNonReferenceType()); 15050 E->setValueKind(Expr::getValueKindForType(DestType)); 15051 15052 return S.MaybeBindToTemporary(E); 15053 } 15054 15055 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15056 // The only case we should ever see here is a function-to-pointer decay. 15057 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15058 assert(E->getValueKind() == VK_RValue); 15059 assert(E->getObjectKind() == OK_Ordinary); 15060 15061 E->setType(DestType); 15062 15063 // Rebuild the sub-expression as the pointee (function) type. 15064 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15065 15066 ExprResult Result = Visit(E->getSubExpr()); 15067 if (!Result.isUsable()) return ExprError(); 15068 15069 E->setSubExpr(Result.get()); 15070 return E; 15071 } else if (E->getCastKind() == CK_LValueToRValue) { 15072 assert(E->getValueKind() == VK_RValue); 15073 assert(E->getObjectKind() == OK_Ordinary); 15074 15075 assert(isa<BlockPointerType>(E->getType())); 15076 15077 E->setType(DestType); 15078 15079 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15080 DestType = S.Context.getLValueReferenceType(DestType); 15081 15082 ExprResult Result = Visit(E->getSubExpr()); 15083 if (!Result.isUsable()) return ExprError(); 15084 15085 E->setSubExpr(Result.get()); 15086 return E; 15087 } else { 15088 llvm_unreachable("Unhandled cast type!"); 15089 } 15090 } 15091 15092 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15093 ExprValueKind ValueKind = VK_LValue; 15094 QualType Type = DestType; 15095 15096 // We know how to make this work for certain kinds of decls: 15097 15098 // - functions 15099 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15100 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15101 DestType = Ptr->getPointeeType(); 15102 ExprResult Result = resolveDecl(E, VD); 15103 if (Result.isInvalid()) return ExprError(); 15104 return S.ImpCastExprToType(Result.get(), Type, 15105 CK_FunctionToPointerDecay, VK_RValue); 15106 } 15107 15108 if (!Type->isFunctionType()) { 15109 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15110 << VD << E->getSourceRange(); 15111 return ExprError(); 15112 } 15113 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15114 // We must match the FunctionDecl's type to the hack introduced in 15115 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15116 // type. See the lengthy commentary in that routine. 15117 QualType FDT = FD->getType(); 15118 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15119 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15120 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15121 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15122 SourceLocation Loc = FD->getLocation(); 15123 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15124 FD->getDeclContext(), 15125 Loc, Loc, FD->getNameInfo().getName(), 15126 DestType, FD->getTypeSourceInfo(), 15127 SC_None, false/*isInlineSpecified*/, 15128 FD->hasPrototype(), 15129 false/*isConstexprSpecified*/); 15130 15131 if (FD->getQualifier()) 15132 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15133 15134 SmallVector<ParmVarDecl*, 16> Params; 15135 for (const auto &AI : FT->param_types()) { 15136 ParmVarDecl *Param = 15137 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15138 Param->setScopeInfo(0, Params.size()); 15139 Params.push_back(Param); 15140 } 15141 NewFD->setParams(Params); 15142 DRE->setDecl(NewFD); 15143 VD = DRE->getDecl(); 15144 } 15145 } 15146 15147 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15148 if (MD->isInstance()) { 15149 ValueKind = VK_RValue; 15150 Type = S.Context.BoundMemberTy; 15151 } 15152 15153 // Function references aren't l-values in C. 15154 if (!S.getLangOpts().CPlusPlus) 15155 ValueKind = VK_RValue; 15156 15157 // - variables 15158 } else if (isa<VarDecl>(VD)) { 15159 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15160 Type = RefTy->getPointeeType(); 15161 } else if (Type->isFunctionType()) { 15162 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15163 << VD << E->getSourceRange(); 15164 return ExprError(); 15165 } 15166 15167 // - nothing else 15168 } else { 15169 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15170 << VD << E->getSourceRange(); 15171 return ExprError(); 15172 } 15173 15174 // Modifying the declaration like this is friendly to IR-gen but 15175 // also really dangerous. 15176 VD->setType(DestType); 15177 E->setType(Type); 15178 E->setValueKind(ValueKind); 15179 return E; 15180 } 15181 15182 /// Check a cast of an unknown-any type. We intentionally only 15183 /// trigger this for C-style casts. 15184 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15185 Expr *CastExpr, CastKind &CastKind, 15186 ExprValueKind &VK, CXXCastPath &Path) { 15187 // The type we're casting to must be either void or complete. 15188 if (!CastType->isVoidType() && 15189 RequireCompleteType(TypeRange.getBegin(), CastType, 15190 diag::err_typecheck_cast_to_incomplete)) 15191 return ExprError(); 15192 15193 // Rewrite the casted expression from scratch. 15194 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15195 if (!result.isUsable()) return ExprError(); 15196 15197 CastExpr = result.get(); 15198 VK = CastExpr->getValueKind(); 15199 CastKind = CK_NoOp; 15200 15201 return CastExpr; 15202 } 15203 15204 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15205 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15206 } 15207 15208 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15209 Expr *arg, QualType ¶mType) { 15210 // If the syntactic form of the argument is not an explicit cast of 15211 // any sort, just do default argument promotion. 15212 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15213 if (!castArg) { 15214 ExprResult result = DefaultArgumentPromotion(arg); 15215 if (result.isInvalid()) return ExprError(); 15216 paramType = result.get()->getType(); 15217 return result; 15218 } 15219 15220 // Otherwise, use the type that was written in the explicit cast. 15221 assert(!arg->hasPlaceholderType()); 15222 paramType = castArg->getTypeAsWritten(); 15223 15224 // Copy-initialize a parameter of that type. 15225 InitializedEntity entity = 15226 InitializedEntity::InitializeParameter(Context, paramType, 15227 /*consumed*/ false); 15228 return PerformCopyInitialization(entity, callLoc, arg); 15229 } 15230 15231 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15232 Expr *orig = E; 15233 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15234 while (true) { 15235 E = E->IgnoreParenImpCasts(); 15236 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15237 E = call->getCallee(); 15238 diagID = diag::err_uncasted_call_of_unknown_any; 15239 } else { 15240 break; 15241 } 15242 } 15243 15244 SourceLocation loc; 15245 NamedDecl *d; 15246 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15247 loc = ref->getLocation(); 15248 d = ref->getDecl(); 15249 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15250 loc = mem->getMemberLoc(); 15251 d = mem->getMemberDecl(); 15252 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15253 diagID = diag::err_uncasted_call_of_unknown_any; 15254 loc = msg->getSelectorStartLoc(); 15255 d = msg->getMethodDecl(); 15256 if (!d) { 15257 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15258 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15259 << orig->getSourceRange(); 15260 return ExprError(); 15261 } 15262 } else { 15263 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15264 << E->getSourceRange(); 15265 return ExprError(); 15266 } 15267 15268 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15269 15270 // Never recoverable. 15271 return ExprError(); 15272 } 15273 15274 /// Check for operands with placeholder types and complain if found. 15275 /// Returns true if there was an error and no recovery was possible. 15276 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 15277 if (!getLangOpts().CPlusPlus) { 15278 // C cannot handle TypoExpr nodes on either side of a binop because it 15279 // doesn't handle dependent types properly, so make sure any TypoExprs have 15280 // been dealt with before checking the operands. 15281 ExprResult Result = CorrectDelayedTyposInExpr(E); 15282 if (!Result.isUsable()) return ExprError(); 15283 E = Result.get(); 15284 } 15285 15286 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 15287 if (!placeholderType) return E; 15288 15289 switch (placeholderType->getKind()) { 15290 15291 // Overloaded expressions. 15292 case BuiltinType::Overload: { 15293 // Try to resolve a single function template specialization. 15294 // This is obligatory. 15295 ExprResult Result = E; 15296 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 15297 return Result; 15298 15299 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 15300 // leaves Result unchanged on failure. 15301 Result = E; 15302 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 15303 return Result; 15304 15305 // If that failed, try to recover with a call. 15306 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 15307 /*complain*/ true); 15308 return Result; 15309 } 15310 15311 // Bound member functions. 15312 case BuiltinType::BoundMember: { 15313 ExprResult result = E; 15314 const Expr *BME = E->IgnoreParens(); 15315 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 15316 // Try to give a nicer diagnostic if it is a bound member that we recognize. 15317 if (isa<CXXPseudoDestructorExpr>(BME)) { 15318 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 15319 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 15320 if (ME->getMemberNameInfo().getName().getNameKind() == 15321 DeclarationName::CXXDestructorName) 15322 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 15323 } 15324 tryToRecoverWithCall(result, PD, 15325 /*complain*/ true); 15326 return result; 15327 } 15328 15329 // ARC unbridged casts. 15330 case BuiltinType::ARCUnbridgedCast: { 15331 Expr *realCast = stripARCUnbridgedCast(E); 15332 diagnoseARCUnbridgedCast(realCast); 15333 return realCast; 15334 } 15335 15336 // Expressions of unknown type. 15337 case BuiltinType::UnknownAny: 15338 return diagnoseUnknownAnyExpr(*this, E); 15339 15340 // Pseudo-objects. 15341 case BuiltinType::PseudoObject: 15342 return checkPseudoObjectRValue(E); 15343 15344 case BuiltinType::BuiltinFn: { 15345 // Accept __noop without parens by implicitly converting it to a call expr. 15346 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 15347 if (DRE) { 15348 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 15349 if (FD->getBuiltinID() == Builtin::BI__noop) { 15350 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 15351 CK_BuiltinFnToFnPtr).get(); 15352 return new (Context) CallExpr(Context, E, None, Context.IntTy, 15353 VK_RValue, SourceLocation()); 15354 } 15355 } 15356 15357 Diag(E->getLocStart(), diag::err_builtin_fn_use); 15358 return ExprError(); 15359 } 15360 15361 // Expressions of unknown type. 15362 case BuiltinType::OMPArraySection: 15363 Diag(E->getLocStart(), diag::err_omp_array_section_use); 15364 return ExprError(); 15365 15366 // Everything else should be impossible. 15367 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 15368 case BuiltinType::Id: 15369 #include "clang/Basic/OpenCLImageTypes.def" 15370 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 15371 #define PLACEHOLDER_TYPE(Id, SingletonId) 15372 #include "clang/AST/BuiltinTypes.def" 15373 break; 15374 } 15375 15376 llvm_unreachable("invalid placeholder type!"); 15377 } 15378 15379 bool Sema::CheckCaseExpression(Expr *E) { 15380 if (E->isTypeDependent()) 15381 return true; 15382 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 15383 return E->getType()->isIntegralOrEnumerationType(); 15384 return false; 15385 } 15386 15387 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 15388 ExprResult 15389 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 15390 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 15391 "Unknown Objective-C Boolean value!"); 15392 QualType BoolT = Context.ObjCBuiltinBoolTy; 15393 if (!Context.getBOOLDecl()) { 15394 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 15395 Sema::LookupOrdinaryName); 15396 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 15397 NamedDecl *ND = Result.getFoundDecl(); 15398 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 15399 Context.setBOOLDecl(TD); 15400 } 15401 } 15402 if (Context.getBOOLDecl()) 15403 BoolT = Context.getBOOLType(); 15404 return new (Context) 15405 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 15406 } 15407 15408 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 15409 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 15410 SourceLocation RParen) { 15411 15412 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 15413 15414 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 15415 [&](const AvailabilitySpec &Spec) { 15416 return Spec.getPlatform() == Platform; 15417 }); 15418 15419 VersionTuple Version; 15420 if (Spec != AvailSpecs.end()) 15421 Version = Spec->getVersion(); 15422 15423 return new (Context) 15424 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 15425 } 15426