1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/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/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/AnalysisBasedWarnings.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/DelayedDiagnostic.h" 36 #include "clang/Sema/Designator.h" 37 #include "clang/Sema/Initialization.h" 38 #include "clang/Sema/Lookup.h" 39 #include "clang/Sema/ParsedTemplate.h" 40 #include "clang/Sema/Scope.h" 41 #include "clang/Sema/ScopeInfo.h" 42 #include "clang/Sema/SemaFixItUtils.h" 43 #include "clang/Sema/Template.h" 44 using namespace clang; 45 using namespace sema; 46 47 /// \brief Determine whether the use of this declaration is valid, without 48 /// emitting diagnostics. 49 bool Sema::CanUseDecl(NamedDecl *D) { 50 // See if this is an auto-typed variable whose initializer we are parsing. 51 if (ParsingInitForAutoVars.count(D)) 52 return false; 53 54 // See if this is a deleted function. 55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 56 if (FD->isDeleted()) 57 return false; 58 } 59 60 // See if this function is unavailable. 61 if (D->getAvailability() == AR_Unavailable && 62 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 63 return false; 64 65 return true; 66 } 67 68 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 69 // Warn if this is used but marked unused. 70 if (D->hasAttr<UnusedAttr>()) { 71 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 72 if (!DC->hasAttr<UnusedAttr>()) 73 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 74 } 75 } 76 77 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 78 NamedDecl *D, SourceLocation Loc, 79 const ObjCInterfaceDecl *UnknownObjCClass) { 80 // See if this declaration is unavailable or deprecated. 81 std::string Message; 82 AvailabilityResult Result = D->getAvailability(&Message); 83 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 84 if (Result == AR_Available) { 85 const DeclContext *DC = ECD->getDeclContext(); 86 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 87 Result = TheEnumDecl->getAvailability(&Message); 88 } 89 90 const ObjCPropertyDecl *ObjCPDecl = 0; 91 if (Result == AR_Deprecated || Result == AR_Unavailable) { 92 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 93 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 94 AvailabilityResult PDeclResult = PD->getAvailability(0); 95 if (PDeclResult == Result) 96 ObjCPDecl = PD; 97 } 98 } 99 } 100 101 switch (Result) { 102 case AR_Available: 103 case AR_NotYetIntroduced: 104 break; 105 106 case AR_Deprecated: 107 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl); 108 break; 109 110 case AR_Unavailable: 111 if (S.getCurContextAvailability() != AR_Unavailable) { 112 if (Message.empty()) { 113 if (!UnknownObjCClass) { 114 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 115 if (ObjCPDecl) 116 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 117 << ObjCPDecl->getDeclName() << 1; 118 } 119 else 120 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 121 << D->getDeclName(); 122 } 123 else 124 S.Diag(Loc, diag::err_unavailable_message) 125 << D->getDeclName() << Message; 126 S.Diag(D->getLocation(), diag::note_unavailable_here) 127 << isa<FunctionDecl>(D) << false; 128 if (ObjCPDecl) 129 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 130 << ObjCPDecl->getDeclName() << 1; 131 } 132 break; 133 } 134 return Result; 135 } 136 137 /// \brief Emit a note explaining that this function is deleted or unavailable. 138 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 139 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 140 141 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) { 142 // If the method was explicitly defaulted, point at that declaration. 143 if (!Method->isImplicit()) 144 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 145 146 // Try to diagnose why this special member function was implicitly 147 // deleted. This might fail, if that reason no longer applies. 148 CXXSpecialMember CSM = getSpecialMember(Method); 149 if (CSM != CXXInvalid) 150 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 151 152 return; 153 } 154 155 Diag(Decl->getLocation(), diag::note_unavailable_here) 156 << 1 << Decl->isDeleted(); 157 } 158 159 /// \brief Determine whether a FunctionDecl was ever declared with an 160 /// explicit storage class. 161 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 162 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 163 E = D->redecls_end(); 164 I != E; ++I) { 165 if (I->getStorageClassAsWritten() != SC_None) 166 return true; 167 } 168 return false; 169 } 170 171 /// \brief Check whether we're in an extern inline function and referring to a 172 /// variable or function with internal linkage (C11 6.7.4p3). 173 /// 174 /// This is only a warning because we used to silently accept this code, but 175 /// in many cases it will not behave correctly. This is not enabled in C++ mode 176 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 177 /// and so while there may still be user mistakes, most of the time we can't 178 /// prove that there are errors. 179 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 180 const NamedDecl *D, 181 SourceLocation Loc) { 182 // This is disabled under C++; there are too many ways for this to fire in 183 // contexts where the warning is a false positive, or where it is technically 184 // correct but benign. 185 if (S.getLangOpts().CPlusPlus) 186 return; 187 188 // Check if this is an inlined function or method. 189 FunctionDecl *Current = S.getCurFunctionDecl(); 190 if (!Current) 191 return; 192 if (!Current->isInlined()) 193 return; 194 if (Current->getLinkage() != ExternalLinkage) 195 return; 196 197 // Check if the decl has internal linkage. 198 if (D->getLinkage() != InternalLinkage) 199 return; 200 201 // Downgrade from ExtWarn to Extension if 202 // (1) the supposedly external inline function is in the main file, 203 // and probably won't be included anywhere else. 204 // (2) the thing we're referencing is a pure function. 205 // (3) the thing we're referencing is another inline function. 206 // This last can give us false negatives, but it's better than warning on 207 // wrappers for simple C library functions. 208 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 209 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc); 210 if (!DowngradeWarning && UsedFn) 211 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 212 213 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 214 : diag::warn_internal_in_extern_inline) 215 << /*IsVar=*/!UsedFn << D; 216 217 // Suggest "static" on the inline function, if possible. 218 if (!hasAnyExplicitStorageClass(Current)) { 219 const FunctionDecl *FirstDecl = Current->getCanonicalDecl(); 220 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin(); 221 S.Diag(DeclBegin, diag::note_convert_inline_to_static) 222 << Current << FixItHint::CreateInsertion(DeclBegin, "static "); 223 } 224 225 S.Diag(D->getCanonicalDecl()->getLocation(), 226 diag::note_internal_decl_declared_here) 227 << D; 228 } 229 230 /// \brief Determine whether the use of this declaration is valid, and 231 /// emit any corresponding diagnostics. 232 /// 233 /// This routine diagnoses various problems with referencing 234 /// declarations that can occur when using a declaration. For example, 235 /// it might warn if a deprecated or unavailable declaration is being 236 /// used, or produce an error (and return true) if a C++0x deleted 237 /// function is being used. 238 /// 239 /// \returns true if there was an error (this declaration cannot be 240 /// referenced), false otherwise. 241 /// 242 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 243 const ObjCInterfaceDecl *UnknownObjCClass) { 244 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 245 // If there were any diagnostics suppressed by template argument deduction, 246 // emit them now. 247 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 248 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 249 if (Pos != SuppressedDiagnostics.end()) { 250 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 251 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 252 Diag(Suppressed[I].first, Suppressed[I].second); 253 254 // Clear out the list of suppressed diagnostics, so that we don't emit 255 // them again for this specialization. However, we don't obsolete this 256 // entry from the table, because we want to avoid ever emitting these 257 // diagnostics again. 258 Suppressed.clear(); 259 } 260 } 261 262 // See if this is an auto-typed variable whose initializer we are parsing. 263 if (ParsingInitForAutoVars.count(D)) { 264 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 265 << D->getDeclName(); 266 return true; 267 } 268 269 // See if this is a deleted function. 270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 271 if (FD->isDeleted()) { 272 Diag(Loc, diag::err_deleted_function_use); 273 NoteDeletedFunction(FD); 274 return true; 275 } 276 } 277 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 278 279 DiagnoseUnusedOfDecl(*this, D, Loc); 280 281 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 282 283 return false; 284 } 285 286 /// \brief Retrieve the message suffix that should be added to a 287 /// diagnostic complaining about the given function being deleted or 288 /// unavailable. 289 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 290 std::string Message; 291 if (FD->getAvailability(&Message)) 292 return ": " + Message; 293 294 return std::string(); 295 } 296 297 /// DiagnoseSentinelCalls - This routine checks whether a call or 298 /// message-send is to a declaration with the sentinel attribute, and 299 /// if so, it checks that the requirements of the sentinel are 300 /// satisfied. 301 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 302 Expr **args, unsigned numArgs) { 303 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 304 if (!attr) 305 return; 306 307 // The number of formal parameters of the declaration. 308 unsigned numFormalParams; 309 310 // The kind of declaration. This is also an index into a %select in 311 // the diagnostic. 312 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 313 314 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 315 numFormalParams = MD->param_size(); 316 calleeType = CT_Method; 317 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 318 numFormalParams = FD->param_size(); 319 calleeType = CT_Function; 320 } else if (isa<VarDecl>(D)) { 321 QualType type = cast<ValueDecl>(D)->getType(); 322 const FunctionType *fn = 0; 323 if (const PointerType *ptr = type->getAs<PointerType>()) { 324 fn = ptr->getPointeeType()->getAs<FunctionType>(); 325 if (!fn) return; 326 calleeType = CT_Function; 327 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 328 fn = ptr->getPointeeType()->castAs<FunctionType>(); 329 calleeType = CT_Block; 330 } else { 331 return; 332 } 333 334 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 335 numFormalParams = proto->getNumArgs(); 336 } else { 337 numFormalParams = 0; 338 } 339 } else { 340 return; 341 } 342 343 // "nullPos" is the number of formal parameters at the end which 344 // effectively count as part of the variadic arguments. This is 345 // useful if you would prefer to not have *any* formal parameters, 346 // but the language forces you to have at least one. 347 unsigned nullPos = attr->getNullPos(); 348 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 349 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 350 351 // The number of arguments which should follow the sentinel. 352 unsigned numArgsAfterSentinel = attr->getSentinel(); 353 354 // If there aren't enough arguments for all the formal parameters, 355 // the sentinel, and the args after the sentinel, complain. 356 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) { 357 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 358 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 359 return; 360 } 361 362 // Otherwise, find the sentinel expression. 363 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1]; 364 if (!sentinelExpr) return; 365 if (sentinelExpr->isValueDependent()) return; 366 if (Context.isSentinelNullExpr(sentinelExpr)) return; 367 368 // Pick a reasonable string to insert. Optimistically use 'nil' or 369 // 'NULL' if those are actually defined in the context. Only use 370 // 'nil' for ObjC methods, where it's much more likely that the 371 // variadic arguments form a list of object pointers. 372 SourceLocation MissingNilLoc 373 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 374 std::string NullValue; 375 if (calleeType == CT_Method && 376 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 377 NullValue = "nil"; 378 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 379 NullValue = "NULL"; 380 else 381 NullValue = "(void*) 0"; 382 383 if (MissingNilLoc.isInvalid()) 384 Diag(Loc, diag::warn_missing_sentinel) << calleeType; 385 else 386 Diag(MissingNilLoc, diag::warn_missing_sentinel) 387 << calleeType 388 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 389 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 390 } 391 392 SourceRange Sema::getExprRange(Expr *E) const { 393 return E ? E->getSourceRange() : SourceRange(); 394 } 395 396 //===----------------------------------------------------------------------===// 397 // Standard Promotions and Conversions 398 //===----------------------------------------------------------------------===// 399 400 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 401 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 402 // Handle any placeholder expressions which made it here. 403 if (E->getType()->isPlaceholderType()) { 404 ExprResult result = CheckPlaceholderExpr(E); 405 if (result.isInvalid()) return ExprError(); 406 E = result.take(); 407 } 408 409 QualType Ty = E->getType(); 410 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 411 412 if (Ty->isFunctionType()) 413 E = ImpCastExprToType(E, Context.getPointerType(Ty), 414 CK_FunctionToPointerDecay).take(); 415 else if (Ty->isArrayType()) { 416 // In C90 mode, arrays only promote to pointers if the array expression is 417 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 418 // type 'array of type' is converted to an expression that has type 'pointer 419 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 420 // that has type 'array of type' ...". The relevant change is "an lvalue" 421 // (C90) to "an expression" (C99). 422 // 423 // C++ 4.2p1: 424 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 425 // T" can be converted to an rvalue of type "pointer to T". 426 // 427 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 428 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 429 CK_ArrayToPointerDecay).take(); 430 } 431 return Owned(E); 432 } 433 434 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 435 // Check to see if we are dereferencing a null pointer. If so, 436 // and if not volatile-qualified, this is undefined behavior that the 437 // optimizer will delete, so warn about it. People sometimes try to use this 438 // to get a deterministic trap and are surprised by clang's behavior. This 439 // only handles the pattern "*null", which is a very syntactic check. 440 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 441 if (UO->getOpcode() == UO_Deref && 442 UO->getSubExpr()->IgnoreParenCasts()-> 443 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 444 !UO->getType().isVolatileQualified()) { 445 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 446 S.PDiag(diag::warn_indirection_through_null) 447 << UO->getSubExpr()->getSourceRange()); 448 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 449 S.PDiag(diag::note_indirection_through_null)); 450 } 451 } 452 453 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 454 // Handle any placeholder expressions which made it here. 455 if (E->getType()->isPlaceholderType()) { 456 ExprResult result = CheckPlaceholderExpr(E); 457 if (result.isInvalid()) return ExprError(); 458 E = result.take(); 459 } 460 461 // C++ [conv.lval]p1: 462 // A glvalue of a non-function, non-array type T can be 463 // converted to a prvalue. 464 if (!E->isGLValue()) return Owned(E); 465 466 QualType T = E->getType(); 467 assert(!T.isNull() && "r-value conversion on typeless expression?"); 468 469 // We don't want to throw lvalue-to-rvalue casts on top of 470 // expressions of certain types in C++. 471 if (getLangOpts().CPlusPlus && 472 (E->getType() == Context.OverloadTy || 473 T->isDependentType() || 474 T->isRecordType())) 475 return Owned(E); 476 477 // The C standard is actually really unclear on this point, and 478 // DR106 tells us what the result should be but not why. It's 479 // generally best to say that void types just doesn't undergo 480 // lvalue-to-rvalue at all. Note that expressions of unqualified 481 // 'void' type are never l-values, but qualified void can be. 482 if (T->isVoidType()) 483 return Owned(E); 484 485 CheckForNullPointerDereference(*this, E); 486 487 // C++ [conv.lval]p1: 488 // [...] If T is a non-class type, the type of the prvalue is the 489 // cv-unqualified version of T. Otherwise, the type of the 490 // rvalue is T. 491 // 492 // C99 6.3.2.1p2: 493 // If the lvalue has qualified type, the value has the unqualified 494 // version of the type of the lvalue; otherwise, the value has the 495 // type of the lvalue. 496 if (T.hasQualifiers()) 497 T = T.getUnqualifiedType(); 498 499 UpdateMarkingForLValueToRValue(E); 500 501 // Loading a __weak object implicitly retains the value, so we need a cleanup to 502 // balance that. 503 if (getLangOpts().ObjCAutoRefCount && 504 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 505 ExprNeedsCleanups = true; 506 507 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 508 E, 0, VK_RValue)); 509 510 // C11 6.3.2.1p2: 511 // ... if the lvalue has atomic type, the value has the non-atomic version 512 // of the type of the lvalue ... 513 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 514 T = Atomic->getValueType().getUnqualifiedType(); 515 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 516 Res.get(), 0, VK_RValue)); 517 } 518 519 return Res; 520 } 521 522 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 523 ExprResult Res = DefaultFunctionArrayConversion(E); 524 if (Res.isInvalid()) 525 return ExprError(); 526 Res = DefaultLvalueConversion(Res.take()); 527 if (Res.isInvalid()) 528 return ExprError(); 529 return Res; 530 } 531 532 533 /// UsualUnaryConversions - Performs various conversions that are common to most 534 /// operators (C99 6.3). The conversions of array and function types are 535 /// sometimes suppressed. For example, the array->pointer conversion doesn't 536 /// apply if the array is an argument to the sizeof or address (&) operators. 537 /// In these instances, this routine should *not* be called. 538 ExprResult Sema::UsualUnaryConversions(Expr *E) { 539 // First, convert to an r-value. 540 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 541 if (Res.isInvalid()) 542 return Owned(E); 543 E = Res.take(); 544 545 QualType Ty = E->getType(); 546 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 547 548 // Half FP is a bit different: it's a storage-only type, meaning that any 549 // "use" of it should be promoted to float. 550 if (Ty->isHalfType()) 551 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 552 553 // Try to perform integral promotions if the object has a theoretically 554 // promotable type. 555 if (Ty->isIntegralOrUnscopedEnumerationType()) { 556 // C99 6.3.1.1p2: 557 // 558 // The following may be used in an expression wherever an int or 559 // unsigned int may be used: 560 // - an object or expression with an integer type whose integer 561 // conversion rank is less than or equal to the rank of int 562 // and unsigned int. 563 // - A bit-field of type _Bool, int, signed int, or unsigned int. 564 // 565 // If an int can represent all values of the original type, the 566 // value is converted to an int; otherwise, it is converted to an 567 // unsigned int. These are called the integer promotions. All 568 // other types are unchanged by the integer promotions. 569 570 QualType PTy = Context.isPromotableBitField(E); 571 if (!PTy.isNull()) { 572 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 573 return Owned(E); 574 } 575 if (Ty->isPromotableIntegerType()) { 576 QualType PT = Context.getPromotedIntegerType(Ty); 577 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 578 return Owned(E); 579 } 580 } 581 return Owned(E); 582 } 583 584 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 585 /// do not have a prototype. Arguments that have type float are promoted to 586 /// double. All other argument types are converted by UsualUnaryConversions(). 587 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 588 QualType Ty = E->getType(); 589 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 590 591 ExprResult Res = UsualUnaryConversions(E); 592 if (Res.isInvalid()) 593 return Owned(E); 594 E = Res.take(); 595 596 // If this is a 'float' (CVR qualified or typedef) promote to double. 597 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 598 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 599 600 // C++ performs lvalue-to-rvalue conversion as a default argument 601 // promotion, even on class types, but note: 602 // C++11 [conv.lval]p2: 603 // When an lvalue-to-rvalue conversion occurs in an unevaluated 604 // operand or a subexpression thereof the value contained in the 605 // referenced object is not accessed. Otherwise, if the glvalue 606 // has a class type, the conversion copy-initializes a temporary 607 // of type T from the glvalue and the result of the conversion 608 // is a prvalue for the temporary. 609 // FIXME: add some way to gate this entire thing for correctness in 610 // potentially potentially evaluated contexts. 611 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 612 ExprResult Temp = PerformCopyInitialization( 613 InitializedEntity::InitializeTemporary(E->getType()), 614 E->getExprLoc(), 615 Owned(E)); 616 if (Temp.isInvalid()) 617 return ExprError(); 618 E = Temp.get(); 619 } 620 621 return Owned(E); 622 } 623 624 /// Determine the degree of POD-ness for an expression. 625 /// Incomplete types are considered POD, since this check can be performed 626 /// when we're in an unevaluated context. 627 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 628 if (Ty->isIncompleteType()) { 629 if (Ty->isObjCObjectType()) 630 return VAK_Invalid; 631 return VAK_Valid; 632 } 633 634 if (Ty.isCXX98PODType(Context)) 635 return VAK_Valid; 636 637 // C++11 [expr.call]p7: 638 // Passing a potentially-evaluated argument of class type (Clause 9) 639 // having a non-trivial copy constructor, a non-trivial move constructor, 640 // or a non-trivial destructor, with no corresponding parameter, 641 // is conditionally-supported with implementation-defined semantics. 642 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 643 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 644 if (!Record->hasNonTrivialCopyConstructor() && 645 !Record->hasNonTrivialMoveConstructor() && 646 !Record->hasNonTrivialDestructor()) 647 return VAK_ValidInCXX11; 648 649 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 650 return VAK_Valid; 651 return VAK_Invalid; 652 } 653 654 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) { 655 // Don't allow one to pass an Objective-C interface to a vararg. 656 const QualType & Ty = E->getType(); 657 658 // Complain about passing non-POD types through varargs. 659 switch (isValidVarArgType(Ty)) { 660 case VAK_Valid: 661 break; 662 case VAK_ValidInCXX11: 663 DiagRuntimeBehavior(E->getLocStart(), 0, 664 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 665 << E->getType() << CT); 666 break; 667 case VAK_Invalid: { 668 if (Ty->isObjCObjectType()) 669 return DiagRuntimeBehavior(E->getLocStart(), 0, 670 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 671 << Ty << CT); 672 673 return DiagRuntimeBehavior(E->getLocStart(), 0, 674 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 675 << getLangOpts().CPlusPlus11 << Ty << CT); 676 } 677 } 678 // c++ rules are enforced elsewhere. 679 return false; 680 } 681 682 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 683 /// will create a trap if the resulting type is not a POD type. 684 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 685 FunctionDecl *FDecl) { 686 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 687 // Strip the unbridged-cast placeholder expression off, if applicable. 688 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 689 (CT == VariadicMethod || 690 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 691 E = stripARCUnbridgedCast(E); 692 693 // Otherwise, do normal placeholder checking. 694 } else { 695 ExprResult ExprRes = CheckPlaceholderExpr(E); 696 if (ExprRes.isInvalid()) 697 return ExprError(); 698 E = ExprRes.take(); 699 } 700 } 701 702 ExprResult ExprRes = DefaultArgumentPromotion(E); 703 if (ExprRes.isInvalid()) 704 return ExprError(); 705 E = ExprRes.take(); 706 707 // Diagnostics regarding non-POD argument types are 708 // emitted along with format string checking in Sema::CheckFunctionCall(). 709 if (isValidVarArgType(E->getType()) == VAK_Invalid) { 710 // Turn this into a trap. 711 CXXScopeSpec SS; 712 SourceLocation TemplateKWLoc; 713 UnqualifiedId Name; 714 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 715 E->getLocStart()); 716 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 717 Name, true, false); 718 if (TrapFn.isInvalid()) 719 return ExprError(); 720 721 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 722 E->getLocStart(), MultiExprArg(), 723 E->getLocEnd()); 724 if (Call.isInvalid()) 725 return ExprError(); 726 727 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 728 Call.get(), E); 729 if (Comma.isInvalid()) 730 return ExprError(); 731 return Comma.get(); 732 } 733 734 if (!getLangOpts().CPlusPlus && 735 RequireCompleteType(E->getExprLoc(), E->getType(), 736 diag::err_call_incomplete_argument)) 737 return ExprError(); 738 739 return Owned(E); 740 } 741 742 /// \brief Converts an integer to complex float type. Helper function of 743 /// UsualArithmeticConversions() 744 /// 745 /// \return false if the integer expression is an integer type and is 746 /// successfully converted to the complex type. 747 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 748 ExprResult &ComplexExpr, 749 QualType IntTy, 750 QualType ComplexTy, 751 bool SkipCast) { 752 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 753 if (SkipCast) return false; 754 if (IntTy->isIntegerType()) { 755 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 756 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 757 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 758 CK_FloatingRealToComplex); 759 } else { 760 assert(IntTy->isComplexIntegerType()); 761 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 762 CK_IntegralComplexToFloatingComplex); 763 } 764 return false; 765 } 766 767 /// \brief Takes two complex float types and converts them to the same type. 768 /// Helper function of UsualArithmeticConversions() 769 static QualType 770 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 771 ExprResult &RHS, QualType LHSType, 772 QualType RHSType, 773 bool IsCompAssign) { 774 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 775 776 if (order < 0) { 777 // _Complex float -> _Complex double 778 if (!IsCompAssign) 779 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 780 return RHSType; 781 } 782 if (order > 0) 783 // _Complex float -> _Complex double 784 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 785 return LHSType; 786 } 787 788 /// \brief Converts otherExpr to complex float and promotes complexExpr if 789 /// necessary. Helper function of UsualArithmeticConversions() 790 static QualType handleOtherComplexFloatConversion(Sema &S, 791 ExprResult &ComplexExpr, 792 ExprResult &OtherExpr, 793 QualType ComplexTy, 794 QualType OtherTy, 795 bool ConvertComplexExpr, 796 bool ConvertOtherExpr) { 797 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 798 799 // If just the complexExpr is complex, the otherExpr needs to be converted, 800 // and the complexExpr might need to be promoted. 801 if (order > 0) { // complexExpr is wider 802 // float -> _Complex double 803 if (ConvertOtherExpr) { 804 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 805 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 806 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 807 CK_FloatingRealToComplex); 808 } 809 return ComplexTy; 810 } 811 812 // otherTy is at least as wide. Find its corresponding complex type. 813 QualType result = (order == 0 ? ComplexTy : 814 S.Context.getComplexType(OtherTy)); 815 816 // double -> _Complex double 817 if (ConvertOtherExpr) 818 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 819 CK_FloatingRealToComplex); 820 821 // _Complex float -> _Complex double 822 if (ConvertComplexExpr && order < 0) 823 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 824 CK_FloatingComplexCast); 825 826 return result; 827 } 828 829 /// \brief Handle arithmetic conversion with complex types. Helper function of 830 /// UsualArithmeticConversions() 831 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 832 ExprResult &RHS, QualType LHSType, 833 QualType RHSType, 834 bool IsCompAssign) { 835 // if we have an integer operand, the result is the complex type. 836 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 837 /*skipCast*/false)) 838 return LHSType; 839 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 840 /*skipCast*/IsCompAssign)) 841 return RHSType; 842 843 // This handles complex/complex, complex/float, or float/complex. 844 // When both operands are complex, the shorter operand is converted to the 845 // type of the longer, and that is the type of the result. This corresponds 846 // to what is done when combining two real floating-point operands. 847 // The fun begins when size promotion occur across type domains. 848 // From H&S 6.3.4: When one operand is complex and the other is a real 849 // floating-point type, the less precise type is converted, within it's 850 // real or complex domain, to the precision of the other type. For example, 851 // when combining a "long double" with a "double _Complex", the 852 // "double _Complex" is promoted to "long double _Complex". 853 854 bool LHSComplexFloat = LHSType->isComplexType(); 855 bool RHSComplexFloat = RHSType->isComplexType(); 856 857 // If both are complex, just cast to the more precise type. 858 if (LHSComplexFloat && RHSComplexFloat) 859 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 860 LHSType, RHSType, 861 IsCompAssign); 862 863 // If only one operand is complex, promote it if necessary and convert the 864 // other operand to complex. 865 if (LHSComplexFloat) 866 return handleOtherComplexFloatConversion( 867 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 868 /*convertOtherExpr*/ true); 869 870 assert(RHSComplexFloat); 871 return handleOtherComplexFloatConversion( 872 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 873 /*convertOtherExpr*/ !IsCompAssign); 874 } 875 876 /// \brief Hande arithmetic conversion from integer to float. Helper function 877 /// of UsualArithmeticConversions() 878 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 879 ExprResult &IntExpr, 880 QualType FloatTy, QualType IntTy, 881 bool ConvertFloat, bool ConvertInt) { 882 if (IntTy->isIntegerType()) { 883 if (ConvertInt) 884 // Convert intExpr to the lhs floating point type. 885 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 886 CK_IntegralToFloating); 887 return FloatTy; 888 } 889 890 // Convert both sides to the appropriate complex float. 891 assert(IntTy->isComplexIntegerType()); 892 QualType result = S.Context.getComplexType(FloatTy); 893 894 // _Complex int -> _Complex float 895 if (ConvertInt) 896 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 897 CK_IntegralComplexToFloatingComplex); 898 899 // float -> _Complex float 900 if (ConvertFloat) 901 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 902 CK_FloatingRealToComplex); 903 904 return result; 905 } 906 907 /// \brief Handle arithmethic conversion with floating point types. Helper 908 /// function of UsualArithmeticConversions() 909 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 910 ExprResult &RHS, QualType LHSType, 911 QualType RHSType, bool IsCompAssign) { 912 bool LHSFloat = LHSType->isRealFloatingType(); 913 bool RHSFloat = RHSType->isRealFloatingType(); 914 915 // If we have two real floating types, convert the smaller operand 916 // to the bigger result. 917 if (LHSFloat && RHSFloat) { 918 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 919 if (order > 0) { 920 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 921 return LHSType; 922 } 923 924 assert(order < 0 && "illegal float comparison"); 925 if (!IsCompAssign) 926 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 927 return RHSType; 928 } 929 930 if (LHSFloat) 931 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 932 /*convertFloat=*/!IsCompAssign, 933 /*convertInt=*/ true); 934 assert(RHSFloat); 935 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 936 /*convertInt=*/ true, 937 /*convertFloat=*/!IsCompAssign); 938 } 939 940 /// \brief Handle conversions with GCC complex int extension. Helper function 941 /// of UsualArithmeticConversions() 942 // FIXME: if the operands are (int, _Complex long), we currently 943 // don't promote the complex. Also, signedness? 944 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 945 ExprResult &RHS, QualType LHSType, 946 QualType RHSType, 947 bool IsCompAssign) { 948 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 949 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 950 951 if (LHSComplexInt && RHSComplexInt) { 952 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(), 953 RHSComplexInt->getElementType()); 954 assert(order && "inequal types with equal element ordering"); 955 if (order > 0) { 956 // _Complex int -> _Complex long 957 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast); 958 return LHSType; 959 } 960 961 if (!IsCompAssign) 962 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast); 963 return RHSType; 964 } 965 966 if (LHSComplexInt) { 967 // int -> _Complex int 968 // FIXME: This needs to take integer ranks into account 969 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(), 970 CK_IntegralCast); 971 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex); 972 return LHSType; 973 } 974 975 assert(RHSComplexInt); 976 // int -> _Complex int 977 // FIXME: This needs to take integer ranks into account 978 if (!IsCompAssign) { 979 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(), 980 CK_IntegralCast); 981 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex); 982 } 983 return RHSType; 984 } 985 986 /// \brief Handle integer arithmetic conversions. Helper function of 987 /// UsualArithmeticConversions() 988 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 989 ExprResult &RHS, QualType LHSType, 990 QualType RHSType, bool IsCompAssign) { 991 // The rules for this case are in C99 6.3.1.8 992 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 993 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 994 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 995 if (LHSSigned == RHSSigned) { 996 // Same signedness; use the higher-ranked type 997 if (order >= 0) { 998 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 999 return LHSType; 1000 } else if (!IsCompAssign) 1001 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 1002 return RHSType; 1003 } else if (order != (LHSSigned ? 1 : -1)) { 1004 // The unsigned type has greater than or equal rank to the 1005 // signed type, so use the unsigned type 1006 if (RHSSigned) { 1007 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 1008 return LHSType; 1009 } else if (!IsCompAssign) 1010 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 1011 return RHSType; 1012 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1013 // The two types are different widths; if we are here, that 1014 // means the signed type is larger than the unsigned type, so 1015 // use the signed type. 1016 if (LHSSigned) { 1017 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 1018 return LHSType; 1019 } else if (!IsCompAssign) 1020 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 1021 return RHSType; 1022 } else { 1023 // The signed type is higher-ranked than the unsigned type, 1024 // but isn't actually any bigger (like unsigned int and long 1025 // on most 32-bit systems). Use the unsigned type corresponding 1026 // to the signed type. 1027 QualType result = 1028 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1029 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast); 1030 if (!IsCompAssign) 1031 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast); 1032 return result; 1033 } 1034 } 1035 1036 /// UsualArithmeticConversions - Performs various conversions that are common to 1037 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1038 /// routine returns the first non-arithmetic type found. The client is 1039 /// responsible for emitting appropriate error diagnostics. 1040 /// FIXME: verify the conversion rules for "complex int" are consistent with 1041 /// GCC. 1042 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1043 bool IsCompAssign) { 1044 if (!IsCompAssign) { 1045 LHS = UsualUnaryConversions(LHS.take()); 1046 if (LHS.isInvalid()) 1047 return QualType(); 1048 } 1049 1050 RHS = UsualUnaryConversions(RHS.take()); 1051 if (RHS.isInvalid()) 1052 return QualType(); 1053 1054 // For conversion purposes, we ignore any qualifiers. 1055 // For example, "const float" and "float" are equivalent. 1056 QualType LHSType = 1057 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1058 QualType RHSType = 1059 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1060 1061 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1062 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1063 LHSType = AtomicLHS->getValueType(); 1064 1065 // If both types are identical, no conversion is needed. 1066 if (LHSType == RHSType) 1067 return LHSType; 1068 1069 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1070 // The caller can deal with this (e.g. pointer + int). 1071 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1072 return QualType(); 1073 1074 // Apply unary and bitfield promotions to the LHS's type. 1075 QualType LHSUnpromotedType = LHSType; 1076 if (LHSType->isPromotableIntegerType()) 1077 LHSType = Context.getPromotedIntegerType(LHSType); 1078 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1079 if (!LHSBitfieldPromoteTy.isNull()) 1080 LHSType = LHSBitfieldPromoteTy; 1081 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1082 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1083 1084 // If both types are identical, no conversion is needed. 1085 if (LHSType == RHSType) 1086 return LHSType; 1087 1088 // At this point, we have two different arithmetic types. 1089 1090 // Handle complex types first (C99 6.3.1.8p1). 1091 if (LHSType->isComplexType() || RHSType->isComplexType()) 1092 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1093 IsCompAssign); 1094 1095 // Now handle "real" floating types (i.e. float, double, long double). 1096 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1097 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1098 IsCompAssign); 1099 1100 // Handle GCC complex int extension. 1101 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1102 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1103 IsCompAssign); 1104 1105 // Finally, we have two differing integer types. 1106 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType, 1107 IsCompAssign); 1108 } 1109 1110 //===----------------------------------------------------------------------===// 1111 // Semantic Analysis for various Expression Types 1112 //===----------------------------------------------------------------------===// 1113 1114 1115 ExprResult 1116 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1117 SourceLocation DefaultLoc, 1118 SourceLocation RParenLoc, 1119 Expr *ControllingExpr, 1120 MultiTypeArg ArgTypes, 1121 MultiExprArg ArgExprs) { 1122 unsigned NumAssocs = ArgTypes.size(); 1123 assert(NumAssocs == ArgExprs.size()); 1124 1125 ParsedType *ParsedTypes = ArgTypes.data(); 1126 Expr **Exprs = ArgExprs.data(); 1127 1128 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1129 for (unsigned i = 0; i < NumAssocs; ++i) { 1130 if (ParsedTypes[i]) 1131 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]); 1132 else 1133 Types[i] = 0; 1134 } 1135 1136 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1137 ControllingExpr, Types, Exprs, 1138 NumAssocs); 1139 delete [] Types; 1140 return ER; 1141 } 1142 1143 ExprResult 1144 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1145 SourceLocation DefaultLoc, 1146 SourceLocation RParenLoc, 1147 Expr *ControllingExpr, 1148 TypeSourceInfo **Types, 1149 Expr **Exprs, 1150 unsigned NumAssocs) { 1151 bool TypeErrorFound = false, 1152 IsResultDependent = ControllingExpr->isTypeDependent(), 1153 ContainsUnexpandedParameterPack 1154 = ControllingExpr->containsUnexpandedParameterPack(); 1155 1156 for (unsigned i = 0; i < NumAssocs; ++i) { 1157 if (Exprs[i]->containsUnexpandedParameterPack()) 1158 ContainsUnexpandedParameterPack = true; 1159 1160 if (Types[i]) { 1161 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1162 ContainsUnexpandedParameterPack = true; 1163 1164 if (Types[i]->getType()->isDependentType()) { 1165 IsResultDependent = true; 1166 } else { 1167 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1168 // complete object type other than a variably modified type." 1169 unsigned D = 0; 1170 if (Types[i]->getType()->isIncompleteType()) 1171 D = diag::err_assoc_type_incomplete; 1172 else if (!Types[i]->getType()->isObjectType()) 1173 D = diag::err_assoc_type_nonobject; 1174 else if (Types[i]->getType()->isVariablyModifiedType()) 1175 D = diag::err_assoc_type_variably_modified; 1176 1177 if (D != 0) { 1178 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1179 << Types[i]->getTypeLoc().getSourceRange() 1180 << Types[i]->getType(); 1181 TypeErrorFound = true; 1182 } 1183 1184 // C11 6.5.1.1p2 "No two generic associations in the same generic 1185 // selection shall specify compatible types." 1186 for (unsigned j = i+1; j < NumAssocs; ++j) 1187 if (Types[j] && !Types[j]->getType()->isDependentType() && 1188 Context.typesAreCompatible(Types[i]->getType(), 1189 Types[j]->getType())) { 1190 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1191 diag::err_assoc_compatible_types) 1192 << Types[j]->getTypeLoc().getSourceRange() 1193 << Types[j]->getType() 1194 << Types[i]->getType(); 1195 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1196 diag::note_compat_assoc) 1197 << Types[i]->getTypeLoc().getSourceRange() 1198 << Types[i]->getType(); 1199 TypeErrorFound = true; 1200 } 1201 } 1202 } 1203 } 1204 if (TypeErrorFound) 1205 return ExprError(); 1206 1207 // If we determined that the generic selection is result-dependent, don't 1208 // try to compute the result expression. 1209 if (IsResultDependent) 1210 return Owned(new (Context) GenericSelectionExpr( 1211 Context, KeyLoc, ControllingExpr, 1212 llvm::makeArrayRef(Types, NumAssocs), 1213 llvm::makeArrayRef(Exprs, NumAssocs), 1214 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1215 1216 SmallVector<unsigned, 1> CompatIndices; 1217 unsigned DefaultIndex = -1U; 1218 for (unsigned i = 0; i < NumAssocs; ++i) { 1219 if (!Types[i]) 1220 DefaultIndex = i; 1221 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1222 Types[i]->getType())) 1223 CompatIndices.push_back(i); 1224 } 1225 1226 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1227 // type compatible with at most one of the types named in its generic 1228 // association list." 1229 if (CompatIndices.size() > 1) { 1230 // We strip parens here because the controlling expression is typically 1231 // parenthesized in macro definitions. 1232 ControllingExpr = ControllingExpr->IgnoreParens(); 1233 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1234 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1235 << (unsigned) CompatIndices.size(); 1236 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1237 E = CompatIndices.end(); I != E; ++I) { 1238 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1239 diag::note_compat_assoc) 1240 << Types[*I]->getTypeLoc().getSourceRange() 1241 << Types[*I]->getType(); 1242 } 1243 return ExprError(); 1244 } 1245 1246 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1247 // its controlling expression shall have type compatible with exactly one of 1248 // the types named in its generic association list." 1249 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1250 // We strip parens here because the controlling expression is typically 1251 // parenthesized in macro definitions. 1252 ControllingExpr = ControllingExpr->IgnoreParens(); 1253 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1254 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1255 return ExprError(); 1256 } 1257 1258 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1259 // type name that is compatible with the type of the controlling expression, 1260 // then the result expression of the generic selection is the expression 1261 // in that generic association. Otherwise, the result expression of the 1262 // generic selection is the expression in the default generic association." 1263 unsigned ResultIndex = 1264 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1265 1266 return Owned(new (Context) GenericSelectionExpr( 1267 Context, KeyLoc, ControllingExpr, 1268 llvm::makeArrayRef(Types, NumAssocs), 1269 llvm::makeArrayRef(Exprs, NumAssocs), 1270 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1271 ResultIndex)); 1272 } 1273 1274 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1275 /// location of the token and the offset of the ud-suffix within it. 1276 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1277 unsigned Offset) { 1278 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1279 S.getLangOpts()); 1280 } 1281 1282 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1283 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1284 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1285 IdentifierInfo *UDSuffix, 1286 SourceLocation UDSuffixLoc, 1287 ArrayRef<Expr*> Args, 1288 SourceLocation LitEndLoc) { 1289 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1290 1291 QualType ArgTy[2]; 1292 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1293 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1294 if (ArgTy[ArgIdx]->isArrayType()) 1295 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1296 } 1297 1298 DeclarationName OpName = 1299 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1300 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1301 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1302 1303 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1304 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1305 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1306 return ExprError(); 1307 1308 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1309 } 1310 1311 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1312 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1313 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1314 /// multiple tokens. However, the common case is that StringToks points to one 1315 /// string. 1316 /// 1317 ExprResult 1318 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1319 Scope *UDLScope) { 1320 assert(NumStringToks && "Must have at least one string!"); 1321 1322 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1323 if (Literal.hadError) 1324 return ExprError(); 1325 1326 SmallVector<SourceLocation, 4> StringTokLocs; 1327 for (unsigned i = 0; i != NumStringToks; ++i) 1328 StringTokLocs.push_back(StringToks[i].getLocation()); 1329 1330 QualType StrTy = Context.CharTy; 1331 if (Literal.isWide()) 1332 StrTy = Context.getWCharType(); 1333 else if (Literal.isUTF16()) 1334 StrTy = Context.Char16Ty; 1335 else if (Literal.isUTF32()) 1336 StrTy = Context.Char32Ty; 1337 else if (Literal.isPascal()) 1338 StrTy = Context.UnsignedCharTy; 1339 1340 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1341 if (Literal.isWide()) 1342 Kind = StringLiteral::Wide; 1343 else if (Literal.isUTF8()) 1344 Kind = StringLiteral::UTF8; 1345 else if (Literal.isUTF16()) 1346 Kind = StringLiteral::UTF16; 1347 else if (Literal.isUTF32()) 1348 Kind = StringLiteral::UTF32; 1349 1350 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1351 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1352 StrTy.addConst(); 1353 1354 // Get an array type for the string, according to C99 6.4.5. This includes 1355 // the nul terminator character as well as the string length for pascal 1356 // strings. 1357 StrTy = Context.getConstantArrayType(StrTy, 1358 llvm::APInt(32, Literal.GetNumStringChars()+1), 1359 ArrayType::Normal, 0); 1360 1361 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1362 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1363 Kind, Literal.Pascal, StrTy, 1364 &StringTokLocs[0], 1365 StringTokLocs.size()); 1366 if (Literal.getUDSuffix().empty()) 1367 return Owned(Lit); 1368 1369 // We're building a user-defined literal. 1370 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1371 SourceLocation UDSuffixLoc = 1372 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1373 Literal.getUDSuffixOffset()); 1374 1375 // Make sure we're allowed user-defined literals here. 1376 if (!UDLScope) 1377 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1378 1379 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1380 // operator "" X (str, len) 1381 QualType SizeType = Context.getSizeType(); 1382 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1383 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1384 StringTokLocs[0]); 1385 Expr *Args[] = { Lit, LenArg }; 1386 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1387 Args, StringTokLocs.back()); 1388 } 1389 1390 ExprResult 1391 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1392 SourceLocation Loc, 1393 const CXXScopeSpec *SS) { 1394 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1395 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1396 } 1397 1398 /// BuildDeclRefExpr - Build an expression that references a 1399 /// declaration that does not require a closure capture. 1400 ExprResult 1401 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1402 const DeclarationNameInfo &NameInfo, 1403 const CXXScopeSpec *SS) { 1404 if (getLangOpts().CUDA) 1405 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1406 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1407 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1408 CalleeTarget = IdentifyCUDATarget(Callee); 1409 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1410 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1411 << CalleeTarget << D->getIdentifier() << CallerTarget; 1412 Diag(D->getLocation(), diag::note_previous_decl) 1413 << D->getIdentifier(); 1414 return ExprError(); 1415 } 1416 } 1417 1418 bool refersToEnclosingScope = 1419 (CurContext != D->getDeclContext() && 1420 D->getDeclContext()->isFunctionOrMethod()); 1421 1422 DeclRefExpr *E = DeclRefExpr::Create(Context, 1423 SS ? SS->getWithLocInContext(Context) 1424 : NestedNameSpecifierLoc(), 1425 SourceLocation(), 1426 D, refersToEnclosingScope, 1427 NameInfo, Ty, VK); 1428 1429 MarkDeclRefReferenced(E); 1430 1431 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1432 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1433 DiagnosticsEngine::Level Level = 1434 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1435 E->getLocStart()); 1436 if (Level != DiagnosticsEngine::Ignored) 1437 getCurFunction()->recordUseOfWeak(E); 1438 } 1439 1440 // Just in case we're building an illegal pointer-to-member. 1441 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1442 if (FD && FD->isBitField()) 1443 E->setObjectKind(OK_BitField); 1444 1445 return Owned(E); 1446 } 1447 1448 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1449 /// possibly a list of template arguments. 1450 /// 1451 /// If this produces template arguments, it is permitted to call 1452 /// DecomposeTemplateName. 1453 /// 1454 /// This actually loses a lot of source location information for 1455 /// non-standard name kinds; we should consider preserving that in 1456 /// some way. 1457 void 1458 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1459 TemplateArgumentListInfo &Buffer, 1460 DeclarationNameInfo &NameInfo, 1461 const TemplateArgumentListInfo *&TemplateArgs) { 1462 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1463 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1464 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1465 1466 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1467 Id.TemplateId->NumArgs); 1468 translateTemplateArguments(TemplateArgsPtr, Buffer); 1469 1470 TemplateName TName = Id.TemplateId->Template.get(); 1471 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1472 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1473 TemplateArgs = &Buffer; 1474 } else { 1475 NameInfo = GetNameFromUnqualifiedId(Id); 1476 TemplateArgs = 0; 1477 } 1478 } 1479 1480 /// Diagnose an empty lookup. 1481 /// 1482 /// \return false if new lookup candidates were found 1483 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1484 CorrectionCandidateCallback &CCC, 1485 TemplateArgumentListInfo *ExplicitTemplateArgs, 1486 llvm::ArrayRef<Expr *> Args) { 1487 DeclarationName Name = R.getLookupName(); 1488 1489 unsigned diagnostic = diag::err_undeclared_var_use; 1490 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1491 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1492 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1493 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1494 diagnostic = diag::err_undeclared_use; 1495 diagnostic_suggest = diag::err_undeclared_use_suggest; 1496 } 1497 1498 // If the original lookup was an unqualified lookup, fake an 1499 // unqualified lookup. This is useful when (for example) the 1500 // original lookup would not have found something because it was a 1501 // dependent name. 1502 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1503 ? CurContext : 0; 1504 while (DC) { 1505 if (isa<CXXRecordDecl>(DC)) { 1506 LookupQualifiedName(R, DC); 1507 1508 if (!R.empty()) { 1509 // Don't give errors about ambiguities in this lookup. 1510 R.suppressDiagnostics(); 1511 1512 // During a default argument instantiation the CurContext points 1513 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1514 // function parameter list, hence add an explicit check. 1515 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1516 ActiveTemplateInstantiations.back().Kind == 1517 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1518 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1519 bool isInstance = CurMethod && 1520 CurMethod->isInstance() && 1521 DC == CurMethod->getParent() && !isDefaultArgument; 1522 1523 1524 // Give a code modification hint to insert 'this->'. 1525 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1526 // Actually quite difficult! 1527 if (getLangOpts().MicrosoftMode) 1528 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1529 if (isInstance) { 1530 Diag(R.getNameLoc(), diagnostic) << Name 1531 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1532 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1533 CallsUndergoingInstantiation.back()->getCallee()); 1534 1535 1536 CXXMethodDecl *DepMethod; 1537 if (CurMethod->getTemplatedKind() == 1538 FunctionDecl::TK_FunctionTemplateSpecialization) 1539 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1540 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1541 else 1542 DepMethod = cast<CXXMethodDecl>( 1543 CurMethod->getInstantiatedFromMemberFunction()); 1544 assert(DepMethod && "No template pattern found"); 1545 1546 QualType DepThisType = DepMethod->getThisType(Context); 1547 CheckCXXThisCapture(R.getNameLoc()); 1548 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1549 R.getNameLoc(), DepThisType, false); 1550 TemplateArgumentListInfo TList; 1551 if (ULE->hasExplicitTemplateArgs()) 1552 ULE->copyTemplateArgumentsInto(TList); 1553 1554 CXXScopeSpec SS; 1555 SS.Adopt(ULE->getQualifierLoc()); 1556 CXXDependentScopeMemberExpr *DepExpr = 1557 CXXDependentScopeMemberExpr::Create( 1558 Context, DepThis, DepThisType, true, SourceLocation(), 1559 SS.getWithLocInContext(Context), 1560 ULE->getTemplateKeywordLoc(), 0, 1561 R.getLookupNameInfo(), 1562 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1563 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1564 } else { 1565 Diag(R.getNameLoc(), diagnostic) << Name; 1566 } 1567 1568 // Do we really want to note all of these? 1569 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1570 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1571 1572 // Return true if we are inside a default argument instantiation 1573 // and the found name refers to an instance member function, otherwise 1574 // the function calling DiagnoseEmptyLookup will try to create an 1575 // implicit member call and this is wrong for default argument. 1576 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1577 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1578 return true; 1579 } 1580 1581 // Tell the callee to try to recover. 1582 return false; 1583 } 1584 1585 R.clear(); 1586 } 1587 1588 // In Microsoft mode, if we are performing lookup from within a friend 1589 // function definition declared at class scope then we must set 1590 // DC to the lexical parent to be able to search into the parent 1591 // class. 1592 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1593 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1594 DC->getLexicalParent()->isRecord()) 1595 DC = DC->getLexicalParent(); 1596 else 1597 DC = DC->getParent(); 1598 } 1599 1600 // We didn't find anything, so try to correct for a typo. 1601 TypoCorrection Corrected; 1602 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1603 S, &SS, CCC))) { 1604 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1605 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1606 R.setLookupName(Corrected.getCorrection()); 1607 1608 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1609 if (Corrected.isOverloaded()) { 1610 OverloadCandidateSet OCS(R.getNameLoc()); 1611 OverloadCandidateSet::iterator Best; 1612 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1613 CDEnd = Corrected.end(); 1614 CD != CDEnd; ++CD) { 1615 if (FunctionTemplateDecl *FTD = 1616 dyn_cast<FunctionTemplateDecl>(*CD)) 1617 AddTemplateOverloadCandidate( 1618 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1619 Args, OCS); 1620 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1621 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1622 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1623 Args, OCS); 1624 } 1625 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1626 case OR_Success: 1627 ND = Best->Function; 1628 break; 1629 default: 1630 break; 1631 } 1632 } 1633 R.addDecl(ND); 1634 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1635 if (SS.isEmpty()) 1636 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1637 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1638 else 1639 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1640 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1641 << SS.getRange() 1642 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 1643 CorrectedStr); 1644 if (ND) 1645 Diag(ND->getLocation(), diag::note_previous_decl) 1646 << CorrectedQuotedStr; 1647 1648 // Tell the callee to try to recover. 1649 return false; 1650 } 1651 1652 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1653 // FIXME: If we ended up with a typo for a type name or 1654 // Objective-C class name, we're in trouble because the parser 1655 // is in the wrong place to recover. Suggest the typo 1656 // correction, but don't make it a fix-it since we're not going 1657 // to recover well anyway. 1658 if (SS.isEmpty()) 1659 Diag(R.getNameLoc(), diagnostic_suggest) 1660 << Name << CorrectedQuotedStr; 1661 else 1662 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1663 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1664 << SS.getRange(); 1665 1666 // Don't try to recover; it won't work. 1667 return true; 1668 } 1669 } else { 1670 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1671 // because we aren't able to recover. 1672 if (SS.isEmpty()) 1673 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1674 else 1675 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1676 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1677 << SS.getRange(); 1678 return true; 1679 } 1680 } 1681 R.clear(); 1682 1683 // Emit a special diagnostic for failed member lookups. 1684 // FIXME: computing the declaration context might fail here (?) 1685 if (!SS.isEmpty()) { 1686 Diag(R.getNameLoc(), diag::err_no_member) 1687 << Name << computeDeclContext(SS, false) 1688 << SS.getRange(); 1689 return true; 1690 } 1691 1692 // Give up, we can't recover. 1693 Diag(R.getNameLoc(), diagnostic) << Name; 1694 return true; 1695 } 1696 1697 ExprResult Sema::ActOnIdExpression(Scope *S, 1698 CXXScopeSpec &SS, 1699 SourceLocation TemplateKWLoc, 1700 UnqualifiedId &Id, 1701 bool HasTrailingLParen, 1702 bool IsAddressOfOperand, 1703 CorrectionCandidateCallback *CCC) { 1704 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1705 "cannot be direct & operand and have a trailing lparen"); 1706 1707 if (SS.isInvalid()) 1708 return ExprError(); 1709 1710 TemplateArgumentListInfo TemplateArgsBuffer; 1711 1712 // Decompose the UnqualifiedId into the following data. 1713 DeclarationNameInfo NameInfo; 1714 const TemplateArgumentListInfo *TemplateArgs; 1715 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1716 1717 DeclarationName Name = NameInfo.getName(); 1718 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1719 SourceLocation NameLoc = NameInfo.getLoc(); 1720 1721 // C++ [temp.dep.expr]p3: 1722 // An id-expression is type-dependent if it contains: 1723 // -- an identifier that was declared with a dependent type, 1724 // (note: handled after lookup) 1725 // -- a template-id that is dependent, 1726 // (note: handled in BuildTemplateIdExpr) 1727 // -- a conversion-function-id that specifies a dependent type, 1728 // -- a nested-name-specifier that contains a class-name that 1729 // names a dependent type. 1730 // Determine whether this is a member of an unknown specialization; 1731 // we need to handle these differently. 1732 bool DependentID = false; 1733 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1734 Name.getCXXNameType()->isDependentType()) { 1735 DependentID = true; 1736 } else if (SS.isSet()) { 1737 if (DeclContext *DC = computeDeclContext(SS, false)) { 1738 if (RequireCompleteDeclContext(SS, DC)) 1739 return ExprError(); 1740 } else { 1741 DependentID = true; 1742 } 1743 } 1744 1745 if (DependentID) 1746 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1747 IsAddressOfOperand, TemplateArgs); 1748 1749 // Perform the required lookup. 1750 LookupResult R(*this, NameInfo, 1751 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1752 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1753 if (TemplateArgs) { 1754 // Lookup the template name again to correctly establish the context in 1755 // which it was found. This is really unfortunate as we already did the 1756 // lookup to determine that it was a template name in the first place. If 1757 // this becomes a performance hit, we can work harder to preserve those 1758 // results until we get here but it's likely not worth it. 1759 bool MemberOfUnknownSpecialization; 1760 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1761 MemberOfUnknownSpecialization); 1762 1763 if (MemberOfUnknownSpecialization || 1764 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1765 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1766 IsAddressOfOperand, TemplateArgs); 1767 } else { 1768 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1769 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1770 1771 // If the result might be in a dependent base class, this is a dependent 1772 // id-expression. 1773 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1774 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1775 IsAddressOfOperand, TemplateArgs); 1776 1777 // If this reference is in an Objective-C method, then we need to do 1778 // some special Objective-C lookup, too. 1779 if (IvarLookupFollowUp) { 1780 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1781 if (E.isInvalid()) 1782 return ExprError(); 1783 1784 if (Expr *Ex = E.takeAs<Expr>()) 1785 return Owned(Ex); 1786 } 1787 } 1788 1789 if (R.isAmbiguous()) 1790 return ExprError(); 1791 1792 // Determine whether this name might be a candidate for 1793 // argument-dependent lookup. 1794 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1795 1796 if (R.empty() && !ADL) { 1797 // Otherwise, this could be an implicitly declared function reference (legal 1798 // in C90, extension in C99, forbidden in C++). 1799 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1800 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1801 if (D) R.addDecl(D); 1802 } 1803 1804 // If this name wasn't predeclared and if this is not a function 1805 // call, diagnose the problem. 1806 if (R.empty()) { 1807 1808 // In Microsoft mode, if we are inside a template class member function 1809 // and we can't resolve an identifier then assume the identifier is type 1810 // dependent. The goal is to postpone name lookup to instantiation time 1811 // to be able to search into type dependent base classes. 1812 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 1813 isa<CXXMethodDecl>(CurContext)) 1814 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1815 IsAddressOfOperand, TemplateArgs); 1816 1817 CorrectionCandidateCallback DefaultValidator; 1818 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 1819 return ExprError(); 1820 1821 assert(!R.empty() && 1822 "DiagnoseEmptyLookup returned false but added no results"); 1823 1824 // If we found an Objective-C instance variable, let 1825 // LookupInObjCMethod build the appropriate expression to 1826 // reference the ivar. 1827 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1828 R.clear(); 1829 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1830 // In a hopelessly buggy code, Objective-C instance variable 1831 // lookup fails and no expression will be built to reference it. 1832 if (!E.isInvalid() && !E.get()) 1833 return ExprError(); 1834 return E; 1835 } 1836 } 1837 } 1838 1839 // This is guaranteed from this point on. 1840 assert(!R.empty() || ADL); 1841 1842 // Check whether this might be a C++ implicit instance member access. 1843 // C++ [class.mfct.non-static]p3: 1844 // When an id-expression that is not part of a class member access 1845 // syntax and not used to form a pointer to member is used in the 1846 // body of a non-static member function of class X, if name lookup 1847 // resolves the name in the id-expression to a non-static non-type 1848 // member of some class C, the id-expression is transformed into a 1849 // class member access expression using (*this) as the 1850 // postfix-expression to the left of the . operator. 1851 // 1852 // But we don't actually need to do this for '&' operands if R 1853 // resolved to a function or overloaded function set, because the 1854 // expression is ill-formed if it actually works out to be a 1855 // non-static member function: 1856 // 1857 // C++ [expr.ref]p4: 1858 // Otherwise, if E1.E2 refers to a non-static member function. . . 1859 // [t]he expression can be used only as the left-hand operand of a 1860 // member function call. 1861 // 1862 // There are other safeguards against such uses, but it's important 1863 // to get this right here so that we don't end up making a 1864 // spuriously dependent expression if we're inside a dependent 1865 // instance method. 1866 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1867 bool MightBeImplicitMember; 1868 if (!IsAddressOfOperand) 1869 MightBeImplicitMember = true; 1870 else if (!SS.isEmpty()) 1871 MightBeImplicitMember = false; 1872 else if (R.isOverloadedResult()) 1873 MightBeImplicitMember = false; 1874 else if (R.isUnresolvableResult()) 1875 MightBeImplicitMember = true; 1876 else 1877 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 1878 isa<IndirectFieldDecl>(R.getFoundDecl()); 1879 1880 if (MightBeImplicitMember) 1881 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 1882 R, TemplateArgs); 1883 } 1884 1885 if (TemplateArgs || TemplateKWLoc.isValid()) 1886 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 1887 1888 return BuildDeclarationNameExpr(SS, R, ADL); 1889 } 1890 1891 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1892 /// declaration name, generally during template instantiation. 1893 /// There's a large number of things which don't need to be done along 1894 /// this path. 1895 ExprResult 1896 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1897 const DeclarationNameInfo &NameInfo, 1898 bool IsAddressOfOperand) { 1899 DeclContext *DC = computeDeclContext(SS, false); 1900 if (!DC) 1901 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 1902 NameInfo, /*TemplateArgs=*/0); 1903 1904 if (RequireCompleteDeclContext(SS, DC)) 1905 return ExprError(); 1906 1907 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1908 LookupQualifiedName(R, DC); 1909 1910 if (R.isAmbiguous()) 1911 return ExprError(); 1912 1913 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1914 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 1915 NameInfo, /*TemplateArgs=*/0); 1916 1917 if (R.empty()) { 1918 Diag(NameInfo.getLoc(), diag::err_no_member) 1919 << NameInfo.getName() << DC << SS.getRange(); 1920 return ExprError(); 1921 } 1922 1923 // Defend against this resolving to an implicit member access. We usually 1924 // won't get here if this might be a legitimate a class member (we end up in 1925 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 1926 // a pointer-to-member or in an unevaluated context in C++11. 1927 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 1928 return BuildPossibleImplicitMemberExpr(SS, 1929 /*TemplateKWLoc=*/SourceLocation(), 1930 R, /*TemplateArgs=*/0); 1931 1932 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 1933 } 1934 1935 /// LookupInObjCMethod - The parser has read a name in, and Sema has 1936 /// detected that we're currently inside an ObjC method. Perform some 1937 /// additional lookup. 1938 /// 1939 /// Ideally, most of this would be done by lookup, but there's 1940 /// actually quite a lot of extra work involved. 1941 /// 1942 /// Returns a null sentinel to indicate trivial success. 1943 ExprResult 1944 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1945 IdentifierInfo *II, bool AllowBuiltinCreation) { 1946 SourceLocation Loc = Lookup.getNameLoc(); 1947 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1948 1949 // There are two cases to handle here. 1) scoped lookup could have failed, 1950 // in which case we should look for an ivar. 2) scoped lookup could have 1951 // found a decl, but that decl is outside the current instance method (i.e. 1952 // a global variable). In these two cases, we do a lookup for an ivar with 1953 // this name, if the lookup sucedes, we replace it our current decl. 1954 1955 // If we're in a class method, we don't normally want to look for 1956 // ivars. But if we don't find anything else, and there's an 1957 // ivar, that's an error. 1958 bool IsClassMethod = CurMethod->isClassMethod(); 1959 1960 bool LookForIvars; 1961 if (Lookup.empty()) 1962 LookForIvars = true; 1963 else if (IsClassMethod) 1964 LookForIvars = false; 1965 else 1966 LookForIvars = (Lookup.isSingleResult() && 1967 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1968 ObjCInterfaceDecl *IFace = 0; 1969 if (LookForIvars) { 1970 IFace = CurMethod->getClassInterface(); 1971 ObjCInterfaceDecl *ClassDeclared; 1972 ObjCIvarDecl *IV = 0; 1973 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 1974 // Diagnose using an ivar in a class method. 1975 if (IsClassMethod) 1976 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1977 << IV->getDeclName()); 1978 1979 // If we're referencing an invalid decl, just return this as a silent 1980 // error node. The error diagnostic was already emitted on the decl. 1981 if (IV->isInvalidDecl()) 1982 return ExprError(); 1983 1984 // Check if referencing a field with __attribute__((deprecated)). 1985 if (DiagnoseUseOfDecl(IV, Loc)) 1986 return ExprError(); 1987 1988 // Diagnose the use of an ivar outside of the declaring class. 1989 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1990 !declaresSameEntity(ClassDeclared, IFace) && 1991 !getLangOpts().DebuggerSupport) 1992 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1993 1994 // FIXME: This should use a new expr for a direct reference, don't 1995 // turn this into Self->ivar, just return a BareIVarExpr or something. 1996 IdentifierInfo &II = Context.Idents.get("self"); 1997 UnqualifiedId SelfName; 1998 SelfName.setIdentifier(&II, SourceLocation()); 1999 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2000 CXXScopeSpec SelfScopeSpec; 2001 SourceLocation TemplateKWLoc; 2002 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2003 SelfName, false, false); 2004 if (SelfExpr.isInvalid()) 2005 return ExprError(); 2006 2007 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2008 if (SelfExpr.isInvalid()) 2009 return ExprError(); 2010 2011 MarkAnyDeclReferenced(Loc, IV); 2012 2013 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2014 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize) 2015 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2016 2017 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2018 Loc, 2019 SelfExpr.take(), 2020 true, true); 2021 2022 if (getLangOpts().ObjCAutoRefCount) { 2023 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2024 DiagnosticsEngine::Level Level = 2025 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2026 if (Level != DiagnosticsEngine::Ignored) 2027 getCurFunction()->recordUseOfWeak(Result); 2028 } 2029 if (CurContext->isClosure()) 2030 Diag(Loc, diag::warn_implicitly_retains_self) 2031 << FixItHint::CreateInsertion(Loc, "self->"); 2032 } 2033 2034 return Owned(Result); 2035 } 2036 } else if (CurMethod->isInstanceMethod()) { 2037 // We should warn if a local variable hides an ivar. 2038 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2039 ObjCInterfaceDecl *ClassDeclared; 2040 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2041 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2042 declaresSameEntity(IFace, ClassDeclared)) 2043 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2044 } 2045 } 2046 } else if (Lookup.isSingleResult() && 2047 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2048 // If accessing a stand-alone ivar in a class method, this is an error. 2049 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2050 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2051 << IV->getDeclName()); 2052 } 2053 2054 if (Lookup.empty() && II && AllowBuiltinCreation) { 2055 // FIXME. Consolidate this with similar code in LookupName. 2056 if (unsigned BuiltinID = II->getBuiltinID()) { 2057 if (!(getLangOpts().CPlusPlus && 2058 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2059 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2060 S, Lookup.isForRedeclaration(), 2061 Lookup.getNameLoc()); 2062 if (D) Lookup.addDecl(D); 2063 } 2064 } 2065 } 2066 // Sentinel value saying that we didn't do anything special. 2067 return Owned((Expr*) 0); 2068 } 2069 2070 /// \brief Cast a base object to a member's actual type. 2071 /// 2072 /// Logically this happens in three phases: 2073 /// 2074 /// * First we cast from the base type to the naming class. 2075 /// The naming class is the class into which we were looking 2076 /// when we found the member; it's the qualifier type if a 2077 /// qualifier was provided, and otherwise it's the base type. 2078 /// 2079 /// * Next we cast from the naming class to the declaring class. 2080 /// If the member we found was brought into a class's scope by 2081 /// a using declaration, this is that class; otherwise it's 2082 /// the class declaring the member. 2083 /// 2084 /// * Finally we cast from the declaring class to the "true" 2085 /// declaring class of the member. This conversion does not 2086 /// obey access control. 2087 ExprResult 2088 Sema::PerformObjectMemberConversion(Expr *From, 2089 NestedNameSpecifier *Qualifier, 2090 NamedDecl *FoundDecl, 2091 NamedDecl *Member) { 2092 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2093 if (!RD) 2094 return Owned(From); 2095 2096 QualType DestRecordType; 2097 QualType DestType; 2098 QualType FromRecordType; 2099 QualType FromType = From->getType(); 2100 bool PointerConversions = false; 2101 if (isa<FieldDecl>(Member)) { 2102 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2103 2104 if (FromType->getAs<PointerType>()) { 2105 DestType = Context.getPointerType(DestRecordType); 2106 FromRecordType = FromType->getPointeeType(); 2107 PointerConversions = true; 2108 } else { 2109 DestType = DestRecordType; 2110 FromRecordType = FromType; 2111 } 2112 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2113 if (Method->isStatic()) 2114 return Owned(From); 2115 2116 DestType = Method->getThisType(Context); 2117 DestRecordType = DestType->getPointeeType(); 2118 2119 if (FromType->getAs<PointerType>()) { 2120 FromRecordType = FromType->getPointeeType(); 2121 PointerConversions = true; 2122 } else { 2123 FromRecordType = FromType; 2124 DestType = DestRecordType; 2125 } 2126 } else { 2127 // No conversion necessary. 2128 return Owned(From); 2129 } 2130 2131 if (DestType->isDependentType() || FromType->isDependentType()) 2132 return Owned(From); 2133 2134 // If the unqualified types are the same, no conversion is necessary. 2135 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2136 return Owned(From); 2137 2138 SourceRange FromRange = From->getSourceRange(); 2139 SourceLocation FromLoc = FromRange.getBegin(); 2140 2141 ExprValueKind VK = From->getValueKind(); 2142 2143 // C++ [class.member.lookup]p8: 2144 // [...] Ambiguities can often be resolved by qualifying a name with its 2145 // class name. 2146 // 2147 // If the member was a qualified name and the qualified referred to a 2148 // specific base subobject type, we'll cast to that intermediate type 2149 // first and then to the object in which the member is declared. That allows 2150 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2151 // 2152 // class Base { public: int x; }; 2153 // class Derived1 : public Base { }; 2154 // class Derived2 : public Base { }; 2155 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2156 // 2157 // void VeryDerived::f() { 2158 // x = 17; // error: ambiguous base subobjects 2159 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2160 // } 2161 if (Qualifier) { 2162 QualType QType = QualType(Qualifier->getAsType(), 0); 2163 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 2164 assert(QType->isRecordType() && "lookup done with non-record type"); 2165 2166 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2167 2168 // In C++98, the qualifier type doesn't actually have to be a base 2169 // type of the object type, in which case we just ignore it. 2170 // Otherwise build the appropriate casts. 2171 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2172 CXXCastPath BasePath; 2173 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2174 FromLoc, FromRange, &BasePath)) 2175 return ExprError(); 2176 2177 if (PointerConversions) 2178 QType = Context.getPointerType(QType); 2179 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2180 VK, &BasePath).take(); 2181 2182 FromType = QType; 2183 FromRecordType = QRecordType; 2184 2185 // If the qualifier type was the same as the destination type, 2186 // we're done. 2187 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2188 return Owned(From); 2189 } 2190 } 2191 2192 bool IgnoreAccess = false; 2193 2194 // If we actually found the member through a using declaration, cast 2195 // down to the using declaration's type. 2196 // 2197 // Pointer equality is fine here because only one declaration of a 2198 // class ever has member declarations. 2199 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2200 assert(isa<UsingShadowDecl>(FoundDecl)); 2201 QualType URecordType = Context.getTypeDeclType( 2202 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2203 2204 // We only need to do this if the naming-class to declaring-class 2205 // conversion is non-trivial. 2206 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2207 assert(IsDerivedFrom(FromRecordType, URecordType)); 2208 CXXCastPath BasePath; 2209 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2210 FromLoc, FromRange, &BasePath)) 2211 return ExprError(); 2212 2213 QualType UType = URecordType; 2214 if (PointerConversions) 2215 UType = Context.getPointerType(UType); 2216 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2217 VK, &BasePath).take(); 2218 FromType = UType; 2219 FromRecordType = URecordType; 2220 } 2221 2222 // We don't do access control for the conversion from the 2223 // declaring class to the true declaring class. 2224 IgnoreAccess = true; 2225 } 2226 2227 CXXCastPath BasePath; 2228 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2229 FromLoc, FromRange, &BasePath, 2230 IgnoreAccess)) 2231 return ExprError(); 2232 2233 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2234 VK, &BasePath); 2235 } 2236 2237 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2238 const LookupResult &R, 2239 bool HasTrailingLParen) { 2240 // Only when used directly as the postfix-expression of a call. 2241 if (!HasTrailingLParen) 2242 return false; 2243 2244 // Never if a scope specifier was provided. 2245 if (SS.isSet()) 2246 return false; 2247 2248 // Only in C++ or ObjC++. 2249 if (!getLangOpts().CPlusPlus) 2250 return false; 2251 2252 // Turn off ADL when we find certain kinds of declarations during 2253 // normal lookup: 2254 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2255 NamedDecl *D = *I; 2256 2257 // C++0x [basic.lookup.argdep]p3: 2258 // -- a declaration of a class member 2259 // Since using decls preserve this property, we check this on the 2260 // original decl. 2261 if (D->isCXXClassMember()) 2262 return false; 2263 2264 // C++0x [basic.lookup.argdep]p3: 2265 // -- a block-scope function declaration that is not a 2266 // using-declaration 2267 // NOTE: we also trigger this for function templates (in fact, we 2268 // don't check the decl type at all, since all other decl types 2269 // turn off ADL anyway). 2270 if (isa<UsingShadowDecl>(D)) 2271 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2272 else if (D->getDeclContext()->isFunctionOrMethod()) 2273 return false; 2274 2275 // C++0x [basic.lookup.argdep]p3: 2276 // -- a declaration that is neither a function or a function 2277 // template 2278 // And also for builtin functions. 2279 if (isa<FunctionDecl>(D)) { 2280 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2281 2282 // But also builtin functions. 2283 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2284 return false; 2285 } else if (!isa<FunctionTemplateDecl>(D)) 2286 return false; 2287 } 2288 2289 return true; 2290 } 2291 2292 2293 /// Diagnoses obvious problems with the use of the given declaration 2294 /// as an expression. This is only actually called for lookups that 2295 /// were not overloaded, and it doesn't promise that the declaration 2296 /// will in fact be used. 2297 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2298 if (isa<TypedefNameDecl>(D)) { 2299 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2300 return true; 2301 } 2302 2303 if (isa<ObjCInterfaceDecl>(D)) { 2304 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2305 return true; 2306 } 2307 2308 if (isa<NamespaceDecl>(D)) { 2309 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2310 return true; 2311 } 2312 2313 return false; 2314 } 2315 2316 ExprResult 2317 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2318 LookupResult &R, 2319 bool NeedsADL) { 2320 // If this is a single, fully-resolved result and we don't need ADL, 2321 // just build an ordinary singleton decl ref. 2322 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2323 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 2324 R.getFoundDecl()); 2325 2326 // We only need to check the declaration if there's exactly one 2327 // result, because in the overloaded case the results can only be 2328 // functions and function templates. 2329 if (R.isSingleResult() && 2330 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2331 return ExprError(); 2332 2333 // Otherwise, just build an unresolved lookup expression. Suppress 2334 // any lookup-related diagnostics; we'll hash these out later, when 2335 // we've picked a target. 2336 R.suppressDiagnostics(); 2337 2338 UnresolvedLookupExpr *ULE 2339 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2340 SS.getWithLocInContext(Context), 2341 R.getLookupNameInfo(), 2342 NeedsADL, R.isOverloadedResult(), 2343 R.begin(), R.end()); 2344 2345 return Owned(ULE); 2346 } 2347 2348 /// \brief Complete semantic analysis for a reference to the given declaration. 2349 ExprResult 2350 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2351 const DeclarationNameInfo &NameInfo, 2352 NamedDecl *D) { 2353 assert(D && "Cannot refer to a NULL declaration"); 2354 assert(!isa<FunctionTemplateDecl>(D) && 2355 "Cannot refer unambiguously to a function template"); 2356 2357 SourceLocation Loc = NameInfo.getLoc(); 2358 if (CheckDeclInExpr(*this, Loc, D)) 2359 return ExprError(); 2360 2361 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2362 // Specifically diagnose references to class templates that are missing 2363 // a template argument list. 2364 Diag(Loc, diag::err_template_decl_ref) 2365 << Template << SS.getRange(); 2366 Diag(Template->getLocation(), diag::note_template_decl_here); 2367 return ExprError(); 2368 } 2369 2370 // Make sure that we're referring to a value. 2371 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2372 if (!VD) { 2373 Diag(Loc, diag::err_ref_non_value) 2374 << D << SS.getRange(); 2375 Diag(D->getLocation(), diag::note_declared_at); 2376 return ExprError(); 2377 } 2378 2379 // Check whether this declaration can be used. Note that we suppress 2380 // this check when we're going to perform argument-dependent lookup 2381 // on this function name, because this might not be the function 2382 // that overload resolution actually selects. 2383 if (DiagnoseUseOfDecl(VD, Loc)) 2384 return ExprError(); 2385 2386 // Only create DeclRefExpr's for valid Decl's. 2387 if (VD->isInvalidDecl()) 2388 return ExprError(); 2389 2390 // Handle members of anonymous structs and unions. If we got here, 2391 // and the reference is to a class member indirect field, then this 2392 // must be the subject of a pointer-to-member expression. 2393 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2394 if (!indirectField->isCXXClassMember()) 2395 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2396 indirectField); 2397 2398 { 2399 QualType type = VD->getType(); 2400 ExprValueKind valueKind = VK_RValue; 2401 2402 switch (D->getKind()) { 2403 // Ignore all the non-ValueDecl kinds. 2404 #define ABSTRACT_DECL(kind) 2405 #define VALUE(type, base) 2406 #define DECL(type, base) \ 2407 case Decl::type: 2408 #include "clang/AST/DeclNodes.inc" 2409 llvm_unreachable("invalid value decl kind"); 2410 2411 // These shouldn't make it here. 2412 case Decl::ObjCAtDefsField: 2413 case Decl::ObjCIvar: 2414 llvm_unreachable("forming non-member reference to ivar?"); 2415 2416 // Enum constants are always r-values and never references. 2417 // Unresolved using declarations are dependent. 2418 case Decl::EnumConstant: 2419 case Decl::UnresolvedUsingValue: 2420 valueKind = VK_RValue; 2421 break; 2422 2423 // Fields and indirect fields that got here must be for 2424 // pointer-to-member expressions; we just call them l-values for 2425 // internal consistency, because this subexpression doesn't really 2426 // exist in the high-level semantics. 2427 case Decl::Field: 2428 case Decl::IndirectField: 2429 assert(getLangOpts().CPlusPlus && 2430 "building reference to field in C?"); 2431 2432 // These can't have reference type in well-formed programs, but 2433 // for internal consistency we do this anyway. 2434 type = type.getNonReferenceType(); 2435 valueKind = VK_LValue; 2436 break; 2437 2438 // Non-type template parameters are either l-values or r-values 2439 // depending on the type. 2440 case Decl::NonTypeTemplateParm: { 2441 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2442 type = reftype->getPointeeType(); 2443 valueKind = VK_LValue; // even if the parameter is an r-value reference 2444 break; 2445 } 2446 2447 // For non-references, we need to strip qualifiers just in case 2448 // the template parameter was declared as 'const int' or whatever. 2449 valueKind = VK_RValue; 2450 type = type.getUnqualifiedType(); 2451 break; 2452 } 2453 2454 case Decl::Var: 2455 // In C, "extern void blah;" is valid and is an r-value. 2456 if (!getLangOpts().CPlusPlus && 2457 !type.hasQualifiers() && 2458 type->isVoidType()) { 2459 valueKind = VK_RValue; 2460 break; 2461 } 2462 // fallthrough 2463 2464 case Decl::ImplicitParam: 2465 case Decl::ParmVar: { 2466 // These are always l-values. 2467 valueKind = VK_LValue; 2468 type = type.getNonReferenceType(); 2469 2470 // FIXME: Does the addition of const really only apply in 2471 // potentially-evaluated contexts? Since the variable isn't actually 2472 // captured in an unevaluated context, it seems that the answer is no. 2473 if (!isUnevaluatedContext()) { 2474 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2475 if (!CapturedType.isNull()) 2476 type = CapturedType; 2477 } 2478 2479 break; 2480 } 2481 2482 case Decl::Function: { 2483 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2484 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2485 type = Context.BuiltinFnTy; 2486 valueKind = VK_RValue; 2487 break; 2488 } 2489 } 2490 2491 const FunctionType *fty = type->castAs<FunctionType>(); 2492 2493 // If we're referring to a function with an __unknown_anytype 2494 // result type, make the entire expression __unknown_anytype. 2495 if (fty->getResultType() == Context.UnknownAnyTy) { 2496 type = Context.UnknownAnyTy; 2497 valueKind = VK_RValue; 2498 break; 2499 } 2500 2501 // Functions are l-values in C++. 2502 if (getLangOpts().CPlusPlus) { 2503 valueKind = VK_LValue; 2504 break; 2505 } 2506 2507 // C99 DR 316 says that, if a function type comes from a 2508 // function definition (without a prototype), that type is only 2509 // used for checking compatibility. Therefore, when referencing 2510 // the function, we pretend that we don't have the full function 2511 // type. 2512 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2513 isa<FunctionProtoType>(fty)) 2514 type = Context.getFunctionNoProtoType(fty->getResultType(), 2515 fty->getExtInfo()); 2516 2517 // Functions are r-values in C. 2518 valueKind = VK_RValue; 2519 break; 2520 } 2521 2522 case Decl::CXXMethod: 2523 // If we're referring to a method with an __unknown_anytype 2524 // result type, make the entire expression __unknown_anytype. 2525 // This should only be possible with a type written directly. 2526 if (const FunctionProtoType *proto 2527 = dyn_cast<FunctionProtoType>(VD->getType())) 2528 if (proto->getResultType() == Context.UnknownAnyTy) { 2529 type = Context.UnknownAnyTy; 2530 valueKind = VK_RValue; 2531 break; 2532 } 2533 2534 // C++ methods are l-values if static, r-values if non-static. 2535 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2536 valueKind = VK_LValue; 2537 break; 2538 } 2539 // fallthrough 2540 2541 case Decl::CXXConversion: 2542 case Decl::CXXDestructor: 2543 case Decl::CXXConstructor: 2544 valueKind = VK_RValue; 2545 break; 2546 } 2547 2548 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS); 2549 } 2550 } 2551 2552 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2553 PredefinedExpr::IdentType IT; 2554 2555 switch (Kind) { 2556 default: llvm_unreachable("Unknown simple primary expr!"); 2557 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2558 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2559 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2560 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2561 } 2562 2563 // Pre-defined identifiers are of type char[x], where x is the length of the 2564 // string. 2565 2566 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2567 // Blocks and lambdas can occur at global scope. Don't emit a warning. 2568 if (!currentDecl) { 2569 if (const BlockScopeInfo *BSI = getCurBlock()) 2570 currentDecl = BSI->TheDecl; 2571 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2572 currentDecl = LSI->CallOperator; 2573 } 2574 2575 if (!currentDecl) { 2576 Diag(Loc, diag::ext_predef_outside_function); 2577 currentDecl = Context.getTranslationUnitDecl(); 2578 } 2579 2580 QualType ResTy; 2581 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2582 ResTy = Context.DependentTy; 2583 } else { 2584 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2585 2586 llvm::APInt LengthI(32, Length + 1); 2587 if (IT == PredefinedExpr::LFunction) 2588 ResTy = Context.WCharTy.withConst(); 2589 else 2590 ResTy = Context.CharTy.withConst(); 2591 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2592 } 2593 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2594 } 2595 2596 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2597 SmallString<16> CharBuffer; 2598 bool Invalid = false; 2599 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2600 if (Invalid) 2601 return ExprError(); 2602 2603 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2604 PP, Tok.getKind()); 2605 if (Literal.hadError()) 2606 return ExprError(); 2607 2608 QualType Ty; 2609 if (Literal.isWide()) 2610 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++. 2611 else if (Literal.isUTF16()) 2612 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2613 else if (Literal.isUTF32()) 2614 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2615 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2616 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2617 else 2618 Ty = Context.CharTy; // 'x' -> char in C++ 2619 2620 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2621 if (Literal.isWide()) 2622 Kind = CharacterLiteral::Wide; 2623 else if (Literal.isUTF16()) 2624 Kind = CharacterLiteral::UTF16; 2625 else if (Literal.isUTF32()) 2626 Kind = CharacterLiteral::UTF32; 2627 2628 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2629 Tok.getLocation()); 2630 2631 if (Literal.getUDSuffix().empty()) 2632 return Owned(Lit); 2633 2634 // We're building a user-defined literal. 2635 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2636 SourceLocation UDSuffixLoc = 2637 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2638 2639 // Make sure we're allowed user-defined literals here. 2640 if (!UDLScope) 2641 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2642 2643 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2644 // operator "" X (ch) 2645 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2646 llvm::makeArrayRef(&Lit, 1), 2647 Tok.getLocation()); 2648 } 2649 2650 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2651 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2652 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2653 Context.IntTy, Loc)); 2654 } 2655 2656 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2657 QualType Ty, SourceLocation Loc) { 2658 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2659 2660 using llvm::APFloat; 2661 APFloat Val(Format); 2662 2663 APFloat::opStatus result = Literal.GetFloatValue(Val); 2664 2665 // Overflow is always an error, but underflow is only an error if 2666 // we underflowed to zero (APFloat reports denormals as underflow). 2667 if ((result & APFloat::opOverflow) || 2668 ((result & APFloat::opUnderflow) && Val.isZero())) { 2669 unsigned diagnostic; 2670 SmallString<20> buffer; 2671 if (result & APFloat::opOverflow) { 2672 diagnostic = diag::warn_float_overflow; 2673 APFloat::getLargest(Format).toString(buffer); 2674 } else { 2675 diagnostic = diag::warn_float_underflow; 2676 APFloat::getSmallest(Format).toString(buffer); 2677 } 2678 2679 S.Diag(Loc, diagnostic) 2680 << Ty 2681 << StringRef(buffer.data(), buffer.size()); 2682 } 2683 2684 bool isExact = (result == APFloat::opOK); 2685 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2686 } 2687 2688 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2689 // Fast path for a single digit (which is quite common). A single digit 2690 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2691 if (Tok.getLength() == 1) { 2692 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2693 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2694 } 2695 2696 SmallString<128> SpellingBuffer; 2697 // NumericLiteralParser wants to overread by one character. Add padding to 2698 // the buffer in case the token is copied to the buffer. If getSpelling() 2699 // returns a StringRef to the memory buffer, it should have a null char at 2700 // the EOF, so it is also safe. 2701 SpellingBuffer.resize(Tok.getLength() + 1); 2702 2703 // Get the spelling of the token, which eliminates trigraphs, etc. 2704 bool Invalid = false; 2705 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2706 if (Invalid) 2707 return ExprError(); 2708 2709 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2710 if (Literal.hadError) 2711 return ExprError(); 2712 2713 if (Literal.hasUDSuffix()) { 2714 // We're building a user-defined literal. 2715 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2716 SourceLocation UDSuffixLoc = 2717 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2718 2719 // Make sure we're allowed user-defined literals here. 2720 if (!UDLScope) 2721 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2722 2723 QualType CookedTy; 2724 if (Literal.isFloatingLiteral()) { 2725 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2726 // long double, the literal is treated as a call of the form 2727 // operator "" X (f L) 2728 CookedTy = Context.LongDoubleTy; 2729 } else { 2730 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2731 // unsigned long long, the literal is treated as a call of the form 2732 // operator "" X (n ULL) 2733 CookedTy = Context.UnsignedLongLongTy; 2734 } 2735 2736 DeclarationName OpName = 2737 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2738 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2739 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2740 2741 // Perform literal operator lookup to determine if we're building a raw 2742 // literal or a cooked one. 2743 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2744 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1), 2745 /*AllowRawAndTemplate*/true)) { 2746 case LOLR_Error: 2747 return ExprError(); 2748 2749 case LOLR_Cooked: { 2750 Expr *Lit; 2751 if (Literal.isFloatingLiteral()) { 2752 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2753 } else { 2754 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2755 if (Literal.GetIntegerValue(ResultVal)) 2756 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2757 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2758 Tok.getLocation()); 2759 } 2760 return BuildLiteralOperatorCall(R, OpNameInfo, 2761 llvm::makeArrayRef(&Lit, 1), 2762 Tok.getLocation()); 2763 } 2764 2765 case LOLR_Raw: { 2766 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2767 // literal is treated as a call of the form 2768 // operator "" X ("n") 2769 SourceLocation TokLoc = Tok.getLocation(); 2770 unsigned Length = Literal.getUDSuffixOffset(); 2771 QualType StrTy = Context.getConstantArrayType( 2772 Context.CharTy, llvm::APInt(32, Length + 1), 2773 ArrayType::Normal, 0); 2774 Expr *Lit = StringLiteral::Create( 2775 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 2776 /*Pascal*/false, StrTy, &TokLoc, 1); 2777 return BuildLiteralOperatorCall(R, OpNameInfo, 2778 llvm::makeArrayRef(&Lit, 1), TokLoc); 2779 } 2780 2781 case LOLR_Template: 2782 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2783 // template), L is treated as a call fo the form 2784 // operator "" X <'c1', 'c2', ... 'ck'>() 2785 // where n is the source character sequence c1 c2 ... ck. 2786 TemplateArgumentListInfo ExplicitArgs; 2787 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2788 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2789 llvm::APSInt Value(CharBits, CharIsUnsigned); 2790 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2791 Value = TokSpelling[I]; 2792 TemplateArgument Arg(Context, Value, Context.CharTy); 2793 TemplateArgumentLocInfo ArgInfo; 2794 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2795 } 2796 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(), 2797 Tok.getLocation(), &ExplicitArgs); 2798 } 2799 2800 llvm_unreachable("unexpected literal operator lookup result"); 2801 } 2802 2803 Expr *Res; 2804 2805 if (Literal.isFloatingLiteral()) { 2806 QualType Ty; 2807 if (Literal.isFloat) 2808 Ty = Context.FloatTy; 2809 else if (!Literal.isLong) 2810 Ty = Context.DoubleTy; 2811 else 2812 Ty = Context.LongDoubleTy; 2813 2814 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 2815 2816 if (Ty == Context.DoubleTy) { 2817 if (getLangOpts().SinglePrecisionConstants) { 2818 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2819 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2820 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2821 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2822 } 2823 } 2824 } else if (!Literal.isIntegerLiteral()) { 2825 return ExprError(); 2826 } else { 2827 QualType Ty; 2828 2829 // 'long long' is a C99 or C++11 feature. 2830 if (!getLangOpts().C99 && Literal.isLongLong) { 2831 if (getLangOpts().CPlusPlus) 2832 Diag(Tok.getLocation(), 2833 getLangOpts().CPlusPlus11 ? 2834 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 2835 else 2836 Diag(Tok.getLocation(), diag::ext_c99_longlong); 2837 } 2838 2839 // Get the value in the widest-possible width. 2840 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 2841 // The microsoft literal suffix extensions support 128-bit literals, which 2842 // may be wider than [u]intmax_t. 2843 // FIXME: Actually, they don't. We seem to have accidentally invented the 2844 // i128 suffix. 2845 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 2846 PP.getTargetInfo().hasInt128Type()) 2847 MaxWidth = 128; 2848 llvm::APInt ResultVal(MaxWidth, 0); 2849 2850 if (Literal.GetIntegerValue(ResultVal)) { 2851 // If this value didn't fit into uintmax_t, warn and force to ull. 2852 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2853 Ty = Context.UnsignedLongLongTy; 2854 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2855 "long long is not intmax_t?"); 2856 } else { 2857 // If this value fits into a ULL, try to figure out what else it fits into 2858 // according to the rules of C99 6.4.4.1p5. 2859 2860 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2861 // be an unsigned int. 2862 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2863 2864 // Check from smallest to largest, picking the smallest type we can. 2865 unsigned Width = 0; 2866 if (!Literal.isLong && !Literal.isLongLong) { 2867 // Are int/unsigned possibilities? 2868 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2869 2870 // Does it fit in a unsigned int? 2871 if (ResultVal.isIntN(IntSize)) { 2872 // Does it fit in a signed int? 2873 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2874 Ty = Context.IntTy; 2875 else if (AllowUnsigned) 2876 Ty = Context.UnsignedIntTy; 2877 Width = IntSize; 2878 } 2879 } 2880 2881 // Are long/unsigned long possibilities? 2882 if (Ty.isNull() && !Literal.isLongLong) { 2883 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 2884 2885 // Does it fit in a unsigned long? 2886 if (ResultVal.isIntN(LongSize)) { 2887 // Does it fit in a signed long? 2888 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2889 Ty = Context.LongTy; 2890 else if (AllowUnsigned) 2891 Ty = Context.UnsignedLongTy; 2892 Width = LongSize; 2893 } 2894 } 2895 2896 // Check long long if needed. 2897 if (Ty.isNull()) { 2898 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 2899 2900 // Does it fit in a unsigned long long? 2901 if (ResultVal.isIntN(LongLongSize)) { 2902 // Does it fit in a signed long long? 2903 // To be compatible with MSVC, hex integer literals ending with the 2904 // LL or i64 suffix are always signed in Microsoft mode. 2905 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 2906 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 2907 Ty = Context.LongLongTy; 2908 else if (AllowUnsigned) 2909 Ty = Context.UnsignedLongLongTy; 2910 Width = LongLongSize; 2911 } 2912 } 2913 2914 // If it doesn't fit in unsigned long long, and we're using Microsoft 2915 // extensions, then its a 128-bit integer literal. 2916 if (Ty.isNull() && Literal.isMicrosoftInteger && 2917 PP.getTargetInfo().hasInt128Type()) { 2918 if (Literal.isUnsigned) 2919 Ty = Context.UnsignedInt128Ty; 2920 else 2921 Ty = Context.Int128Ty; 2922 Width = 128; 2923 } 2924 2925 // If we still couldn't decide a type, we probably have something that 2926 // does not fit in a signed long long, but has no U suffix. 2927 if (Ty.isNull()) { 2928 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2929 Ty = Context.UnsignedLongLongTy; 2930 Width = Context.getTargetInfo().getLongLongWidth(); 2931 } 2932 2933 if (ResultVal.getBitWidth() != Width) 2934 ResultVal = ResultVal.trunc(Width); 2935 } 2936 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 2937 } 2938 2939 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2940 if (Literal.isImaginary) 2941 Res = new (Context) ImaginaryLiteral(Res, 2942 Context.getComplexType(Res->getType())); 2943 2944 return Owned(Res); 2945 } 2946 2947 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 2948 assert((E != 0) && "ActOnParenExpr() missing expr"); 2949 return Owned(new (Context) ParenExpr(L, R, E)); 2950 } 2951 2952 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 2953 SourceLocation Loc, 2954 SourceRange ArgRange) { 2955 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 2956 // scalar or vector data type argument..." 2957 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 2958 // type (C99 6.2.5p18) or void. 2959 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 2960 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 2961 << T << ArgRange; 2962 return true; 2963 } 2964 2965 assert((T->isVoidType() || !T->isIncompleteType()) && 2966 "Scalar types should always be complete"); 2967 return false; 2968 } 2969 2970 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 2971 SourceLocation Loc, 2972 SourceRange ArgRange, 2973 UnaryExprOrTypeTrait TraitKind) { 2974 // C99 6.5.3.4p1: 2975 if (T->isFunctionType()) { 2976 // alignof(function) is allowed as an extension. 2977 if (TraitKind == UETT_SizeOf) 2978 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange; 2979 return false; 2980 } 2981 2982 // Allow sizeof(void)/alignof(void) as an extension. 2983 if (T->isVoidType()) { 2984 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange; 2985 return false; 2986 } 2987 2988 return true; 2989 } 2990 2991 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 2992 SourceLocation Loc, 2993 SourceRange ArgRange, 2994 UnaryExprOrTypeTrait TraitKind) { 2995 // Reject sizeof(interface) and sizeof(interface<proto>) if the 2996 // runtime doesn't allow it. 2997 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 2998 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 2999 << T << (TraitKind == UETT_SizeOf) 3000 << ArgRange; 3001 return true; 3002 } 3003 3004 return false; 3005 } 3006 3007 /// \brief Check the constrains on expression operands to unary type expression 3008 /// and type traits. 3009 /// 3010 /// Completes any types necessary and validates the constraints on the operand 3011 /// expression. The logic mostly mirrors the type-based overload, but may modify 3012 /// the expression as it completes the type for that expression through template 3013 /// instantiation, etc. 3014 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3015 UnaryExprOrTypeTrait ExprKind) { 3016 QualType ExprTy = E->getType(); 3017 3018 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3019 // the result is the size of the referenced type." 3020 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3021 // result shall be the alignment of the referenced type." 3022 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 3023 ExprTy = Ref->getPointeeType(); 3024 3025 if (ExprKind == UETT_VecStep) 3026 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3027 E->getSourceRange()); 3028 3029 // Whitelist some types as extensions 3030 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3031 E->getSourceRange(), ExprKind)) 3032 return false; 3033 3034 if (RequireCompleteExprType(E, 3035 diag::err_sizeof_alignof_incomplete_type, 3036 ExprKind, E->getSourceRange())) 3037 return true; 3038 3039 // Completeing the expression's type may have changed it. 3040 ExprTy = E->getType(); 3041 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 3042 ExprTy = Ref->getPointeeType(); 3043 3044 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3045 E->getSourceRange(), ExprKind)) 3046 return true; 3047 3048 if (ExprKind == UETT_SizeOf) { 3049 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3050 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3051 QualType OType = PVD->getOriginalType(); 3052 QualType Type = PVD->getType(); 3053 if (Type->isPointerType() && OType->isArrayType()) { 3054 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3055 << Type << OType; 3056 Diag(PVD->getLocation(), diag::note_declared_at); 3057 } 3058 } 3059 } 3060 } 3061 3062 return false; 3063 } 3064 3065 /// \brief Check the constraints on operands to unary expression and type 3066 /// traits. 3067 /// 3068 /// This will complete any types necessary, and validate the various constraints 3069 /// on those operands. 3070 /// 3071 /// The UsualUnaryConversions() function is *not* called by this routine. 3072 /// C99 6.3.2.1p[2-4] all state: 3073 /// Except when it is the operand of the sizeof operator ... 3074 /// 3075 /// C++ [expr.sizeof]p4 3076 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3077 /// standard conversions are not applied to the operand of sizeof. 3078 /// 3079 /// This policy is followed for all of the unary trait expressions. 3080 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3081 SourceLocation OpLoc, 3082 SourceRange ExprRange, 3083 UnaryExprOrTypeTrait ExprKind) { 3084 if (ExprType->isDependentType()) 3085 return false; 3086 3087 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3088 // the result is the size of the referenced type." 3089 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3090 // result shall be the alignment of the referenced type." 3091 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3092 ExprType = Ref->getPointeeType(); 3093 3094 if (ExprKind == UETT_VecStep) 3095 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3096 3097 // Whitelist some types as extensions 3098 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3099 ExprKind)) 3100 return false; 3101 3102 if (RequireCompleteType(OpLoc, ExprType, 3103 diag::err_sizeof_alignof_incomplete_type, 3104 ExprKind, ExprRange)) 3105 return true; 3106 3107 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3108 ExprKind)) 3109 return true; 3110 3111 return false; 3112 } 3113 3114 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3115 E = E->IgnoreParens(); 3116 3117 // alignof decl is always ok. 3118 if (isa<DeclRefExpr>(E)) 3119 return false; 3120 3121 // Cannot know anything else if the expression is dependent. 3122 if (E->isTypeDependent()) 3123 return false; 3124 3125 if (E->getBitField()) { 3126 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3127 << 1 << E->getSourceRange(); 3128 return true; 3129 } 3130 3131 // Alignment of a field access is always okay, so long as it isn't a 3132 // bit-field. 3133 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 3134 if (isa<FieldDecl>(ME->getMemberDecl())) 3135 return false; 3136 3137 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3138 } 3139 3140 bool Sema::CheckVecStepExpr(Expr *E) { 3141 E = E->IgnoreParens(); 3142 3143 // Cannot know anything else if the expression is dependent. 3144 if (E->isTypeDependent()) 3145 return false; 3146 3147 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3148 } 3149 3150 /// \brief Build a sizeof or alignof expression given a type operand. 3151 ExprResult 3152 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3153 SourceLocation OpLoc, 3154 UnaryExprOrTypeTrait ExprKind, 3155 SourceRange R) { 3156 if (!TInfo) 3157 return ExprError(); 3158 3159 QualType T = TInfo->getType(); 3160 3161 if (!T->isDependentType() && 3162 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3163 return ExprError(); 3164 3165 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3166 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3167 Context.getSizeType(), 3168 OpLoc, R.getEnd())); 3169 } 3170 3171 /// \brief Build a sizeof or alignof expression given an expression 3172 /// operand. 3173 ExprResult 3174 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3175 UnaryExprOrTypeTrait ExprKind) { 3176 ExprResult PE = CheckPlaceholderExpr(E); 3177 if (PE.isInvalid()) 3178 return ExprError(); 3179 3180 E = PE.get(); 3181 3182 // Verify that the operand is valid. 3183 bool isInvalid = false; 3184 if (E->isTypeDependent()) { 3185 // Delay type-checking for type-dependent expressions. 3186 } else if (ExprKind == UETT_AlignOf) { 3187 isInvalid = CheckAlignOfExpr(*this, E); 3188 } else if (ExprKind == UETT_VecStep) { 3189 isInvalid = CheckVecStepExpr(E); 3190 } else if (E->getBitField()) { // C99 6.5.3.4p1. 3191 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3192 isInvalid = true; 3193 } else { 3194 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3195 } 3196 3197 if (isInvalid) 3198 return ExprError(); 3199 3200 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3201 PE = TransformToPotentiallyEvaluated(E); 3202 if (PE.isInvalid()) return ExprError(); 3203 E = PE.take(); 3204 } 3205 3206 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3207 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3208 ExprKind, E, Context.getSizeType(), OpLoc, 3209 E->getSourceRange().getEnd())); 3210 } 3211 3212 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3213 /// expr and the same for @c alignof and @c __alignof 3214 /// Note that the ArgRange is invalid if isType is false. 3215 ExprResult 3216 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3217 UnaryExprOrTypeTrait ExprKind, bool IsType, 3218 void *TyOrEx, const SourceRange &ArgRange) { 3219 // If error parsing type, ignore. 3220 if (TyOrEx == 0) return ExprError(); 3221 3222 if (IsType) { 3223 TypeSourceInfo *TInfo; 3224 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3225 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3226 } 3227 3228 Expr *ArgEx = (Expr *)TyOrEx; 3229 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3230 return Result; 3231 } 3232 3233 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3234 bool IsReal) { 3235 if (V.get()->isTypeDependent()) 3236 return S.Context.DependentTy; 3237 3238 // _Real and _Imag are only l-values for normal l-values. 3239 if (V.get()->getObjectKind() != OK_Ordinary) { 3240 V = S.DefaultLvalueConversion(V.take()); 3241 if (V.isInvalid()) 3242 return QualType(); 3243 } 3244 3245 // These operators return the element type of a complex type. 3246 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3247 return CT->getElementType(); 3248 3249 // Otherwise they pass through real integer and floating point types here. 3250 if (V.get()->getType()->isArithmeticType()) 3251 return V.get()->getType(); 3252 3253 // Test for placeholders. 3254 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3255 if (PR.isInvalid()) return QualType(); 3256 if (PR.get() != V.get()) { 3257 V = PR; 3258 return CheckRealImagOperand(S, V, Loc, IsReal); 3259 } 3260 3261 // Reject anything else. 3262 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3263 << (IsReal ? "__real" : "__imag"); 3264 return QualType(); 3265 } 3266 3267 3268 3269 ExprResult 3270 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3271 tok::TokenKind Kind, Expr *Input) { 3272 UnaryOperatorKind Opc; 3273 switch (Kind) { 3274 default: llvm_unreachable("Unknown unary op!"); 3275 case tok::plusplus: Opc = UO_PostInc; break; 3276 case tok::minusminus: Opc = UO_PostDec; break; 3277 } 3278 3279 // Since this might is a postfix expression, get rid of ParenListExprs. 3280 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3281 if (Result.isInvalid()) return ExprError(); 3282 Input = Result.take(); 3283 3284 return BuildUnaryOp(S, OpLoc, Opc, Input); 3285 } 3286 3287 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3288 /// 3289 /// \return true on error 3290 static bool checkArithmeticOnObjCPointer(Sema &S, 3291 SourceLocation opLoc, 3292 Expr *op) { 3293 assert(op->getType()->isObjCObjectPointerType()); 3294 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3295 return false; 3296 3297 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3298 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3299 << op->getSourceRange(); 3300 return true; 3301 } 3302 3303 ExprResult 3304 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 3305 Expr *Idx, SourceLocation RLoc) { 3306 // Since this might be a postfix expression, get rid of ParenListExprs. 3307 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 3308 if (Result.isInvalid()) return ExprError(); 3309 Base = Result.take(); 3310 3311 Expr *LHSExp = Base, *RHSExp = Idx; 3312 3313 if (getLangOpts().CPlusPlus && 3314 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 3315 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3316 Context.DependentTy, 3317 VK_LValue, OK_Ordinary, 3318 RLoc)); 3319 } 3320 3321 if (getLangOpts().CPlusPlus && 3322 (LHSExp->getType()->isRecordType() || 3323 LHSExp->getType()->isEnumeralType() || 3324 RHSExp->getType()->isRecordType() || 3325 RHSExp->getType()->isEnumeralType()) && 3326 !LHSExp->getType()->isObjCObjectPointerType()) { 3327 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 3328 } 3329 3330 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 3331 } 3332 3333 ExprResult 3334 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3335 Expr *Idx, SourceLocation RLoc) { 3336 Expr *LHSExp = Base; 3337 Expr *RHSExp = Idx; 3338 3339 // Perform default conversions. 3340 if (!LHSExp->getType()->getAs<VectorType>()) { 3341 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3342 if (Result.isInvalid()) 3343 return ExprError(); 3344 LHSExp = Result.take(); 3345 } 3346 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3347 if (Result.isInvalid()) 3348 return ExprError(); 3349 RHSExp = Result.take(); 3350 3351 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3352 ExprValueKind VK = VK_LValue; 3353 ExprObjectKind OK = OK_Ordinary; 3354 3355 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3356 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3357 // in the subscript position. As a result, we need to derive the array base 3358 // and index from the expression types. 3359 Expr *BaseExpr, *IndexExpr; 3360 QualType ResultType; 3361 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3362 BaseExpr = LHSExp; 3363 IndexExpr = RHSExp; 3364 ResultType = Context.DependentTy; 3365 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3366 BaseExpr = LHSExp; 3367 IndexExpr = RHSExp; 3368 ResultType = PTy->getPointeeType(); 3369 } else if (const ObjCObjectPointerType *PTy = 3370 LHSTy->getAs<ObjCObjectPointerType>()) { 3371 BaseExpr = LHSExp; 3372 IndexExpr = RHSExp; 3373 3374 // Use custom logic if this should be the pseudo-object subscript 3375 // expression. 3376 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()) 3377 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3378 3379 ResultType = PTy->getPointeeType(); 3380 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3381 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3382 << ResultType << BaseExpr->getSourceRange(); 3383 return ExprError(); 3384 } 3385 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3386 // Handle the uncommon case of "123[Ptr]". 3387 BaseExpr = RHSExp; 3388 IndexExpr = LHSExp; 3389 ResultType = PTy->getPointeeType(); 3390 } else if (const ObjCObjectPointerType *PTy = 3391 RHSTy->getAs<ObjCObjectPointerType>()) { 3392 // Handle the uncommon case of "123[Ptr]". 3393 BaseExpr = RHSExp; 3394 IndexExpr = LHSExp; 3395 ResultType = PTy->getPointeeType(); 3396 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3397 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3398 << ResultType << BaseExpr->getSourceRange(); 3399 return ExprError(); 3400 } 3401 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3402 BaseExpr = LHSExp; // vectors: V[123] 3403 IndexExpr = RHSExp; 3404 VK = LHSExp->getValueKind(); 3405 if (VK != VK_RValue) 3406 OK = OK_VectorComponent; 3407 3408 // FIXME: need to deal with const... 3409 ResultType = VTy->getElementType(); 3410 } else if (LHSTy->isArrayType()) { 3411 // If we see an array that wasn't promoted by 3412 // DefaultFunctionArrayLvalueConversion, it must be an array that 3413 // wasn't promoted because of the C90 rule that doesn't 3414 // allow promoting non-lvalue arrays. Warn, then 3415 // force the promotion here. 3416 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3417 LHSExp->getSourceRange(); 3418 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3419 CK_ArrayToPointerDecay).take(); 3420 LHSTy = LHSExp->getType(); 3421 3422 BaseExpr = LHSExp; 3423 IndexExpr = RHSExp; 3424 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3425 } else if (RHSTy->isArrayType()) { 3426 // Same as previous, except for 123[f().a] case 3427 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3428 RHSExp->getSourceRange(); 3429 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3430 CK_ArrayToPointerDecay).take(); 3431 RHSTy = RHSExp->getType(); 3432 3433 BaseExpr = RHSExp; 3434 IndexExpr = LHSExp; 3435 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3436 } else { 3437 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3438 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3439 } 3440 // C99 6.5.2.1p1 3441 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3442 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3443 << IndexExpr->getSourceRange()); 3444 3445 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3446 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3447 && !IndexExpr->isTypeDependent()) 3448 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3449 3450 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3451 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3452 // type. Note that Functions are not objects, and that (in C99 parlance) 3453 // incomplete types are not object types. 3454 if (ResultType->isFunctionType()) { 3455 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3456 << ResultType << BaseExpr->getSourceRange(); 3457 return ExprError(); 3458 } 3459 3460 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3461 // GNU extension: subscripting on pointer to void 3462 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3463 << BaseExpr->getSourceRange(); 3464 3465 // C forbids expressions of unqualified void type from being l-values. 3466 // See IsCForbiddenLValueType. 3467 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3468 } else if (!ResultType->isDependentType() && 3469 RequireCompleteType(LLoc, ResultType, 3470 diag::err_subscript_incomplete_type, BaseExpr)) 3471 return ExprError(); 3472 3473 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3474 !ResultType.isCForbiddenLValueType()); 3475 3476 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3477 ResultType, VK, OK, RLoc)); 3478 } 3479 3480 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3481 FunctionDecl *FD, 3482 ParmVarDecl *Param) { 3483 if (Param->hasUnparsedDefaultArg()) { 3484 Diag(CallLoc, 3485 diag::err_use_of_default_argument_to_function_declared_later) << 3486 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3487 Diag(UnparsedDefaultArgLocs[Param], 3488 diag::note_default_argument_declared_here); 3489 return ExprError(); 3490 } 3491 3492 if (Param->hasUninstantiatedDefaultArg()) { 3493 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3494 3495 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3496 Param); 3497 3498 // Instantiate the expression. 3499 MultiLevelTemplateArgumentList ArgList 3500 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3501 3502 std::pair<const TemplateArgument *, unsigned> Innermost 3503 = ArgList.getInnermost(); 3504 InstantiatingTemplate Inst(*this, CallLoc, Param, 3505 ArrayRef<TemplateArgument>(Innermost.first, 3506 Innermost.second)); 3507 if (Inst) 3508 return ExprError(); 3509 3510 ExprResult Result; 3511 { 3512 // C++ [dcl.fct.default]p5: 3513 // The names in the [default argument] expression are bound, and 3514 // the semantic constraints are checked, at the point where the 3515 // default argument expression appears. 3516 ContextRAII SavedContext(*this, FD); 3517 LocalInstantiationScope Local(*this); 3518 Result = SubstExpr(UninstExpr, ArgList); 3519 } 3520 if (Result.isInvalid()) 3521 return ExprError(); 3522 3523 // Check the expression as an initializer for the parameter. 3524 InitializedEntity Entity 3525 = InitializedEntity::InitializeParameter(Context, Param); 3526 InitializationKind Kind 3527 = InitializationKind::CreateCopy(Param->getLocation(), 3528 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3529 Expr *ResultE = Result.takeAs<Expr>(); 3530 3531 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3532 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3533 if (Result.isInvalid()) 3534 return ExprError(); 3535 3536 Expr *Arg = Result.takeAs<Expr>(); 3537 CheckImplicitConversions(Arg, Param->getOuterLocStart()); 3538 // Build the default argument expression. 3539 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3540 } 3541 3542 // If the default expression creates temporaries, we need to 3543 // push them to the current stack of expression temporaries so they'll 3544 // be properly destroyed. 3545 // FIXME: We should really be rebuilding the default argument with new 3546 // bound temporaries; see the comment in PR5810. 3547 // We don't need to do that with block decls, though, because 3548 // blocks in default argument expression can never capture anything. 3549 if (isa<ExprWithCleanups>(Param->getInit())) { 3550 // Set the "needs cleanups" bit regardless of whether there are 3551 // any explicit objects. 3552 ExprNeedsCleanups = true; 3553 3554 // Append all the objects to the cleanup list. Right now, this 3555 // should always be a no-op, because blocks in default argument 3556 // expressions should never be able to capture anything. 3557 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3558 "default argument expression has capturing blocks?"); 3559 } 3560 3561 // We already type-checked the argument, so we know it works. 3562 // Just mark all of the declarations in this potentially-evaluated expression 3563 // as being "referenced". 3564 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3565 /*SkipLocalVariables=*/true); 3566 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3567 } 3568 3569 3570 Sema::VariadicCallType 3571 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3572 Expr *Fn) { 3573 if (Proto && Proto->isVariadic()) { 3574 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3575 return VariadicConstructor; 3576 else if (Fn && Fn->getType()->isBlockPointerType()) 3577 return VariadicBlock; 3578 else if (FDecl) { 3579 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3580 if (Method->isInstance()) 3581 return VariadicMethod; 3582 } 3583 return VariadicFunction; 3584 } 3585 return VariadicDoesNotApply; 3586 } 3587 3588 /// ConvertArgumentsForCall - Converts the arguments specified in 3589 /// Args/NumArgs to the parameter types of the function FDecl with 3590 /// function prototype Proto. Call is the call expression itself, and 3591 /// Fn is the function expression. For a C++ member function, this 3592 /// routine does not attempt to convert the object argument. Returns 3593 /// true if the call is ill-formed. 3594 bool 3595 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3596 FunctionDecl *FDecl, 3597 const FunctionProtoType *Proto, 3598 Expr **Args, unsigned NumArgs, 3599 SourceLocation RParenLoc, 3600 bool IsExecConfig) { 3601 // Bail out early if calling a builtin with custom typechecking. 3602 // We don't need to do this in the 3603 if (FDecl) 3604 if (unsigned ID = FDecl->getBuiltinID()) 3605 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3606 return false; 3607 3608 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3609 // assignment, to the types of the corresponding parameter, ... 3610 unsigned NumArgsInProto = Proto->getNumArgs(); 3611 bool Invalid = false; 3612 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3613 unsigned FnKind = Fn->getType()->isBlockPointerType() 3614 ? 1 /* block */ 3615 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3616 : 0 /* function */); 3617 3618 // If too few arguments are available (and we don't have default 3619 // arguments for the remaining parameters), don't make the call. 3620 if (NumArgs < NumArgsInProto) { 3621 if (NumArgs < MinArgs) { 3622 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3623 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3624 ? diag::err_typecheck_call_too_few_args_one 3625 : diag::err_typecheck_call_too_few_args_at_least_one) 3626 << FnKind 3627 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 3628 else 3629 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3630 ? diag::err_typecheck_call_too_few_args 3631 : diag::err_typecheck_call_too_few_args_at_least) 3632 << FnKind 3633 << MinArgs << NumArgs << Fn->getSourceRange(); 3634 3635 // Emit the location of the prototype. 3636 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3637 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3638 << FDecl; 3639 3640 return true; 3641 } 3642 Call->setNumArgs(Context, NumArgsInProto); 3643 } 3644 3645 // If too many are passed and not variadic, error on the extras and drop 3646 // them. 3647 if (NumArgs > NumArgsInProto) { 3648 if (!Proto->isVariadic()) { 3649 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3650 Diag(Args[NumArgsInProto]->getLocStart(), 3651 MinArgs == NumArgsInProto 3652 ? diag::err_typecheck_call_too_many_args_one 3653 : diag::err_typecheck_call_too_many_args_at_most_one) 3654 << FnKind 3655 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange() 3656 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3657 Args[NumArgs-1]->getLocEnd()); 3658 else 3659 Diag(Args[NumArgsInProto]->getLocStart(), 3660 MinArgs == NumArgsInProto 3661 ? diag::err_typecheck_call_too_many_args 3662 : diag::err_typecheck_call_too_many_args_at_most) 3663 << FnKind 3664 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3665 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3666 Args[NumArgs-1]->getLocEnd()); 3667 3668 // Emit the location of the prototype. 3669 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3670 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3671 << FDecl; 3672 3673 // This deletes the extra arguments. 3674 Call->setNumArgs(Context, NumArgsInProto); 3675 return true; 3676 } 3677 } 3678 SmallVector<Expr *, 8> AllArgs; 3679 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 3680 3681 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 3682 Proto, 0, Args, NumArgs, AllArgs, CallType); 3683 if (Invalid) 3684 return true; 3685 unsigned TotalNumArgs = AllArgs.size(); 3686 for (unsigned i = 0; i < TotalNumArgs; ++i) 3687 Call->setArg(i, AllArgs[i]); 3688 3689 return false; 3690 } 3691 3692 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3693 FunctionDecl *FDecl, 3694 const FunctionProtoType *Proto, 3695 unsigned FirstProtoArg, 3696 Expr **Args, unsigned NumArgs, 3697 SmallVector<Expr *, 8> &AllArgs, 3698 VariadicCallType CallType, 3699 bool AllowExplicit) { 3700 unsigned NumArgsInProto = Proto->getNumArgs(); 3701 unsigned NumArgsToCheck = NumArgs; 3702 bool Invalid = false; 3703 if (NumArgs != NumArgsInProto) 3704 // Use default arguments for missing arguments 3705 NumArgsToCheck = NumArgsInProto; 3706 unsigned ArgIx = 0; 3707 // Continue to check argument types (even if we have too few/many args). 3708 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3709 QualType ProtoArgType = Proto->getArgType(i); 3710 3711 Expr *Arg; 3712 ParmVarDecl *Param; 3713 if (ArgIx < NumArgs) { 3714 Arg = Args[ArgIx++]; 3715 3716 if (RequireCompleteType(Arg->getLocStart(), 3717 ProtoArgType, 3718 diag::err_call_incomplete_argument, Arg)) 3719 return true; 3720 3721 // Pass the argument 3722 Param = 0; 3723 if (FDecl && i < FDecl->getNumParams()) 3724 Param = FDecl->getParamDecl(i); 3725 3726 // Strip the unbridged-cast placeholder expression off, if applicable. 3727 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3728 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3729 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3730 Arg = stripARCUnbridgedCast(Arg); 3731 3732 InitializedEntity Entity = Param ? 3733 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType) 3734 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3735 Proto->isArgConsumed(i)); 3736 ExprResult ArgE = PerformCopyInitialization(Entity, 3737 SourceLocation(), 3738 Owned(Arg), 3739 /*TopLevelOfInitList=*/false, 3740 AllowExplicit); 3741 if (ArgE.isInvalid()) 3742 return true; 3743 3744 Arg = ArgE.takeAs<Expr>(); 3745 } else { 3746 Param = FDecl->getParamDecl(i); 3747 3748 ExprResult ArgExpr = 3749 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3750 if (ArgExpr.isInvalid()) 3751 return true; 3752 3753 Arg = ArgExpr.takeAs<Expr>(); 3754 } 3755 3756 // Check for array bounds violations for each argument to the call. This 3757 // check only triggers warnings when the argument isn't a more complex Expr 3758 // with its own checking, such as a BinaryOperator. 3759 CheckArrayAccess(Arg); 3760 3761 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3762 CheckStaticArrayArgument(CallLoc, Param, Arg); 3763 3764 AllArgs.push_back(Arg); 3765 } 3766 3767 // If this is a variadic call, handle args passed through "...". 3768 if (CallType != VariadicDoesNotApply) { 3769 // Assume that extern "C" functions with variadic arguments that 3770 // return __unknown_anytype aren't *really* variadic. 3771 if (Proto->getResultType() == Context.UnknownAnyTy && 3772 FDecl && FDecl->isExternC()) { 3773 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3774 ExprResult arg; 3775 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens())) 3776 arg = DefaultFunctionArrayLvalueConversion(Args[i]); 3777 else 3778 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl); 3779 Invalid |= arg.isInvalid(); 3780 AllArgs.push_back(arg.take()); 3781 } 3782 3783 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3784 } else { 3785 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3786 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 3787 FDecl); 3788 Invalid |= Arg.isInvalid(); 3789 AllArgs.push_back(Arg.take()); 3790 } 3791 } 3792 3793 // Check for array bounds violations. 3794 for (unsigned i = ArgIx; i != NumArgs; ++i) 3795 CheckArrayAccess(Args[i]); 3796 } 3797 return Invalid; 3798 } 3799 3800 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 3801 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 3802 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL)) 3803 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 3804 << ATL->getLocalSourceRange(); 3805 } 3806 3807 /// CheckStaticArrayArgument - If the given argument corresponds to a static 3808 /// array parameter, check that it is non-null, and that if it is formed by 3809 /// array-to-pointer decay, the underlying array is sufficiently large. 3810 /// 3811 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 3812 /// array type derivation, then for each call to the function, the value of the 3813 /// corresponding actual argument shall provide access to the first element of 3814 /// an array with at least as many elements as specified by the size expression. 3815 void 3816 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 3817 ParmVarDecl *Param, 3818 const Expr *ArgExpr) { 3819 // Static array parameters are not supported in C++. 3820 if (!Param || getLangOpts().CPlusPlus) 3821 return; 3822 3823 QualType OrigTy = Param->getOriginalType(); 3824 3825 const ArrayType *AT = Context.getAsArrayType(OrigTy); 3826 if (!AT || AT->getSizeModifier() != ArrayType::Static) 3827 return; 3828 3829 if (ArgExpr->isNullPointerConstant(Context, 3830 Expr::NPC_NeverValueDependent)) { 3831 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 3832 DiagnoseCalleeStaticArrayParam(*this, Param); 3833 return; 3834 } 3835 3836 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 3837 if (!CAT) 3838 return; 3839 3840 const ConstantArrayType *ArgCAT = 3841 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 3842 if (!ArgCAT) 3843 return; 3844 3845 if (ArgCAT->getSize().ult(CAT->getSize())) { 3846 Diag(CallLoc, diag::warn_static_array_too_small) 3847 << ArgExpr->getSourceRange() 3848 << (unsigned) ArgCAT->getSize().getZExtValue() 3849 << (unsigned) CAT->getSize().getZExtValue(); 3850 DiagnoseCalleeStaticArrayParam(*this, Param); 3851 } 3852 } 3853 3854 /// Given a function expression of unknown-any type, try to rebuild it 3855 /// to have a function type. 3856 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 3857 3858 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3859 /// This provides the location of the left/right parens and a list of comma 3860 /// locations. 3861 ExprResult 3862 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3863 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3864 Expr *ExecConfig, bool IsExecConfig) { 3865 // Since this might be a postfix expression, get rid of ParenListExprs. 3866 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 3867 if (Result.isInvalid()) return ExprError(); 3868 Fn = Result.take(); 3869 3870 if (getLangOpts().CPlusPlus) { 3871 // If this is a pseudo-destructor expression, build the call immediately. 3872 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3873 if (!ArgExprs.empty()) { 3874 // Pseudo-destructor calls should not have any arguments. 3875 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3876 << FixItHint::CreateRemoval( 3877 SourceRange(ArgExprs[0]->getLocStart(), 3878 ArgExprs.back()->getLocEnd())); 3879 } 3880 3881 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(), 3882 Context.VoidTy, VK_RValue, 3883 RParenLoc)); 3884 } 3885 3886 // Determine whether this is a dependent call inside a C++ template, 3887 // in which case we won't do any semantic analysis now. 3888 // FIXME: Will need to cache the results of name lookup (including ADL) in 3889 // Fn. 3890 bool Dependent = false; 3891 if (Fn->isTypeDependent()) 3892 Dependent = true; 3893 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 3894 Dependent = true; 3895 3896 if (Dependent) { 3897 if (ExecConfig) { 3898 return Owned(new (Context) CUDAKernelCallExpr( 3899 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 3900 Context.DependentTy, VK_RValue, RParenLoc)); 3901 } else { 3902 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 3903 Context.DependentTy, VK_RValue, 3904 RParenLoc)); 3905 } 3906 } 3907 3908 // Determine whether this is a call to an object (C++ [over.call.object]). 3909 if (Fn->getType()->isRecordType()) 3910 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 3911 ArgExprs.data(), 3912 ArgExprs.size(), RParenLoc)); 3913 3914 if (Fn->getType() == Context.UnknownAnyTy) { 3915 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3916 if (result.isInvalid()) return ExprError(); 3917 Fn = result.take(); 3918 } 3919 3920 if (Fn->getType() == Context.BoundMemberTy) { 3921 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(), 3922 ArgExprs.size(), RParenLoc); 3923 } 3924 } 3925 3926 // Check for overloaded calls. This can happen even in C due to extensions. 3927 if (Fn->getType() == Context.OverloadTy) { 3928 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 3929 3930 // We aren't supposed to apply this logic for if there's an '&' involved. 3931 if (!find.HasFormOfMemberPointer) { 3932 OverloadExpr *ovl = find.Expression; 3933 if (isa<UnresolvedLookupExpr>(ovl)) { 3934 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 3935 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(), 3936 ArgExprs.size(), RParenLoc, ExecConfig); 3937 } else { 3938 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(), 3939 ArgExprs.size(), RParenLoc); 3940 } 3941 } 3942 } 3943 3944 // If we're directly calling a function, get the appropriate declaration. 3945 if (Fn->getType() == Context.UnknownAnyTy) { 3946 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3947 if (result.isInvalid()) return ExprError(); 3948 Fn = result.take(); 3949 } 3950 3951 Expr *NakedFn = Fn->IgnoreParens(); 3952 3953 NamedDecl *NDecl = 0; 3954 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 3955 if (UnOp->getOpcode() == UO_AddrOf) 3956 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 3957 3958 if (isa<DeclRefExpr>(NakedFn)) 3959 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3960 else if (isa<MemberExpr>(NakedFn)) 3961 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 3962 3963 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(), 3964 ArgExprs.size(), RParenLoc, ExecConfig, 3965 IsExecConfig); 3966 } 3967 3968 ExprResult 3969 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3970 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 3971 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 3972 if (!ConfigDecl) 3973 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 3974 << "cudaConfigureCall"); 3975 QualType ConfigQTy = ConfigDecl->getType(); 3976 3977 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 3978 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 3979 MarkFunctionReferenced(LLLLoc, ConfigDecl); 3980 3981 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 3982 /*IsExecConfig=*/true); 3983 } 3984 3985 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 3986 /// 3987 /// __builtin_astype( value, dst type ) 3988 /// 3989 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3990 SourceLocation BuiltinLoc, 3991 SourceLocation RParenLoc) { 3992 ExprValueKind VK = VK_RValue; 3993 ExprObjectKind OK = OK_Ordinary; 3994 QualType DstTy = GetTypeFromParser(ParsedDestTy); 3995 QualType SrcTy = E->getType(); 3996 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 3997 return ExprError(Diag(BuiltinLoc, 3998 diag::err_invalid_astype_of_different_size) 3999 << DstTy 4000 << SrcTy 4001 << E->getSourceRange()); 4002 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4003 RParenLoc)); 4004 } 4005 4006 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4007 /// i.e. an expression not of \p OverloadTy. The expression should 4008 /// unary-convert to an expression of function-pointer or 4009 /// block-pointer type. 4010 /// 4011 /// \param NDecl the declaration being called, if available 4012 ExprResult 4013 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4014 SourceLocation LParenLoc, 4015 Expr **Args, unsigned NumArgs, 4016 SourceLocation RParenLoc, 4017 Expr *Config, bool IsExecConfig) { 4018 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4019 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4020 4021 // Promote the function operand. 4022 // We special-case function promotion here because we only allow promoting 4023 // builtin functions to function pointers in the callee of a call. 4024 ExprResult Result; 4025 if (BuiltinID && 4026 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4027 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4028 CK_BuiltinFnToFnPtr).take(); 4029 } else { 4030 Result = UsualUnaryConversions(Fn); 4031 } 4032 if (Result.isInvalid()) 4033 return ExprError(); 4034 Fn = Result.take(); 4035 4036 // Make the call expr early, before semantic checks. This guarantees cleanup 4037 // of arguments and function on error. 4038 CallExpr *TheCall; 4039 if (Config) 4040 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4041 cast<CallExpr>(Config), 4042 llvm::makeArrayRef(Args,NumArgs), 4043 Context.BoolTy, 4044 VK_RValue, 4045 RParenLoc); 4046 else 4047 TheCall = new (Context) CallExpr(Context, Fn, 4048 llvm::makeArrayRef(Args, NumArgs), 4049 Context.BoolTy, 4050 VK_RValue, 4051 RParenLoc); 4052 4053 // Bail out early if calling a builtin with custom typechecking. 4054 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4055 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4056 4057 retry: 4058 const FunctionType *FuncT; 4059 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4060 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4061 // have type pointer to function". 4062 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4063 if (FuncT == 0) 4064 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4065 << Fn->getType() << Fn->getSourceRange()); 4066 } else if (const BlockPointerType *BPT = 4067 Fn->getType()->getAs<BlockPointerType>()) { 4068 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4069 } else { 4070 // Handle calls to expressions of unknown-any type. 4071 if (Fn->getType() == Context.UnknownAnyTy) { 4072 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4073 if (rewrite.isInvalid()) return ExprError(); 4074 Fn = rewrite.take(); 4075 TheCall->setCallee(Fn); 4076 goto retry; 4077 } 4078 4079 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4080 << Fn->getType() << Fn->getSourceRange()); 4081 } 4082 4083 if (getLangOpts().CUDA) { 4084 if (Config) { 4085 // CUDA: Kernel calls must be to global functions 4086 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4087 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4088 << FDecl->getName() << Fn->getSourceRange()); 4089 4090 // CUDA: Kernel function must have 'void' return type 4091 if (!FuncT->getResultType()->isVoidType()) 4092 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4093 << Fn->getType() << Fn->getSourceRange()); 4094 } else { 4095 // CUDA: Calls to global functions must be configured 4096 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4097 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4098 << FDecl->getName() << Fn->getSourceRange()); 4099 } 4100 } 4101 4102 // Check for a valid return type 4103 if (CheckCallReturnType(FuncT->getResultType(), 4104 Fn->getLocStart(), TheCall, 4105 FDecl)) 4106 return ExprError(); 4107 4108 // We know the result type of the call, set it. 4109 TheCall->setType(FuncT->getCallResultType(Context)); 4110 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4111 4112 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4113 if (Proto) { 4114 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 4115 RParenLoc, IsExecConfig)) 4116 return ExprError(); 4117 } else { 4118 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4119 4120 if (FDecl) { 4121 // Check if we have too few/too many template arguments, based 4122 // on our knowledge of the function definition. 4123 const FunctionDecl *Def = 0; 4124 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 4125 Proto = Def->getType()->getAs<FunctionProtoType>(); 4126 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 4127 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4128 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 4129 } 4130 4131 // If the function we're calling isn't a function prototype, but we have 4132 // a function prototype from a prior declaratiom, use that prototype. 4133 if (!FDecl->hasPrototype()) 4134 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4135 } 4136 4137 // Promote the arguments (C99 6.5.2.2p6). 4138 for (unsigned i = 0; i != NumArgs; i++) { 4139 Expr *Arg = Args[i]; 4140 4141 if (Proto && i < Proto->getNumArgs()) { 4142 InitializedEntity Entity 4143 = InitializedEntity::InitializeParameter(Context, 4144 Proto->getArgType(i), 4145 Proto->isArgConsumed(i)); 4146 ExprResult ArgE = PerformCopyInitialization(Entity, 4147 SourceLocation(), 4148 Owned(Arg)); 4149 if (ArgE.isInvalid()) 4150 return true; 4151 4152 Arg = ArgE.takeAs<Expr>(); 4153 4154 } else { 4155 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4156 4157 if (ArgE.isInvalid()) 4158 return true; 4159 4160 Arg = ArgE.takeAs<Expr>(); 4161 } 4162 4163 if (RequireCompleteType(Arg->getLocStart(), 4164 Arg->getType(), 4165 diag::err_call_incomplete_argument, Arg)) 4166 return ExprError(); 4167 4168 TheCall->setArg(i, Arg); 4169 } 4170 } 4171 4172 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4173 if (!Method->isStatic()) 4174 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4175 << Fn->getSourceRange()); 4176 4177 // Check for sentinels 4178 if (NDecl) 4179 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 4180 4181 // Do special checking on direct calls to functions. 4182 if (FDecl) { 4183 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4184 return ExprError(); 4185 4186 if (BuiltinID) 4187 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4188 } else if (NDecl) { 4189 if (CheckBlockCall(NDecl, TheCall, Proto)) 4190 return ExprError(); 4191 } 4192 4193 return MaybeBindToTemporary(TheCall); 4194 } 4195 4196 ExprResult 4197 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4198 SourceLocation RParenLoc, Expr *InitExpr) { 4199 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 4200 // FIXME: put back this assert when initializers are worked out. 4201 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4202 4203 TypeSourceInfo *TInfo; 4204 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4205 if (!TInfo) 4206 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4207 4208 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4209 } 4210 4211 ExprResult 4212 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4213 SourceLocation RParenLoc, Expr *LiteralExpr) { 4214 QualType literalType = TInfo->getType(); 4215 4216 if (literalType->isArrayType()) { 4217 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4218 diag::err_illegal_decl_array_incomplete_type, 4219 SourceRange(LParenLoc, 4220 LiteralExpr->getSourceRange().getEnd()))) 4221 return ExprError(); 4222 if (literalType->isVariableArrayType()) 4223 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4224 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4225 } else if (!literalType->isDependentType() && 4226 RequireCompleteType(LParenLoc, literalType, 4227 diag::err_typecheck_decl_incomplete_type, 4228 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4229 return ExprError(); 4230 4231 InitializedEntity Entity 4232 = InitializedEntity::InitializeTemporary(literalType); 4233 InitializationKind Kind 4234 = InitializationKind::CreateCStyleCast(LParenLoc, 4235 SourceRange(LParenLoc, RParenLoc), 4236 /*InitList=*/true); 4237 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1); 4238 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4239 &literalType); 4240 if (Result.isInvalid()) 4241 return ExprError(); 4242 LiteralExpr = Result.get(); 4243 4244 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4245 if (isFileScope) { // 6.5.2.5p3 4246 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4247 return ExprError(); 4248 } 4249 4250 // In C, compound literals are l-values for some reason. 4251 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4252 4253 return MaybeBindToTemporary( 4254 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4255 VK, LiteralExpr, isFileScope)); 4256 } 4257 4258 ExprResult 4259 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4260 SourceLocation RBraceLoc) { 4261 // Immediately handle non-overload placeholders. Overloads can be 4262 // resolved contextually, but everything else here can't. 4263 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4264 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4265 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4266 4267 // Ignore failures; dropping the entire initializer list because 4268 // of one failure would be terrible for indexing/etc. 4269 if (result.isInvalid()) continue; 4270 4271 InitArgList[I] = result.take(); 4272 } 4273 } 4274 4275 // Semantic analysis for initializers is done by ActOnDeclarator() and 4276 // CheckInitializer() - it requires knowledge of the object being intialized. 4277 4278 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4279 RBraceLoc); 4280 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4281 return Owned(E); 4282 } 4283 4284 /// Do an explicit extend of the given block pointer if we're in ARC. 4285 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4286 assert(E.get()->getType()->isBlockPointerType()); 4287 assert(E.get()->isRValue()); 4288 4289 // Only do this in an r-value context. 4290 if (!S.getLangOpts().ObjCAutoRefCount) return; 4291 4292 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4293 CK_ARCExtendBlockObject, E.get(), 4294 /*base path*/ 0, VK_RValue); 4295 S.ExprNeedsCleanups = true; 4296 } 4297 4298 /// Prepare a conversion of the given expression to an ObjC object 4299 /// pointer type. 4300 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4301 QualType type = E.get()->getType(); 4302 if (type->isObjCObjectPointerType()) { 4303 return CK_BitCast; 4304 } else if (type->isBlockPointerType()) { 4305 maybeExtendBlockObject(*this, E); 4306 return CK_BlockPointerToObjCPointerCast; 4307 } else { 4308 assert(type->isPointerType()); 4309 return CK_CPointerToObjCPointerCast; 4310 } 4311 } 4312 4313 /// Prepares for a scalar cast, performing all the necessary stages 4314 /// except the final cast and returning the kind required. 4315 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4316 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4317 // Also, callers should have filtered out the invalid cases with 4318 // pointers. Everything else should be possible. 4319 4320 QualType SrcTy = Src.get()->getType(); 4321 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4322 return CK_NoOp; 4323 4324 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4325 case Type::STK_MemberPointer: 4326 llvm_unreachable("member pointer type in C"); 4327 4328 case Type::STK_CPointer: 4329 case Type::STK_BlockPointer: 4330 case Type::STK_ObjCObjectPointer: 4331 switch (DestTy->getScalarTypeKind()) { 4332 case Type::STK_CPointer: 4333 return CK_BitCast; 4334 case Type::STK_BlockPointer: 4335 return (SrcKind == Type::STK_BlockPointer 4336 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4337 case Type::STK_ObjCObjectPointer: 4338 if (SrcKind == Type::STK_ObjCObjectPointer) 4339 return CK_BitCast; 4340 if (SrcKind == Type::STK_CPointer) 4341 return CK_CPointerToObjCPointerCast; 4342 maybeExtendBlockObject(*this, Src); 4343 return CK_BlockPointerToObjCPointerCast; 4344 case Type::STK_Bool: 4345 return CK_PointerToBoolean; 4346 case Type::STK_Integral: 4347 return CK_PointerToIntegral; 4348 case Type::STK_Floating: 4349 case Type::STK_FloatingComplex: 4350 case Type::STK_IntegralComplex: 4351 case Type::STK_MemberPointer: 4352 llvm_unreachable("illegal cast from pointer"); 4353 } 4354 llvm_unreachable("Should have returned before this"); 4355 4356 case Type::STK_Bool: // casting from bool is like casting from an integer 4357 case Type::STK_Integral: 4358 switch (DestTy->getScalarTypeKind()) { 4359 case Type::STK_CPointer: 4360 case Type::STK_ObjCObjectPointer: 4361 case Type::STK_BlockPointer: 4362 if (Src.get()->isNullPointerConstant(Context, 4363 Expr::NPC_ValueDependentIsNull)) 4364 return CK_NullToPointer; 4365 return CK_IntegralToPointer; 4366 case Type::STK_Bool: 4367 return CK_IntegralToBoolean; 4368 case Type::STK_Integral: 4369 return CK_IntegralCast; 4370 case Type::STK_Floating: 4371 return CK_IntegralToFloating; 4372 case Type::STK_IntegralComplex: 4373 Src = ImpCastExprToType(Src.take(), 4374 DestTy->castAs<ComplexType>()->getElementType(), 4375 CK_IntegralCast); 4376 return CK_IntegralRealToComplex; 4377 case Type::STK_FloatingComplex: 4378 Src = ImpCastExprToType(Src.take(), 4379 DestTy->castAs<ComplexType>()->getElementType(), 4380 CK_IntegralToFloating); 4381 return CK_FloatingRealToComplex; 4382 case Type::STK_MemberPointer: 4383 llvm_unreachable("member pointer type in C"); 4384 } 4385 llvm_unreachable("Should have returned before this"); 4386 4387 case Type::STK_Floating: 4388 switch (DestTy->getScalarTypeKind()) { 4389 case Type::STK_Floating: 4390 return CK_FloatingCast; 4391 case Type::STK_Bool: 4392 return CK_FloatingToBoolean; 4393 case Type::STK_Integral: 4394 return CK_FloatingToIntegral; 4395 case Type::STK_FloatingComplex: 4396 Src = ImpCastExprToType(Src.take(), 4397 DestTy->castAs<ComplexType>()->getElementType(), 4398 CK_FloatingCast); 4399 return CK_FloatingRealToComplex; 4400 case Type::STK_IntegralComplex: 4401 Src = ImpCastExprToType(Src.take(), 4402 DestTy->castAs<ComplexType>()->getElementType(), 4403 CK_FloatingToIntegral); 4404 return CK_IntegralRealToComplex; 4405 case Type::STK_CPointer: 4406 case Type::STK_ObjCObjectPointer: 4407 case Type::STK_BlockPointer: 4408 llvm_unreachable("valid float->pointer cast?"); 4409 case Type::STK_MemberPointer: 4410 llvm_unreachable("member pointer type in C"); 4411 } 4412 llvm_unreachable("Should have returned before this"); 4413 4414 case Type::STK_FloatingComplex: 4415 switch (DestTy->getScalarTypeKind()) { 4416 case Type::STK_FloatingComplex: 4417 return CK_FloatingComplexCast; 4418 case Type::STK_IntegralComplex: 4419 return CK_FloatingComplexToIntegralComplex; 4420 case Type::STK_Floating: { 4421 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4422 if (Context.hasSameType(ET, DestTy)) 4423 return CK_FloatingComplexToReal; 4424 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4425 return CK_FloatingCast; 4426 } 4427 case Type::STK_Bool: 4428 return CK_FloatingComplexToBoolean; 4429 case Type::STK_Integral: 4430 Src = ImpCastExprToType(Src.take(), 4431 SrcTy->castAs<ComplexType>()->getElementType(), 4432 CK_FloatingComplexToReal); 4433 return CK_FloatingToIntegral; 4434 case Type::STK_CPointer: 4435 case Type::STK_ObjCObjectPointer: 4436 case Type::STK_BlockPointer: 4437 llvm_unreachable("valid complex float->pointer cast?"); 4438 case Type::STK_MemberPointer: 4439 llvm_unreachable("member pointer type in C"); 4440 } 4441 llvm_unreachable("Should have returned before this"); 4442 4443 case Type::STK_IntegralComplex: 4444 switch (DestTy->getScalarTypeKind()) { 4445 case Type::STK_FloatingComplex: 4446 return CK_IntegralComplexToFloatingComplex; 4447 case Type::STK_IntegralComplex: 4448 return CK_IntegralComplexCast; 4449 case Type::STK_Integral: { 4450 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4451 if (Context.hasSameType(ET, DestTy)) 4452 return CK_IntegralComplexToReal; 4453 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4454 return CK_IntegralCast; 4455 } 4456 case Type::STK_Bool: 4457 return CK_IntegralComplexToBoolean; 4458 case Type::STK_Floating: 4459 Src = ImpCastExprToType(Src.take(), 4460 SrcTy->castAs<ComplexType>()->getElementType(), 4461 CK_IntegralComplexToReal); 4462 return CK_IntegralToFloating; 4463 case Type::STK_CPointer: 4464 case Type::STK_ObjCObjectPointer: 4465 case Type::STK_BlockPointer: 4466 llvm_unreachable("valid complex int->pointer cast?"); 4467 case Type::STK_MemberPointer: 4468 llvm_unreachable("member pointer type in C"); 4469 } 4470 llvm_unreachable("Should have returned before this"); 4471 } 4472 4473 llvm_unreachable("Unhandled scalar cast"); 4474 } 4475 4476 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4477 CastKind &Kind) { 4478 assert(VectorTy->isVectorType() && "Not a vector type!"); 4479 4480 if (Ty->isVectorType() || Ty->isIntegerType()) { 4481 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4482 return Diag(R.getBegin(), 4483 Ty->isVectorType() ? 4484 diag::err_invalid_conversion_between_vectors : 4485 diag::err_invalid_conversion_between_vector_and_integer) 4486 << VectorTy << Ty << R; 4487 } else 4488 return Diag(R.getBegin(), 4489 diag::err_invalid_conversion_between_vector_and_scalar) 4490 << VectorTy << Ty << R; 4491 4492 Kind = CK_BitCast; 4493 return false; 4494 } 4495 4496 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4497 Expr *CastExpr, CastKind &Kind) { 4498 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4499 4500 QualType SrcTy = CastExpr->getType(); 4501 4502 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4503 // an ExtVectorType. 4504 // In OpenCL, casts between vectors of different types are not allowed. 4505 // (See OpenCL 6.2). 4506 if (SrcTy->isVectorType()) { 4507 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4508 || (getLangOpts().OpenCL && 4509 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4510 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4511 << DestTy << SrcTy << R; 4512 return ExprError(); 4513 } 4514 Kind = CK_BitCast; 4515 return Owned(CastExpr); 4516 } 4517 4518 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4519 // conversion will take place first from scalar to elt type, and then 4520 // splat from elt type to vector. 4521 if (SrcTy->isPointerType()) 4522 return Diag(R.getBegin(), 4523 diag::err_invalid_conversion_between_vector_and_scalar) 4524 << DestTy << SrcTy << R; 4525 4526 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4527 ExprResult CastExprRes = Owned(CastExpr); 4528 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4529 if (CastExprRes.isInvalid()) 4530 return ExprError(); 4531 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4532 4533 Kind = CK_VectorSplat; 4534 return Owned(CastExpr); 4535 } 4536 4537 ExprResult 4538 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4539 Declarator &D, ParsedType &Ty, 4540 SourceLocation RParenLoc, Expr *CastExpr) { 4541 assert(!D.isInvalidType() && (CastExpr != 0) && 4542 "ActOnCastExpr(): missing type or expr"); 4543 4544 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4545 if (D.isInvalidType()) 4546 return ExprError(); 4547 4548 if (getLangOpts().CPlusPlus) { 4549 // Check that there are no default arguments (C++ only). 4550 CheckExtraCXXDefaultArguments(D); 4551 } 4552 4553 checkUnusedDeclAttributes(D); 4554 4555 QualType castType = castTInfo->getType(); 4556 Ty = CreateParsedType(castType, castTInfo); 4557 4558 bool isVectorLiteral = false; 4559 4560 // Check for an altivec or OpenCL literal, 4561 // i.e. all the elements are integer constants. 4562 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4563 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4564 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 4565 && castType->isVectorType() && (PE || PLE)) { 4566 if (PLE && PLE->getNumExprs() == 0) { 4567 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4568 return ExprError(); 4569 } 4570 if (PE || PLE->getNumExprs() == 1) { 4571 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4572 if (!E->getType()->isVectorType()) 4573 isVectorLiteral = true; 4574 } 4575 else 4576 isVectorLiteral = true; 4577 } 4578 4579 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4580 // then handle it as such. 4581 if (isVectorLiteral) 4582 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4583 4584 // If the Expr being casted is a ParenListExpr, handle it specially. 4585 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4586 // sequence of BinOp comma operators. 4587 if (isa<ParenListExpr>(CastExpr)) { 4588 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4589 if (Result.isInvalid()) return ExprError(); 4590 CastExpr = Result.take(); 4591 } 4592 4593 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4594 } 4595 4596 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4597 SourceLocation RParenLoc, Expr *E, 4598 TypeSourceInfo *TInfo) { 4599 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4600 "Expected paren or paren list expression"); 4601 4602 Expr **exprs; 4603 unsigned numExprs; 4604 Expr *subExpr; 4605 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4606 exprs = PE->getExprs(); 4607 numExprs = PE->getNumExprs(); 4608 } else { 4609 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4610 exprs = &subExpr; 4611 numExprs = 1; 4612 } 4613 4614 QualType Ty = TInfo->getType(); 4615 assert(Ty->isVectorType() && "Expected vector type"); 4616 4617 SmallVector<Expr *, 8> initExprs; 4618 const VectorType *VTy = Ty->getAs<VectorType>(); 4619 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4620 4621 // '(...)' form of vector initialization in AltiVec: the number of 4622 // initializers must be one or must match the size of the vector. 4623 // If a single value is specified in the initializer then it will be 4624 // replicated to all the components of the vector 4625 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4626 // The number of initializers must be one or must match the size of the 4627 // vector. If a single value is specified in the initializer then it will 4628 // be replicated to all the components of the vector 4629 if (numExprs == 1) { 4630 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4631 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4632 if (Literal.isInvalid()) 4633 return ExprError(); 4634 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4635 PrepareScalarCast(Literal, ElemTy)); 4636 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4637 } 4638 else if (numExprs < numElems) { 4639 Diag(E->getExprLoc(), 4640 diag::err_incorrect_number_of_vector_initializers); 4641 return ExprError(); 4642 } 4643 else 4644 initExprs.append(exprs, exprs + numExprs); 4645 } 4646 else { 4647 // For OpenCL, when the number of initializers is a single value, 4648 // it will be replicated to all components of the vector. 4649 if (getLangOpts().OpenCL && 4650 VTy->getVectorKind() == VectorType::GenericVector && 4651 numExprs == 1) { 4652 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4653 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4654 if (Literal.isInvalid()) 4655 return ExprError(); 4656 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4657 PrepareScalarCast(Literal, ElemTy)); 4658 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4659 } 4660 4661 initExprs.append(exprs, exprs + numExprs); 4662 } 4663 // FIXME: This means that pretty-printing the final AST will produce curly 4664 // braces instead of the original commas. 4665 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc, 4666 initExprs, RParenLoc); 4667 initE->setType(Ty); 4668 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4669 } 4670 4671 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 4672 /// the ParenListExpr into a sequence of comma binary operators. 4673 ExprResult 4674 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4675 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4676 if (!E) 4677 return Owned(OrigExpr); 4678 4679 ExprResult Result(E->getExpr(0)); 4680 4681 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4682 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4683 E->getExpr(i)); 4684 4685 if (Result.isInvalid()) return ExprError(); 4686 4687 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4688 } 4689 4690 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 4691 SourceLocation R, 4692 MultiExprArg Val) { 4693 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 4694 return Owned(expr); 4695 } 4696 4697 /// \brief Emit a specialized diagnostic when one expression is a null pointer 4698 /// constant and the other is not a pointer. Returns true if a diagnostic is 4699 /// emitted. 4700 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4701 SourceLocation QuestionLoc) { 4702 Expr *NullExpr = LHSExpr; 4703 Expr *NonPointerExpr = RHSExpr; 4704 Expr::NullPointerConstantKind NullKind = 4705 NullExpr->isNullPointerConstant(Context, 4706 Expr::NPC_ValueDependentIsNotNull); 4707 4708 if (NullKind == Expr::NPCK_NotNull) { 4709 NullExpr = RHSExpr; 4710 NonPointerExpr = LHSExpr; 4711 NullKind = 4712 NullExpr->isNullPointerConstant(Context, 4713 Expr::NPC_ValueDependentIsNotNull); 4714 } 4715 4716 if (NullKind == Expr::NPCK_NotNull) 4717 return false; 4718 4719 if (NullKind == Expr::NPCK_ZeroExpression) 4720 return false; 4721 4722 if (NullKind == Expr::NPCK_ZeroLiteral) { 4723 // In this case, check to make sure that we got here from a "NULL" 4724 // string in the source code. 4725 NullExpr = NullExpr->IgnoreParenImpCasts(); 4726 SourceLocation loc = NullExpr->getExprLoc(); 4727 if (!findMacroSpelling(loc, "NULL")) 4728 return false; 4729 } 4730 4731 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 4732 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 4733 << NonPointerExpr->getType() << DiagType 4734 << NonPointerExpr->getSourceRange(); 4735 return true; 4736 } 4737 4738 /// \brief Return false if the condition expression is valid, true otherwise. 4739 static bool checkCondition(Sema &S, Expr *Cond) { 4740 QualType CondTy = Cond->getType(); 4741 4742 // C99 6.5.15p2 4743 if (CondTy->isScalarType()) return false; 4744 4745 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar. 4746 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 4747 return false; 4748 4749 // Emit the proper error message. 4750 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 4751 diag::err_typecheck_cond_expect_scalar : 4752 diag::err_typecheck_cond_expect_scalar_or_vector) 4753 << CondTy; 4754 return true; 4755 } 4756 4757 /// \brief Return false if the two expressions can be converted to a vector, 4758 /// true otherwise 4759 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 4760 ExprResult &RHS, 4761 QualType CondTy) { 4762 // Both operands should be of scalar type. 4763 if (!LHS.get()->getType()->isScalarType()) { 4764 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4765 << CondTy; 4766 return true; 4767 } 4768 if (!RHS.get()->getType()->isScalarType()) { 4769 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4770 << CondTy; 4771 return true; 4772 } 4773 4774 // Implicity convert these scalars to the type of the condition. 4775 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 4776 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 4777 return false; 4778 } 4779 4780 /// \brief Handle when one or both operands are void type. 4781 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 4782 ExprResult &RHS) { 4783 Expr *LHSExpr = LHS.get(); 4784 Expr *RHSExpr = RHS.get(); 4785 4786 if (!LHSExpr->getType()->isVoidType()) 4787 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4788 << RHSExpr->getSourceRange(); 4789 if (!RHSExpr->getType()->isVoidType()) 4790 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4791 << LHSExpr->getSourceRange(); 4792 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 4793 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 4794 return S.Context.VoidTy; 4795 } 4796 4797 /// \brief Return false if the NullExpr can be promoted to PointerTy, 4798 /// true otherwise. 4799 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 4800 QualType PointerTy) { 4801 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 4802 !NullExpr.get()->isNullPointerConstant(S.Context, 4803 Expr::NPC_ValueDependentIsNull)) 4804 return true; 4805 4806 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 4807 return false; 4808 } 4809 4810 /// \brief Checks compatibility between two pointers and return the resulting 4811 /// type. 4812 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 4813 ExprResult &RHS, 4814 SourceLocation Loc) { 4815 QualType LHSTy = LHS.get()->getType(); 4816 QualType RHSTy = RHS.get()->getType(); 4817 4818 if (S.Context.hasSameType(LHSTy, RHSTy)) { 4819 // Two identical pointers types are always compatible. 4820 return LHSTy; 4821 } 4822 4823 QualType lhptee, rhptee; 4824 4825 // Get the pointee types. 4826 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 4827 lhptee = LHSBTy->getPointeeType(); 4828 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 4829 } else { 4830 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 4831 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 4832 } 4833 4834 // C99 6.5.15p6: If both operands are pointers to compatible types or to 4835 // differently qualified versions of compatible types, the result type is 4836 // a pointer to an appropriately qualified version of the composite 4837 // type. 4838 4839 // Only CVR-qualifiers exist in the standard, and the differently-qualified 4840 // clause doesn't make sense for our extensions. E.g. address space 2 should 4841 // be incompatible with address space 3: they may live on different devices or 4842 // anything. 4843 Qualifiers lhQual = lhptee.getQualifiers(); 4844 Qualifiers rhQual = rhptee.getQualifiers(); 4845 4846 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 4847 lhQual.removeCVRQualifiers(); 4848 rhQual.removeCVRQualifiers(); 4849 4850 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 4851 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 4852 4853 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 4854 4855 if (CompositeTy.isNull()) { 4856 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 4857 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4858 << RHS.get()->getSourceRange(); 4859 // In this situation, we assume void* type. No especially good 4860 // reason, but this is what gcc does, and we do have to pick 4861 // to get a consistent AST. 4862 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 4863 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4864 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4865 return incompatTy; 4866 } 4867 4868 // The pointer types are compatible. 4869 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 4870 ResultTy = S.Context.getPointerType(ResultTy); 4871 4872 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 4873 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 4874 return ResultTy; 4875 } 4876 4877 /// \brief Return the resulting type when the operands are both block pointers. 4878 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 4879 ExprResult &LHS, 4880 ExprResult &RHS, 4881 SourceLocation Loc) { 4882 QualType LHSTy = LHS.get()->getType(); 4883 QualType RHSTy = RHS.get()->getType(); 4884 4885 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4886 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4887 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 4888 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4889 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4890 return destType; 4891 } 4892 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 4893 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4894 << RHS.get()->getSourceRange(); 4895 return QualType(); 4896 } 4897 4898 // We have 2 block pointer types. 4899 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4900 } 4901 4902 /// \brief Return the resulting type when the operands are both pointers. 4903 static QualType 4904 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 4905 ExprResult &RHS, 4906 SourceLocation Loc) { 4907 // get the pointer types 4908 QualType LHSTy = LHS.get()->getType(); 4909 QualType RHSTy = RHS.get()->getType(); 4910 4911 // get the "pointed to" types 4912 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4913 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4914 4915 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4916 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4917 // Figure out necessary qualifiers (C99 6.5.15p6) 4918 QualType destPointee 4919 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4920 QualType destType = S.Context.getPointerType(destPointee); 4921 // Add qualifiers if necessary. 4922 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4923 // Promote to void*. 4924 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4925 return destType; 4926 } 4927 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4928 QualType destPointee 4929 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4930 QualType destType = S.Context.getPointerType(destPointee); 4931 // Add qualifiers if necessary. 4932 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4933 // Promote to void*. 4934 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4935 return destType; 4936 } 4937 4938 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4939 } 4940 4941 /// \brief Return false if the first expression is not an integer and the second 4942 /// expression is not a pointer, true otherwise. 4943 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 4944 Expr* PointerExpr, SourceLocation Loc, 4945 bool IsIntFirstExpr) { 4946 if (!PointerExpr->getType()->isPointerType() || 4947 !Int.get()->getType()->isIntegerType()) 4948 return false; 4949 4950 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 4951 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 4952 4953 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4954 << Expr1->getType() << Expr2->getType() 4955 << Expr1->getSourceRange() << Expr2->getSourceRange(); 4956 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 4957 CK_IntegralToPointer); 4958 return true; 4959 } 4960 4961 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 4962 /// In that case, LHS = cond. 4963 /// C99 6.5.15 4964 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 4965 ExprResult &RHS, ExprValueKind &VK, 4966 ExprObjectKind &OK, 4967 SourceLocation QuestionLoc) { 4968 4969 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 4970 if (!LHSResult.isUsable()) return QualType(); 4971 LHS = LHSResult; 4972 4973 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 4974 if (!RHSResult.isUsable()) return QualType(); 4975 RHS = RHSResult; 4976 4977 // C++ is sufficiently different to merit its own checker. 4978 if (getLangOpts().CPlusPlus) 4979 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 4980 4981 VK = VK_RValue; 4982 OK = OK_Ordinary; 4983 4984 Cond = UsualUnaryConversions(Cond.take()); 4985 if (Cond.isInvalid()) 4986 return QualType(); 4987 LHS = UsualUnaryConversions(LHS.take()); 4988 if (LHS.isInvalid()) 4989 return QualType(); 4990 RHS = UsualUnaryConversions(RHS.take()); 4991 if (RHS.isInvalid()) 4992 return QualType(); 4993 4994 QualType CondTy = Cond.get()->getType(); 4995 QualType LHSTy = LHS.get()->getType(); 4996 QualType RHSTy = RHS.get()->getType(); 4997 4998 // first, check the condition. 4999 if (checkCondition(*this, Cond.get())) 5000 return QualType(); 5001 5002 // Now check the two expressions. 5003 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 5004 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5005 5006 // OpenCL: If the condition is a vector, and both operands are scalar, 5007 // attempt to implicity convert them to the vector type to act like the 5008 // built in select. 5009 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5010 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5011 return QualType(); 5012 5013 // If both operands have arithmetic type, do the usual arithmetic conversions 5014 // to find a common type: C99 6.5.15p3,5. 5015 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 5016 UsualArithmeticConversions(LHS, RHS); 5017 if (LHS.isInvalid() || RHS.isInvalid()) 5018 return QualType(); 5019 return LHS.get()->getType(); 5020 } 5021 5022 // If both operands are the same structure or union type, the result is that 5023 // type. 5024 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5025 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5026 if (LHSRT->getDecl() == RHSRT->getDecl()) 5027 // "If both the operands have structure or union type, the result has 5028 // that type." This implies that CV qualifiers are dropped. 5029 return LHSTy.getUnqualifiedType(); 5030 // FIXME: Type of conditional expression must be complete in C mode. 5031 } 5032 5033 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5034 // The following || allows only one side to be void (a GCC-ism). 5035 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5036 return checkConditionalVoidType(*this, LHS, RHS); 5037 } 5038 5039 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5040 // the type of the other operand." 5041 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5042 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5043 5044 // All objective-c pointer type analysis is done here. 5045 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5046 QuestionLoc); 5047 if (LHS.isInvalid() || RHS.isInvalid()) 5048 return QualType(); 5049 if (!compositeType.isNull()) 5050 return compositeType; 5051 5052 5053 // Handle block pointer types. 5054 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5055 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5056 QuestionLoc); 5057 5058 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5059 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5060 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5061 QuestionLoc); 5062 5063 // GCC compatibility: soften pointer/integer mismatch. Note that 5064 // null pointers have been filtered out by this point. 5065 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5066 /*isIntFirstExpr=*/true)) 5067 return RHSTy; 5068 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5069 /*isIntFirstExpr=*/false)) 5070 return LHSTy; 5071 5072 // Emit a better diagnostic if one of the expressions is a null pointer 5073 // constant and the other is not a pointer type. In this case, the user most 5074 // likely forgot to take the address of the other expression. 5075 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5076 return QualType(); 5077 5078 // Otherwise, the operands are not compatible. 5079 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5080 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5081 << RHS.get()->getSourceRange(); 5082 return QualType(); 5083 } 5084 5085 /// FindCompositeObjCPointerType - Helper method to find composite type of 5086 /// two objective-c pointer types of the two input expressions. 5087 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5088 SourceLocation QuestionLoc) { 5089 QualType LHSTy = LHS.get()->getType(); 5090 QualType RHSTy = RHS.get()->getType(); 5091 5092 // Handle things like Class and struct objc_class*. Here we case the result 5093 // to the pseudo-builtin, because that will be implicitly cast back to the 5094 // redefinition type if an attempt is made to access its fields. 5095 if (LHSTy->isObjCClassType() && 5096 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5097 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5098 return LHSTy; 5099 } 5100 if (RHSTy->isObjCClassType() && 5101 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5102 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5103 return RHSTy; 5104 } 5105 // And the same for struct objc_object* / id 5106 if (LHSTy->isObjCIdType() && 5107 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5108 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5109 return LHSTy; 5110 } 5111 if (RHSTy->isObjCIdType() && 5112 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5113 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5114 return RHSTy; 5115 } 5116 // And the same for struct objc_selector* / SEL 5117 if (Context.isObjCSelType(LHSTy) && 5118 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5119 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5120 return LHSTy; 5121 } 5122 if (Context.isObjCSelType(RHSTy) && 5123 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5124 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5125 return RHSTy; 5126 } 5127 // Check constraints for Objective-C object pointers types. 5128 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5129 5130 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5131 // Two identical object pointer types are always compatible. 5132 return LHSTy; 5133 } 5134 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5135 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5136 QualType compositeType = LHSTy; 5137 5138 // If both operands are interfaces and either operand can be 5139 // assigned to the other, use that type as the composite 5140 // type. This allows 5141 // xxx ? (A*) a : (B*) b 5142 // where B is a subclass of A. 5143 // 5144 // Additionally, as for assignment, if either type is 'id' 5145 // allow silent coercion. Finally, if the types are 5146 // incompatible then make sure to use 'id' as the composite 5147 // type so the result is acceptable for sending messages to. 5148 5149 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5150 // It could return the composite type. 5151 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5152 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5153 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5154 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5155 } else if ((LHSTy->isObjCQualifiedIdType() || 5156 RHSTy->isObjCQualifiedIdType()) && 5157 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5158 // Need to handle "id<xx>" explicitly. 5159 // GCC allows qualified id and any Objective-C type to devolve to 5160 // id. Currently localizing to here until clear this should be 5161 // part of ObjCQualifiedIdTypesAreCompatible. 5162 compositeType = Context.getObjCIdType(); 5163 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5164 compositeType = Context.getObjCIdType(); 5165 } else if (!(compositeType = 5166 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5167 ; 5168 else { 5169 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5170 << LHSTy << RHSTy 5171 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5172 QualType incompatTy = Context.getObjCIdType(); 5173 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5174 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5175 return incompatTy; 5176 } 5177 // The object pointer types are compatible. 5178 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5179 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5180 return compositeType; 5181 } 5182 // Check Objective-C object pointer types and 'void *' 5183 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5184 if (getLangOpts().ObjCAutoRefCount) { 5185 // ARC forbids the implicit conversion of object pointers to 'void *', 5186 // so these types are not compatible. 5187 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5188 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5189 LHS = RHS = true; 5190 return QualType(); 5191 } 5192 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5193 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5194 QualType destPointee 5195 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5196 QualType destType = Context.getPointerType(destPointee); 5197 // Add qualifiers if necessary. 5198 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5199 // Promote to void*. 5200 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5201 return destType; 5202 } 5203 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5204 if (getLangOpts().ObjCAutoRefCount) { 5205 // ARC forbids the implicit conversion of object pointers to 'void *', 5206 // so these types are not compatible. 5207 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5208 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5209 LHS = RHS = true; 5210 return QualType(); 5211 } 5212 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5213 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5214 QualType destPointee 5215 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5216 QualType destType = Context.getPointerType(destPointee); 5217 // Add qualifiers if necessary. 5218 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5219 // Promote to void*. 5220 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5221 return destType; 5222 } 5223 return QualType(); 5224 } 5225 5226 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5227 /// ParenRange in parentheses. 5228 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5229 const PartialDiagnostic &Note, 5230 SourceRange ParenRange) { 5231 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5232 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5233 EndLoc.isValid()) { 5234 Self.Diag(Loc, Note) 5235 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5236 << FixItHint::CreateInsertion(EndLoc, ")"); 5237 } else { 5238 // We can't display the parentheses, so just show the bare note. 5239 Self.Diag(Loc, Note) << ParenRange; 5240 } 5241 } 5242 5243 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5244 return Opc >= BO_Mul && Opc <= BO_Shr; 5245 } 5246 5247 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5248 /// expression, either using a built-in or overloaded operator, 5249 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5250 /// expression. 5251 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5252 Expr **RHSExprs) { 5253 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5254 E = E->IgnoreImpCasts(); 5255 E = E->IgnoreConversionOperator(); 5256 E = E->IgnoreImpCasts(); 5257 5258 // Built-in binary operator. 5259 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5260 if (IsArithmeticOp(OP->getOpcode())) { 5261 *Opcode = OP->getOpcode(); 5262 *RHSExprs = OP->getRHS(); 5263 return true; 5264 } 5265 } 5266 5267 // Overloaded operator. 5268 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5269 if (Call->getNumArgs() != 2) 5270 return false; 5271 5272 // Make sure this is really a binary operator that is safe to pass into 5273 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5274 OverloadedOperatorKind OO = Call->getOperator(); 5275 if (OO < OO_Plus || OO > OO_Arrow) 5276 return false; 5277 5278 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5279 if (IsArithmeticOp(OpKind)) { 5280 *Opcode = OpKind; 5281 *RHSExprs = Call->getArg(1); 5282 return true; 5283 } 5284 } 5285 5286 return false; 5287 } 5288 5289 static bool IsLogicOp(BinaryOperatorKind Opc) { 5290 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5291 } 5292 5293 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5294 /// or is a logical expression such as (x==y) which has int type, but is 5295 /// commonly interpreted as boolean. 5296 static bool ExprLooksBoolean(Expr *E) { 5297 E = E->IgnoreParenImpCasts(); 5298 5299 if (E->getType()->isBooleanType()) 5300 return true; 5301 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5302 return IsLogicOp(OP->getOpcode()); 5303 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5304 return OP->getOpcode() == UO_LNot; 5305 5306 return false; 5307 } 5308 5309 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5310 /// and binary operator are mixed in a way that suggests the programmer assumed 5311 /// the conditional operator has higher precedence, for example: 5312 /// "int x = a + someBinaryCondition ? 1 : 2". 5313 static void DiagnoseConditionalPrecedence(Sema &Self, 5314 SourceLocation OpLoc, 5315 Expr *Condition, 5316 Expr *LHSExpr, 5317 Expr *RHSExpr) { 5318 BinaryOperatorKind CondOpcode; 5319 Expr *CondRHS; 5320 5321 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5322 return; 5323 if (!ExprLooksBoolean(CondRHS)) 5324 return; 5325 5326 // The condition is an arithmetic binary expression, with a right- 5327 // hand side that looks boolean, so warn. 5328 5329 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5330 << Condition->getSourceRange() 5331 << BinaryOperator::getOpcodeStr(CondOpcode); 5332 5333 SuggestParentheses(Self, OpLoc, 5334 Self.PDiag(diag::note_precedence_silence) 5335 << BinaryOperator::getOpcodeStr(CondOpcode), 5336 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5337 5338 SuggestParentheses(Self, OpLoc, 5339 Self.PDiag(diag::note_precedence_conditional_first), 5340 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5341 } 5342 5343 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5344 /// in the case of a the GNU conditional expr extension. 5345 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5346 SourceLocation ColonLoc, 5347 Expr *CondExpr, Expr *LHSExpr, 5348 Expr *RHSExpr) { 5349 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5350 // was the condition. 5351 OpaqueValueExpr *opaqueValue = 0; 5352 Expr *commonExpr = 0; 5353 if (LHSExpr == 0) { 5354 commonExpr = CondExpr; 5355 5356 // We usually want to apply unary conversions *before* saving, except 5357 // in the special case of a C++ l-value conditional. 5358 if (!(getLangOpts().CPlusPlus 5359 && !commonExpr->isTypeDependent() 5360 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5361 && commonExpr->isGLValue() 5362 && commonExpr->isOrdinaryOrBitFieldObject() 5363 && RHSExpr->isOrdinaryOrBitFieldObject() 5364 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5365 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5366 if (commonRes.isInvalid()) 5367 return ExprError(); 5368 commonExpr = commonRes.take(); 5369 } 5370 5371 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5372 commonExpr->getType(), 5373 commonExpr->getValueKind(), 5374 commonExpr->getObjectKind(), 5375 commonExpr); 5376 LHSExpr = CondExpr = opaqueValue; 5377 } 5378 5379 ExprValueKind VK = VK_RValue; 5380 ExprObjectKind OK = OK_Ordinary; 5381 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5382 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5383 VK, OK, QuestionLoc); 5384 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5385 RHS.isInvalid()) 5386 return ExprError(); 5387 5388 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5389 RHS.get()); 5390 5391 if (!commonExpr) 5392 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5393 LHS.take(), ColonLoc, 5394 RHS.take(), result, VK, OK)); 5395 5396 return Owned(new (Context) 5397 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5398 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5399 OK)); 5400 } 5401 5402 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5403 // being closely modeled after the C99 spec:-). The odd characteristic of this 5404 // routine is it effectively iqnores the qualifiers on the top level pointee. 5405 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5406 // FIXME: add a couple examples in this comment. 5407 static Sema::AssignConvertType 5408 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5409 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5410 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5411 5412 // get the "pointed to" type (ignoring qualifiers at the top level) 5413 const Type *lhptee, *rhptee; 5414 Qualifiers lhq, rhq; 5415 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5416 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5417 5418 Sema::AssignConvertType ConvTy = Sema::Compatible; 5419 5420 // C99 6.5.16.1p1: This following citation is common to constraints 5421 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5422 // qualifiers of the type *pointed to* by the right; 5423 Qualifiers lq; 5424 5425 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5426 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5427 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5428 // Ignore lifetime for further calculation. 5429 lhq.removeObjCLifetime(); 5430 rhq.removeObjCLifetime(); 5431 } 5432 5433 if (!lhq.compatiblyIncludes(rhq)) { 5434 // Treat address-space mismatches as fatal. TODO: address subspaces 5435 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5436 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5437 5438 // It's okay to add or remove GC or lifetime qualifiers when converting to 5439 // and from void*. 5440 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5441 .compatiblyIncludes( 5442 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5443 && (lhptee->isVoidType() || rhptee->isVoidType())) 5444 ; // keep old 5445 5446 // Treat lifetime mismatches as fatal. 5447 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5448 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5449 5450 // For GCC compatibility, other qualifier mismatches are treated 5451 // as still compatible in C. 5452 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5453 } 5454 5455 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5456 // incomplete type and the other is a pointer to a qualified or unqualified 5457 // version of void... 5458 if (lhptee->isVoidType()) { 5459 if (rhptee->isIncompleteOrObjectType()) 5460 return ConvTy; 5461 5462 // As an extension, we allow cast to/from void* to function pointer. 5463 assert(rhptee->isFunctionType()); 5464 return Sema::FunctionVoidPointer; 5465 } 5466 5467 if (rhptee->isVoidType()) { 5468 if (lhptee->isIncompleteOrObjectType()) 5469 return ConvTy; 5470 5471 // As an extension, we allow cast to/from void* to function pointer. 5472 assert(lhptee->isFunctionType()); 5473 return Sema::FunctionVoidPointer; 5474 } 5475 5476 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5477 // unqualified versions of compatible types, ... 5478 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5479 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5480 // Check if the pointee types are compatible ignoring the sign. 5481 // We explicitly check for char so that we catch "char" vs 5482 // "unsigned char" on systems where "char" is unsigned. 5483 if (lhptee->isCharType()) 5484 ltrans = S.Context.UnsignedCharTy; 5485 else if (lhptee->hasSignedIntegerRepresentation()) 5486 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5487 5488 if (rhptee->isCharType()) 5489 rtrans = S.Context.UnsignedCharTy; 5490 else if (rhptee->hasSignedIntegerRepresentation()) 5491 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5492 5493 if (ltrans == rtrans) { 5494 // Types are compatible ignoring the sign. Qualifier incompatibility 5495 // takes priority over sign incompatibility because the sign 5496 // warning can be disabled. 5497 if (ConvTy != Sema::Compatible) 5498 return ConvTy; 5499 5500 return Sema::IncompatiblePointerSign; 5501 } 5502 5503 // If we are a multi-level pointer, it's possible that our issue is simply 5504 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5505 // the eventual target type is the same and the pointers have the same 5506 // level of indirection, this must be the issue. 5507 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5508 do { 5509 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5510 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5511 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5512 5513 if (lhptee == rhptee) 5514 return Sema::IncompatibleNestedPointerQualifiers; 5515 } 5516 5517 // General pointer incompatibility takes priority over qualifiers. 5518 return Sema::IncompatiblePointer; 5519 } 5520 if (!S.getLangOpts().CPlusPlus && 5521 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5522 return Sema::IncompatiblePointer; 5523 return ConvTy; 5524 } 5525 5526 /// checkBlockPointerTypesForAssignment - This routine determines whether two 5527 /// block pointer types are compatible or whether a block and normal pointer 5528 /// are compatible. It is more restrict than comparing two function pointer 5529 // types. 5530 static Sema::AssignConvertType 5531 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5532 QualType RHSType) { 5533 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5534 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5535 5536 QualType lhptee, rhptee; 5537 5538 // get the "pointed to" type (ignoring qualifiers at the top level) 5539 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5540 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5541 5542 // In C++, the types have to match exactly. 5543 if (S.getLangOpts().CPlusPlus) 5544 return Sema::IncompatibleBlockPointer; 5545 5546 Sema::AssignConvertType ConvTy = Sema::Compatible; 5547 5548 // For blocks we enforce that qualifiers are identical. 5549 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5550 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5551 5552 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5553 return Sema::IncompatibleBlockPointer; 5554 5555 return ConvTy; 5556 } 5557 5558 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5559 /// for assignment compatibility. 5560 static Sema::AssignConvertType 5561 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5562 QualType RHSType) { 5563 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5564 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5565 5566 if (LHSType->isObjCBuiltinType()) { 5567 // Class is not compatible with ObjC object pointers. 5568 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5569 !RHSType->isObjCQualifiedClassType()) 5570 return Sema::IncompatiblePointer; 5571 return Sema::Compatible; 5572 } 5573 if (RHSType->isObjCBuiltinType()) { 5574 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5575 !LHSType->isObjCQualifiedClassType()) 5576 return Sema::IncompatiblePointer; 5577 return Sema::Compatible; 5578 } 5579 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5580 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5581 5582 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 5583 // make an exception for id<P> 5584 !LHSType->isObjCQualifiedIdType()) 5585 return Sema::CompatiblePointerDiscardsQualifiers; 5586 5587 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5588 return Sema::Compatible; 5589 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5590 return Sema::IncompatibleObjCQualifiedId; 5591 return Sema::IncompatiblePointer; 5592 } 5593 5594 Sema::AssignConvertType 5595 Sema::CheckAssignmentConstraints(SourceLocation Loc, 5596 QualType LHSType, QualType RHSType) { 5597 // Fake up an opaque expression. We don't actually care about what 5598 // cast operations are required, so if CheckAssignmentConstraints 5599 // adds casts to this they'll be wasted, but fortunately that doesn't 5600 // usually happen on valid code. 5601 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5602 ExprResult RHSPtr = &RHSExpr; 5603 CastKind K = CK_Invalid; 5604 5605 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5606 } 5607 5608 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5609 /// has code to accommodate several GCC extensions when type checking 5610 /// pointers. Here are some objectionable examples that GCC considers warnings: 5611 /// 5612 /// int a, *pint; 5613 /// short *pshort; 5614 /// struct foo *pfoo; 5615 /// 5616 /// pint = pshort; // warning: assignment from incompatible pointer type 5617 /// a = pint; // warning: assignment makes integer from pointer without a cast 5618 /// pint = a; // warning: assignment makes pointer from integer without a cast 5619 /// pint = pfoo; // warning: assignment from incompatible pointer type 5620 /// 5621 /// As a result, the code for dealing with pointers is more complex than the 5622 /// C99 spec dictates. 5623 /// 5624 /// Sets 'Kind' for any result kind except Incompatible. 5625 Sema::AssignConvertType 5626 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5627 CastKind &Kind) { 5628 QualType RHSType = RHS.get()->getType(); 5629 QualType OrigLHSType = LHSType; 5630 5631 // Get canonical types. We're not formatting these types, just comparing 5632 // them. 5633 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5634 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5635 5636 5637 // Common case: no conversion required. 5638 if (LHSType == RHSType) { 5639 Kind = CK_NoOp; 5640 return Compatible; 5641 } 5642 5643 // If we have an atomic type, try a non-atomic assignment, then just add an 5644 // atomic qualification step. 5645 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 5646 Sema::AssignConvertType result = 5647 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 5648 if (result != Compatible) 5649 return result; 5650 if (Kind != CK_NoOp) 5651 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 5652 Kind = CK_NonAtomicToAtomic; 5653 return Compatible; 5654 } 5655 5656 // If the left-hand side is a reference type, then we are in a 5657 // (rare!) case where we've allowed the use of references in C, 5658 // e.g., as a parameter type in a built-in function. In this case, 5659 // just make sure that the type referenced is compatible with the 5660 // right-hand side type. The caller is responsible for adjusting 5661 // LHSType so that the resulting expression does not have reference 5662 // type. 5663 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5664 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5665 Kind = CK_LValueBitCast; 5666 return Compatible; 5667 } 5668 return Incompatible; 5669 } 5670 5671 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5672 // to the same ExtVector type. 5673 if (LHSType->isExtVectorType()) { 5674 if (RHSType->isExtVectorType()) 5675 return Incompatible; 5676 if (RHSType->isArithmeticType()) { 5677 // CK_VectorSplat does T -> vector T, so first cast to the 5678 // element type. 5679 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5680 if (elType != RHSType) { 5681 Kind = PrepareScalarCast(RHS, elType); 5682 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5683 } 5684 Kind = CK_VectorSplat; 5685 return Compatible; 5686 } 5687 } 5688 5689 // Conversions to or from vector type. 5690 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5691 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5692 // Allow assignments of an AltiVec vector type to an equivalent GCC 5693 // vector type and vice versa 5694 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5695 Kind = CK_BitCast; 5696 return Compatible; 5697 } 5698 5699 // If we are allowing lax vector conversions, and LHS and RHS are both 5700 // vectors, the total size only needs to be the same. This is a bitcast; 5701 // no bits are changed but the result type is different. 5702 if (getLangOpts().LaxVectorConversions && 5703 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5704 Kind = CK_BitCast; 5705 return IncompatibleVectors; 5706 } 5707 } 5708 return Incompatible; 5709 } 5710 5711 // Arithmetic conversions. 5712 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5713 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 5714 Kind = PrepareScalarCast(RHS, LHSType); 5715 return Compatible; 5716 } 5717 5718 // Conversions to normal pointers. 5719 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 5720 // U* -> T* 5721 if (isa<PointerType>(RHSType)) { 5722 Kind = CK_BitCast; 5723 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 5724 } 5725 5726 // int -> T* 5727 if (RHSType->isIntegerType()) { 5728 Kind = CK_IntegralToPointer; // FIXME: null? 5729 return IntToPointer; 5730 } 5731 5732 // C pointers are not compatible with ObjC object pointers, 5733 // with two exceptions: 5734 if (isa<ObjCObjectPointerType>(RHSType)) { 5735 // - conversions to void* 5736 if (LHSPointer->getPointeeType()->isVoidType()) { 5737 Kind = CK_BitCast; 5738 return Compatible; 5739 } 5740 5741 // - conversions from 'Class' to the redefinition type 5742 if (RHSType->isObjCClassType() && 5743 Context.hasSameType(LHSType, 5744 Context.getObjCClassRedefinitionType())) { 5745 Kind = CK_BitCast; 5746 return Compatible; 5747 } 5748 5749 Kind = CK_BitCast; 5750 return IncompatiblePointer; 5751 } 5752 5753 // U^ -> void* 5754 if (RHSType->getAs<BlockPointerType>()) { 5755 if (LHSPointer->getPointeeType()->isVoidType()) { 5756 Kind = CK_BitCast; 5757 return Compatible; 5758 } 5759 } 5760 5761 return Incompatible; 5762 } 5763 5764 // Conversions to block pointers. 5765 if (isa<BlockPointerType>(LHSType)) { 5766 // U^ -> T^ 5767 if (RHSType->isBlockPointerType()) { 5768 Kind = CK_BitCast; 5769 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 5770 } 5771 5772 // int or null -> T^ 5773 if (RHSType->isIntegerType()) { 5774 Kind = CK_IntegralToPointer; // FIXME: null 5775 return IntToBlockPointer; 5776 } 5777 5778 // id -> T^ 5779 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 5780 Kind = CK_AnyPointerToBlockPointerCast; 5781 return Compatible; 5782 } 5783 5784 // void* -> T^ 5785 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 5786 if (RHSPT->getPointeeType()->isVoidType()) { 5787 Kind = CK_AnyPointerToBlockPointerCast; 5788 return Compatible; 5789 } 5790 5791 return Incompatible; 5792 } 5793 5794 // Conversions to Objective-C pointers. 5795 if (isa<ObjCObjectPointerType>(LHSType)) { 5796 // A* -> B* 5797 if (RHSType->isObjCObjectPointerType()) { 5798 Kind = CK_BitCast; 5799 Sema::AssignConvertType result = 5800 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 5801 if (getLangOpts().ObjCAutoRefCount && 5802 result == Compatible && 5803 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 5804 result = IncompatibleObjCWeakRef; 5805 return result; 5806 } 5807 5808 // int or null -> A* 5809 if (RHSType->isIntegerType()) { 5810 Kind = CK_IntegralToPointer; // FIXME: null 5811 return IntToPointer; 5812 } 5813 5814 // In general, C pointers are not compatible with ObjC object pointers, 5815 // with two exceptions: 5816 if (isa<PointerType>(RHSType)) { 5817 Kind = CK_CPointerToObjCPointerCast; 5818 5819 // - conversions from 'void*' 5820 if (RHSType->isVoidPointerType()) { 5821 return Compatible; 5822 } 5823 5824 // - conversions to 'Class' from its redefinition type 5825 if (LHSType->isObjCClassType() && 5826 Context.hasSameType(RHSType, 5827 Context.getObjCClassRedefinitionType())) { 5828 return Compatible; 5829 } 5830 5831 return IncompatiblePointer; 5832 } 5833 5834 // T^ -> A* 5835 if (RHSType->isBlockPointerType()) { 5836 maybeExtendBlockObject(*this, RHS); 5837 Kind = CK_BlockPointerToObjCPointerCast; 5838 return Compatible; 5839 } 5840 5841 return Incompatible; 5842 } 5843 5844 // Conversions from pointers that are not covered by the above. 5845 if (isa<PointerType>(RHSType)) { 5846 // T* -> _Bool 5847 if (LHSType == Context.BoolTy) { 5848 Kind = CK_PointerToBoolean; 5849 return Compatible; 5850 } 5851 5852 // T* -> int 5853 if (LHSType->isIntegerType()) { 5854 Kind = CK_PointerToIntegral; 5855 return PointerToInt; 5856 } 5857 5858 return Incompatible; 5859 } 5860 5861 // Conversions from Objective-C pointers that are not covered by the above. 5862 if (isa<ObjCObjectPointerType>(RHSType)) { 5863 // T* -> _Bool 5864 if (LHSType == Context.BoolTy) { 5865 Kind = CK_PointerToBoolean; 5866 return Compatible; 5867 } 5868 5869 // T* -> int 5870 if (LHSType->isIntegerType()) { 5871 Kind = CK_PointerToIntegral; 5872 return PointerToInt; 5873 } 5874 5875 return Incompatible; 5876 } 5877 5878 // struct A -> struct B 5879 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 5880 if (Context.typesAreCompatible(LHSType, RHSType)) { 5881 Kind = CK_NoOp; 5882 return Compatible; 5883 } 5884 } 5885 5886 return Incompatible; 5887 } 5888 5889 /// \brief Constructs a transparent union from an expression that is 5890 /// used to initialize the transparent union. 5891 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 5892 ExprResult &EResult, QualType UnionType, 5893 FieldDecl *Field) { 5894 // Build an initializer list that designates the appropriate member 5895 // of the transparent union. 5896 Expr *E = EResult.take(); 5897 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 5898 E, SourceLocation()); 5899 Initializer->setType(UnionType); 5900 Initializer->setInitializedFieldInUnion(Field); 5901 5902 // Build a compound literal constructing a value of the transparent 5903 // union type from this initializer list. 5904 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 5905 EResult = S.Owned( 5906 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 5907 VK_RValue, Initializer, false)); 5908 } 5909 5910 Sema::AssignConvertType 5911 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 5912 ExprResult &RHS) { 5913 QualType RHSType = RHS.get()->getType(); 5914 5915 // If the ArgType is a Union type, we want to handle a potential 5916 // transparent_union GCC extension. 5917 const RecordType *UT = ArgType->getAsUnionType(); 5918 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5919 return Incompatible; 5920 5921 // The field to initialize within the transparent union. 5922 RecordDecl *UD = UT->getDecl(); 5923 FieldDecl *InitField = 0; 5924 // It's compatible if the expression matches any of the fields. 5925 for (RecordDecl::field_iterator it = UD->field_begin(), 5926 itend = UD->field_end(); 5927 it != itend; ++it) { 5928 if (it->getType()->isPointerType()) { 5929 // If the transparent union contains a pointer type, we allow: 5930 // 1) void pointer 5931 // 2) null pointer constant 5932 if (RHSType->isPointerType()) 5933 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 5934 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 5935 InitField = *it; 5936 break; 5937 } 5938 5939 if (RHS.get()->isNullPointerConstant(Context, 5940 Expr::NPC_ValueDependentIsNull)) { 5941 RHS = ImpCastExprToType(RHS.take(), it->getType(), 5942 CK_NullToPointer); 5943 InitField = *it; 5944 break; 5945 } 5946 } 5947 5948 CastKind Kind = CK_Invalid; 5949 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 5950 == Compatible) { 5951 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 5952 InitField = *it; 5953 break; 5954 } 5955 } 5956 5957 if (!InitField) 5958 return Incompatible; 5959 5960 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 5961 return Compatible; 5962 } 5963 5964 Sema::AssignConvertType 5965 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5966 bool Diagnose) { 5967 if (getLangOpts().CPlusPlus) { 5968 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 5969 // C++ 5.17p3: If the left operand is not of class type, the 5970 // expression is implicitly converted (C++ 4) to the 5971 // cv-unqualified type of the left operand. 5972 ExprResult Res; 5973 if (Diagnose) { 5974 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5975 AA_Assigning); 5976 } else { 5977 ImplicitConversionSequence ICS = 5978 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5979 /*SuppressUserConversions=*/false, 5980 /*AllowExplicit=*/false, 5981 /*InOverloadResolution=*/false, 5982 /*CStyle=*/false, 5983 /*AllowObjCWritebackConversion=*/false); 5984 if (ICS.isFailure()) 5985 return Incompatible; 5986 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5987 ICS, AA_Assigning); 5988 } 5989 if (Res.isInvalid()) 5990 return Incompatible; 5991 Sema::AssignConvertType result = Compatible; 5992 if (getLangOpts().ObjCAutoRefCount && 5993 !CheckObjCARCUnavailableWeakConversion(LHSType, 5994 RHS.get()->getType())) 5995 result = IncompatibleObjCWeakRef; 5996 RHS = Res; 5997 return result; 5998 } 5999 6000 // FIXME: Currently, we fall through and treat C++ classes like C 6001 // structures. 6002 // FIXME: We also fall through for atomics; not sure what should 6003 // happen there, though. 6004 } 6005 6006 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6007 // a null pointer constant. 6008 if ((LHSType->isPointerType() || 6009 LHSType->isObjCObjectPointerType() || 6010 LHSType->isBlockPointerType()) 6011 && RHS.get()->isNullPointerConstant(Context, 6012 Expr::NPC_ValueDependentIsNull)) { 6013 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6014 return Compatible; 6015 } 6016 6017 // This check seems unnatural, however it is necessary to ensure the proper 6018 // conversion of functions/arrays. If the conversion were done for all 6019 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6020 // expressions that suppress this implicit conversion (&, sizeof). 6021 // 6022 // Suppress this for references: C++ 8.5.3p5. 6023 if (!LHSType->isReferenceType()) { 6024 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6025 if (RHS.isInvalid()) 6026 return Incompatible; 6027 } 6028 6029 CastKind Kind = CK_Invalid; 6030 Sema::AssignConvertType result = 6031 CheckAssignmentConstraints(LHSType, RHS, Kind); 6032 6033 // C99 6.5.16.1p2: The value of the right operand is converted to the 6034 // type of the assignment expression. 6035 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6036 // so that we can use references in built-in functions even in C. 6037 // The getNonReferenceType() call makes sure that the resulting expression 6038 // does not have reference type. 6039 if (result != Incompatible && RHS.get()->getType() != LHSType) 6040 RHS = ImpCastExprToType(RHS.take(), 6041 LHSType.getNonLValueExprType(Context), Kind); 6042 return result; 6043 } 6044 6045 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6046 ExprResult &RHS) { 6047 Diag(Loc, diag::err_typecheck_invalid_operands) 6048 << LHS.get()->getType() << RHS.get()->getType() 6049 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6050 return QualType(); 6051 } 6052 6053 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6054 SourceLocation Loc, bool IsCompAssign) { 6055 if (!IsCompAssign) { 6056 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6057 if (LHS.isInvalid()) 6058 return QualType(); 6059 } 6060 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6061 if (RHS.isInvalid()) 6062 return QualType(); 6063 6064 // For conversion purposes, we ignore any qualifiers. 6065 // For example, "const float" and "float" are equivalent. 6066 QualType LHSType = 6067 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6068 QualType RHSType = 6069 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6070 6071 // If the vector types are identical, return. 6072 if (LHSType == RHSType) 6073 return LHSType; 6074 6075 // Handle the case of equivalent AltiVec and GCC vector types 6076 if (LHSType->isVectorType() && RHSType->isVectorType() && 6077 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6078 if (LHSType->isExtVectorType()) { 6079 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6080 return LHSType; 6081 } 6082 6083 if (!IsCompAssign) 6084 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6085 return RHSType; 6086 } 6087 6088 if (getLangOpts().LaxVectorConversions && 6089 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6090 // If we are allowing lax vector conversions, and LHS and RHS are both 6091 // vectors, the total size only needs to be the same. This is a 6092 // bitcast; no bits are changed but the result type is different. 6093 // FIXME: Should we really be allowing this? 6094 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6095 return LHSType; 6096 } 6097 6098 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6099 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6100 bool swapped = false; 6101 if (RHSType->isExtVectorType() && !IsCompAssign) { 6102 swapped = true; 6103 std::swap(RHS, LHS); 6104 std::swap(RHSType, LHSType); 6105 } 6106 6107 // Handle the case of an ext vector and scalar. 6108 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6109 QualType EltTy = LV->getElementType(); 6110 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6111 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6112 if (order > 0) 6113 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6114 if (order >= 0) { 6115 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6116 if (swapped) std::swap(RHS, LHS); 6117 return LHSType; 6118 } 6119 } 6120 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 6121 RHSType->isRealFloatingType()) { 6122 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6123 if (order > 0) 6124 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6125 if (order >= 0) { 6126 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6127 if (swapped) std::swap(RHS, LHS); 6128 return LHSType; 6129 } 6130 } 6131 } 6132 6133 // Vectors of different size or scalar and non-ext-vector are errors. 6134 if (swapped) std::swap(RHS, LHS); 6135 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6136 << LHS.get()->getType() << RHS.get()->getType() 6137 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6138 return QualType(); 6139 } 6140 6141 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6142 // expression. These are mainly cases where the null pointer is used as an 6143 // integer instead of a pointer. 6144 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6145 SourceLocation Loc, bool IsCompare) { 6146 // The canonical way to check for a GNU null is with isNullPointerConstant, 6147 // but we use a bit of a hack here for speed; this is a relatively 6148 // hot path, and isNullPointerConstant is slow. 6149 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6150 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6151 6152 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6153 6154 // Avoid analyzing cases where the result will either be invalid (and 6155 // diagnosed as such) or entirely valid and not something to warn about. 6156 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6157 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6158 return; 6159 6160 // Comparison operations would not make sense with a null pointer no matter 6161 // what the other expression is. 6162 if (!IsCompare) { 6163 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6164 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6165 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6166 return; 6167 } 6168 6169 // The rest of the operations only make sense with a null pointer 6170 // if the other expression is a pointer. 6171 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6172 NonNullType->canDecayToPointerType()) 6173 return; 6174 6175 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6176 << LHSNull /* LHS is NULL */ << NonNullType 6177 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6178 } 6179 6180 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6181 SourceLocation Loc, 6182 bool IsCompAssign, bool IsDiv) { 6183 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6184 6185 if (LHS.get()->getType()->isVectorType() || 6186 RHS.get()->getType()->isVectorType()) 6187 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6188 6189 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6190 if (LHS.isInvalid() || RHS.isInvalid()) 6191 return QualType(); 6192 6193 6194 if (compType.isNull() || !compType->isArithmeticType()) 6195 return InvalidOperands(Loc, LHS, RHS); 6196 6197 // Check for division by zero. 6198 if (IsDiv && 6199 RHS.get()->isNullPointerConstant(Context, 6200 Expr::NPC_ValueDependentIsNotNull)) 6201 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 6202 << RHS.get()->getSourceRange()); 6203 6204 return compType; 6205 } 6206 6207 QualType Sema::CheckRemainderOperands( 6208 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6209 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6210 6211 if (LHS.get()->getType()->isVectorType() || 6212 RHS.get()->getType()->isVectorType()) { 6213 if (LHS.get()->getType()->hasIntegerRepresentation() && 6214 RHS.get()->getType()->hasIntegerRepresentation()) 6215 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6216 return InvalidOperands(Loc, LHS, RHS); 6217 } 6218 6219 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6220 if (LHS.isInvalid() || RHS.isInvalid()) 6221 return QualType(); 6222 6223 if (compType.isNull() || !compType->isIntegerType()) 6224 return InvalidOperands(Loc, LHS, RHS); 6225 6226 // Check for remainder by zero. 6227 if (RHS.get()->isNullPointerConstant(Context, 6228 Expr::NPC_ValueDependentIsNotNull)) 6229 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 6230 << RHS.get()->getSourceRange()); 6231 6232 return compType; 6233 } 6234 6235 /// \brief Diagnose invalid arithmetic on two void pointers. 6236 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6237 Expr *LHSExpr, Expr *RHSExpr) { 6238 S.Diag(Loc, S.getLangOpts().CPlusPlus 6239 ? diag::err_typecheck_pointer_arith_void_type 6240 : diag::ext_gnu_void_ptr) 6241 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6242 << RHSExpr->getSourceRange(); 6243 } 6244 6245 /// \brief Diagnose invalid arithmetic on a void pointer. 6246 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6247 Expr *Pointer) { 6248 S.Diag(Loc, S.getLangOpts().CPlusPlus 6249 ? diag::err_typecheck_pointer_arith_void_type 6250 : diag::ext_gnu_void_ptr) 6251 << 0 /* one pointer */ << Pointer->getSourceRange(); 6252 } 6253 6254 /// \brief Diagnose invalid arithmetic on two function pointers. 6255 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6256 Expr *LHS, Expr *RHS) { 6257 assert(LHS->getType()->isAnyPointerType()); 6258 assert(RHS->getType()->isAnyPointerType()); 6259 S.Diag(Loc, S.getLangOpts().CPlusPlus 6260 ? diag::err_typecheck_pointer_arith_function_type 6261 : diag::ext_gnu_ptr_func_arith) 6262 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6263 // We only show the second type if it differs from the first. 6264 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6265 RHS->getType()) 6266 << RHS->getType()->getPointeeType() 6267 << LHS->getSourceRange() << RHS->getSourceRange(); 6268 } 6269 6270 /// \brief Diagnose invalid arithmetic on a function pointer. 6271 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6272 Expr *Pointer) { 6273 assert(Pointer->getType()->isAnyPointerType()); 6274 S.Diag(Loc, S.getLangOpts().CPlusPlus 6275 ? diag::err_typecheck_pointer_arith_function_type 6276 : diag::ext_gnu_ptr_func_arith) 6277 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6278 << 0 /* one pointer, so only one type */ 6279 << Pointer->getSourceRange(); 6280 } 6281 6282 /// \brief Emit error if Operand is incomplete pointer type 6283 /// 6284 /// \returns True if pointer has incomplete type 6285 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6286 Expr *Operand) { 6287 assert(Operand->getType()->isAnyPointerType() && 6288 !Operand->getType()->isDependentType()); 6289 QualType PointeeTy = Operand->getType()->getPointeeType(); 6290 return S.RequireCompleteType(Loc, PointeeTy, 6291 diag::err_typecheck_arithmetic_incomplete_type, 6292 PointeeTy, Operand->getSourceRange()); 6293 } 6294 6295 /// \brief Check the validity of an arithmetic pointer operand. 6296 /// 6297 /// If the operand has pointer type, this code will check for pointer types 6298 /// which are invalid in arithmetic operations. These will be diagnosed 6299 /// appropriately, including whether or not the use is supported as an 6300 /// extension. 6301 /// 6302 /// \returns True when the operand is valid to use (even if as an extension). 6303 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6304 Expr *Operand) { 6305 if (!Operand->getType()->isAnyPointerType()) return true; 6306 6307 QualType PointeeTy = Operand->getType()->getPointeeType(); 6308 if (PointeeTy->isVoidType()) { 6309 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6310 return !S.getLangOpts().CPlusPlus; 6311 } 6312 if (PointeeTy->isFunctionType()) { 6313 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6314 return !S.getLangOpts().CPlusPlus; 6315 } 6316 6317 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6318 6319 return true; 6320 } 6321 6322 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6323 /// operands. 6324 /// 6325 /// This routine will diagnose any invalid arithmetic on pointer operands much 6326 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 6327 /// for emitting a single diagnostic even for operations where both LHS and RHS 6328 /// are (potentially problematic) pointers. 6329 /// 6330 /// \returns True when the operand is valid to use (even if as an extension). 6331 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6332 Expr *LHSExpr, Expr *RHSExpr) { 6333 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6334 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6335 if (!isLHSPointer && !isRHSPointer) return true; 6336 6337 QualType LHSPointeeTy, RHSPointeeTy; 6338 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6339 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6340 6341 // Check for arithmetic on pointers to incomplete types. 6342 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6343 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6344 if (isLHSVoidPtr || isRHSVoidPtr) { 6345 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6346 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6347 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6348 6349 return !S.getLangOpts().CPlusPlus; 6350 } 6351 6352 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6353 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6354 if (isLHSFuncPtr || isRHSFuncPtr) { 6355 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6356 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6357 RHSExpr); 6358 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6359 6360 return !S.getLangOpts().CPlusPlus; 6361 } 6362 6363 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6364 return false; 6365 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6366 return false; 6367 6368 return true; 6369 } 6370 6371 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6372 /// literal. 6373 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6374 Expr *LHSExpr, Expr *RHSExpr) { 6375 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6376 Expr* IndexExpr = RHSExpr; 6377 if (!StrExpr) { 6378 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6379 IndexExpr = LHSExpr; 6380 } 6381 6382 bool IsStringPlusInt = StrExpr && 6383 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6384 if (!IsStringPlusInt) 6385 return; 6386 6387 llvm::APSInt index; 6388 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6389 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6390 if (index.isNonNegative() && 6391 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6392 index.isUnsigned())) 6393 return; 6394 } 6395 6396 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6397 Self.Diag(OpLoc, diag::warn_string_plus_int) 6398 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6399 6400 // Only print a fixit for "str" + int, not for int + "str". 6401 if (IndexExpr == RHSExpr) { 6402 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6403 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6404 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6405 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6406 << FixItHint::CreateInsertion(EndLoc, "]"); 6407 } else 6408 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6409 } 6410 6411 /// \brief Emit error when two pointers are incompatible. 6412 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6413 Expr *LHSExpr, Expr *RHSExpr) { 6414 assert(LHSExpr->getType()->isAnyPointerType()); 6415 assert(RHSExpr->getType()->isAnyPointerType()); 6416 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6417 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6418 << RHSExpr->getSourceRange(); 6419 } 6420 6421 QualType Sema::CheckAdditionOperands( // C99 6.5.6 6422 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6423 QualType* CompLHSTy) { 6424 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6425 6426 if (LHS.get()->getType()->isVectorType() || 6427 RHS.get()->getType()->isVectorType()) { 6428 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6429 if (CompLHSTy) *CompLHSTy = compType; 6430 return compType; 6431 } 6432 6433 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6434 if (LHS.isInvalid() || RHS.isInvalid()) 6435 return QualType(); 6436 6437 // Diagnose "string literal" '+' int. 6438 if (Opc == BO_Add) 6439 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6440 6441 // handle the common case first (both operands are arithmetic). 6442 if (!compType.isNull() && compType->isArithmeticType()) { 6443 if (CompLHSTy) *CompLHSTy = compType; 6444 return compType; 6445 } 6446 6447 // Type-checking. Ultimately the pointer's going to be in PExp; 6448 // note that we bias towards the LHS being the pointer. 6449 Expr *PExp = LHS.get(), *IExp = RHS.get(); 6450 6451 bool isObjCPointer; 6452 if (PExp->getType()->isPointerType()) { 6453 isObjCPointer = false; 6454 } else if (PExp->getType()->isObjCObjectPointerType()) { 6455 isObjCPointer = true; 6456 } else { 6457 std::swap(PExp, IExp); 6458 if (PExp->getType()->isPointerType()) { 6459 isObjCPointer = false; 6460 } else if (PExp->getType()->isObjCObjectPointerType()) { 6461 isObjCPointer = true; 6462 } else { 6463 return InvalidOperands(Loc, LHS, RHS); 6464 } 6465 } 6466 assert(PExp->getType()->isAnyPointerType()); 6467 6468 if (!IExp->getType()->isIntegerType()) 6469 return InvalidOperands(Loc, LHS, RHS); 6470 6471 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6472 return QualType(); 6473 6474 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 6475 return QualType(); 6476 6477 // Check array bounds for pointer arithemtic 6478 CheckArrayAccess(PExp, IExp); 6479 6480 if (CompLHSTy) { 6481 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6482 if (LHSTy.isNull()) { 6483 LHSTy = LHS.get()->getType(); 6484 if (LHSTy->isPromotableIntegerType()) 6485 LHSTy = Context.getPromotedIntegerType(LHSTy); 6486 } 6487 *CompLHSTy = LHSTy; 6488 } 6489 6490 return PExp->getType(); 6491 } 6492 6493 // C99 6.5.6 6494 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6495 SourceLocation Loc, 6496 QualType* CompLHSTy) { 6497 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6498 6499 if (LHS.get()->getType()->isVectorType() || 6500 RHS.get()->getType()->isVectorType()) { 6501 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6502 if (CompLHSTy) *CompLHSTy = compType; 6503 return compType; 6504 } 6505 6506 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6507 if (LHS.isInvalid() || RHS.isInvalid()) 6508 return QualType(); 6509 6510 // Enforce type constraints: C99 6.5.6p3. 6511 6512 // Handle the common case first (both operands are arithmetic). 6513 if (!compType.isNull() && compType->isArithmeticType()) { 6514 if (CompLHSTy) *CompLHSTy = compType; 6515 return compType; 6516 } 6517 6518 // Either ptr - int or ptr - ptr. 6519 if (LHS.get()->getType()->isAnyPointerType()) { 6520 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6521 6522 // Diagnose bad cases where we step over interface counts. 6523 if (LHS.get()->getType()->isObjCObjectPointerType() && 6524 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 6525 return QualType(); 6526 6527 // The result type of a pointer-int computation is the pointer type. 6528 if (RHS.get()->getType()->isIntegerType()) { 6529 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6530 return QualType(); 6531 6532 // Check array bounds for pointer arithemtic 6533 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 6534 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 6535 6536 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6537 return LHS.get()->getType(); 6538 } 6539 6540 // Handle pointer-pointer subtractions. 6541 if (const PointerType *RHSPTy 6542 = RHS.get()->getType()->getAs<PointerType>()) { 6543 QualType rpointee = RHSPTy->getPointeeType(); 6544 6545 if (getLangOpts().CPlusPlus) { 6546 // Pointee types must be the same: C++ [expr.add] 6547 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6548 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6549 } 6550 } else { 6551 // Pointee types must be compatible C99 6.5.6p3 6552 if (!Context.typesAreCompatible( 6553 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6554 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6555 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6556 return QualType(); 6557 } 6558 } 6559 6560 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6561 LHS.get(), RHS.get())) 6562 return QualType(); 6563 6564 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6565 return Context.getPointerDiffType(); 6566 } 6567 } 6568 6569 return InvalidOperands(Loc, LHS, RHS); 6570 } 6571 6572 static bool isScopedEnumerationType(QualType T) { 6573 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6574 return ET->getDecl()->isScoped(); 6575 return false; 6576 } 6577 6578 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6579 SourceLocation Loc, unsigned Opc, 6580 QualType LHSType) { 6581 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 6582 // so skip remaining warnings as we don't want to modify values within Sema. 6583 if (S.getLangOpts().OpenCL) 6584 return; 6585 6586 llvm::APSInt Right; 6587 // Check right/shifter operand 6588 if (RHS.get()->isValueDependent() || 6589 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6590 return; 6591 6592 if (Right.isNegative()) { 6593 S.DiagRuntimeBehavior(Loc, RHS.get(), 6594 S.PDiag(diag::warn_shift_negative) 6595 << RHS.get()->getSourceRange()); 6596 return; 6597 } 6598 llvm::APInt LeftBits(Right.getBitWidth(), 6599 S.Context.getTypeSize(LHS.get()->getType())); 6600 if (Right.uge(LeftBits)) { 6601 S.DiagRuntimeBehavior(Loc, RHS.get(), 6602 S.PDiag(diag::warn_shift_gt_typewidth) 6603 << RHS.get()->getSourceRange()); 6604 return; 6605 } 6606 if (Opc != BO_Shl) 6607 return; 6608 6609 // When left shifting an ICE which is signed, we can check for overflow which 6610 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6611 // integers have defined behavior modulo one more than the maximum value 6612 // representable in the result type, so never warn for those. 6613 llvm::APSInt Left; 6614 if (LHS.get()->isValueDependent() || 6615 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6616 LHSType->hasUnsignedIntegerRepresentation()) 6617 return; 6618 llvm::APInt ResultBits = 6619 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6620 if (LeftBits.uge(ResultBits)) 6621 return; 6622 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6623 Result = Result.shl(Right); 6624 6625 // Print the bit representation of the signed integer as an unsigned 6626 // hexadecimal number. 6627 SmallString<40> HexResult; 6628 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6629 6630 // If we are only missing a sign bit, this is less likely to result in actual 6631 // bugs -- if the result is cast back to an unsigned type, it will have the 6632 // expected value. Thus we place this behind a different warning that can be 6633 // turned off separately if needed. 6634 if (LeftBits == ResultBits - 1) { 6635 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6636 << HexResult.str() << LHSType 6637 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6638 return; 6639 } 6640 6641 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6642 << HexResult.str() << Result.getMinSignedBits() << LHSType 6643 << Left.getBitWidth() << LHS.get()->getSourceRange() 6644 << RHS.get()->getSourceRange(); 6645 } 6646 6647 // C99 6.5.7 6648 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6649 SourceLocation Loc, unsigned Opc, 6650 bool IsCompAssign) { 6651 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6652 6653 // C99 6.5.7p2: Each of the operands shall have integer type. 6654 if (!LHS.get()->getType()->hasIntegerRepresentation() || 6655 !RHS.get()->getType()->hasIntegerRepresentation()) 6656 return InvalidOperands(Loc, LHS, RHS); 6657 6658 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6659 // hasIntegerRepresentation() above instead of this. 6660 if (isScopedEnumerationType(LHS.get()->getType()) || 6661 isScopedEnumerationType(RHS.get()->getType())) { 6662 return InvalidOperands(Loc, LHS, RHS); 6663 } 6664 6665 // Vector shifts promote their scalar inputs to vector type. 6666 if (LHS.get()->getType()->isVectorType() || 6667 RHS.get()->getType()->isVectorType()) 6668 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6669 6670 // Shifts don't perform usual arithmetic conversions, they just do integer 6671 // promotions on each operand. C99 6.5.7p3 6672 6673 // For the LHS, do usual unary conversions, but then reset them away 6674 // if this is a compound assignment. 6675 ExprResult OldLHS = LHS; 6676 LHS = UsualUnaryConversions(LHS.take()); 6677 if (LHS.isInvalid()) 6678 return QualType(); 6679 QualType LHSType = LHS.get()->getType(); 6680 if (IsCompAssign) LHS = OldLHS; 6681 6682 // The RHS is simpler. 6683 RHS = UsualUnaryConversions(RHS.take()); 6684 if (RHS.isInvalid()) 6685 return QualType(); 6686 6687 // Sanity-check shift operands 6688 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6689 6690 // "The type of the result is that of the promoted left operand." 6691 return LHSType; 6692 } 6693 6694 static bool IsWithinTemplateSpecialization(Decl *D) { 6695 if (DeclContext *DC = D->getDeclContext()) { 6696 if (isa<ClassTemplateSpecializationDecl>(DC)) 6697 return true; 6698 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6699 return FD->isFunctionTemplateSpecialization(); 6700 } 6701 return false; 6702 } 6703 6704 /// If two different enums are compared, raise a warning. 6705 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, 6706 ExprResult &RHS) { 6707 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType(); 6708 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType(); 6709 6710 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6711 if (!LHSEnumType) 6712 return; 6713 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6714 if (!RHSEnumType) 6715 return; 6716 6717 // Ignore anonymous enums. 6718 if (!LHSEnumType->getDecl()->getIdentifier()) 6719 return; 6720 if (!RHSEnumType->getDecl()->getIdentifier()) 6721 return; 6722 6723 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 6724 return; 6725 6726 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 6727 << LHSStrippedType << RHSStrippedType 6728 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6729 } 6730 6731 /// \brief Diagnose bad pointer comparisons. 6732 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 6733 ExprResult &LHS, ExprResult &RHS, 6734 bool IsError) { 6735 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 6736 : diag::ext_typecheck_comparison_of_distinct_pointers) 6737 << LHS.get()->getType() << RHS.get()->getType() 6738 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6739 } 6740 6741 /// \brief Returns false if the pointers are converted to a composite type, 6742 /// true otherwise. 6743 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 6744 ExprResult &LHS, ExprResult &RHS) { 6745 // C++ [expr.rel]p2: 6746 // [...] Pointer conversions (4.10) and qualification 6747 // conversions (4.4) are performed on pointer operands (or on 6748 // a pointer operand and a null pointer constant) to bring 6749 // them to their composite pointer type. [...] 6750 // 6751 // C++ [expr.eq]p1 uses the same notion for (in)equality 6752 // comparisons of pointers. 6753 6754 // C++ [expr.eq]p2: 6755 // In addition, pointers to members can be compared, or a pointer to 6756 // member and a null pointer constant. Pointer to member conversions 6757 // (4.11) and qualification conversions (4.4) are performed to bring 6758 // them to a common type. If one operand is a null pointer constant, 6759 // the common type is the type of the other operand. Otherwise, the 6760 // common type is a pointer to member type similar (4.4) to the type 6761 // of one of the operands, with a cv-qualification signature (4.4) 6762 // that is the union of the cv-qualification signatures of the operand 6763 // types. 6764 6765 QualType LHSType = LHS.get()->getType(); 6766 QualType RHSType = RHS.get()->getType(); 6767 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 6768 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 6769 6770 bool NonStandardCompositeType = false; 6771 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 6772 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 6773 if (T.isNull()) { 6774 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 6775 return true; 6776 } 6777 6778 if (NonStandardCompositeType) 6779 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 6780 << LHSType << RHSType << T << LHS.get()->getSourceRange() 6781 << RHS.get()->getSourceRange(); 6782 6783 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 6784 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 6785 return false; 6786 } 6787 6788 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 6789 ExprResult &LHS, 6790 ExprResult &RHS, 6791 bool IsError) { 6792 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 6793 : diag::ext_typecheck_comparison_of_fptr_to_void) 6794 << LHS.get()->getType() << RHS.get()->getType() 6795 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6796 } 6797 6798 static bool isObjCObjectLiteral(ExprResult &E) { 6799 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 6800 case Stmt::ObjCArrayLiteralClass: 6801 case Stmt::ObjCDictionaryLiteralClass: 6802 case Stmt::ObjCStringLiteralClass: 6803 case Stmt::ObjCBoxedExprClass: 6804 return true; 6805 default: 6806 // Note that ObjCBoolLiteral is NOT an object literal! 6807 return false; 6808 } 6809 } 6810 6811 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 6812 // Get the LHS object's interface type. 6813 QualType Type = LHS->getType(); 6814 QualType InterfaceType; 6815 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) { 6816 InterfaceType = PTy->getPointeeType(); 6817 if (const ObjCObjectType *iQFaceTy = 6818 InterfaceType->getAsObjCQualifiedInterfaceType()) 6819 InterfaceType = iQFaceTy->getBaseType(); 6820 } else { 6821 // If this is not actually an Objective-C object, bail out. 6822 return false; 6823 } 6824 6825 // If the RHS isn't an Objective-C object, bail out. 6826 if (!RHS->getType()->isObjCObjectPointerType()) 6827 return false; 6828 6829 // Try to find the -isEqual: method. 6830 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 6831 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 6832 InterfaceType, 6833 /*instance=*/true); 6834 if (!Method) { 6835 if (Type->isObjCIdType()) { 6836 // For 'id', just check the global pool. 6837 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 6838 /*receiverId=*/true, 6839 /*warn=*/false); 6840 } else { 6841 // Check protocols. 6842 Method = S.LookupMethodInQualifiedType(IsEqualSel, 6843 cast<ObjCObjectPointerType>(Type), 6844 /*instance=*/true); 6845 } 6846 } 6847 6848 if (!Method) 6849 return false; 6850 6851 QualType T = Method->param_begin()[0]->getType(); 6852 if (!T->isObjCObjectPointerType()) 6853 return false; 6854 6855 QualType R = Method->getResultType(); 6856 if (!R->isScalarType()) 6857 return false; 6858 6859 return true; 6860 } 6861 6862 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 6863 FromE = FromE->IgnoreParenImpCasts(); 6864 switch (FromE->getStmtClass()) { 6865 default: 6866 break; 6867 case Stmt::ObjCStringLiteralClass: 6868 // "string literal" 6869 return LK_String; 6870 case Stmt::ObjCArrayLiteralClass: 6871 // "array literal" 6872 return LK_Array; 6873 case Stmt::ObjCDictionaryLiteralClass: 6874 // "dictionary literal" 6875 return LK_Dictionary; 6876 case Stmt::BlockExprClass: 6877 return LK_Block; 6878 case Stmt::ObjCBoxedExprClass: { 6879 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 6880 switch (Inner->getStmtClass()) { 6881 case Stmt::IntegerLiteralClass: 6882 case Stmt::FloatingLiteralClass: 6883 case Stmt::CharacterLiteralClass: 6884 case Stmt::ObjCBoolLiteralExprClass: 6885 case Stmt::CXXBoolLiteralExprClass: 6886 // "numeric literal" 6887 return LK_Numeric; 6888 case Stmt::ImplicitCastExprClass: { 6889 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 6890 // Boolean literals can be represented by implicit casts. 6891 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 6892 return LK_Numeric; 6893 break; 6894 } 6895 default: 6896 break; 6897 } 6898 return LK_Boxed; 6899 } 6900 } 6901 return LK_None; 6902 } 6903 6904 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 6905 ExprResult &LHS, ExprResult &RHS, 6906 BinaryOperator::Opcode Opc){ 6907 Expr *Literal; 6908 Expr *Other; 6909 if (isObjCObjectLiteral(LHS)) { 6910 Literal = LHS.get(); 6911 Other = RHS.get(); 6912 } else { 6913 Literal = RHS.get(); 6914 Other = LHS.get(); 6915 } 6916 6917 // Don't warn on comparisons against nil. 6918 Other = Other->IgnoreParenCasts(); 6919 if (Other->isNullPointerConstant(S.getASTContext(), 6920 Expr::NPC_ValueDependentIsNotNull)) 6921 return; 6922 6923 // This should be kept in sync with warn_objc_literal_comparison. 6924 // LK_String should always be after the other literals, since it has its own 6925 // warning flag. 6926 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 6927 assert(LiteralKind != Sema::LK_Block); 6928 if (LiteralKind == Sema::LK_None) { 6929 llvm_unreachable("Unknown Objective-C object literal kind"); 6930 } 6931 6932 if (LiteralKind == Sema::LK_String) 6933 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 6934 << Literal->getSourceRange(); 6935 else 6936 S.Diag(Loc, diag::warn_objc_literal_comparison) 6937 << LiteralKind << Literal->getSourceRange(); 6938 6939 if (BinaryOperator::isEqualityOp(Opc) && 6940 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 6941 SourceLocation Start = LHS.get()->getLocStart(); 6942 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 6943 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc)); 6944 6945 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 6946 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 6947 << FixItHint::CreateReplacement(OpRange, "isEqual:") 6948 << FixItHint::CreateInsertion(End, "]"); 6949 } 6950 } 6951 6952 // C99 6.5.8, C++ [expr.rel] 6953 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 6954 SourceLocation Loc, unsigned OpaqueOpc, 6955 bool IsRelational) { 6956 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 6957 6958 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 6959 6960 // Handle vector comparisons separately. 6961 if (LHS.get()->getType()->isVectorType() || 6962 RHS.get()->getType()->isVectorType()) 6963 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 6964 6965 QualType LHSType = LHS.get()->getType(); 6966 QualType RHSType = RHS.get()->getType(); 6967 6968 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 6969 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 6970 6971 checkEnumComparison(*this, Loc, LHS, RHS); 6972 6973 if (!LHSType->hasFloatingRepresentation() && 6974 !(LHSType->isBlockPointerType() && IsRelational) && 6975 !LHS.get()->getLocStart().isMacroID() && 6976 !RHS.get()->getLocStart().isMacroID()) { 6977 // For non-floating point types, check for self-comparisons of the form 6978 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6979 // often indicate logic errors in the program. 6980 // 6981 // NOTE: Don't warn about comparison expressions resulting from macro 6982 // expansion. Also don't warn about comparisons which are only self 6983 // comparisons within a template specialization. The warnings should catch 6984 // obvious cases in the definition of the template anyways. The idea is to 6985 // warn when the typed comparison operator will always evaluate to the same 6986 // result. 6987 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 6988 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 6989 if (DRL->getDecl() == DRR->getDecl() && 6990 !IsWithinTemplateSpecialization(DRL->getDecl())) { 6991 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6992 << 0 // self- 6993 << (Opc == BO_EQ 6994 || Opc == BO_LE 6995 || Opc == BO_GE)); 6996 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 6997 !DRL->getDecl()->getType()->isReferenceType() && 6998 !DRR->getDecl()->getType()->isReferenceType()) { 6999 // what is it always going to eval to? 7000 char always_evals_to; 7001 switch(Opc) { 7002 case BO_EQ: // e.g. array1 == array2 7003 always_evals_to = 0; // false 7004 break; 7005 case BO_NE: // e.g. array1 != array2 7006 always_evals_to = 1; // true 7007 break; 7008 default: 7009 // best we can say is 'a constant' 7010 always_evals_to = 2; // e.g. array1 <= array2 7011 break; 7012 } 7013 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7014 << 1 // array 7015 << always_evals_to); 7016 } 7017 } 7018 } 7019 7020 if (isa<CastExpr>(LHSStripped)) 7021 LHSStripped = LHSStripped->IgnoreParenCasts(); 7022 if (isa<CastExpr>(RHSStripped)) 7023 RHSStripped = RHSStripped->IgnoreParenCasts(); 7024 7025 // Warn about comparisons against a string constant (unless the other 7026 // operand is null), the user probably wants strcmp. 7027 Expr *literalString = 0; 7028 Expr *literalStringStripped = 0; 7029 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7030 !RHSStripped->isNullPointerConstant(Context, 7031 Expr::NPC_ValueDependentIsNull)) { 7032 literalString = LHS.get(); 7033 literalStringStripped = LHSStripped; 7034 } else if ((isa<StringLiteral>(RHSStripped) || 7035 isa<ObjCEncodeExpr>(RHSStripped)) && 7036 !LHSStripped->isNullPointerConstant(Context, 7037 Expr::NPC_ValueDependentIsNull)) { 7038 literalString = RHS.get(); 7039 literalStringStripped = RHSStripped; 7040 } 7041 7042 if (literalString) { 7043 std::string resultComparison; 7044 switch (Opc) { 7045 case BO_LT: resultComparison = ") < 0"; break; 7046 case BO_GT: resultComparison = ") > 0"; break; 7047 case BO_LE: resultComparison = ") <= 0"; break; 7048 case BO_GE: resultComparison = ") >= 0"; break; 7049 case BO_EQ: resultComparison = ") == 0"; break; 7050 case BO_NE: resultComparison = ") != 0"; break; 7051 default: llvm_unreachable("Invalid comparison operator"); 7052 } 7053 7054 DiagRuntimeBehavior(Loc, 0, 7055 PDiag(diag::warn_stringcompare) 7056 << isa<ObjCEncodeExpr>(literalStringStripped) 7057 << literalString->getSourceRange()); 7058 } 7059 } 7060 7061 // C99 6.5.8p3 / C99 6.5.9p4 7062 if (LHS.get()->getType()->isArithmeticType() && 7063 RHS.get()->getType()->isArithmeticType()) { 7064 UsualArithmeticConversions(LHS, RHS); 7065 if (LHS.isInvalid() || RHS.isInvalid()) 7066 return QualType(); 7067 } 7068 else { 7069 LHS = UsualUnaryConversions(LHS.take()); 7070 if (LHS.isInvalid()) 7071 return QualType(); 7072 7073 RHS = UsualUnaryConversions(RHS.take()); 7074 if (RHS.isInvalid()) 7075 return QualType(); 7076 } 7077 7078 LHSType = LHS.get()->getType(); 7079 RHSType = RHS.get()->getType(); 7080 7081 // The result of comparisons is 'bool' in C++, 'int' in C. 7082 QualType ResultTy = Context.getLogicalOperationType(); 7083 7084 if (IsRelational) { 7085 if (LHSType->isRealType() && RHSType->isRealType()) 7086 return ResultTy; 7087 } else { 7088 // Check for comparisons of floating point operands using != and ==. 7089 if (LHSType->hasFloatingRepresentation()) 7090 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7091 7092 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7093 return ResultTy; 7094 } 7095 7096 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7097 Expr::NPC_ValueDependentIsNull); 7098 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7099 Expr::NPC_ValueDependentIsNull); 7100 7101 // All of the following pointer-related warnings are GCC extensions, except 7102 // when handling null pointer constants. 7103 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7104 QualType LCanPointeeTy = 7105 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7106 QualType RCanPointeeTy = 7107 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7108 7109 if (getLangOpts().CPlusPlus) { 7110 if (LCanPointeeTy == RCanPointeeTy) 7111 return ResultTy; 7112 if (!IsRelational && 7113 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7114 // Valid unless comparison between non-null pointer and function pointer 7115 // This is a gcc extension compatibility comparison. 7116 // In a SFINAE context, we treat this as a hard error to maintain 7117 // conformance with the C++ standard. 7118 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7119 && !LHSIsNull && !RHSIsNull) { 7120 diagnoseFunctionPointerToVoidComparison( 7121 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext()); 7122 7123 if (isSFINAEContext()) 7124 return QualType(); 7125 7126 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7127 return ResultTy; 7128 } 7129 } 7130 7131 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7132 return QualType(); 7133 else 7134 return ResultTy; 7135 } 7136 // C99 6.5.9p2 and C99 6.5.8p2 7137 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7138 RCanPointeeTy.getUnqualifiedType())) { 7139 // Valid unless a relational comparison of function pointers 7140 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7141 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7142 << LHSType << RHSType << LHS.get()->getSourceRange() 7143 << RHS.get()->getSourceRange(); 7144 } 7145 } else if (!IsRelational && 7146 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7147 // Valid unless comparison between non-null pointer and function pointer 7148 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7149 && !LHSIsNull && !RHSIsNull) 7150 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7151 /*isError*/false); 7152 } else { 7153 // Invalid 7154 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7155 } 7156 if (LCanPointeeTy != RCanPointeeTy) { 7157 if (LHSIsNull && !RHSIsNull) 7158 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7159 else 7160 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7161 } 7162 return ResultTy; 7163 } 7164 7165 if (getLangOpts().CPlusPlus) { 7166 // Comparison of nullptr_t with itself. 7167 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7168 return ResultTy; 7169 7170 // Comparison of pointers with null pointer constants and equality 7171 // comparisons of member pointers to null pointer constants. 7172 if (RHSIsNull && 7173 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7174 (!IsRelational && 7175 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7176 RHS = ImpCastExprToType(RHS.take(), LHSType, 7177 LHSType->isMemberPointerType() 7178 ? CK_NullToMemberPointer 7179 : CK_NullToPointer); 7180 return ResultTy; 7181 } 7182 if (LHSIsNull && 7183 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7184 (!IsRelational && 7185 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7186 LHS = ImpCastExprToType(LHS.take(), RHSType, 7187 RHSType->isMemberPointerType() 7188 ? CK_NullToMemberPointer 7189 : CK_NullToPointer); 7190 return ResultTy; 7191 } 7192 7193 // Comparison of member pointers. 7194 if (!IsRelational && 7195 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7196 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7197 return QualType(); 7198 else 7199 return ResultTy; 7200 } 7201 7202 // Handle scoped enumeration types specifically, since they don't promote 7203 // to integers. 7204 if (LHS.get()->getType()->isEnumeralType() && 7205 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7206 RHS.get()->getType())) 7207 return ResultTy; 7208 } 7209 7210 // Handle block pointer types. 7211 if (!IsRelational && LHSType->isBlockPointerType() && 7212 RHSType->isBlockPointerType()) { 7213 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7214 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7215 7216 if (!LHSIsNull && !RHSIsNull && 7217 !Context.typesAreCompatible(lpointee, rpointee)) { 7218 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7219 << LHSType << RHSType << LHS.get()->getSourceRange() 7220 << RHS.get()->getSourceRange(); 7221 } 7222 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7223 return ResultTy; 7224 } 7225 7226 // Allow block pointers to be compared with null pointer constants. 7227 if (!IsRelational 7228 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7229 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7230 if (!LHSIsNull && !RHSIsNull) { 7231 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7232 ->getPointeeType()->isVoidType()) 7233 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7234 ->getPointeeType()->isVoidType()))) 7235 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7236 << LHSType << RHSType << LHS.get()->getSourceRange() 7237 << RHS.get()->getSourceRange(); 7238 } 7239 if (LHSIsNull && !RHSIsNull) 7240 LHS = ImpCastExprToType(LHS.take(), RHSType, 7241 RHSType->isPointerType() ? CK_BitCast 7242 : CK_AnyPointerToBlockPointerCast); 7243 else 7244 RHS = ImpCastExprToType(RHS.take(), LHSType, 7245 LHSType->isPointerType() ? CK_BitCast 7246 : CK_AnyPointerToBlockPointerCast); 7247 return ResultTy; 7248 } 7249 7250 if (LHSType->isObjCObjectPointerType() || 7251 RHSType->isObjCObjectPointerType()) { 7252 const PointerType *LPT = LHSType->getAs<PointerType>(); 7253 const PointerType *RPT = RHSType->getAs<PointerType>(); 7254 if (LPT || RPT) { 7255 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7256 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7257 7258 if (!LPtrToVoid && !RPtrToVoid && 7259 !Context.typesAreCompatible(LHSType, RHSType)) { 7260 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7261 /*isError*/false); 7262 } 7263 if (LHSIsNull && !RHSIsNull) 7264 LHS = ImpCastExprToType(LHS.take(), RHSType, 7265 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7266 else 7267 RHS = ImpCastExprToType(RHS.take(), LHSType, 7268 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7269 return ResultTy; 7270 } 7271 if (LHSType->isObjCObjectPointerType() && 7272 RHSType->isObjCObjectPointerType()) { 7273 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7274 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7275 /*isError*/false); 7276 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7277 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7278 7279 if (LHSIsNull && !RHSIsNull) 7280 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7281 else 7282 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7283 return ResultTy; 7284 } 7285 } 7286 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7287 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7288 unsigned DiagID = 0; 7289 bool isError = false; 7290 if (LangOpts.DebuggerSupport) { 7291 // Under a debugger, allow the comparison of pointers to integers, 7292 // since users tend to want to compare addresses. 7293 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7294 (RHSIsNull && RHSType->isIntegerType())) { 7295 if (IsRelational && !getLangOpts().CPlusPlus) 7296 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7297 } else if (IsRelational && !getLangOpts().CPlusPlus) 7298 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7299 else if (getLangOpts().CPlusPlus) { 7300 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7301 isError = true; 7302 } else 7303 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7304 7305 if (DiagID) { 7306 Diag(Loc, DiagID) 7307 << LHSType << RHSType << LHS.get()->getSourceRange() 7308 << RHS.get()->getSourceRange(); 7309 if (isError) 7310 return QualType(); 7311 } 7312 7313 if (LHSType->isIntegerType()) 7314 LHS = ImpCastExprToType(LHS.take(), RHSType, 7315 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7316 else 7317 RHS = ImpCastExprToType(RHS.take(), LHSType, 7318 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7319 return ResultTy; 7320 } 7321 7322 // Handle block pointers. 7323 if (!IsRelational && RHSIsNull 7324 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 7325 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 7326 return ResultTy; 7327 } 7328 if (!IsRelational && LHSIsNull 7329 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 7330 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 7331 return ResultTy; 7332 } 7333 7334 return InvalidOperands(Loc, LHS, RHS); 7335 } 7336 7337 7338 // Return a signed type that is of identical size and number of elements. 7339 // For floating point vectors, return an integer type of identical size 7340 // and number of elements. 7341 QualType Sema::GetSignedVectorType(QualType V) { 7342 const VectorType *VTy = V->getAs<VectorType>(); 7343 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7344 if (TypeSize == Context.getTypeSize(Context.CharTy)) 7345 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 7346 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 7347 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 7348 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 7349 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7350 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 7351 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7352 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7353 "Unhandled vector element size in vector compare"); 7354 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7355 } 7356 7357 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 7358 /// operates on extended vector types. Instead of producing an IntTy result, 7359 /// like a scalar comparison, a vector comparison produces a vector of integer 7360 /// types. 7361 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7362 SourceLocation Loc, 7363 bool IsRelational) { 7364 // Check to make sure we're operating on vectors of the same type and width, 7365 // Allowing one side to be a scalar of element type. 7366 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 7367 if (vType.isNull()) 7368 return vType; 7369 7370 QualType LHSType = LHS.get()->getType(); 7371 7372 // If AltiVec, the comparison results in a numeric type, i.e. 7373 // bool for C++, int for C 7374 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 7375 return Context.getLogicalOperationType(); 7376 7377 // For non-floating point types, check for self-comparisons of the form 7378 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7379 // often indicate logic errors in the program. 7380 if (!LHSType->hasFloatingRepresentation()) { 7381 if (DeclRefExpr* DRL 7382 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7383 if (DeclRefExpr* DRR 7384 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7385 if (DRL->getDecl() == DRR->getDecl()) 7386 DiagRuntimeBehavior(Loc, 0, 7387 PDiag(diag::warn_comparison_always) 7388 << 0 // self- 7389 << 2 // "a constant" 7390 ); 7391 } 7392 7393 // Check for comparisons of floating point operands using != and ==. 7394 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 7395 assert (RHS.get()->getType()->hasFloatingRepresentation()); 7396 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7397 } 7398 7399 // Return a signed type for the vector. 7400 return GetSignedVectorType(LHSType); 7401 } 7402 7403 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7404 SourceLocation Loc) { 7405 // Ensure that either both operands are of the same vector type, or 7406 // one operand is of a vector type and the other is of its element type. 7407 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 7408 if (vType.isNull() || vType->isFloatingType()) 7409 return InvalidOperands(Loc, LHS, RHS); 7410 7411 return GetSignedVectorType(LHS.get()->getType()); 7412 } 7413 7414 inline QualType Sema::CheckBitwiseOperands( 7415 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7416 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7417 7418 if (LHS.get()->getType()->isVectorType() || 7419 RHS.get()->getType()->isVectorType()) { 7420 if (LHS.get()->getType()->hasIntegerRepresentation() && 7421 RHS.get()->getType()->hasIntegerRepresentation()) 7422 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7423 7424 return InvalidOperands(Loc, LHS, RHS); 7425 } 7426 7427 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 7428 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 7429 IsCompAssign); 7430 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 7431 return QualType(); 7432 LHS = LHSResult.take(); 7433 RHS = RHSResult.take(); 7434 7435 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 7436 return compType; 7437 return InvalidOperands(Loc, LHS, RHS); 7438 } 7439 7440 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7441 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 7442 7443 // Check vector operands differently. 7444 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 7445 return CheckVectorLogicalOperands(LHS, RHS, Loc); 7446 7447 // Diagnose cases where the user write a logical and/or but probably meant a 7448 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7449 // is a constant. 7450 if (LHS.get()->getType()->isIntegerType() && 7451 !LHS.get()->getType()->isBooleanType() && 7452 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 7453 // Don't warn in macros or template instantiations. 7454 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 7455 // If the RHS can be constant folded, and if it constant folds to something 7456 // that isn't 0 or 1 (which indicate a potential logical operation that 7457 // happened to fold to true/false) then warn. 7458 // Parens on the RHS are ignored. 7459 llvm::APSInt Result; 7460 if (RHS.get()->EvaluateAsInt(Result, Context)) 7461 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 7462 (Result != 0 && Result != 1)) { 7463 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7464 << RHS.get()->getSourceRange() 7465 << (Opc == BO_LAnd ? "&&" : "||"); 7466 // Suggest replacing the logical operator with the bitwise version 7467 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 7468 << (Opc == BO_LAnd ? "&" : "|") 7469 << FixItHint::CreateReplacement(SourceRange( 7470 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 7471 getLangOpts())), 7472 Opc == BO_LAnd ? "&" : "|"); 7473 if (Opc == BO_LAnd) 7474 // Suggest replacing "Foo() && kNonZero" with "Foo()" 7475 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 7476 << FixItHint::CreateRemoval( 7477 SourceRange( 7478 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 7479 0, getSourceManager(), 7480 getLangOpts()), 7481 RHS.get()->getLocEnd())); 7482 } 7483 } 7484 7485 if (!Context.getLangOpts().CPlusPlus) { 7486 LHS = UsualUnaryConversions(LHS.take()); 7487 if (LHS.isInvalid()) 7488 return QualType(); 7489 7490 RHS = UsualUnaryConversions(RHS.take()); 7491 if (RHS.isInvalid()) 7492 return QualType(); 7493 7494 if (!LHS.get()->getType()->isScalarType() || 7495 !RHS.get()->getType()->isScalarType()) 7496 return InvalidOperands(Loc, LHS, RHS); 7497 7498 return Context.IntTy; 7499 } 7500 7501 // The following is safe because we only use this method for 7502 // non-overloadable operands. 7503 7504 // C++ [expr.log.and]p1 7505 // C++ [expr.log.or]p1 7506 // The operands are both contextually converted to type bool. 7507 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 7508 if (LHSRes.isInvalid()) 7509 return InvalidOperands(Loc, LHS, RHS); 7510 LHS = LHSRes; 7511 7512 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 7513 if (RHSRes.isInvalid()) 7514 return InvalidOperands(Loc, LHS, RHS); 7515 RHS = RHSRes; 7516 7517 // C++ [expr.log.and]p2 7518 // C++ [expr.log.or]p2 7519 // The result is a bool. 7520 return Context.BoolTy; 7521 } 7522 7523 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression 7524 /// is a read-only property; return true if so. A readonly property expression 7525 /// depends on various declarations and thus must be treated specially. 7526 /// 7527 static bool IsReadonlyProperty(Expr *E, Sema &S) { 7528 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 7529 if (!PropExpr) return false; 7530 if (PropExpr->isImplicitProperty()) return false; 7531 7532 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 7533 QualType BaseType = PropExpr->isSuperReceiver() ? 7534 PropExpr->getSuperReceiverType() : 7535 PropExpr->getBase()->getType(); 7536 7537 if (const ObjCObjectPointerType *OPT = 7538 BaseType->getAsObjCInterfacePointerType()) 7539 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 7540 if (S.isPropertyReadonly(PDecl, IFace)) 7541 return true; 7542 return false; 7543 } 7544 7545 static bool IsReadonlyMessage(Expr *E, Sema &S) { 7546 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 7547 if (!ME) return false; 7548 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 7549 ObjCMessageExpr *Base = 7550 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 7551 if (!Base) return false; 7552 return Base->getMethodDecl() != 0; 7553 } 7554 7555 /// Is the given expression (which must be 'const') a reference to a 7556 /// variable which was originally non-const, but which has become 7557 /// 'const' due to being captured within a block? 7558 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 7559 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 7560 assert(E->isLValue() && E->getType().isConstQualified()); 7561 E = E->IgnoreParens(); 7562 7563 // Must be a reference to a declaration from an enclosing scope. 7564 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 7565 if (!DRE) return NCCK_None; 7566 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 7567 7568 // The declaration must be a variable which is not declared 'const'. 7569 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 7570 if (!var) return NCCK_None; 7571 if (var->getType().isConstQualified()) return NCCK_None; 7572 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 7573 7574 // Decide whether the first capture was for a block or a lambda. 7575 DeclContext *DC = S.CurContext; 7576 while (DC->getParent() != var->getDeclContext()) 7577 DC = DC->getParent(); 7578 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 7579 } 7580 7581 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7582 /// emit an error and return true. If so, return false. 7583 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7584 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 7585 SourceLocation OrigLoc = Loc; 7586 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7587 &Loc); 7588 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 7589 IsLV = Expr::MLV_ReadonlyProperty; 7590 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 7591 IsLV = Expr::MLV_InvalidMessageExpression; 7592 if (IsLV == Expr::MLV_Valid) 7593 return false; 7594 7595 unsigned Diag = 0; 7596 bool NeedType = false; 7597 switch (IsLV) { // C99 6.5.16p2 7598 case Expr::MLV_ConstQualified: 7599 Diag = diag::err_typecheck_assign_const; 7600 7601 // Use a specialized diagnostic when we're assigning to an object 7602 // from an enclosing function or block. 7603 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 7604 if (NCCK == NCCK_Block) 7605 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7606 else 7607 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 7608 break; 7609 } 7610 7611 // In ARC, use some specialized diagnostics for occasions where we 7612 // infer 'const'. These are always pseudo-strong variables. 7613 if (S.getLangOpts().ObjCAutoRefCount) { 7614 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 7615 if (declRef && isa<VarDecl>(declRef->getDecl())) { 7616 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 7617 7618 // Use the normal diagnostic if it's pseudo-__strong but the 7619 // user actually wrote 'const'. 7620 if (var->isARCPseudoStrong() && 7621 (!var->getTypeSourceInfo() || 7622 !var->getTypeSourceInfo()->getType().isConstQualified())) { 7623 // There are two pseudo-strong cases: 7624 // - self 7625 ObjCMethodDecl *method = S.getCurMethodDecl(); 7626 if (method && var == method->getSelfDecl()) 7627 Diag = method->isClassMethod() 7628 ? diag::err_typecheck_arc_assign_self_class_method 7629 : diag::err_typecheck_arc_assign_self; 7630 7631 // - fast enumeration variables 7632 else 7633 Diag = diag::err_typecheck_arr_assign_enumeration; 7634 7635 SourceRange Assign; 7636 if (Loc != OrigLoc) 7637 Assign = SourceRange(OrigLoc, OrigLoc); 7638 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7639 // We need to preserve the AST regardless, so migration tool 7640 // can do its job. 7641 return false; 7642 } 7643 } 7644 } 7645 7646 break; 7647 case Expr::MLV_ArrayType: 7648 case Expr::MLV_ArrayTemporary: 7649 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7650 NeedType = true; 7651 break; 7652 case Expr::MLV_NotObjectType: 7653 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7654 NeedType = true; 7655 break; 7656 case Expr::MLV_LValueCast: 7657 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7658 break; 7659 case Expr::MLV_Valid: 7660 llvm_unreachable("did not take early return for MLV_Valid"); 7661 case Expr::MLV_InvalidExpression: 7662 case Expr::MLV_MemberFunction: 7663 case Expr::MLV_ClassTemporary: 7664 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7665 break; 7666 case Expr::MLV_IncompleteType: 7667 case Expr::MLV_IncompleteVoidType: 7668 return S.RequireCompleteType(Loc, E->getType(), 7669 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 7670 case Expr::MLV_DuplicateVectorComponents: 7671 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7672 break; 7673 case Expr::MLV_ReadonlyProperty: 7674 case Expr::MLV_NoSetterProperty: 7675 llvm_unreachable("readonly properties should be processed differently"); 7676 case Expr::MLV_InvalidMessageExpression: 7677 Diag = diag::error_readonly_message_assignment; 7678 break; 7679 case Expr::MLV_SubObjCPropertySetting: 7680 Diag = diag::error_no_subobject_property_setting; 7681 break; 7682 } 7683 7684 SourceRange Assign; 7685 if (Loc != OrigLoc) 7686 Assign = SourceRange(OrigLoc, OrigLoc); 7687 if (NeedType) 7688 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7689 else 7690 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7691 return true; 7692 } 7693 7694 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 7695 SourceLocation Loc, 7696 Sema &Sema) { 7697 // C / C++ fields 7698 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 7699 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 7700 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 7701 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 7702 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 7703 } 7704 7705 // Objective-C instance variables 7706 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 7707 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 7708 if (OL && OR && OL->getDecl() == OR->getDecl()) { 7709 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 7710 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 7711 if (RL && RR && RL->getDecl() == RR->getDecl()) 7712 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 7713 } 7714 } 7715 7716 // C99 6.5.16.1 7717 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 7718 SourceLocation Loc, 7719 QualType CompoundType) { 7720 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 7721 7722 // Verify that LHS is a modifiable lvalue, and emit error if not. 7723 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 7724 return QualType(); 7725 7726 QualType LHSType = LHSExpr->getType(); 7727 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 7728 CompoundType; 7729 AssignConvertType ConvTy; 7730 if (CompoundType.isNull()) { 7731 Expr *RHSCheck = RHS.get(); 7732 7733 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 7734 7735 QualType LHSTy(LHSType); 7736 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 7737 if (RHS.isInvalid()) 7738 return QualType(); 7739 // Special case of NSObject attributes on c-style pointer types. 7740 if (ConvTy == IncompatiblePointer && 7741 ((Context.isObjCNSObjectType(LHSType) && 7742 RHSType->isObjCObjectPointerType()) || 7743 (Context.isObjCNSObjectType(RHSType) && 7744 LHSType->isObjCObjectPointerType()))) 7745 ConvTy = Compatible; 7746 7747 if (ConvTy == Compatible && 7748 LHSType->isObjCObjectType()) 7749 Diag(Loc, diag::err_objc_object_assignment) 7750 << LHSType; 7751 7752 // If the RHS is a unary plus or minus, check to see if they = and + are 7753 // right next to each other. If so, the user may have typo'd "x =+ 4" 7754 // instead of "x += 4". 7755 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 7756 RHSCheck = ICE->getSubExpr(); 7757 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 7758 if ((UO->getOpcode() == UO_Plus || 7759 UO->getOpcode() == UO_Minus) && 7760 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 7761 // Only if the two operators are exactly adjacent. 7762 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 7763 // And there is a space or other character before the subexpr of the 7764 // unary +/-. We don't want to warn on "x=-1". 7765 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 7766 UO->getSubExpr()->getLocStart().isFileID()) { 7767 Diag(Loc, diag::warn_not_compound_assign) 7768 << (UO->getOpcode() == UO_Plus ? "+" : "-") 7769 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 7770 } 7771 } 7772 7773 if (ConvTy == Compatible) { 7774 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 7775 // Warn about retain cycles where a block captures the LHS, but 7776 // not if the LHS is a simple variable into which the block is 7777 // being stored...unless that variable can be captured by reference! 7778 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 7779 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 7780 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 7781 checkRetainCycles(LHSExpr, RHS.get()); 7782 7783 // It is safe to assign a weak reference into a strong variable. 7784 // Although this code can still have problems: 7785 // id x = self.weakProp; 7786 // id y = self.weakProp; 7787 // we do not warn to warn spuriously when 'x' and 'y' are on separate 7788 // paths through the function. This should be revisited if 7789 // -Wrepeated-use-of-weak is made flow-sensitive. 7790 DiagnosticsEngine::Level Level = 7791 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 7792 RHS.get()->getLocStart()); 7793 if (Level != DiagnosticsEngine::Ignored) 7794 getCurFunction()->markSafeWeakUse(RHS.get()); 7795 7796 } else if (getLangOpts().ObjCAutoRefCount) { 7797 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 7798 } 7799 } 7800 } else { 7801 // Compound assignment "x += y" 7802 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 7803 } 7804 7805 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 7806 RHS.get(), AA_Assigning)) 7807 return QualType(); 7808 7809 CheckForNullPointerDereference(*this, LHSExpr); 7810 7811 // C99 6.5.16p3: The type of an assignment expression is the type of the 7812 // left operand unless the left operand has qualified type, in which case 7813 // it is the unqualified version of the type of the left operand. 7814 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 7815 // is converted to the type of the assignment expression (above). 7816 // C++ 5.17p1: the type of the assignment expression is that of its left 7817 // operand. 7818 return (getLangOpts().CPlusPlus 7819 ? LHSType : LHSType.getUnqualifiedType()); 7820 } 7821 7822 // C99 6.5.17 7823 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 7824 SourceLocation Loc) { 7825 LHS = S.CheckPlaceholderExpr(LHS.take()); 7826 RHS = S.CheckPlaceholderExpr(RHS.take()); 7827 if (LHS.isInvalid() || RHS.isInvalid()) 7828 return QualType(); 7829 7830 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 7831 // operands, but not unary promotions. 7832 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 7833 7834 // So we treat the LHS as a ignored value, and in C++ we allow the 7835 // containing site to determine what should be done with the RHS. 7836 LHS = S.IgnoredValueConversions(LHS.take()); 7837 if (LHS.isInvalid()) 7838 return QualType(); 7839 7840 S.DiagnoseUnusedExprResult(LHS.get()); 7841 7842 if (!S.getLangOpts().CPlusPlus) { 7843 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 7844 if (RHS.isInvalid()) 7845 return QualType(); 7846 if (!RHS.get()->getType()->isVoidType()) 7847 S.RequireCompleteType(Loc, RHS.get()->getType(), 7848 diag::err_incomplete_type); 7849 } 7850 7851 return RHS.get()->getType(); 7852 } 7853 7854 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 7855 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 7856 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 7857 ExprValueKind &VK, 7858 SourceLocation OpLoc, 7859 bool IsInc, bool IsPrefix) { 7860 if (Op->isTypeDependent()) 7861 return S.Context.DependentTy; 7862 7863 QualType ResType = Op->getType(); 7864 // Atomic types can be used for increment / decrement where the non-atomic 7865 // versions can, so ignore the _Atomic() specifier for the purpose of 7866 // checking. 7867 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7868 ResType = ResAtomicType->getValueType(); 7869 7870 assert(!ResType.isNull() && "no type for increment/decrement expression"); 7871 7872 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 7873 // Decrement of bool is not allowed. 7874 if (!IsInc) { 7875 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 7876 return QualType(); 7877 } 7878 // Increment of bool sets it to true, but is deprecated. 7879 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 7880 } else if (ResType->isRealType()) { 7881 // OK! 7882 } else if (ResType->isPointerType()) { 7883 // C99 6.5.2.4p2, 6.5.6p2 7884 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 7885 return QualType(); 7886 } else if (ResType->isObjCObjectPointerType()) { 7887 // On modern runtimes, ObjC pointer arithmetic is forbidden. 7888 // Otherwise, we just need a complete type. 7889 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 7890 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 7891 return QualType(); 7892 } else if (ResType->isAnyComplexType()) { 7893 // C99 does not support ++/-- on complex types, we allow as an extension. 7894 S.Diag(OpLoc, diag::ext_integer_increment_complex) 7895 << ResType << Op->getSourceRange(); 7896 } else if (ResType->isPlaceholderType()) { 7897 ExprResult PR = S.CheckPlaceholderExpr(Op); 7898 if (PR.isInvalid()) return QualType(); 7899 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 7900 IsInc, IsPrefix); 7901 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 7902 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 7903 } else { 7904 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 7905 << ResType << int(IsInc) << Op->getSourceRange(); 7906 return QualType(); 7907 } 7908 // At this point, we know we have a real, complex or pointer type. 7909 // Now make sure the operand is a modifiable lvalue. 7910 if (CheckForModifiableLvalue(Op, OpLoc, S)) 7911 return QualType(); 7912 // In C++, a prefix increment is the same type as the operand. Otherwise 7913 // (in C or with postfix), the increment is the unqualified type of the 7914 // operand. 7915 if (IsPrefix && S.getLangOpts().CPlusPlus) { 7916 VK = VK_LValue; 7917 return ResType; 7918 } else { 7919 VK = VK_RValue; 7920 return ResType.getUnqualifiedType(); 7921 } 7922 } 7923 7924 7925 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 7926 /// This routine allows us to typecheck complex/recursive expressions 7927 /// where the declaration is needed for type checking. We only need to 7928 /// handle cases when the expression references a function designator 7929 /// or is an lvalue. Here are some examples: 7930 /// - &(x) => x 7931 /// - &*****f => f for f a function designator. 7932 /// - &s.xx => s 7933 /// - &s.zz[1].yy -> s, if zz is an array 7934 /// - *(x + 1) -> x, if x is an array 7935 /// - &"123"[2] -> 0 7936 /// - & __real__ x -> x 7937 static ValueDecl *getPrimaryDecl(Expr *E) { 7938 switch (E->getStmtClass()) { 7939 case Stmt::DeclRefExprClass: 7940 return cast<DeclRefExpr>(E)->getDecl(); 7941 case Stmt::MemberExprClass: 7942 // If this is an arrow operator, the address is an offset from 7943 // the base's value, so the object the base refers to is 7944 // irrelevant. 7945 if (cast<MemberExpr>(E)->isArrow()) 7946 return 0; 7947 // Otherwise, the expression refers to a part of the base 7948 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 7949 case Stmt::ArraySubscriptExprClass: { 7950 // FIXME: This code shouldn't be necessary! We should catch the implicit 7951 // promotion of register arrays earlier. 7952 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 7953 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 7954 if (ICE->getSubExpr()->getType()->isArrayType()) 7955 return getPrimaryDecl(ICE->getSubExpr()); 7956 } 7957 return 0; 7958 } 7959 case Stmt::UnaryOperatorClass: { 7960 UnaryOperator *UO = cast<UnaryOperator>(E); 7961 7962 switch(UO->getOpcode()) { 7963 case UO_Real: 7964 case UO_Imag: 7965 case UO_Extension: 7966 return getPrimaryDecl(UO->getSubExpr()); 7967 default: 7968 return 0; 7969 } 7970 } 7971 case Stmt::ParenExprClass: 7972 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 7973 case Stmt::ImplicitCastExprClass: 7974 // If the result of an implicit cast is an l-value, we care about 7975 // the sub-expression; otherwise, the result here doesn't matter. 7976 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 7977 default: 7978 return 0; 7979 } 7980 } 7981 7982 namespace { 7983 enum { 7984 AO_Bit_Field = 0, 7985 AO_Vector_Element = 1, 7986 AO_Property_Expansion = 2, 7987 AO_Register_Variable = 3, 7988 AO_No_Error = 4 7989 }; 7990 } 7991 /// \brief Diagnose invalid operand for address of operations. 7992 /// 7993 /// \param Type The type of operand which cannot have its address taken. 7994 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 7995 Expr *E, unsigned Type) { 7996 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 7997 } 7998 7999 /// CheckAddressOfOperand - The operand of & must be either a function 8000 /// designator or an lvalue designating an object. If it is an lvalue, the 8001 /// object cannot be declared with storage class register or be a bit field. 8002 /// Note: The usual conversions are *not* applied to the operand of the & 8003 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8004 /// In C++, the operand might be an overloaded function name, in which case 8005 /// we allow the '&' but retain the overloaded-function type. 8006 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 8007 SourceLocation OpLoc) { 8008 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8009 if (PTy->getKind() == BuiltinType::Overload) { 8010 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 8011 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8012 << OrigOp.get()->getSourceRange(); 8013 return QualType(); 8014 } 8015 8016 return S.Context.OverloadTy; 8017 } 8018 8019 if (PTy->getKind() == BuiltinType::UnknownAny) 8020 return S.Context.UnknownAnyTy; 8021 8022 if (PTy->getKind() == BuiltinType::BoundMember) { 8023 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8024 << OrigOp.get()->getSourceRange(); 8025 return QualType(); 8026 } 8027 8028 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 8029 if (OrigOp.isInvalid()) return QualType(); 8030 } 8031 8032 if (OrigOp.get()->isTypeDependent()) 8033 return S.Context.DependentTy; 8034 8035 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8036 8037 // Make sure to ignore parentheses in subsequent checks 8038 Expr *op = OrigOp.get()->IgnoreParens(); 8039 8040 if (S.getLangOpts().C99) { 8041 // Implement C99-only parts of addressof rules. 8042 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8043 if (uOp->getOpcode() == UO_Deref) 8044 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8045 // (assuming the deref expression is valid). 8046 return uOp->getSubExpr()->getType(); 8047 } 8048 // Technically, there should be a check for array subscript 8049 // expressions here, but the result of one is always an lvalue anyway. 8050 } 8051 ValueDecl *dcl = getPrimaryDecl(op); 8052 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 8053 unsigned AddressOfError = AO_No_Error; 8054 8055 if (lval == Expr::LV_ClassTemporary) { 8056 bool sfinae = S.isSFINAEContext(); 8057 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary 8058 : diag::ext_typecheck_addrof_class_temporary) 8059 << op->getType() << op->getSourceRange(); 8060 if (sfinae) 8061 return QualType(); 8062 } else if (isa<ObjCSelectorExpr>(op)) { 8063 return S.Context.getPointerType(op->getType()); 8064 } else if (lval == Expr::LV_MemberFunction) { 8065 // If it's an instance method, make a member pointer. 8066 // The expression must have exactly the form &A::foo. 8067 8068 // If the underlying expression isn't a decl ref, give up. 8069 if (!isa<DeclRefExpr>(op)) { 8070 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8071 << OrigOp.get()->getSourceRange(); 8072 return QualType(); 8073 } 8074 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8075 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8076 8077 // The id-expression was parenthesized. 8078 if (OrigOp.get() != DRE) { 8079 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 8080 << OrigOp.get()->getSourceRange(); 8081 8082 // The method was named without a qualifier. 8083 } else if (!DRE->getQualifier()) { 8084 if (MD->getParent()->getName().empty()) 8085 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8086 << op->getSourceRange(); 8087 else { 8088 SmallString<32> Str; 8089 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8090 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8091 << op->getSourceRange() 8092 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8093 } 8094 } 8095 8096 return S.Context.getMemberPointerType(op->getType(), 8097 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8098 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8099 // C99 6.5.3.2p1 8100 // The operand must be either an l-value or a function designator 8101 if (!op->getType()->isFunctionType()) { 8102 // Use a special diagnostic for loads from property references. 8103 if (isa<PseudoObjectExpr>(op)) { 8104 AddressOfError = AO_Property_Expansion; 8105 } else { 8106 // FIXME: emit more specific diag... 8107 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8108 << op->getSourceRange(); 8109 return QualType(); 8110 } 8111 } 8112 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8113 // The operand cannot be a bit-field 8114 AddressOfError = AO_Bit_Field; 8115 } else if (op->getObjectKind() == OK_VectorComponent) { 8116 // The operand cannot be an element of a vector 8117 AddressOfError = AO_Vector_Element; 8118 } else if (dcl) { // C99 6.5.3.2p1 8119 // We have an lvalue with a decl. Make sure the decl is not declared 8120 // with the register storage-class specifier. 8121 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8122 // in C++ it is not error to take address of a register 8123 // variable (c++03 7.1.1P3) 8124 if (vd->getStorageClass() == SC_Register && 8125 !S.getLangOpts().CPlusPlus) { 8126 AddressOfError = AO_Register_Variable; 8127 } 8128 } else if (isa<FunctionTemplateDecl>(dcl)) { 8129 return S.Context.OverloadTy; 8130 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8131 // Okay: we can take the address of a field. 8132 // Could be a pointer to member, though, if there is an explicit 8133 // scope qualifier for the class. 8134 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8135 DeclContext *Ctx = dcl->getDeclContext(); 8136 if (Ctx && Ctx->isRecord()) { 8137 if (dcl->getType()->isReferenceType()) { 8138 S.Diag(OpLoc, 8139 diag::err_cannot_form_pointer_to_member_of_reference_type) 8140 << dcl->getDeclName() << dcl->getType(); 8141 return QualType(); 8142 } 8143 8144 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8145 Ctx = Ctx->getParent(); 8146 return S.Context.getMemberPointerType(op->getType(), 8147 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8148 } 8149 } 8150 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8151 llvm_unreachable("Unknown/unexpected decl type"); 8152 } 8153 8154 if (AddressOfError != AO_No_Error) { 8155 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 8156 return QualType(); 8157 } 8158 8159 if (lval == Expr::LV_IncompleteVoidType) { 8160 // Taking the address of a void variable is technically illegal, but we 8161 // allow it in cases which are otherwise valid. 8162 // Example: "extern void x; void* y = &x;". 8163 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8164 } 8165 8166 // If the operand has type "type", the result has type "pointer to type". 8167 if (op->getType()->isObjCObjectType()) 8168 return S.Context.getObjCObjectPointerType(op->getType()); 8169 return S.Context.getPointerType(op->getType()); 8170 } 8171 8172 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8173 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8174 SourceLocation OpLoc) { 8175 if (Op->isTypeDependent()) 8176 return S.Context.DependentTy; 8177 8178 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8179 if (ConvResult.isInvalid()) 8180 return QualType(); 8181 Op = ConvResult.take(); 8182 QualType OpTy = Op->getType(); 8183 QualType Result; 8184 8185 if (isa<CXXReinterpretCastExpr>(Op)) { 8186 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8187 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8188 Op->getSourceRange()); 8189 } 8190 8191 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8192 // is an incomplete type or void. It would be possible to warn about 8193 // dereferencing a void pointer, but it's completely well-defined, and such a 8194 // warning is unlikely to catch any mistakes. 8195 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8196 Result = PT->getPointeeType(); 8197 else if (const ObjCObjectPointerType *OPT = 8198 OpTy->getAs<ObjCObjectPointerType>()) 8199 Result = OPT->getPointeeType(); 8200 else { 8201 ExprResult PR = S.CheckPlaceholderExpr(Op); 8202 if (PR.isInvalid()) return QualType(); 8203 if (PR.take() != Op) 8204 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8205 } 8206 8207 if (Result.isNull()) { 8208 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8209 << OpTy << Op->getSourceRange(); 8210 return QualType(); 8211 } 8212 8213 // Dereferences are usually l-values... 8214 VK = VK_LValue; 8215 8216 // ...except that certain expressions are never l-values in C. 8217 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8218 VK = VK_RValue; 8219 8220 return Result; 8221 } 8222 8223 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8224 tok::TokenKind Kind) { 8225 BinaryOperatorKind Opc; 8226 switch (Kind) { 8227 default: llvm_unreachable("Unknown binop!"); 8228 case tok::periodstar: Opc = BO_PtrMemD; break; 8229 case tok::arrowstar: Opc = BO_PtrMemI; break; 8230 case tok::star: Opc = BO_Mul; break; 8231 case tok::slash: Opc = BO_Div; break; 8232 case tok::percent: Opc = BO_Rem; break; 8233 case tok::plus: Opc = BO_Add; break; 8234 case tok::minus: Opc = BO_Sub; break; 8235 case tok::lessless: Opc = BO_Shl; break; 8236 case tok::greatergreater: Opc = BO_Shr; break; 8237 case tok::lessequal: Opc = BO_LE; break; 8238 case tok::less: Opc = BO_LT; break; 8239 case tok::greaterequal: Opc = BO_GE; break; 8240 case tok::greater: Opc = BO_GT; break; 8241 case tok::exclaimequal: Opc = BO_NE; break; 8242 case tok::equalequal: Opc = BO_EQ; break; 8243 case tok::amp: Opc = BO_And; break; 8244 case tok::caret: Opc = BO_Xor; break; 8245 case tok::pipe: Opc = BO_Or; break; 8246 case tok::ampamp: Opc = BO_LAnd; break; 8247 case tok::pipepipe: Opc = BO_LOr; break; 8248 case tok::equal: Opc = BO_Assign; break; 8249 case tok::starequal: Opc = BO_MulAssign; break; 8250 case tok::slashequal: Opc = BO_DivAssign; break; 8251 case tok::percentequal: Opc = BO_RemAssign; break; 8252 case tok::plusequal: Opc = BO_AddAssign; break; 8253 case tok::minusequal: Opc = BO_SubAssign; break; 8254 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8255 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8256 case tok::ampequal: Opc = BO_AndAssign; break; 8257 case tok::caretequal: Opc = BO_XorAssign; break; 8258 case tok::pipeequal: Opc = BO_OrAssign; break; 8259 case tok::comma: Opc = BO_Comma; break; 8260 } 8261 return Opc; 8262 } 8263 8264 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8265 tok::TokenKind Kind) { 8266 UnaryOperatorKind Opc; 8267 switch (Kind) { 8268 default: llvm_unreachable("Unknown unary op!"); 8269 case tok::plusplus: Opc = UO_PreInc; break; 8270 case tok::minusminus: Opc = UO_PreDec; break; 8271 case tok::amp: Opc = UO_AddrOf; break; 8272 case tok::star: Opc = UO_Deref; break; 8273 case tok::plus: Opc = UO_Plus; break; 8274 case tok::minus: Opc = UO_Minus; break; 8275 case tok::tilde: Opc = UO_Not; break; 8276 case tok::exclaim: Opc = UO_LNot; break; 8277 case tok::kw___real: Opc = UO_Real; break; 8278 case tok::kw___imag: Opc = UO_Imag; break; 8279 case tok::kw___extension__: Opc = UO_Extension; break; 8280 } 8281 return Opc; 8282 } 8283 8284 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8285 /// This warning is only emitted for builtin assignment operations. It is also 8286 /// suppressed in the event of macro expansions. 8287 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8288 SourceLocation OpLoc) { 8289 if (!S.ActiveTemplateInstantiations.empty()) 8290 return; 8291 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8292 return; 8293 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8294 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8295 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8296 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8297 if (!LHSDeclRef || !RHSDeclRef || 8298 LHSDeclRef->getLocation().isMacroID() || 8299 RHSDeclRef->getLocation().isMacroID()) 8300 return; 8301 const ValueDecl *LHSDecl = 8302 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8303 const ValueDecl *RHSDecl = 8304 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8305 if (LHSDecl != RHSDecl) 8306 return; 8307 if (LHSDecl->getType().isVolatileQualified()) 8308 return; 8309 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 8310 if (RefTy->getPointeeType().isVolatileQualified()) 8311 return; 8312 8313 S.Diag(OpLoc, diag::warn_self_assignment) 8314 << LHSDeclRef->getType() 8315 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8316 } 8317 8318 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 8319 /// operator @p Opc at location @c TokLoc. This routine only supports 8320 /// built-in operations; ActOnBinOp handles overloaded operators. 8321 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8322 BinaryOperatorKind Opc, 8323 Expr *LHSExpr, Expr *RHSExpr) { 8324 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 8325 // The syntax only allows initializer lists on the RHS of assignment, 8326 // so we don't need to worry about accepting invalid code for 8327 // non-assignment operators. 8328 // C++11 5.17p9: 8329 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 8330 // of x = {} is x = T(). 8331 InitializationKind Kind = 8332 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 8333 InitializedEntity Entity = 8334 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 8335 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1); 8336 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 8337 if (Init.isInvalid()) 8338 return Init; 8339 RHSExpr = Init.take(); 8340 } 8341 8342 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 8343 QualType ResultTy; // Result type of the binary operator. 8344 // The following two variables are used for compound assignment operators 8345 QualType CompLHSTy; // Type of LHS after promotions for computation 8346 QualType CompResultTy; // Type of computation result 8347 ExprValueKind VK = VK_RValue; 8348 ExprObjectKind OK = OK_Ordinary; 8349 8350 switch (Opc) { 8351 case BO_Assign: 8352 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 8353 if (getLangOpts().CPlusPlus && 8354 LHS.get()->getObjectKind() != OK_ObjCProperty) { 8355 VK = LHS.get()->getValueKind(); 8356 OK = LHS.get()->getObjectKind(); 8357 } 8358 if (!ResultTy.isNull()) 8359 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 8360 break; 8361 case BO_PtrMemD: 8362 case BO_PtrMemI: 8363 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 8364 Opc == BO_PtrMemI); 8365 break; 8366 case BO_Mul: 8367 case BO_Div: 8368 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 8369 Opc == BO_Div); 8370 break; 8371 case BO_Rem: 8372 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 8373 break; 8374 case BO_Add: 8375 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 8376 break; 8377 case BO_Sub: 8378 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 8379 break; 8380 case BO_Shl: 8381 case BO_Shr: 8382 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 8383 break; 8384 case BO_LE: 8385 case BO_LT: 8386 case BO_GE: 8387 case BO_GT: 8388 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 8389 break; 8390 case BO_EQ: 8391 case BO_NE: 8392 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 8393 break; 8394 case BO_And: 8395 case BO_Xor: 8396 case BO_Or: 8397 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 8398 break; 8399 case BO_LAnd: 8400 case BO_LOr: 8401 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 8402 break; 8403 case BO_MulAssign: 8404 case BO_DivAssign: 8405 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 8406 Opc == BO_DivAssign); 8407 CompLHSTy = CompResultTy; 8408 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8409 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8410 break; 8411 case BO_RemAssign: 8412 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 8413 CompLHSTy = CompResultTy; 8414 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8415 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8416 break; 8417 case BO_AddAssign: 8418 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 8419 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8420 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8421 break; 8422 case BO_SubAssign: 8423 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 8424 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8425 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8426 break; 8427 case BO_ShlAssign: 8428 case BO_ShrAssign: 8429 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 8430 CompLHSTy = CompResultTy; 8431 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8432 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8433 break; 8434 case BO_AndAssign: 8435 case BO_XorAssign: 8436 case BO_OrAssign: 8437 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 8438 CompLHSTy = CompResultTy; 8439 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8440 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8441 break; 8442 case BO_Comma: 8443 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 8444 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 8445 VK = RHS.get()->getValueKind(); 8446 OK = RHS.get()->getObjectKind(); 8447 } 8448 break; 8449 } 8450 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 8451 return ExprError(); 8452 8453 // Check for array bounds violations for both sides of the BinaryOperator 8454 CheckArrayAccess(LHS.get()); 8455 CheckArrayAccess(RHS.get()); 8456 8457 if (CompResultTy.isNull()) 8458 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 8459 ResultTy, VK, OK, OpLoc, 8460 FPFeatures.fp_contract)); 8461 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 8462 OK_ObjCProperty) { 8463 VK = VK_LValue; 8464 OK = LHS.get()->getObjectKind(); 8465 } 8466 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 8467 ResultTy, VK, OK, CompLHSTy, 8468 CompResultTy, OpLoc, 8469 FPFeatures.fp_contract)); 8470 } 8471 8472 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 8473 /// operators are mixed in a way that suggests that the programmer forgot that 8474 /// comparison operators have higher precedence. The most typical example of 8475 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 8476 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 8477 SourceLocation OpLoc, Expr *LHSExpr, 8478 Expr *RHSExpr) { 8479 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 8480 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 8481 8482 // Check that one of the sides is a comparison operator. 8483 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 8484 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 8485 if (!isLeftComp && !isRightComp) 8486 return; 8487 8488 // Bitwise operations are sometimes used as eager logical ops. 8489 // Don't diagnose this. 8490 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 8491 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 8492 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 8493 return; 8494 8495 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 8496 OpLoc) 8497 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 8498 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 8499 SourceRange ParensRange = isLeftComp ? 8500 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 8501 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 8502 8503 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 8504 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 8505 SuggestParentheses(Self, OpLoc, 8506 Self.PDiag(diag::note_precedence_silence) << OpStr, 8507 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 8508 SuggestParentheses(Self, OpLoc, 8509 Self.PDiag(diag::note_precedence_bitwise_first) 8510 << BinaryOperator::getOpcodeStr(Opc), 8511 ParensRange); 8512 } 8513 8514 /// \brief It accepts a '&' expr that is inside a '|' one. 8515 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 8516 /// in parentheses. 8517 static void 8518 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 8519 BinaryOperator *Bop) { 8520 assert(Bop->getOpcode() == BO_And); 8521 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 8522 << Bop->getSourceRange() << OpLoc; 8523 SuggestParentheses(Self, Bop->getOperatorLoc(), 8524 Self.PDiag(diag::note_precedence_silence) 8525 << Bop->getOpcodeStr(), 8526 Bop->getSourceRange()); 8527 } 8528 8529 /// \brief It accepts a '&&' expr that is inside a '||' one. 8530 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 8531 /// in parentheses. 8532 static void 8533 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 8534 BinaryOperator *Bop) { 8535 assert(Bop->getOpcode() == BO_LAnd); 8536 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 8537 << Bop->getSourceRange() << OpLoc; 8538 SuggestParentheses(Self, Bop->getOperatorLoc(), 8539 Self.PDiag(diag::note_precedence_silence) 8540 << Bop->getOpcodeStr(), 8541 Bop->getSourceRange()); 8542 } 8543 8544 /// \brief Returns true if the given expression can be evaluated as a constant 8545 /// 'true'. 8546 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 8547 bool Res; 8548 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 8549 } 8550 8551 /// \brief Returns true if the given expression can be evaluated as a constant 8552 /// 'false'. 8553 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 8554 bool Res; 8555 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 8556 } 8557 8558 /// \brief Look for '&&' in the left hand of a '||' expr. 8559 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 8560 Expr *LHSExpr, Expr *RHSExpr) { 8561 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 8562 if (Bop->getOpcode() == BO_LAnd) { 8563 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 8564 if (EvaluatesAsFalse(S, RHSExpr)) 8565 return; 8566 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 8567 if (!EvaluatesAsTrue(S, Bop->getLHS())) 8568 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8569 } else if (Bop->getOpcode() == BO_LOr) { 8570 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 8571 // If it's "a || b && 1 || c" we didn't warn earlier for 8572 // "a || b && 1", but warn now. 8573 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 8574 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 8575 } 8576 } 8577 } 8578 } 8579 8580 /// \brief Look for '&&' in the right hand of a '||' expr. 8581 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 8582 Expr *LHSExpr, Expr *RHSExpr) { 8583 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 8584 if (Bop->getOpcode() == BO_LAnd) { 8585 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 8586 if (EvaluatesAsFalse(S, LHSExpr)) 8587 return; 8588 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 8589 if (!EvaluatesAsTrue(S, Bop->getRHS())) 8590 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8591 } 8592 } 8593 } 8594 8595 /// \brief Look for '&' in the left or right hand of a '|' expr. 8596 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 8597 Expr *OrArg) { 8598 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 8599 if (Bop->getOpcode() == BO_And) 8600 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 8601 } 8602 } 8603 8604 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 8605 Expr *SubExpr, StringRef Shift) { 8606 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 8607 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 8608 StringRef Op = Bop->getOpcodeStr(); 8609 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 8610 << Bop->getSourceRange() << OpLoc << Shift << Op; 8611 SuggestParentheses(S, Bop->getOperatorLoc(), 8612 S.PDiag(diag::note_precedence_silence) << Op, 8613 Bop->getSourceRange()); 8614 } 8615 } 8616 } 8617 8618 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 8619 /// precedence. 8620 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 8621 SourceLocation OpLoc, Expr *LHSExpr, 8622 Expr *RHSExpr){ 8623 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 8624 if (BinaryOperator::isBitwiseOp(Opc)) 8625 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 8626 8627 // Diagnose "arg1 & arg2 | arg3" 8628 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8629 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 8630 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 8631 } 8632 8633 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 8634 // We don't warn for 'assert(a || b && "bad")' since this is safe. 8635 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8636 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 8637 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 8638 } 8639 8640 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 8641 || Opc == BO_Shr) { 8642 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 8643 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 8644 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 8645 } 8646 } 8647 8648 // Binary Operators. 'Tok' is the token for the operator. 8649 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 8650 tok::TokenKind Kind, 8651 Expr *LHSExpr, Expr *RHSExpr) { 8652 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 8653 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 8654 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 8655 8656 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 8657 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 8658 8659 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 8660 } 8661 8662 /// Build an overloaded binary operator expression in the given scope. 8663 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 8664 BinaryOperatorKind Opc, 8665 Expr *LHS, Expr *RHS) { 8666 // Find all of the overloaded operators visible from this 8667 // point. We perform both an operator-name lookup from the local 8668 // scope and an argument-dependent lookup based on the types of 8669 // the arguments. 8670 UnresolvedSet<16> Functions; 8671 OverloadedOperatorKind OverOp 8672 = BinaryOperator::getOverloadedOperator(Opc); 8673 if (Sc && OverOp != OO_None) 8674 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 8675 RHS->getType(), Functions); 8676 8677 // Build the (potentially-overloaded, potentially-dependent) 8678 // binary operation. 8679 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 8680 } 8681 8682 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 8683 BinaryOperatorKind Opc, 8684 Expr *LHSExpr, Expr *RHSExpr) { 8685 // We want to end up calling one of checkPseudoObjectAssignment 8686 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 8687 // both expressions are overloadable or either is type-dependent), 8688 // or CreateBuiltinBinOp (in any other case). We also want to get 8689 // any placeholder types out of the way. 8690 8691 // Handle pseudo-objects in the LHS. 8692 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 8693 // Assignments with a pseudo-object l-value need special analysis. 8694 if (pty->getKind() == BuiltinType::PseudoObject && 8695 BinaryOperator::isAssignmentOp(Opc)) 8696 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 8697 8698 // Don't resolve overloads if the other type is overloadable. 8699 if (pty->getKind() == BuiltinType::Overload) { 8700 // We can't actually test that if we still have a placeholder, 8701 // though. Fortunately, none of the exceptions we see in that 8702 // code below are valid when the LHS is an overload set. Note 8703 // that an overload set can be dependently-typed, but it never 8704 // instantiates to having an overloadable type. 8705 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8706 if (resolvedRHS.isInvalid()) return ExprError(); 8707 RHSExpr = resolvedRHS.take(); 8708 8709 if (RHSExpr->isTypeDependent() || 8710 RHSExpr->getType()->isOverloadableType()) 8711 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8712 } 8713 8714 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 8715 if (LHS.isInvalid()) return ExprError(); 8716 LHSExpr = LHS.take(); 8717 } 8718 8719 // Handle pseudo-objects in the RHS. 8720 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 8721 // An overload in the RHS can potentially be resolved by the type 8722 // being assigned to. 8723 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 8724 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8725 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8726 8727 if (LHSExpr->getType()->isOverloadableType()) 8728 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8729 8730 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8731 } 8732 8733 // Don't resolve overloads if the other type is overloadable. 8734 if (pty->getKind() == BuiltinType::Overload && 8735 LHSExpr->getType()->isOverloadableType()) 8736 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8737 8738 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8739 if (!resolvedRHS.isUsable()) return ExprError(); 8740 RHSExpr = resolvedRHS.take(); 8741 } 8742 8743 if (getLangOpts().CPlusPlus) { 8744 // If either expression is type-dependent, always build an 8745 // overloaded op. 8746 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8747 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8748 8749 // Otherwise, build an overloaded op if either expression has an 8750 // overloadable type. 8751 if (LHSExpr->getType()->isOverloadableType() || 8752 RHSExpr->getType()->isOverloadableType()) 8753 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8754 } 8755 8756 // Build a built-in binary operation. 8757 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8758 } 8759 8760 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 8761 UnaryOperatorKind Opc, 8762 Expr *InputExpr) { 8763 ExprResult Input = Owned(InputExpr); 8764 ExprValueKind VK = VK_RValue; 8765 ExprObjectKind OK = OK_Ordinary; 8766 QualType resultType; 8767 switch (Opc) { 8768 case UO_PreInc: 8769 case UO_PreDec: 8770 case UO_PostInc: 8771 case UO_PostDec: 8772 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 8773 Opc == UO_PreInc || 8774 Opc == UO_PostInc, 8775 Opc == UO_PreInc || 8776 Opc == UO_PreDec); 8777 break; 8778 case UO_AddrOf: 8779 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 8780 break; 8781 case UO_Deref: { 8782 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8783 if (Input.isInvalid()) return ExprError(); 8784 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 8785 break; 8786 } 8787 case UO_Plus: 8788 case UO_Minus: 8789 Input = UsualUnaryConversions(Input.take()); 8790 if (Input.isInvalid()) return ExprError(); 8791 resultType = Input.get()->getType(); 8792 if (resultType->isDependentType()) 8793 break; 8794 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 8795 resultType->isVectorType()) 8796 break; 8797 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7 8798 resultType->isEnumeralType()) 8799 break; 8800 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 8801 Opc == UO_Plus && 8802 resultType->isPointerType()) 8803 break; 8804 8805 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8806 << resultType << Input.get()->getSourceRange()); 8807 8808 case UO_Not: // bitwise complement 8809 Input = UsualUnaryConversions(Input.take()); 8810 if (Input.isInvalid()) return ExprError(); 8811 resultType = Input.get()->getType(); 8812 if (resultType->isDependentType()) 8813 break; 8814 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 8815 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 8816 // C99 does not support '~' for complex conjugation. 8817 Diag(OpLoc, diag::ext_integer_complement_complex) 8818 << resultType << Input.get()->getSourceRange(); 8819 else if (resultType->hasIntegerRepresentation()) 8820 break; 8821 else { 8822 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8823 << resultType << Input.get()->getSourceRange()); 8824 } 8825 break; 8826 8827 case UO_LNot: // logical negation 8828 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 8829 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8830 if (Input.isInvalid()) return ExprError(); 8831 resultType = Input.get()->getType(); 8832 8833 // Though we still have to promote half FP to float... 8834 if (resultType->isHalfType()) { 8835 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 8836 resultType = Context.FloatTy; 8837 } 8838 8839 if (resultType->isDependentType()) 8840 break; 8841 if (resultType->isScalarType()) { 8842 // C99 6.5.3.3p1: ok, fallthrough; 8843 if (Context.getLangOpts().CPlusPlus) { 8844 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 8845 // operand contextually converted to bool. 8846 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 8847 ScalarTypeToBooleanCastKind(resultType)); 8848 } 8849 } else if (resultType->isExtVectorType()) { 8850 // Vector logical not returns the signed variant of the operand type. 8851 resultType = GetSignedVectorType(resultType); 8852 break; 8853 } else { 8854 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8855 << resultType << Input.get()->getSourceRange()); 8856 } 8857 8858 // LNot always has type int. C99 6.5.3.3p5. 8859 // In C++, it's bool. C++ 5.3.1p8 8860 resultType = Context.getLogicalOperationType(); 8861 break; 8862 case UO_Real: 8863 case UO_Imag: 8864 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 8865 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 8866 // complex l-values to ordinary l-values and all other values to r-values. 8867 if (Input.isInvalid()) return ExprError(); 8868 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 8869 if (Input.get()->getValueKind() != VK_RValue && 8870 Input.get()->getObjectKind() == OK_Ordinary) 8871 VK = Input.get()->getValueKind(); 8872 } else if (!getLangOpts().CPlusPlus) { 8873 // In C, a volatile scalar is read by __imag. In C++, it is not. 8874 Input = DefaultLvalueConversion(Input.take()); 8875 } 8876 break; 8877 case UO_Extension: 8878 resultType = Input.get()->getType(); 8879 VK = Input.get()->getValueKind(); 8880 OK = Input.get()->getObjectKind(); 8881 break; 8882 } 8883 if (resultType.isNull() || Input.isInvalid()) 8884 return ExprError(); 8885 8886 // Check for array bounds violations in the operand of the UnaryOperator, 8887 // except for the '*' and '&' operators that have to be handled specially 8888 // by CheckArrayAccess (as there are special cases like &array[arraysize] 8889 // that are explicitly defined as valid by the standard). 8890 if (Opc != UO_AddrOf && Opc != UO_Deref) 8891 CheckArrayAccess(Input.get()); 8892 8893 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 8894 VK, OK, OpLoc)); 8895 } 8896 8897 /// \brief Determine whether the given expression is a qualified member 8898 /// access expression, of a form that could be turned into a pointer to member 8899 /// with the address-of operator. 8900 static bool isQualifiedMemberAccess(Expr *E) { 8901 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8902 if (!DRE->getQualifier()) 8903 return false; 8904 8905 ValueDecl *VD = DRE->getDecl(); 8906 if (!VD->isCXXClassMember()) 8907 return false; 8908 8909 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 8910 return true; 8911 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 8912 return Method->isInstance(); 8913 8914 return false; 8915 } 8916 8917 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 8918 if (!ULE->getQualifier()) 8919 return false; 8920 8921 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 8922 DEnd = ULE->decls_end(); 8923 D != DEnd; ++D) { 8924 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 8925 if (Method->isInstance()) 8926 return true; 8927 } else { 8928 // Overload set does not contain methods. 8929 break; 8930 } 8931 } 8932 8933 return false; 8934 } 8935 8936 return false; 8937 } 8938 8939 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 8940 UnaryOperatorKind Opc, Expr *Input) { 8941 // First things first: handle placeholders so that the 8942 // overloaded-operator check considers the right type. 8943 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 8944 // Increment and decrement of pseudo-object references. 8945 if (pty->getKind() == BuiltinType::PseudoObject && 8946 UnaryOperator::isIncrementDecrementOp(Opc)) 8947 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 8948 8949 // extension is always a builtin operator. 8950 if (Opc == UO_Extension) 8951 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8952 8953 // & gets special logic for several kinds of placeholder. 8954 // The builtin code knows what to do. 8955 if (Opc == UO_AddrOf && 8956 (pty->getKind() == BuiltinType::Overload || 8957 pty->getKind() == BuiltinType::UnknownAny || 8958 pty->getKind() == BuiltinType::BoundMember)) 8959 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8960 8961 // Anything else needs to be handled now. 8962 ExprResult Result = CheckPlaceholderExpr(Input); 8963 if (Result.isInvalid()) return ExprError(); 8964 Input = Result.take(); 8965 } 8966 8967 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 8968 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 8969 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 8970 // Find all of the overloaded operators visible from this 8971 // point. We perform both an operator-name lookup from the local 8972 // scope and an argument-dependent lookup based on the types of 8973 // the arguments. 8974 UnresolvedSet<16> Functions; 8975 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 8976 if (S && OverOp != OO_None) 8977 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 8978 Functions); 8979 8980 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 8981 } 8982 8983 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8984 } 8985 8986 // Unary Operators. 'Tok' is the token for the operator. 8987 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 8988 tok::TokenKind Op, Expr *Input) { 8989 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 8990 } 8991 8992 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 8993 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 8994 LabelDecl *TheDecl) { 8995 TheDecl->setUsed(); 8996 // Create the AST node. The address of a label always has type 'void*'. 8997 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 8998 Context.getPointerType(Context.VoidTy))); 8999 } 9000 9001 /// Given the last statement in a statement-expression, check whether 9002 /// the result is a producing expression (like a call to an 9003 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9004 /// release out of the full-expression. Otherwise, return null. 9005 /// Cannot fail. 9006 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9007 // Should always be wrapped with one of these. 9008 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9009 if (!cleanups) return 0; 9010 9011 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9012 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9013 return 0; 9014 9015 // Splice out the cast. This shouldn't modify any interesting 9016 // features of the statement. 9017 Expr *producer = cast->getSubExpr(); 9018 assert(producer->getType() == cast->getType()); 9019 assert(producer->getValueKind() == cast->getValueKind()); 9020 cleanups->setSubExpr(producer); 9021 return cleanups; 9022 } 9023 9024 void Sema::ActOnStartStmtExpr() { 9025 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9026 } 9027 9028 void Sema::ActOnStmtExprError() { 9029 // Note that function is also called by TreeTransform when leaving a 9030 // StmtExpr scope without rebuilding anything. 9031 9032 DiscardCleanupsInEvaluationContext(); 9033 PopExpressionEvaluationContext(); 9034 } 9035 9036 ExprResult 9037 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9038 SourceLocation RPLoc) { // "({..})" 9039 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9040 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9041 9042 if (hasAnyUnrecoverableErrorsInThisFunction()) 9043 DiscardCleanupsInEvaluationContext(); 9044 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9045 PopExpressionEvaluationContext(); 9046 9047 bool isFileScope 9048 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9049 if (isFileScope) 9050 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9051 9052 // FIXME: there are a variety of strange constraints to enforce here, for 9053 // example, it is not possible to goto into a stmt expression apparently. 9054 // More semantic analysis is needed. 9055 9056 // If there are sub stmts in the compound stmt, take the type of the last one 9057 // as the type of the stmtexpr. 9058 QualType Ty = Context.VoidTy; 9059 bool StmtExprMayBindToTemp = false; 9060 if (!Compound->body_empty()) { 9061 Stmt *LastStmt = Compound->body_back(); 9062 LabelStmt *LastLabelStmt = 0; 9063 // If LastStmt is a label, skip down through into the body. 9064 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9065 LastLabelStmt = Label; 9066 LastStmt = Label->getSubStmt(); 9067 } 9068 9069 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9070 // Do function/array conversion on the last expression, but not 9071 // lvalue-to-rvalue. However, initialize an unqualified type. 9072 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9073 if (LastExpr.isInvalid()) 9074 return ExprError(); 9075 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9076 9077 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9078 // In ARC, if the final expression ends in a consume, splice 9079 // the consume out and bind it later. In the alternate case 9080 // (when dealing with a retainable type), the result 9081 // initialization will create a produce. In both cases the 9082 // result will be +1, and we'll need to balance that out with 9083 // a bind. 9084 if (Expr *rebuiltLastStmt 9085 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9086 LastExpr = rebuiltLastStmt; 9087 } else { 9088 LastExpr = PerformCopyInitialization( 9089 InitializedEntity::InitializeResult(LPLoc, 9090 Ty, 9091 false), 9092 SourceLocation(), 9093 LastExpr); 9094 } 9095 9096 if (LastExpr.isInvalid()) 9097 return ExprError(); 9098 if (LastExpr.get() != 0) { 9099 if (!LastLabelStmt) 9100 Compound->setLastStmt(LastExpr.take()); 9101 else 9102 LastLabelStmt->setSubStmt(LastExpr.take()); 9103 StmtExprMayBindToTemp = true; 9104 } 9105 } 9106 } 9107 } 9108 9109 // FIXME: Check that expression type is complete/non-abstract; statement 9110 // expressions are not lvalues. 9111 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9112 if (StmtExprMayBindToTemp) 9113 return MaybeBindToTemporary(ResStmtExpr); 9114 return Owned(ResStmtExpr); 9115 } 9116 9117 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9118 TypeSourceInfo *TInfo, 9119 OffsetOfComponent *CompPtr, 9120 unsigned NumComponents, 9121 SourceLocation RParenLoc) { 9122 QualType ArgTy = TInfo->getType(); 9123 bool Dependent = ArgTy->isDependentType(); 9124 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9125 9126 // We must have at least one component that refers to the type, and the first 9127 // one is known to be a field designator. Verify that the ArgTy represents 9128 // a struct/union/class. 9129 if (!Dependent && !ArgTy->isRecordType()) 9130 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9131 << ArgTy << TypeRange); 9132 9133 // Type must be complete per C99 7.17p3 because a declaring a variable 9134 // with an incomplete type would be ill-formed. 9135 if (!Dependent 9136 && RequireCompleteType(BuiltinLoc, ArgTy, 9137 diag::err_offsetof_incomplete_type, TypeRange)) 9138 return ExprError(); 9139 9140 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9141 // GCC extension, diagnose them. 9142 // FIXME: This diagnostic isn't actually visible because the location is in 9143 // a system header! 9144 if (NumComponents != 1) 9145 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9146 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9147 9148 bool DidWarnAboutNonPOD = false; 9149 QualType CurrentType = ArgTy; 9150 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9151 SmallVector<OffsetOfNode, 4> Comps; 9152 SmallVector<Expr*, 4> Exprs; 9153 for (unsigned i = 0; i != NumComponents; ++i) { 9154 const OffsetOfComponent &OC = CompPtr[i]; 9155 if (OC.isBrackets) { 9156 // Offset of an array sub-field. TODO: Should we allow vector elements? 9157 if (!CurrentType->isDependentType()) { 9158 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9159 if(!AT) 9160 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9161 << CurrentType); 9162 CurrentType = AT->getElementType(); 9163 } else 9164 CurrentType = Context.DependentTy; 9165 9166 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9167 if (IdxRval.isInvalid()) 9168 return ExprError(); 9169 Expr *Idx = IdxRval.take(); 9170 9171 // The expression must be an integral expression. 9172 // FIXME: An integral constant expression? 9173 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9174 !Idx->getType()->isIntegerType()) 9175 return ExprError(Diag(Idx->getLocStart(), 9176 diag::err_typecheck_subscript_not_integer) 9177 << Idx->getSourceRange()); 9178 9179 // Record this array index. 9180 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9181 Exprs.push_back(Idx); 9182 continue; 9183 } 9184 9185 // Offset of a field. 9186 if (CurrentType->isDependentType()) { 9187 // We have the offset of a field, but we can't look into the dependent 9188 // type. Just record the identifier of the field. 9189 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 9190 CurrentType = Context.DependentTy; 9191 continue; 9192 } 9193 9194 // We need to have a complete type to look into. 9195 if (RequireCompleteType(OC.LocStart, CurrentType, 9196 diag::err_offsetof_incomplete_type)) 9197 return ExprError(); 9198 9199 // Look for the designated field. 9200 const RecordType *RC = CurrentType->getAs<RecordType>(); 9201 if (!RC) 9202 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 9203 << CurrentType); 9204 RecordDecl *RD = RC->getDecl(); 9205 9206 // C++ [lib.support.types]p5: 9207 // The macro offsetof accepts a restricted set of type arguments in this 9208 // International Standard. type shall be a POD structure or a POD union 9209 // (clause 9). 9210 // C++11 [support.types]p4: 9211 // If type is not a standard-layout class (Clause 9), the results are 9212 // undefined. 9213 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9214 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 9215 unsigned DiagID = 9216 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 9217 : diag::warn_offsetof_non_pod_type; 9218 9219 if (!IsSafe && !DidWarnAboutNonPOD && 9220 DiagRuntimeBehavior(BuiltinLoc, 0, 9221 PDiag(DiagID) 9222 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 9223 << CurrentType)) 9224 DidWarnAboutNonPOD = true; 9225 } 9226 9227 // Look for the field. 9228 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 9229 LookupQualifiedName(R, RD); 9230 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 9231 IndirectFieldDecl *IndirectMemberDecl = 0; 9232 if (!MemberDecl) { 9233 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 9234 MemberDecl = IndirectMemberDecl->getAnonField(); 9235 } 9236 9237 if (!MemberDecl) 9238 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 9239 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 9240 OC.LocEnd)); 9241 9242 // C99 7.17p3: 9243 // (If the specified member is a bit-field, the behavior is undefined.) 9244 // 9245 // We diagnose this as an error. 9246 if (MemberDecl->isBitField()) { 9247 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 9248 << MemberDecl->getDeclName() 9249 << SourceRange(BuiltinLoc, RParenLoc); 9250 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 9251 return ExprError(); 9252 } 9253 9254 RecordDecl *Parent = MemberDecl->getParent(); 9255 if (IndirectMemberDecl) 9256 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 9257 9258 // If the member was found in a base class, introduce OffsetOfNodes for 9259 // the base class indirections. 9260 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9261 /*DetectVirtual=*/false); 9262 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 9263 CXXBasePath &Path = Paths.front(); 9264 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 9265 B != BEnd; ++B) 9266 Comps.push_back(OffsetOfNode(B->Base)); 9267 } 9268 9269 if (IndirectMemberDecl) { 9270 for (IndirectFieldDecl::chain_iterator FI = 9271 IndirectMemberDecl->chain_begin(), 9272 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 9273 assert(isa<FieldDecl>(*FI)); 9274 Comps.push_back(OffsetOfNode(OC.LocStart, 9275 cast<FieldDecl>(*FI), OC.LocEnd)); 9276 } 9277 } else 9278 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 9279 9280 CurrentType = MemberDecl->getType().getNonReferenceType(); 9281 } 9282 9283 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 9284 TInfo, Comps, Exprs, RParenLoc)); 9285 } 9286 9287 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 9288 SourceLocation BuiltinLoc, 9289 SourceLocation TypeLoc, 9290 ParsedType ParsedArgTy, 9291 OffsetOfComponent *CompPtr, 9292 unsigned NumComponents, 9293 SourceLocation RParenLoc) { 9294 9295 TypeSourceInfo *ArgTInfo; 9296 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 9297 if (ArgTy.isNull()) 9298 return ExprError(); 9299 9300 if (!ArgTInfo) 9301 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 9302 9303 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 9304 RParenLoc); 9305 } 9306 9307 9308 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 9309 Expr *CondExpr, 9310 Expr *LHSExpr, Expr *RHSExpr, 9311 SourceLocation RPLoc) { 9312 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 9313 9314 ExprValueKind VK = VK_RValue; 9315 ExprObjectKind OK = OK_Ordinary; 9316 QualType resType; 9317 bool ValueDependent = false; 9318 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 9319 resType = Context.DependentTy; 9320 ValueDependent = true; 9321 } else { 9322 // The conditional expression is required to be a constant expression. 9323 llvm::APSInt condEval(32); 9324 ExprResult CondICE 9325 = VerifyIntegerConstantExpression(CondExpr, &condEval, 9326 diag::err_typecheck_choose_expr_requires_constant, false); 9327 if (CondICE.isInvalid()) 9328 return ExprError(); 9329 CondExpr = CondICE.take(); 9330 9331 // If the condition is > zero, then the AST type is the same as the LSHExpr. 9332 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 9333 9334 resType = ActiveExpr->getType(); 9335 ValueDependent = ActiveExpr->isValueDependent(); 9336 VK = ActiveExpr->getValueKind(); 9337 OK = ActiveExpr->getObjectKind(); 9338 } 9339 9340 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 9341 resType, VK, OK, RPLoc, 9342 resType->isDependentType(), 9343 ValueDependent)); 9344 } 9345 9346 //===----------------------------------------------------------------------===// 9347 // Clang Extensions. 9348 //===----------------------------------------------------------------------===// 9349 9350 /// ActOnBlockStart - This callback is invoked when a block literal is started. 9351 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 9352 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 9353 PushBlockScope(CurScope, Block); 9354 CurContext->addDecl(Block); 9355 if (CurScope) 9356 PushDeclContext(CurScope, Block); 9357 else 9358 CurContext = Block; 9359 9360 getCurBlock()->HasImplicitReturnType = true; 9361 9362 // Enter a new evaluation context to insulate the block from any 9363 // cleanups from the enclosing full-expression. 9364 PushExpressionEvaluationContext(PotentiallyEvaluated); 9365 } 9366 9367 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 9368 Scope *CurScope) { 9369 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 9370 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 9371 BlockScopeInfo *CurBlock = getCurBlock(); 9372 9373 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 9374 QualType T = Sig->getType(); 9375 9376 // FIXME: We should allow unexpanded parameter packs here, but that would, 9377 // in turn, make the block expression contain unexpanded parameter packs. 9378 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 9379 // Drop the parameters. 9380 FunctionProtoType::ExtProtoInfo EPI; 9381 EPI.HasTrailingReturn = false; 9382 EPI.TypeQuals |= DeclSpec::TQ_const; 9383 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0, 9384 EPI); 9385 Sig = Context.getTrivialTypeSourceInfo(T); 9386 } 9387 9388 // GetTypeForDeclarator always produces a function type for a block 9389 // literal signature. Furthermore, it is always a FunctionProtoType 9390 // unless the function was written with a typedef. 9391 assert(T->isFunctionType() && 9392 "GetTypeForDeclarator made a non-function block signature"); 9393 9394 // Look for an explicit signature in that function type. 9395 FunctionProtoTypeLoc ExplicitSignature; 9396 9397 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 9398 if (isa<FunctionProtoTypeLoc>(tmp)) { 9399 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp); 9400 9401 // Check whether that explicit signature was synthesized by 9402 // GetTypeForDeclarator. If so, don't save that as part of the 9403 // written signature. 9404 if (ExplicitSignature.getLocalRangeBegin() == 9405 ExplicitSignature.getLocalRangeEnd()) { 9406 // This would be much cheaper if we stored TypeLocs instead of 9407 // TypeSourceInfos. 9408 TypeLoc Result = ExplicitSignature.getResultLoc(); 9409 unsigned Size = Result.getFullDataSize(); 9410 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 9411 Sig->getTypeLoc().initializeFullCopy(Result, Size); 9412 9413 ExplicitSignature = FunctionProtoTypeLoc(); 9414 } 9415 } 9416 9417 CurBlock->TheDecl->setSignatureAsWritten(Sig); 9418 CurBlock->FunctionType = T; 9419 9420 const FunctionType *Fn = T->getAs<FunctionType>(); 9421 QualType RetTy = Fn->getResultType(); 9422 bool isVariadic = 9423 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 9424 9425 CurBlock->TheDecl->setIsVariadic(isVariadic); 9426 9427 // Don't allow returning a objc interface by value. 9428 if (RetTy->isObjCObjectType()) { 9429 Diag(ParamInfo.getLocStart(), 9430 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 9431 return; 9432 } 9433 9434 // Context.DependentTy is used as a placeholder for a missing block 9435 // return type. TODO: what should we do with declarators like: 9436 // ^ * { ... } 9437 // If the answer is "apply template argument deduction".... 9438 if (RetTy != Context.DependentTy) { 9439 CurBlock->ReturnType = RetTy; 9440 CurBlock->TheDecl->setBlockMissingReturnType(false); 9441 CurBlock->HasImplicitReturnType = false; 9442 } 9443 9444 // Push block parameters from the declarator if we had them. 9445 SmallVector<ParmVarDecl*, 8> Params; 9446 if (ExplicitSignature) { 9447 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 9448 ParmVarDecl *Param = ExplicitSignature.getArg(I); 9449 if (Param->getIdentifier() == 0 && 9450 !Param->isImplicit() && 9451 !Param->isInvalidDecl() && 9452 !getLangOpts().CPlusPlus) 9453 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9454 Params.push_back(Param); 9455 } 9456 9457 // Fake up parameter variables if we have a typedef, like 9458 // ^ fntype { ... } 9459 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 9460 for (FunctionProtoType::arg_type_iterator 9461 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 9462 ParmVarDecl *Param = 9463 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 9464 ParamInfo.getLocStart(), 9465 *I); 9466 Params.push_back(Param); 9467 } 9468 } 9469 9470 // Set the parameters on the block decl. 9471 if (!Params.empty()) { 9472 CurBlock->TheDecl->setParams(Params); 9473 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 9474 CurBlock->TheDecl->param_end(), 9475 /*CheckParameterNames=*/false); 9476 } 9477 9478 // Finally we can process decl attributes. 9479 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 9480 9481 // Put the parameter variables in scope. We can bail out immediately 9482 // if we don't have any. 9483 if (Params.empty()) 9484 return; 9485 9486 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 9487 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 9488 (*AI)->setOwningFunction(CurBlock->TheDecl); 9489 9490 // If this has an identifier, add it to the scope stack. 9491 if ((*AI)->getIdentifier()) { 9492 CheckShadow(CurBlock->TheScope, *AI); 9493 9494 PushOnScopeChains(*AI, CurBlock->TheScope); 9495 } 9496 } 9497 } 9498 9499 /// ActOnBlockError - If there is an error parsing a block, this callback 9500 /// is invoked to pop the information about the block from the action impl. 9501 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 9502 // Leave the expression-evaluation context. 9503 DiscardCleanupsInEvaluationContext(); 9504 PopExpressionEvaluationContext(); 9505 9506 // Pop off CurBlock, handle nested blocks. 9507 PopDeclContext(); 9508 PopFunctionScopeInfo(); 9509 } 9510 9511 /// ActOnBlockStmtExpr - This is called when the body of a block statement 9512 /// literal was successfully completed. ^(int x){...} 9513 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 9514 Stmt *Body, Scope *CurScope) { 9515 // If blocks are disabled, emit an error. 9516 if (!LangOpts.Blocks) 9517 Diag(CaretLoc, diag::err_blocks_disable); 9518 9519 // Leave the expression-evaluation context. 9520 if (hasAnyUnrecoverableErrorsInThisFunction()) 9521 DiscardCleanupsInEvaluationContext(); 9522 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 9523 PopExpressionEvaluationContext(); 9524 9525 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 9526 9527 if (BSI->HasImplicitReturnType) 9528 deduceClosureReturnType(*BSI); 9529 9530 PopDeclContext(); 9531 9532 QualType RetTy = Context.VoidTy; 9533 if (!BSI->ReturnType.isNull()) 9534 RetTy = BSI->ReturnType; 9535 9536 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 9537 QualType BlockTy; 9538 9539 // Set the captured variables on the block. 9540 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 9541 SmallVector<BlockDecl::Capture, 4> Captures; 9542 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 9543 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 9544 if (Cap.isThisCapture()) 9545 continue; 9546 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 9547 Cap.isNested(), Cap.getCopyExpr()); 9548 Captures.push_back(NewCap); 9549 } 9550 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 9551 BSI->CXXThisCaptureIndex != 0); 9552 9553 // If the user wrote a function type in some form, try to use that. 9554 if (!BSI->FunctionType.isNull()) { 9555 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 9556 9557 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 9558 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 9559 9560 // Turn protoless block types into nullary block types. 9561 if (isa<FunctionNoProtoType>(FTy)) { 9562 FunctionProtoType::ExtProtoInfo EPI; 9563 EPI.ExtInfo = Ext; 9564 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 9565 9566 // Otherwise, if we don't need to change anything about the function type, 9567 // preserve its sugar structure. 9568 } else if (FTy->getResultType() == RetTy && 9569 (!NoReturn || FTy->getNoReturnAttr())) { 9570 BlockTy = BSI->FunctionType; 9571 9572 // Otherwise, make the minimal modifications to the function type. 9573 } else { 9574 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 9575 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9576 EPI.TypeQuals = 0; // FIXME: silently? 9577 EPI.ExtInfo = Ext; 9578 BlockTy = Context.getFunctionType(RetTy, 9579 FPT->arg_type_begin(), 9580 FPT->getNumArgs(), 9581 EPI); 9582 } 9583 9584 // If we don't have a function type, just build one from nothing. 9585 } else { 9586 FunctionProtoType::ExtProtoInfo EPI; 9587 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 9588 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 9589 } 9590 9591 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 9592 BSI->TheDecl->param_end()); 9593 BlockTy = Context.getBlockPointerType(BlockTy); 9594 9595 // If needed, diagnose invalid gotos and switches in the block. 9596 if (getCurFunction()->NeedsScopeChecking() && 9597 !hasAnyUnrecoverableErrorsInThisFunction() && 9598 !PP.isCodeCompletionEnabled()) 9599 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 9600 9601 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 9602 9603 // Try to apply the named return value optimization. We have to check again 9604 // if we can do this, though, because blocks keep return statements around 9605 // to deduce an implicit return type. 9606 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 9607 !BSI->TheDecl->isDependentContext()) 9608 computeNRVO(Body, getCurBlock()); 9609 9610 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 9611 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 9612 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 9613 9614 // If the block isn't obviously global, i.e. it captures anything at 9615 // all, then we need to do a few things in the surrounding context: 9616 if (Result->getBlockDecl()->hasCaptures()) { 9617 // First, this expression has a new cleanup object. 9618 ExprCleanupObjects.push_back(Result->getBlockDecl()); 9619 ExprNeedsCleanups = true; 9620 9621 // It also gets a branch-protected scope if any of the captured 9622 // variables needs destruction. 9623 for (BlockDecl::capture_const_iterator 9624 ci = Result->getBlockDecl()->capture_begin(), 9625 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 9626 const VarDecl *var = ci->getVariable(); 9627 if (var->getType().isDestructedType() != QualType::DK_none) { 9628 getCurFunction()->setHasBranchProtectedScope(); 9629 break; 9630 } 9631 } 9632 } 9633 9634 return Owned(Result); 9635 } 9636 9637 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 9638 Expr *E, ParsedType Ty, 9639 SourceLocation RPLoc) { 9640 TypeSourceInfo *TInfo; 9641 GetTypeFromParser(Ty, &TInfo); 9642 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 9643 } 9644 9645 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 9646 Expr *E, TypeSourceInfo *TInfo, 9647 SourceLocation RPLoc) { 9648 Expr *OrigExpr = E; 9649 9650 // Get the va_list type 9651 QualType VaListType = Context.getBuiltinVaListType(); 9652 if (VaListType->isArrayType()) { 9653 // Deal with implicit array decay; for example, on x86-64, 9654 // va_list is an array, but it's supposed to decay to 9655 // a pointer for va_arg. 9656 VaListType = Context.getArrayDecayedType(VaListType); 9657 // Make sure the input expression also decays appropriately. 9658 ExprResult Result = UsualUnaryConversions(E); 9659 if (Result.isInvalid()) 9660 return ExprError(); 9661 E = Result.take(); 9662 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 9663 // If va_list is a record type and we are compiling in C++ mode, 9664 // check the argument using reference binding. 9665 InitializedEntity Entity 9666 = InitializedEntity::InitializeParameter(Context, 9667 Context.getLValueReferenceType(VaListType), false); 9668 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 9669 if (Init.isInvalid()) 9670 return ExprError(); 9671 E = Init.takeAs<Expr>(); 9672 } else { 9673 // Otherwise, the va_list argument must be an l-value because 9674 // it is modified by va_arg. 9675 if (!E->isTypeDependent() && 9676 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 9677 return ExprError(); 9678 } 9679 9680 if (!E->isTypeDependent() && 9681 !Context.hasSameType(VaListType, E->getType())) { 9682 return ExprError(Diag(E->getLocStart(), 9683 diag::err_first_argument_to_va_arg_not_of_type_va_list) 9684 << OrigExpr->getType() << E->getSourceRange()); 9685 } 9686 9687 if (!TInfo->getType()->isDependentType()) { 9688 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 9689 diag::err_second_parameter_to_va_arg_incomplete, 9690 TInfo->getTypeLoc())) 9691 return ExprError(); 9692 9693 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 9694 TInfo->getType(), 9695 diag::err_second_parameter_to_va_arg_abstract, 9696 TInfo->getTypeLoc())) 9697 return ExprError(); 9698 9699 if (!TInfo->getType().isPODType(Context)) { 9700 Diag(TInfo->getTypeLoc().getBeginLoc(), 9701 TInfo->getType()->isObjCLifetimeType() 9702 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 9703 : diag::warn_second_parameter_to_va_arg_not_pod) 9704 << TInfo->getType() 9705 << TInfo->getTypeLoc().getSourceRange(); 9706 } 9707 9708 // Check for va_arg where arguments of the given type will be promoted 9709 // (i.e. this va_arg is guaranteed to have undefined behavior). 9710 QualType PromoteType; 9711 if (TInfo->getType()->isPromotableIntegerType()) { 9712 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 9713 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 9714 PromoteType = QualType(); 9715 } 9716 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 9717 PromoteType = Context.DoubleTy; 9718 if (!PromoteType.isNull()) 9719 Diag(TInfo->getTypeLoc().getBeginLoc(), 9720 diag::warn_second_parameter_to_va_arg_never_compatible) 9721 << TInfo->getType() 9722 << PromoteType 9723 << TInfo->getTypeLoc().getSourceRange(); 9724 } 9725 9726 QualType T = TInfo->getType().getNonLValueExprType(Context); 9727 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 9728 } 9729 9730 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 9731 // The type of __null will be int or long, depending on the size of 9732 // pointers on the target. 9733 QualType Ty; 9734 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 9735 if (pw == Context.getTargetInfo().getIntWidth()) 9736 Ty = Context.IntTy; 9737 else if (pw == Context.getTargetInfo().getLongWidth()) 9738 Ty = Context.LongTy; 9739 else if (pw == Context.getTargetInfo().getLongLongWidth()) 9740 Ty = Context.LongLongTy; 9741 else { 9742 llvm_unreachable("I don't know size of pointer!"); 9743 } 9744 9745 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 9746 } 9747 9748 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 9749 Expr *SrcExpr, FixItHint &Hint) { 9750 if (!SemaRef.getLangOpts().ObjC1) 9751 return; 9752 9753 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 9754 if (!PT) 9755 return; 9756 9757 // Check if the destination is of type 'id'. 9758 if (!PT->isObjCIdType()) { 9759 // Check if the destination is the 'NSString' interface. 9760 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 9761 if (!ID || !ID->getIdentifier()->isStr("NSString")) 9762 return; 9763 } 9764 9765 // Ignore any parens, implicit casts (should only be 9766 // array-to-pointer decays), and not-so-opaque values. The last is 9767 // important for making this trigger for property assignments. 9768 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 9769 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 9770 if (OV->getSourceExpr()) 9771 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 9772 9773 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 9774 if (!SL || !SL->isAscii()) 9775 return; 9776 9777 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 9778 } 9779 9780 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 9781 SourceLocation Loc, 9782 QualType DstType, QualType SrcType, 9783 Expr *SrcExpr, AssignmentAction Action, 9784 bool *Complained) { 9785 if (Complained) 9786 *Complained = false; 9787 9788 // Decode the result (notice that AST's are still created for extensions). 9789 bool CheckInferredResultType = false; 9790 bool isInvalid = false; 9791 unsigned DiagKind = 0; 9792 FixItHint Hint; 9793 ConversionFixItGenerator ConvHints; 9794 bool MayHaveConvFixit = false; 9795 bool MayHaveFunctionDiff = false; 9796 9797 switch (ConvTy) { 9798 case Compatible: 9799 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 9800 return false; 9801 9802 case PointerToInt: 9803 DiagKind = diag::ext_typecheck_convert_pointer_int; 9804 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9805 MayHaveConvFixit = true; 9806 break; 9807 case IntToPointer: 9808 DiagKind = diag::ext_typecheck_convert_int_pointer; 9809 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9810 MayHaveConvFixit = true; 9811 break; 9812 case IncompatiblePointer: 9813 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 9814 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 9815 CheckInferredResultType = DstType->isObjCObjectPointerType() && 9816 SrcType->isObjCObjectPointerType(); 9817 if (Hint.isNull() && !CheckInferredResultType) { 9818 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9819 } 9820 MayHaveConvFixit = true; 9821 break; 9822 case IncompatiblePointerSign: 9823 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 9824 break; 9825 case FunctionVoidPointer: 9826 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 9827 break; 9828 case IncompatiblePointerDiscardsQualifiers: { 9829 // Perform array-to-pointer decay if necessary. 9830 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 9831 9832 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 9833 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 9834 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 9835 DiagKind = diag::err_typecheck_incompatible_address_space; 9836 break; 9837 9838 9839 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 9840 DiagKind = diag::err_typecheck_incompatible_ownership; 9841 break; 9842 } 9843 9844 llvm_unreachable("unknown error case for discarding qualifiers!"); 9845 // fallthrough 9846 } 9847 case CompatiblePointerDiscardsQualifiers: 9848 // If the qualifiers lost were because we were applying the 9849 // (deprecated) C++ conversion from a string literal to a char* 9850 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 9851 // Ideally, this check would be performed in 9852 // checkPointerTypesForAssignment. However, that would require a 9853 // bit of refactoring (so that the second argument is an 9854 // expression, rather than a type), which should be done as part 9855 // of a larger effort to fix checkPointerTypesForAssignment for 9856 // C++ semantics. 9857 if (getLangOpts().CPlusPlus && 9858 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 9859 return false; 9860 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 9861 break; 9862 case IncompatibleNestedPointerQualifiers: 9863 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 9864 break; 9865 case IntToBlockPointer: 9866 DiagKind = diag::err_int_to_block_pointer; 9867 break; 9868 case IncompatibleBlockPointer: 9869 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 9870 break; 9871 case IncompatibleObjCQualifiedId: 9872 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 9873 // it can give a more specific diagnostic. 9874 DiagKind = diag::warn_incompatible_qualified_id; 9875 break; 9876 case IncompatibleVectors: 9877 DiagKind = diag::warn_incompatible_vectors; 9878 break; 9879 case IncompatibleObjCWeakRef: 9880 DiagKind = diag::err_arc_weak_unavailable_assign; 9881 break; 9882 case Incompatible: 9883 DiagKind = diag::err_typecheck_convert_incompatible; 9884 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9885 MayHaveConvFixit = true; 9886 isInvalid = true; 9887 MayHaveFunctionDiff = true; 9888 break; 9889 } 9890 9891 QualType FirstType, SecondType; 9892 switch (Action) { 9893 case AA_Assigning: 9894 case AA_Initializing: 9895 // The destination type comes first. 9896 FirstType = DstType; 9897 SecondType = SrcType; 9898 break; 9899 9900 case AA_Returning: 9901 case AA_Passing: 9902 case AA_Converting: 9903 case AA_Sending: 9904 case AA_Casting: 9905 // The source type comes first. 9906 FirstType = SrcType; 9907 SecondType = DstType; 9908 break; 9909 } 9910 9911 PartialDiagnostic FDiag = PDiag(DiagKind); 9912 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 9913 9914 // If we can fix the conversion, suggest the FixIts. 9915 assert(ConvHints.isNull() || Hint.isNull()); 9916 if (!ConvHints.isNull()) { 9917 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 9918 HE = ConvHints.Hints.end(); HI != HE; ++HI) 9919 FDiag << *HI; 9920 } else { 9921 FDiag << Hint; 9922 } 9923 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 9924 9925 if (MayHaveFunctionDiff) 9926 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 9927 9928 Diag(Loc, FDiag); 9929 9930 if (SecondType == Context.OverloadTy) 9931 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 9932 FirstType); 9933 9934 if (CheckInferredResultType) 9935 EmitRelatedResultTypeNote(SrcExpr); 9936 9937 if (Complained) 9938 *Complained = true; 9939 return isInvalid; 9940 } 9941 9942 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 9943 llvm::APSInt *Result) { 9944 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 9945 public: 9946 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 9947 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 9948 } 9949 } Diagnoser; 9950 9951 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 9952 } 9953 9954 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 9955 llvm::APSInt *Result, 9956 unsigned DiagID, 9957 bool AllowFold) { 9958 class IDDiagnoser : public VerifyICEDiagnoser { 9959 unsigned DiagID; 9960 9961 public: 9962 IDDiagnoser(unsigned DiagID) 9963 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 9964 9965 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 9966 S.Diag(Loc, DiagID) << SR; 9967 } 9968 } Diagnoser(DiagID); 9969 9970 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 9971 } 9972 9973 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 9974 SourceRange SR) { 9975 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 9976 } 9977 9978 ExprResult 9979 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 9980 VerifyICEDiagnoser &Diagnoser, 9981 bool AllowFold) { 9982 SourceLocation DiagLoc = E->getLocStart(); 9983 9984 if (getLangOpts().CPlusPlus11) { 9985 // C++11 [expr.const]p5: 9986 // If an expression of literal class type is used in a context where an 9987 // integral constant expression is required, then that class type shall 9988 // have a single non-explicit conversion function to an integral or 9989 // unscoped enumeration type 9990 ExprResult Converted; 9991 if (!Diagnoser.Suppress) { 9992 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 9993 public: 9994 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { } 9995 9996 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9997 QualType T) { 9998 return S.Diag(Loc, diag::err_ice_not_integral) << T; 9999 } 10000 10001 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10002 SourceLocation Loc, 10003 QualType T) { 10004 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10005 } 10006 10007 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10008 SourceLocation Loc, 10009 QualType T, 10010 QualType ConvTy) { 10011 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10012 } 10013 10014 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10015 CXXConversionDecl *Conv, 10016 QualType ConvTy) { 10017 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10018 << ConvTy->isEnumeralType() << ConvTy; 10019 } 10020 10021 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10022 QualType T) { 10023 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10024 } 10025 10026 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10027 CXXConversionDecl *Conv, 10028 QualType ConvTy) { 10029 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10030 << ConvTy->isEnumeralType() << ConvTy; 10031 } 10032 10033 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10034 SourceLocation Loc, 10035 QualType T, 10036 QualType ConvTy) { 10037 return DiagnosticBuilder::getEmpty(); 10038 } 10039 } ConvertDiagnoser; 10040 10041 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10042 ConvertDiagnoser, 10043 /*AllowScopedEnumerations*/ false); 10044 } else { 10045 // The caller wants to silently enquire whether this is an ICE. Don't 10046 // produce any diagnostics if it isn't. 10047 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser { 10048 public: 10049 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { } 10050 10051 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10052 QualType T) { 10053 return DiagnosticBuilder::getEmpty(); 10054 } 10055 10056 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10057 SourceLocation Loc, 10058 QualType T) { 10059 return DiagnosticBuilder::getEmpty(); 10060 } 10061 10062 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10063 SourceLocation Loc, 10064 QualType T, 10065 QualType ConvTy) { 10066 return DiagnosticBuilder::getEmpty(); 10067 } 10068 10069 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10070 CXXConversionDecl *Conv, 10071 QualType ConvTy) { 10072 return DiagnosticBuilder::getEmpty(); 10073 } 10074 10075 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10076 QualType T) { 10077 return DiagnosticBuilder::getEmpty(); 10078 } 10079 10080 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10081 CXXConversionDecl *Conv, 10082 QualType ConvTy) { 10083 return DiagnosticBuilder::getEmpty(); 10084 } 10085 10086 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10087 SourceLocation Loc, 10088 QualType T, 10089 QualType ConvTy) { 10090 return DiagnosticBuilder::getEmpty(); 10091 } 10092 } ConvertDiagnoser; 10093 10094 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10095 ConvertDiagnoser, false); 10096 } 10097 if (Converted.isInvalid()) 10098 return Converted; 10099 E = Converted.take(); 10100 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10101 return ExprError(); 10102 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10103 // An ICE must be of integral or unscoped enumeration type. 10104 if (!Diagnoser.Suppress) 10105 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10106 return ExprError(); 10107 } 10108 10109 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10110 // in the non-ICE case. 10111 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10112 if (Result) 10113 *Result = E->EvaluateKnownConstInt(Context); 10114 return Owned(E); 10115 } 10116 10117 Expr::EvalResult EvalResult; 10118 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 10119 EvalResult.Diag = &Notes; 10120 10121 // Try to evaluate the expression, and produce diagnostics explaining why it's 10122 // not a constant expression as a side-effect. 10123 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10124 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10125 10126 // In C++11, we can rely on diagnostics being produced for any expression 10127 // which is not a constant expression. If no diagnostics were produced, then 10128 // this is a constant expression. 10129 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10130 if (Result) 10131 *Result = EvalResult.Val.getInt(); 10132 return Owned(E); 10133 } 10134 10135 // If our only note is the usual "invalid subexpression" note, just point 10136 // the caret at its location rather than producing an essentially 10137 // redundant note. 10138 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10139 diag::note_invalid_subexpr_in_const_expr) { 10140 DiagLoc = Notes[0].first; 10141 Notes.clear(); 10142 } 10143 10144 if (!Folded || !AllowFold) { 10145 if (!Diagnoser.Suppress) { 10146 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10147 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10148 Diag(Notes[I].first, Notes[I].second); 10149 } 10150 10151 return ExprError(); 10152 } 10153 10154 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10155 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10156 Diag(Notes[I].first, Notes[I].second); 10157 10158 if (Result) 10159 *Result = EvalResult.Val.getInt(); 10160 return Owned(E); 10161 } 10162 10163 namespace { 10164 // Handle the case where we conclude a expression which we speculatively 10165 // considered to be unevaluated is actually evaluated. 10166 class TransformToPE : public TreeTransform<TransformToPE> { 10167 typedef TreeTransform<TransformToPE> BaseTransform; 10168 10169 public: 10170 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10171 10172 // Make sure we redo semantic analysis 10173 bool AlwaysRebuild() { return true; } 10174 10175 // Make sure we handle LabelStmts correctly. 10176 // FIXME: This does the right thing, but maybe we need a more general 10177 // fix to TreeTransform? 10178 StmtResult TransformLabelStmt(LabelStmt *S) { 10179 S->getDecl()->setStmt(0); 10180 return BaseTransform::TransformLabelStmt(S); 10181 } 10182 10183 // We need to special-case DeclRefExprs referring to FieldDecls which 10184 // are not part of a member pointer formation; normal TreeTransforming 10185 // doesn't catch this case because of the way we represent them in the AST. 10186 // FIXME: This is a bit ugly; is it really the best way to handle this 10187 // case? 10188 // 10189 // Error on DeclRefExprs referring to FieldDecls. 10190 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10191 if (isa<FieldDecl>(E->getDecl()) && 10192 !SemaRef.isUnevaluatedContext()) 10193 return SemaRef.Diag(E->getLocation(), 10194 diag::err_invalid_non_static_member_use) 10195 << E->getDecl() << E->getSourceRange(); 10196 10197 return BaseTransform::TransformDeclRefExpr(E); 10198 } 10199 10200 // Exception: filter out member pointer formation 10201 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10202 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10203 return E; 10204 10205 return BaseTransform::TransformUnaryOperator(E); 10206 } 10207 10208 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10209 // Lambdas never need to be transformed. 10210 return E; 10211 } 10212 }; 10213 } 10214 10215 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10216 assert(ExprEvalContexts.back().Context == Unevaluated && 10217 "Should only transform unevaluated expressions"); 10218 ExprEvalContexts.back().Context = 10219 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10220 if (ExprEvalContexts.back().Context == Unevaluated) 10221 return E; 10222 return TransformToPE(*this).TransformExpr(E); 10223 } 10224 10225 void 10226 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10227 Decl *LambdaContextDecl, 10228 bool IsDecltype) { 10229 ExprEvalContexts.push_back( 10230 ExpressionEvaluationContextRecord(NewContext, 10231 ExprCleanupObjects.size(), 10232 ExprNeedsCleanups, 10233 LambdaContextDecl, 10234 IsDecltype)); 10235 ExprNeedsCleanups = false; 10236 if (!MaybeODRUseExprs.empty()) 10237 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 10238 } 10239 10240 void 10241 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10242 ReuseLambdaContextDecl_t, 10243 bool IsDecltype) { 10244 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl; 10245 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype); 10246 } 10247 10248 void Sema::PopExpressionEvaluationContext() { 10249 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 10250 10251 if (!Rec.Lambdas.empty()) { 10252 if (Rec.Context == Unevaluated) { 10253 // C++11 [expr.prim.lambda]p2: 10254 // A lambda-expression shall not appear in an unevaluated operand 10255 // (Clause 5). 10256 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 10257 Diag(Rec.Lambdas[I]->getLocStart(), 10258 diag::err_lambda_unevaluated_operand); 10259 } else { 10260 // Mark the capture expressions odr-used. This was deferred 10261 // during lambda expression creation. 10262 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 10263 LambdaExpr *Lambda = Rec.Lambdas[I]; 10264 for (LambdaExpr::capture_init_iterator 10265 C = Lambda->capture_init_begin(), 10266 CEnd = Lambda->capture_init_end(); 10267 C != CEnd; ++C) { 10268 MarkDeclarationsReferencedInExpr(*C); 10269 } 10270 } 10271 } 10272 } 10273 10274 // When are coming out of an unevaluated context, clear out any 10275 // temporaries that we may have created as part of the evaluation of 10276 // the expression in that context: they aren't relevant because they 10277 // will never be constructed. 10278 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) { 10279 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 10280 ExprCleanupObjects.end()); 10281 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 10282 CleanupVarDeclMarking(); 10283 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 10284 // Otherwise, merge the contexts together. 10285 } else { 10286 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 10287 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 10288 Rec.SavedMaybeODRUseExprs.end()); 10289 } 10290 10291 // Pop the current expression evaluation context off the stack. 10292 ExprEvalContexts.pop_back(); 10293 } 10294 10295 void Sema::DiscardCleanupsInEvaluationContext() { 10296 ExprCleanupObjects.erase( 10297 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 10298 ExprCleanupObjects.end()); 10299 ExprNeedsCleanups = false; 10300 MaybeODRUseExprs.clear(); 10301 } 10302 10303 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 10304 if (!E->getType()->isVariablyModifiedType()) 10305 return E; 10306 return TransformToPotentiallyEvaluated(E); 10307 } 10308 10309 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 10310 // Do not mark anything as "used" within a dependent context; wait for 10311 // an instantiation. 10312 if (SemaRef.CurContext->isDependentContext()) 10313 return false; 10314 10315 switch (SemaRef.ExprEvalContexts.back().Context) { 10316 case Sema::Unevaluated: 10317 // We are in an expression that is not potentially evaluated; do nothing. 10318 // (Depending on how you read the standard, we actually do need to do 10319 // something here for null pointer constants, but the standard's 10320 // definition of a null pointer constant is completely crazy.) 10321 return false; 10322 10323 case Sema::ConstantEvaluated: 10324 case Sema::PotentiallyEvaluated: 10325 // We are in a potentially evaluated expression (or a constant-expression 10326 // in C++03); we need to do implicit template instantiation, implicitly 10327 // define class members, and mark most declarations as used. 10328 return true; 10329 10330 case Sema::PotentiallyEvaluatedIfUsed: 10331 // Referenced declarations will only be used if the construct in the 10332 // containing expression is used. 10333 return false; 10334 } 10335 llvm_unreachable("Invalid context"); 10336 } 10337 10338 /// \brief Mark a function referenced, and check whether it is odr-used 10339 /// (C++ [basic.def.odr]p2, C99 6.9p3) 10340 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 10341 assert(Func && "No function?"); 10342 10343 Func->setReferenced(); 10344 10345 // C++11 [basic.def.odr]p3: 10346 // A function whose name appears as a potentially-evaluated expression is 10347 // odr-used if it is the unique lookup result or the selected member of a 10348 // set of overloaded functions [...]. 10349 // 10350 // We (incorrectly) mark overload resolution as an unevaluated context, so we 10351 // can just check that here. Skip the rest of this function if we've already 10352 // marked the function as used. 10353 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 10354 // C++11 [temp.inst]p3: 10355 // Unless a function template specialization has been explicitly 10356 // instantiated or explicitly specialized, the function template 10357 // specialization is implicitly instantiated when the specialization is 10358 // referenced in a context that requires a function definition to exist. 10359 // 10360 // We consider constexpr function templates to be referenced in a context 10361 // that requires a definition to exist whenever they are referenced. 10362 // 10363 // FIXME: This instantiates constexpr functions too frequently. If this is 10364 // really an unevaluated context (and we're not just in the definition of a 10365 // function template or overload resolution or other cases which we 10366 // incorrectly consider to be unevaluated contexts), and we're not in a 10367 // subexpression which we actually need to evaluate (for instance, a 10368 // template argument, array bound or an expression in a braced-init-list), 10369 // we are not permitted to instantiate this constexpr function definition. 10370 // 10371 // FIXME: This also implicitly defines special members too frequently. They 10372 // are only supposed to be implicitly defined if they are odr-used, but they 10373 // are not odr-used from constant expressions in unevaluated contexts. 10374 // However, they cannot be referenced if they are deleted, and they are 10375 // deleted whenever the implicit definition of the special member would 10376 // fail. 10377 if (!Func->isConstexpr() || Func->getBody()) 10378 return; 10379 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 10380 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 10381 return; 10382 } 10383 10384 // Note that this declaration has been used. 10385 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 10386 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 10387 if (Constructor->isDefaultConstructor()) { 10388 if (Constructor->isTrivial()) 10389 return; 10390 if (!Constructor->isUsed(false)) 10391 DefineImplicitDefaultConstructor(Loc, Constructor); 10392 } else if (Constructor->isCopyConstructor()) { 10393 if (!Constructor->isUsed(false)) 10394 DefineImplicitCopyConstructor(Loc, Constructor); 10395 } else if (Constructor->isMoveConstructor()) { 10396 if (!Constructor->isUsed(false)) 10397 DefineImplicitMoveConstructor(Loc, Constructor); 10398 } 10399 } 10400 10401 MarkVTableUsed(Loc, Constructor->getParent()); 10402 } else if (CXXDestructorDecl *Destructor = 10403 dyn_cast<CXXDestructorDecl>(Func)) { 10404 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 10405 !Destructor->isUsed(false)) 10406 DefineImplicitDestructor(Loc, Destructor); 10407 if (Destructor->isVirtual()) 10408 MarkVTableUsed(Loc, Destructor->getParent()); 10409 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 10410 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 10411 MethodDecl->isOverloadedOperator() && 10412 MethodDecl->getOverloadedOperator() == OO_Equal) { 10413 if (!MethodDecl->isUsed(false)) { 10414 if (MethodDecl->isCopyAssignmentOperator()) 10415 DefineImplicitCopyAssignment(Loc, MethodDecl); 10416 else 10417 DefineImplicitMoveAssignment(Loc, MethodDecl); 10418 } 10419 } else if (isa<CXXConversionDecl>(MethodDecl) && 10420 MethodDecl->getParent()->isLambda()) { 10421 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 10422 if (Conversion->isLambdaToBlockPointerConversion()) 10423 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 10424 else 10425 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 10426 } else if (MethodDecl->isVirtual()) 10427 MarkVTableUsed(Loc, MethodDecl->getParent()); 10428 } 10429 10430 // Recursive functions should be marked when used from another function. 10431 // FIXME: Is this really right? 10432 if (CurContext == Func) return; 10433 10434 // Resolve the exception specification for any function which is 10435 // used: CodeGen will need it. 10436 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 10437 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 10438 ResolveExceptionSpec(Loc, FPT); 10439 10440 // Implicit instantiation of function templates and member functions of 10441 // class templates. 10442 if (Func->isImplicitlyInstantiable()) { 10443 bool AlreadyInstantiated = false; 10444 SourceLocation PointOfInstantiation = Loc; 10445 if (FunctionTemplateSpecializationInfo *SpecInfo 10446 = Func->getTemplateSpecializationInfo()) { 10447 if (SpecInfo->getPointOfInstantiation().isInvalid()) 10448 SpecInfo->setPointOfInstantiation(Loc); 10449 else if (SpecInfo->getTemplateSpecializationKind() 10450 == TSK_ImplicitInstantiation) { 10451 AlreadyInstantiated = true; 10452 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 10453 } 10454 } else if (MemberSpecializationInfo *MSInfo 10455 = Func->getMemberSpecializationInfo()) { 10456 if (MSInfo->getPointOfInstantiation().isInvalid()) 10457 MSInfo->setPointOfInstantiation(Loc); 10458 else if (MSInfo->getTemplateSpecializationKind() 10459 == TSK_ImplicitInstantiation) { 10460 AlreadyInstantiated = true; 10461 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10462 } 10463 } 10464 10465 if (!AlreadyInstantiated || Func->isConstexpr()) { 10466 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 10467 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass()) 10468 PendingLocalImplicitInstantiations.push_back( 10469 std::make_pair(Func, PointOfInstantiation)); 10470 else if (Func->isConstexpr()) 10471 // Do not defer instantiations of constexpr functions, to avoid the 10472 // expression evaluator needing to call back into Sema if it sees a 10473 // call to such a function. 10474 InstantiateFunctionDefinition(PointOfInstantiation, Func); 10475 else { 10476 PendingInstantiations.push_back(std::make_pair(Func, 10477 PointOfInstantiation)); 10478 // Notify the consumer that a function was implicitly instantiated. 10479 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 10480 } 10481 } 10482 } else { 10483 // Walk redefinitions, as some of them may be instantiable. 10484 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 10485 e(Func->redecls_end()); i != e; ++i) { 10486 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 10487 MarkFunctionReferenced(Loc, *i); 10488 } 10489 } 10490 10491 // Keep track of used but undefined functions. 10492 if (!Func->isPure() && !Func->hasBody() && 10493 Func->getLinkage() != ExternalLinkage) { 10494 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()]; 10495 if (old.isInvalid()) old = Loc; 10496 } 10497 10498 Func->setUsed(true); 10499 } 10500 10501 static void 10502 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 10503 VarDecl *var, DeclContext *DC) { 10504 DeclContext *VarDC = var->getDeclContext(); 10505 10506 // If the parameter still belongs to the translation unit, then 10507 // we're actually just using one parameter in the declaration of 10508 // the next. 10509 if (isa<ParmVarDecl>(var) && 10510 isa<TranslationUnitDecl>(VarDC)) 10511 return; 10512 10513 // For C code, don't diagnose about capture if we're not actually in code 10514 // right now; it's impossible to write a non-constant expression outside of 10515 // function context, so we'll get other (more useful) diagnostics later. 10516 // 10517 // For C++, things get a bit more nasty... it would be nice to suppress this 10518 // diagnostic for certain cases like using a local variable in an array bound 10519 // for a member of a local class, but the correct predicate is not obvious. 10520 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 10521 return; 10522 10523 if (isa<CXXMethodDecl>(VarDC) && 10524 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 10525 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 10526 << var->getIdentifier(); 10527 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 10528 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 10529 << var->getIdentifier() << fn->getDeclName(); 10530 } else if (isa<BlockDecl>(VarDC)) { 10531 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 10532 << var->getIdentifier(); 10533 } else { 10534 // FIXME: Is there any other context where a local variable can be 10535 // declared? 10536 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 10537 << var->getIdentifier(); 10538 } 10539 10540 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 10541 << var->getIdentifier(); 10542 10543 // FIXME: Add additional diagnostic info about class etc. which prevents 10544 // capture. 10545 } 10546 10547 /// \brief Capture the given variable in the given lambda expression. 10548 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 10549 VarDecl *Var, QualType FieldType, 10550 QualType DeclRefType, 10551 SourceLocation Loc, 10552 bool RefersToEnclosingLocal) { 10553 CXXRecordDecl *Lambda = LSI->Lambda; 10554 10555 // Build the non-static data member. 10556 FieldDecl *Field 10557 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 10558 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 10559 0, false, ICIS_NoInit); 10560 Field->setImplicit(true); 10561 Field->setAccess(AS_private); 10562 Lambda->addDecl(Field); 10563 10564 // C++11 [expr.prim.lambda]p21: 10565 // When the lambda-expression is evaluated, the entities that 10566 // are captured by copy are used to direct-initialize each 10567 // corresponding non-static data member of the resulting closure 10568 // object. (For array members, the array elements are 10569 // direct-initialized in increasing subscript order.) These 10570 // initializations are performed in the (unspecified) order in 10571 // which the non-static data members are declared. 10572 10573 // Introduce a new evaluation context for the initialization, so 10574 // that temporaries introduced as part of the capture are retained 10575 // to be re-"exported" from the lambda expression itself. 10576 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 10577 10578 // C++ [expr.prim.labda]p12: 10579 // An entity captured by a lambda-expression is odr-used (3.2) in 10580 // the scope containing the lambda-expression. 10581 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 10582 DeclRefType, VK_LValue, Loc); 10583 Var->setReferenced(true); 10584 Var->setUsed(true); 10585 10586 // When the field has array type, create index variables for each 10587 // dimension of the array. We use these index variables to subscript 10588 // the source array, and other clients (e.g., CodeGen) will perform 10589 // the necessary iteration with these index variables. 10590 SmallVector<VarDecl *, 4> IndexVariables; 10591 QualType BaseType = FieldType; 10592 QualType SizeType = S.Context.getSizeType(); 10593 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 10594 while (const ConstantArrayType *Array 10595 = S.Context.getAsConstantArrayType(BaseType)) { 10596 // Create the iteration variable for this array index. 10597 IdentifierInfo *IterationVarName = 0; 10598 { 10599 SmallString<8> Str; 10600 llvm::raw_svector_ostream OS(Str); 10601 OS << "__i" << IndexVariables.size(); 10602 IterationVarName = &S.Context.Idents.get(OS.str()); 10603 } 10604 VarDecl *IterationVar 10605 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 10606 IterationVarName, SizeType, 10607 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 10608 SC_None, SC_None); 10609 IndexVariables.push_back(IterationVar); 10610 LSI->ArrayIndexVars.push_back(IterationVar); 10611 10612 // Create a reference to the iteration variable. 10613 ExprResult IterationVarRef 10614 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 10615 assert(!IterationVarRef.isInvalid() && 10616 "Reference to invented variable cannot fail!"); 10617 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 10618 assert(!IterationVarRef.isInvalid() && 10619 "Conversion of invented variable cannot fail!"); 10620 10621 // Subscript the array with this iteration variable. 10622 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 10623 Ref, Loc, IterationVarRef.take(), Loc); 10624 if (Subscript.isInvalid()) { 10625 S.CleanupVarDeclMarking(); 10626 S.DiscardCleanupsInEvaluationContext(); 10627 S.PopExpressionEvaluationContext(); 10628 return ExprError(); 10629 } 10630 10631 Ref = Subscript.take(); 10632 BaseType = Array->getElementType(); 10633 } 10634 10635 // Construct the entity that we will be initializing. For an array, this 10636 // will be first element in the array, which may require several levels 10637 // of array-subscript entities. 10638 SmallVector<InitializedEntity, 4> Entities; 10639 Entities.reserve(1 + IndexVariables.size()); 10640 Entities.push_back( 10641 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 10642 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 10643 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 10644 0, 10645 Entities.back())); 10646 10647 InitializationKind InitKind 10648 = InitializationKind::CreateDirect(Loc, Loc, Loc); 10649 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1); 10650 ExprResult Result(true); 10651 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1)) 10652 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 10653 10654 // If this initialization requires any cleanups (e.g., due to a 10655 // default argument to a copy constructor), note that for the 10656 // lambda. 10657 if (S.ExprNeedsCleanups) 10658 LSI->ExprNeedsCleanups = true; 10659 10660 // Exit the expression evaluation context used for the capture. 10661 S.CleanupVarDeclMarking(); 10662 S.DiscardCleanupsInEvaluationContext(); 10663 S.PopExpressionEvaluationContext(); 10664 return Result; 10665 } 10666 10667 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 10668 TryCaptureKind Kind, SourceLocation EllipsisLoc, 10669 bool BuildAndDiagnose, 10670 QualType &CaptureType, 10671 QualType &DeclRefType) { 10672 bool Nested = false; 10673 10674 DeclContext *DC = CurContext; 10675 if (Var->getDeclContext() == DC) return true; 10676 if (!Var->hasLocalStorage()) return true; 10677 10678 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 10679 10680 // Walk up the stack to determine whether we can capture the variable, 10681 // performing the "simple" checks that don't depend on type. We stop when 10682 // we've either hit the declared scope of the variable or find an existing 10683 // capture of that variable. 10684 CaptureType = Var->getType(); 10685 DeclRefType = CaptureType.getNonReferenceType(); 10686 bool Explicit = (Kind != TryCapture_Implicit); 10687 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 10688 do { 10689 // Only block literals and lambda expressions can capture; other 10690 // scopes don't work. 10691 DeclContext *ParentDC; 10692 if (isa<BlockDecl>(DC)) 10693 ParentDC = DC->getParent(); 10694 else if (isa<CXXMethodDecl>(DC) && 10695 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 10696 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 10697 ParentDC = DC->getParent()->getParent(); 10698 else { 10699 if (BuildAndDiagnose) 10700 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 10701 return true; 10702 } 10703 10704 CapturingScopeInfo *CSI = 10705 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 10706 10707 // Check whether we've already captured it. 10708 if (CSI->CaptureMap.count(Var)) { 10709 // If we found a capture, any subcaptures are nested. 10710 Nested = true; 10711 10712 // Retrieve the capture type for this variable. 10713 CaptureType = CSI->getCapture(Var).getCaptureType(); 10714 10715 // Compute the type of an expression that refers to this variable. 10716 DeclRefType = CaptureType.getNonReferenceType(); 10717 10718 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 10719 if (Cap.isCopyCapture() && 10720 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 10721 DeclRefType.addConst(); 10722 break; 10723 } 10724 10725 bool IsBlock = isa<BlockScopeInfo>(CSI); 10726 bool IsLambda = !IsBlock; 10727 10728 // Lambdas are not allowed to capture unnamed variables 10729 // (e.g. anonymous unions). 10730 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 10731 // assuming that's the intent. 10732 if (IsLambda && !Var->getDeclName()) { 10733 if (BuildAndDiagnose) { 10734 Diag(Loc, diag::err_lambda_capture_anonymous_var); 10735 Diag(Var->getLocation(), diag::note_declared_at); 10736 } 10737 return true; 10738 } 10739 10740 // Prohibit variably-modified types; they're difficult to deal with. 10741 if (Var->getType()->isVariablyModifiedType()) { 10742 if (BuildAndDiagnose) { 10743 if (IsBlock) 10744 Diag(Loc, diag::err_ref_vm_type); 10745 else 10746 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 10747 Diag(Var->getLocation(), diag::note_previous_decl) 10748 << Var->getDeclName(); 10749 } 10750 return true; 10751 } 10752 10753 // Lambdas are not allowed to capture __block variables; they don't 10754 // support the expected semantics. 10755 if (IsLambda && HasBlocksAttr) { 10756 if (BuildAndDiagnose) { 10757 Diag(Loc, diag::err_lambda_capture_block) 10758 << Var->getDeclName(); 10759 Diag(Var->getLocation(), diag::note_previous_decl) 10760 << Var->getDeclName(); 10761 } 10762 return true; 10763 } 10764 10765 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 10766 // No capture-default 10767 if (BuildAndDiagnose) { 10768 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 10769 Diag(Var->getLocation(), diag::note_previous_decl) 10770 << Var->getDeclName(); 10771 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 10772 diag::note_lambda_decl); 10773 } 10774 return true; 10775 } 10776 10777 FunctionScopesIndex--; 10778 DC = ParentDC; 10779 Explicit = false; 10780 } while (!Var->getDeclContext()->Equals(DC)); 10781 10782 // Walk back down the scope stack, computing the type of the capture at 10783 // each step, checking type-specific requirements, and adding captures if 10784 // requested. 10785 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 10786 ++I) { 10787 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 10788 10789 // Compute the type of the capture and of a reference to the capture within 10790 // this scope. 10791 if (isa<BlockScopeInfo>(CSI)) { 10792 Expr *CopyExpr = 0; 10793 bool ByRef = false; 10794 10795 // Blocks are not allowed to capture arrays. 10796 if (CaptureType->isArrayType()) { 10797 if (BuildAndDiagnose) { 10798 Diag(Loc, diag::err_ref_array_type); 10799 Diag(Var->getLocation(), diag::note_previous_decl) 10800 << Var->getDeclName(); 10801 } 10802 return true; 10803 } 10804 10805 // Forbid the block-capture of autoreleasing variables. 10806 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 10807 if (BuildAndDiagnose) { 10808 Diag(Loc, diag::err_arc_autoreleasing_capture) 10809 << /*block*/ 0; 10810 Diag(Var->getLocation(), diag::note_previous_decl) 10811 << Var->getDeclName(); 10812 } 10813 return true; 10814 } 10815 10816 if (HasBlocksAttr || CaptureType->isReferenceType()) { 10817 // Block capture by reference does not change the capture or 10818 // declaration reference types. 10819 ByRef = true; 10820 } else { 10821 // Block capture by copy introduces 'const'. 10822 CaptureType = CaptureType.getNonReferenceType().withConst(); 10823 DeclRefType = CaptureType; 10824 10825 if (getLangOpts().CPlusPlus && BuildAndDiagnose) { 10826 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 10827 // The capture logic needs the destructor, so make sure we mark it. 10828 // Usually this is unnecessary because most local variables have 10829 // their destructors marked at declaration time, but parameters are 10830 // an exception because it's technically only the call site that 10831 // actually requires the destructor. 10832 if (isa<ParmVarDecl>(Var)) 10833 FinalizeVarWithDestructor(Var, Record); 10834 10835 // According to the blocks spec, the capture of a variable from 10836 // the stack requires a const copy constructor. This is not true 10837 // of the copy/move done to move a __block variable to the heap. 10838 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested, 10839 DeclRefType.withConst(), 10840 VK_LValue, Loc); 10841 10842 ExprResult Result 10843 = PerformCopyInitialization( 10844 InitializedEntity::InitializeBlock(Var->getLocation(), 10845 CaptureType, false), 10846 Loc, Owned(DeclRef)); 10847 10848 // Build a full-expression copy expression if initialization 10849 // succeeded and used a non-trivial constructor. Recover from 10850 // errors by pretending that the copy isn't necessary. 10851 if (!Result.isInvalid() && 10852 !cast<CXXConstructExpr>(Result.get())->getConstructor() 10853 ->isTrivial()) { 10854 Result = MaybeCreateExprWithCleanups(Result); 10855 CopyExpr = Result.take(); 10856 } 10857 } 10858 } 10859 } 10860 10861 // Actually capture the variable. 10862 if (BuildAndDiagnose) 10863 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 10864 SourceLocation(), CaptureType, CopyExpr); 10865 Nested = true; 10866 continue; 10867 } 10868 10869 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 10870 10871 // Determine whether we are capturing by reference or by value. 10872 bool ByRef = false; 10873 if (I == N - 1 && Kind != TryCapture_Implicit) { 10874 ByRef = (Kind == TryCapture_ExplicitByRef); 10875 } else { 10876 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 10877 } 10878 10879 // Compute the type of the field that will capture this variable. 10880 if (ByRef) { 10881 // C++11 [expr.prim.lambda]p15: 10882 // An entity is captured by reference if it is implicitly or 10883 // explicitly captured but not captured by copy. It is 10884 // unspecified whether additional unnamed non-static data 10885 // members are declared in the closure type for entities 10886 // captured by reference. 10887 // 10888 // FIXME: It is not clear whether we want to build an lvalue reference 10889 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 10890 // to do the former, while EDG does the latter. Core issue 1249 will 10891 // clarify, but for now we follow GCC because it's a more permissive and 10892 // easily defensible position. 10893 CaptureType = Context.getLValueReferenceType(DeclRefType); 10894 } else { 10895 // C++11 [expr.prim.lambda]p14: 10896 // For each entity captured by copy, an unnamed non-static 10897 // data member is declared in the closure type. The 10898 // declaration order of these members is unspecified. The type 10899 // of such a data member is the type of the corresponding 10900 // captured entity if the entity is not a reference to an 10901 // object, or the referenced type otherwise. [Note: If the 10902 // captured entity is a reference to a function, the 10903 // corresponding data member is also a reference to a 10904 // function. - end note ] 10905 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 10906 if (!RefType->getPointeeType()->isFunctionType()) 10907 CaptureType = RefType->getPointeeType(); 10908 } 10909 10910 // Forbid the lambda copy-capture of autoreleasing variables. 10911 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 10912 if (BuildAndDiagnose) { 10913 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 10914 Diag(Var->getLocation(), diag::note_previous_decl) 10915 << Var->getDeclName(); 10916 } 10917 return true; 10918 } 10919 } 10920 10921 // Capture this variable in the lambda. 10922 Expr *CopyExpr = 0; 10923 if (BuildAndDiagnose) { 10924 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 10925 DeclRefType, Loc, 10926 Nested); 10927 if (!Result.isInvalid()) 10928 CopyExpr = Result.take(); 10929 } 10930 10931 // Compute the type of a reference to this captured variable. 10932 if (ByRef) 10933 DeclRefType = CaptureType.getNonReferenceType(); 10934 else { 10935 // C++ [expr.prim.lambda]p5: 10936 // The closure type for a lambda-expression has a public inline 10937 // function call operator [...]. This function call operator is 10938 // declared const (9.3.1) if and only if the lambda-expression’s 10939 // parameter-declaration-clause is not followed by mutable. 10940 DeclRefType = CaptureType.getNonReferenceType(); 10941 if (!LSI->Mutable && !CaptureType->isReferenceType()) 10942 DeclRefType.addConst(); 10943 } 10944 10945 // Add the capture. 10946 if (BuildAndDiagnose) 10947 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 10948 EllipsisLoc, CaptureType, CopyExpr); 10949 Nested = true; 10950 } 10951 10952 return false; 10953 } 10954 10955 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 10956 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 10957 QualType CaptureType; 10958 QualType DeclRefType; 10959 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 10960 /*BuildAndDiagnose=*/true, CaptureType, 10961 DeclRefType); 10962 } 10963 10964 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 10965 QualType CaptureType; 10966 QualType DeclRefType; 10967 10968 // Determine whether we can capture this variable. 10969 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 10970 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 10971 return QualType(); 10972 10973 return DeclRefType; 10974 } 10975 10976 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 10977 SourceLocation Loc) { 10978 // Keep track of used but undefined variables. 10979 // FIXME: We shouldn't suppress this warning for static data members. 10980 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 10981 Var->getLinkage() != ExternalLinkage && 10982 !(Var->isStaticDataMember() && Var->hasInit())) { 10983 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()]; 10984 if (old.isInvalid()) old = Loc; 10985 } 10986 10987 SemaRef.tryCaptureVariable(Var, Loc); 10988 10989 Var->setUsed(true); 10990 } 10991 10992 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 10993 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 10994 // an object that satisfies the requirements for appearing in a 10995 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 10996 // is immediately applied." This function handles the lvalue-to-rvalue 10997 // conversion part. 10998 MaybeODRUseExprs.erase(E->IgnoreParens()); 10999 } 11000 11001 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 11002 if (!Res.isUsable()) 11003 return Res; 11004 11005 // If a constant-expression is a reference to a variable where we delay 11006 // deciding whether it is an odr-use, just assume we will apply the 11007 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 11008 // (a non-type template argument), we have special handling anyway. 11009 UpdateMarkingForLValueToRValue(Res.get()); 11010 return Res; 11011 } 11012 11013 void Sema::CleanupVarDeclMarking() { 11014 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 11015 e = MaybeODRUseExprs.end(); 11016 i != e; ++i) { 11017 VarDecl *Var; 11018 SourceLocation Loc; 11019 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 11020 Var = cast<VarDecl>(DRE->getDecl()); 11021 Loc = DRE->getLocation(); 11022 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 11023 Var = cast<VarDecl>(ME->getMemberDecl()); 11024 Loc = ME->getMemberLoc(); 11025 } else { 11026 llvm_unreachable("Unexpcted expression"); 11027 } 11028 11029 MarkVarDeclODRUsed(*this, Var, Loc); 11030 } 11031 11032 MaybeODRUseExprs.clear(); 11033 } 11034 11035 // Mark a VarDecl referenced, and perform the necessary handling to compute 11036 // odr-uses. 11037 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 11038 VarDecl *Var, Expr *E) { 11039 Var->setReferenced(); 11040 11041 if (!IsPotentiallyEvaluatedContext(SemaRef)) 11042 return; 11043 11044 // Implicit instantiation of static data members of class templates. 11045 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) { 11046 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 11047 assert(MSInfo && "Missing member specialization information?"); 11048 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 11049 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && 11050 (!AlreadyInstantiated || 11051 Var->isUsableInConstantExpressions(SemaRef.Context))) { 11052 if (!AlreadyInstantiated) { 11053 // This is a modification of an existing AST node. Notify listeners. 11054 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 11055 L->StaticDataMemberInstantiated(Var); 11056 MSInfo->setPointOfInstantiation(Loc); 11057 } 11058 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11059 if (Var->isUsableInConstantExpressions(SemaRef.Context)) 11060 // Do not defer instantiations of variables which could be used in a 11061 // constant expression. 11062 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var); 11063 else 11064 SemaRef.PendingInstantiations.push_back( 11065 std::make_pair(Var, PointOfInstantiation)); 11066 } 11067 } 11068 11069 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 11070 // the requirements for appearing in a constant expression (5.19) and, if 11071 // it is an object, the lvalue-to-rvalue conversion (4.1) 11072 // is immediately applied." We check the first part here, and 11073 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 11074 // Note that we use the C++11 definition everywhere because nothing in 11075 // C++03 depends on whether we get the C++03 version correct. The second 11076 // part does not apply to references, since they are not objects. 11077 const VarDecl *DefVD; 11078 if (E && !isa<ParmVarDecl>(Var) && 11079 Var->isUsableInConstantExpressions(SemaRef.Context) && 11080 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) { 11081 if (!Var->getType()->isReferenceType()) 11082 SemaRef.MaybeODRUseExprs.insert(E); 11083 } else 11084 MarkVarDeclODRUsed(SemaRef, Var, Loc); 11085 } 11086 11087 /// \brief Mark a variable referenced, and check whether it is odr-used 11088 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 11089 /// used directly for normal expressions referring to VarDecl. 11090 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 11091 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 11092 } 11093 11094 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 11095 Decl *D, Expr *E) { 11096 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 11097 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 11098 return; 11099 } 11100 11101 SemaRef.MarkAnyDeclReferenced(Loc, D); 11102 11103 // If this is a call to a method via a cast, also mark the method in the 11104 // derived class used in case codegen can devirtualize the call. 11105 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11106 if (!ME) 11107 return; 11108 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 11109 if (!MD) 11110 return; 11111 const Expr *Base = ME->getBase(); 11112 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 11113 if (!MostDerivedClassDecl) 11114 return; 11115 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 11116 if (!DM) 11117 return; 11118 SemaRef.MarkAnyDeclReferenced(Loc, DM); 11119 } 11120 11121 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 11122 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 11123 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E); 11124 } 11125 11126 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 11127 void Sema::MarkMemberReferenced(MemberExpr *E) { 11128 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E); 11129 } 11130 11131 /// \brief Perform marking for a reference to an arbitrary declaration. It 11132 /// marks the declaration referenced, and performs odr-use checking for functions 11133 /// and variables. This method should not be used when building an normal 11134 /// expression which refers to a variable. 11135 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) { 11136 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 11137 MarkVariableReferenced(Loc, VD); 11138 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 11139 MarkFunctionReferenced(Loc, FD); 11140 else 11141 D->setReferenced(); 11142 } 11143 11144 namespace { 11145 // Mark all of the declarations referenced 11146 // FIXME: Not fully implemented yet! We need to have a better understanding 11147 // of when we're entering 11148 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 11149 Sema &S; 11150 SourceLocation Loc; 11151 11152 public: 11153 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 11154 11155 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 11156 11157 bool TraverseTemplateArgument(const TemplateArgument &Arg); 11158 bool TraverseRecordType(RecordType *T); 11159 }; 11160 } 11161 11162 bool MarkReferencedDecls::TraverseTemplateArgument( 11163 const TemplateArgument &Arg) { 11164 if (Arg.getKind() == TemplateArgument::Declaration) { 11165 if (Decl *D = Arg.getAsDecl()) 11166 S.MarkAnyDeclReferenced(Loc, D); 11167 } 11168 11169 return Inherited::TraverseTemplateArgument(Arg); 11170 } 11171 11172 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 11173 if (ClassTemplateSpecializationDecl *Spec 11174 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 11175 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 11176 return TraverseTemplateArguments(Args.data(), Args.size()); 11177 } 11178 11179 return true; 11180 } 11181 11182 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 11183 MarkReferencedDecls Marker(*this, Loc); 11184 Marker.TraverseType(Context.getCanonicalType(T)); 11185 } 11186 11187 namespace { 11188 /// \brief Helper class that marks all of the declarations referenced by 11189 /// potentially-evaluated subexpressions as "referenced". 11190 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 11191 Sema &S; 11192 bool SkipLocalVariables; 11193 11194 public: 11195 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 11196 11197 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 11198 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 11199 11200 void VisitDeclRefExpr(DeclRefExpr *E) { 11201 // If we were asked not to visit local variables, don't. 11202 if (SkipLocalVariables) { 11203 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 11204 if (VD->hasLocalStorage()) 11205 return; 11206 } 11207 11208 S.MarkDeclRefReferenced(E); 11209 } 11210 11211 void VisitMemberExpr(MemberExpr *E) { 11212 S.MarkMemberReferenced(E); 11213 Inherited::VisitMemberExpr(E); 11214 } 11215 11216 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 11217 S.MarkFunctionReferenced(E->getLocStart(), 11218 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 11219 Visit(E->getSubExpr()); 11220 } 11221 11222 void VisitCXXNewExpr(CXXNewExpr *E) { 11223 if (E->getOperatorNew()) 11224 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 11225 if (E->getOperatorDelete()) 11226 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11227 Inherited::VisitCXXNewExpr(E); 11228 } 11229 11230 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 11231 if (E->getOperatorDelete()) 11232 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11233 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 11234 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 11235 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 11236 S.MarkFunctionReferenced(E->getLocStart(), 11237 S.LookupDestructor(Record)); 11238 } 11239 11240 Inherited::VisitCXXDeleteExpr(E); 11241 } 11242 11243 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11244 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 11245 Inherited::VisitCXXConstructExpr(E); 11246 } 11247 11248 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 11249 Visit(E->getExpr()); 11250 } 11251 11252 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11253 Inherited::VisitImplicitCastExpr(E); 11254 11255 if (E->getCastKind() == CK_LValueToRValue) 11256 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 11257 } 11258 }; 11259 } 11260 11261 /// \brief Mark any declarations that appear within this expression or any 11262 /// potentially-evaluated subexpressions as "referenced". 11263 /// 11264 /// \param SkipLocalVariables If true, don't mark local variables as 11265 /// 'referenced'. 11266 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 11267 bool SkipLocalVariables) { 11268 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 11269 } 11270 11271 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 11272 /// of the program being compiled. 11273 /// 11274 /// This routine emits the given diagnostic when the code currently being 11275 /// type-checked is "potentially evaluated", meaning that there is a 11276 /// possibility that the code will actually be executable. Code in sizeof() 11277 /// expressions, code used only during overload resolution, etc., are not 11278 /// potentially evaluated. This routine will suppress such diagnostics or, 11279 /// in the absolutely nutty case of potentially potentially evaluated 11280 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 11281 /// later. 11282 /// 11283 /// This routine should be used for all diagnostics that describe the run-time 11284 /// behavior of a program, such as passing a non-POD value through an ellipsis. 11285 /// Failure to do so will likely result in spurious diagnostics or failures 11286 /// during overload resolution or within sizeof/alignof/typeof/typeid. 11287 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 11288 const PartialDiagnostic &PD) { 11289 switch (ExprEvalContexts.back().Context) { 11290 case Unevaluated: 11291 // The argument will never be evaluated, so don't complain. 11292 break; 11293 11294 case ConstantEvaluated: 11295 // Relevant diagnostics should be produced by constant evaluation. 11296 break; 11297 11298 case PotentiallyEvaluated: 11299 case PotentiallyEvaluatedIfUsed: 11300 if (Statement && getCurFunctionOrMethodDecl()) { 11301 FunctionScopes.back()->PossiblyUnreachableDiags. 11302 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 11303 } 11304 else 11305 Diag(Loc, PD); 11306 11307 return true; 11308 } 11309 11310 return false; 11311 } 11312 11313 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 11314 CallExpr *CE, FunctionDecl *FD) { 11315 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 11316 return false; 11317 11318 // If we're inside a decltype's expression, don't check for a valid return 11319 // type or construct temporaries until we know whether this is the last call. 11320 if (ExprEvalContexts.back().IsDecltype) { 11321 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 11322 return false; 11323 } 11324 11325 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 11326 FunctionDecl *FD; 11327 CallExpr *CE; 11328 11329 public: 11330 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 11331 : FD(FD), CE(CE) { } 11332 11333 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 11334 if (!FD) { 11335 S.Diag(Loc, diag::err_call_incomplete_return) 11336 << T << CE->getSourceRange(); 11337 return; 11338 } 11339 11340 S.Diag(Loc, diag::err_call_function_incomplete_return) 11341 << CE->getSourceRange() << FD->getDeclName() << T; 11342 S.Diag(FD->getLocation(), 11343 diag::note_function_with_incomplete_return_type_declared_here) 11344 << FD->getDeclName(); 11345 } 11346 } Diagnoser(FD, CE); 11347 11348 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 11349 return true; 11350 11351 return false; 11352 } 11353 11354 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 11355 // will prevent this condition from triggering, which is what we want. 11356 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 11357 SourceLocation Loc; 11358 11359 unsigned diagnostic = diag::warn_condition_is_assignment; 11360 bool IsOrAssign = false; 11361 11362 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 11363 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 11364 return; 11365 11366 IsOrAssign = Op->getOpcode() == BO_OrAssign; 11367 11368 // Greylist some idioms by putting them into a warning subcategory. 11369 if (ObjCMessageExpr *ME 11370 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 11371 Selector Sel = ME->getSelector(); 11372 11373 // self = [<foo> init...] 11374 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 11375 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11376 11377 // <foo> = [<bar> nextObject] 11378 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 11379 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11380 } 11381 11382 Loc = Op->getOperatorLoc(); 11383 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 11384 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 11385 return; 11386 11387 IsOrAssign = Op->getOperator() == OO_PipeEqual; 11388 Loc = Op->getOperatorLoc(); 11389 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 11390 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 11391 else { 11392 // Not an assignment. 11393 return; 11394 } 11395 11396 Diag(Loc, diagnostic) << E->getSourceRange(); 11397 11398 SourceLocation Open = E->getLocStart(); 11399 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 11400 Diag(Loc, diag::note_condition_assign_silence) 11401 << FixItHint::CreateInsertion(Open, "(") 11402 << FixItHint::CreateInsertion(Close, ")"); 11403 11404 if (IsOrAssign) 11405 Diag(Loc, diag::note_condition_or_assign_to_comparison) 11406 << FixItHint::CreateReplacement(Loc, "!="); 11407 else 11408 Diag(Loc, diag::note_condition_assign_to_comparison) 11409 << FixItHint::CreateReplacement(Loc, "=="); 11410 } 11411 11412 /// \brief Redundant parentheses over an equality comparison can indicate 11413 /// that the user intended an assignment used as condition. 11414 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 11415 // Don't warn if the parens came from a macro. 11416 SourceLocation parenLoc = ParenE->getLocStart(); 11417 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 11418 return; 11419 // Don't warn for dependent expressions. 11420 if (ParenE->isTypeDependent()) 11421 return; 11422 11423 Expr *E = ParenE->IgnoreParens(); 11424 11425 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 11426 if (opE->getOpcode() == BO_EQ && 11427 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 11428 == Expr::MLV_Valid) { 11429 SourceLocation Loc = opE->getOperatorLoc(); 11430 11431 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 11432 SourceRange ParenERange = ParenE->getSourceRange(); 11433 Diag(Loc, diag::note_equality_comparison_silence) 11434 << FixItHint::CreateRemoval(ParenERange.getBegin()) 11435 << FixItHint::CreateRemoval(ParenERange.getEnd()); 11436 Diag(Loc, diag::note_equality_comparison_to_assign) 11437 << FixItHint::CreateReplacement(Loc, "="); 11438 } 11439 } 11440 11441 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 11442 DiagnoseAssignmentAsCondition(E); 11443 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 11444 DiagnoseEqualityWithExtraParens(parenE); 11445 11446 ExprResult result = CheckPlaceholderExpr(E); 11447 if (result.isInvalid()) return ExprError(); 11448 E = result.take(); 11449 11450 if (!E->isTypeDependent()) { 11451 if (getLangOpts().CPlusPlus) 11452 return CheckCXXBooleanCondition(E); // C++ 6.4p4 11453 11454 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 11455 if (ERes.isInvalid()) 11456 return ExprError(); 11457 E = ERes.take(); 11458 11459 QualType T = E->getType(); 11460 if (!T->isScalarType()) { // C99 6.8.4.1p1 11461 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 11462 << T << E->getSourceRange(); 11463 return ExprError(); 11464 } 11465 } 11466 11467 return Owned(E); 11468 } 11469 11470 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 11471 Expr *SubExpr) { 11472 if (!SubExpr) 11473 return ExprError(); 11474 11475 return CheckBooleanCondition(SubExpr, Loc); 11476 } 11477 11478 namespace { 11479 /// A visitor for rebuilding a call to an __unknown_any expression 11480 /// to have an appropriate type. 11481 struct RebuildUnknownAnyFunction 11482 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 11483 11484 Sema &S; 11485 11486 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 11487 11488 ExprResult VisitStmt(Stmt *S) { 11489 llvm_unreachable("unexpected statement!"); 11490 } 11491 11492 ExprResult VisitExpr(Expr *E) { 11493 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 11494 << E->getSourceRange(); 11495 return ExprError(); 11496 } 11497 11498 /// Rebuild an expression which simply semantically wraps another 11499 /// expression which it shares the type and value kind of. 11500 template <class T> ExprResult rebuildSugarExpr(T *E) { 11501 ExprResult SubResult = Visit(E->getSubExpr()); 11502 if (SubResult.isInvalid()) return ExprError(); 11503 11504 Expr *SubExpr = SubResult.take(); 11505 E->setSubExpr(SubExpr); 11506 E->setType(SubExpr->getType()); 11507 E->setValueKind(SubExpr->getValueKind()); 11508 assert(E->getObjectKind() == OK_Ordinary); 11509 return E; 11510 } 11511 11512 ExprResult VisitParenExpr(ParenExpr *E) { 11513 return rebuildSugarExpr(E); 11514 } 11515 11516 ExprResult VisitUnaryExtension(UnaryOperator *E) { 11517 return rebuildSugarExpr(E); 11518 } 11519 11520 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 11521 ExprResult SubResult = Visit(E->getSubExpr()); 11522 if (SubResult.isInvalid()) return ExprError(); 11523 11524 Expr *SubExpr = SubResult.take(); 11525 E->setSubExpr(SubExpr); 11526 E->setType(S.Context.getPointerType(SubExpr->getType())); 11527 assert(E->getValueKind() == VK_RValue); 11528 assert(E->getObjectKind() == OK_Ordinary); 11529 return E; 11530 } 11531 11532 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 11533 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 11534 11535 E->setType(VD->getType()); 11536 11537 assert(E->getValueKind() == VK_RValue); 11538 if (S.getLangOpts().CPlusPlus && 11539 !(isa<CXXMethodDecl>(VD) && 11540 cast<CXXMethodDecl>(VD)->isInstance())) 11541 E->setValueKind(VK_LValue); 11542 11543 return E; 11544 } 11545 11546 ExprResult VisitMemberExpr(MemberExpr *E) { 11547 return resolveDecl(E, E->getMemberDecl()); 11548 } 11549 11550 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 11551 return resolveDecl(E, E->getDecl()); 11552 } 11553 }; 11554 } 11555 11556 /// Given a function expression of unknown-any type, try to rebuild it 11557 /// to have a function type. 11558 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 11559 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 11560 if (Result.isInvalid()) return ExprError(); 11561 return S.DefaultFunctionArrayConversion(Result.take()); 11562 } 11563 11564 namespace { 11565 /// A visitor for rebuilding an expression of type __unknown_anytype 11566 /// into one which resolves the type directly on the referring 11567 /// expression. Strict preservation of the original source 11568 /// structure is not a goal. 11569 struct RebuildUnknownAnyExpr 11570 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 11571 11572 Sema &S; 11573 11574 /// The current destination type. 11575 QualType DestType; 11576 11577 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 11578 : S(S), DestType(CastType) {} 11579 11580 ExprResult VisitStmt(Stmt *S) { 11581 llvm_unreachable("unexpected statement!"); 11582 } 11583 11584 ExprResult VisitExpr(Expr *E) { 11585 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 11586 << E->getSourceRange(); 11587 return ExprError(); 11588 } 11589 11590 ExprResult VisitCallExpr(CallExpr *E); 11591 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 11592 11593 /// Rebuild an expression which simply semantically wraps another 11594 /// expression which it shares the type and value kind of. 11595 template <class T> ExprResult rebuildSugarExpr(T *E) { 11596 ExprResult SubResult = Visit(E->getSubExpr()); 11597 if (SubResult.isInvalid()) return ExprError(); 11598 Expr *SubExpr = SubResult.take(); 11599 E->setSubExpr(SubExpr); 11600 E->setType(SubExpr->getType()); 11601 E->setValueKind(SubExpr->getValueKind()); 11602 assert(E->getObjectKind() == OK_Ordinary); 11603 return E; 11604 } 11605 11606 ExprResult VisitParenExpr(ParenExpr *E) { 11607 return rebuildSugarExpr(E); 11608 } 11609 11610 ExprResult VisitUnaryExtension(UnaryOperator *E) { 11611 return rebuildSugarExpr(E); 11612 } 11613 11614 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 11615 const PointerType *Ptr = DestType->getAs<PointerType>(); 11616 if (!Ptr) { 11617 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 11618 << E->getSourceRange(); 11619 return ExprError(); 11620 } 11621 assert(E->getValueKind() == VK_RValue); 11622 assert(E->getObjectKind() == OK_Ordinary); 11623 E->setType(DestType); 11624 11625 // Build the sub-expression as if it were an object of the pointee type. 11626 DestType = Ptr->getPointeeType(); 11627 ExprResult SubResult = Visit(E->getSubExpr()); 11628 if (SubResult.isInvalid()) return ExprError(); 11629 E->setSubExpr(SubResult.take()); 11630 return E; 11631 } 11632 11633 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 11634 11635 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 11636 11637 ExprResult VisitMemberExpr(MemberExpr *E) { 11638 return resolveDecl(E, E->getMemberDecl()); 11639 } 11640 11641 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 11642 return resolveDecl(E, E->getDecl()); 11643 } 11644 }; 11645 } 11646 11647 /// Rebuilds a call expression which yielded __unknown_anytype. 11648 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 11649 Expr *CalleeExpr = E->getCallee(); 11650 11651 enum FnKind { 11652 FK_MemberFunction, 11653 FK_FunctionPointer, 11654 FK_BlockPointer 11655 }; 11656 11657 FnKind Kind; 11658 QualType CalleeType = CalleeExpr->getType(); 11659 if (CalleeType == S.Context.BoundMemberTy) { 11660 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 11661 Kind = FK_MemberFunction; 11662 CalleeType = Expr::findBoundMemberType(CalleeExpr); 11663 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 11664 CalleeType = Ptr->getPointeeType(); 11665 Kind = FK_FunctionPointer; 11666 } else { 11667 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 11668 Kind = FK_BlockPointer; 11669 } 11670 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 11671 11672 // Verify that this is a legal result type of a function. 11673 if (DestType->isArrayType() || DestType->isFunctionType()) { 11674 unsigned diagID = diag::err_func_returning_array_function; 11675 if (Kind == FK_BlockPointer) 11676 diagID = diag::err_block_returning_array_function; 11677 11678 S.Diag(E->getExprLoc(), diagID) 11679 << DestType->isFunctionType() << DestType; 11680 return ExprError(); 11681 } 11682 11683 // Otherwise, go ahead and set DestType as the call's result. 11684 E->setType(DestType.getNonLValueExprType(S.Context)); 11685 E->setValueKind(Expr::getValueKindForType(DestType)); 11686 assert(E->getObjectKind() == OK_Ordinary); 11687 11688 // Rebuild the function type, replacing the result type with DestType. 11689 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType)) 11690 DestType = S.Context.getFunctionType(DestType, 11691 Proto->arg_type_begin(), 11692 Proto->getNumArgs(), 11693 Proto->getExtProtoInfo()); 11694 else 11695 DestType = S.Context.getFunctionNoProtoType(DestType, 11696 FnType->getExtInfo()); 11697 11698 // Rebuild the appropriate pointer-to-function type. 11699 switch (Kind) { 11700 case FK_MemberFunction: 11701 // Nothing to do. 11702 break; 11703 11704 case FK_FunctionPointer: 11705 DestType = S.Context.getPointerType(DestType); 11706 break; 11707 11708 case FK_BlockPointer: 11709 DestType = S.Context.getBlockPointerType(DestType); 11710 break; 11711 } 11712 11713 // Finally, we can recurse. 11714 ExprResult CalleeResult = Visit(CalleeExpr); 11715 if (!CalleeResult.isUsable()) return ExprError(); 11716 E->setCallee(CalleeResult.take()); 11717 11718 // Bind a temporary if necessary. 11719 return S.MaybeBindToTemporary(E); 11720 } 11721 11722 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 11723 // Verify that this is a legal result type of a call. 11724 if (DestType->isArrayType() || DestType->isFunctionType()) { 11725 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 11726 << DestType->isFunctionType() << DestType; 11727 return ExprError(); 11728 } 11729 11730 // Rewrite the method result type if available. 11731 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 11732 assert(Method->getResultType() == S.Context.UnknownAnyTy); 11733 Method->setResultType(DestType); 11734 } 11735 11736 // Change the type of the message. 11737 E->setType(DestType.getNonReferenceType()); 11738 E->setValueKind(Expr::getValueKindForType(DestType)); 11739 11740 return S.MaybeBindToTemporary(E); 11741 } 11742 11743 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 11744 // The only case we should ever see here is a function-to-pointer decay. 11745 if (E->getCastKind() == CK_FunctionToPointerDecay) { 11746 assert(E->getValueKind() == VK_RValue); 11747 assert(E->getObjectKind() == OK_Ordinary); 11748 11749 E->setType(DestType); 11750 11751 // Rebuild the sub-expression as the pointee (function) type. 11752 DestType = DestType->castAs<PointerType>()->getPointeeType(); 11753 11754 ExprResult Result = Visit(E->getSubExpr()); 11755 if (!Result.isUsable()) return ExprError(); 11756 11757 E->setSubExpr(Result.take()); 11758 return S.Owned(E); 11759 } else if (E->getCastKind() == CK_LValueToRValue) { 11760 assert(E->getValueKind() == VK_RValue); 11761 assert(E->getObjectKind() == OK_Ordinary); 11762 11763 assert(isa<BlockPointerType>(E->getType())); 11764 11765 E->setType(DestType); 11766 11767 // The sub-expression has to be a lvalue reference, so rebuild it as such. 11768 DestType = S.Context.getLValueReferenceType(DestType); 11769 11770 ExprResult Result = Visit(E->getSubExpr()); 11771 if (!Result.isUsable()) return ExprError(); 11772 11773 E->setSubExpr(Result.take()); 11774 return S.Owned(E); 11775 } else { 11776 llvm_unreachable("Unhandled cast type!"); 11777 } 11778 } 11779 11780 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 11781 ExprValueKind ValueKind = VK_LValue; 11782 QualType Type = DestType; 11783 11784 // We know how to make this work for certain kinds of decls: 11785 11786 // - functions 11787 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 11788 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 11789 DestType = Ptr->getPointeeType(); 11790 ExprResult Result = resolveDecl(E, VD); 11791 if (Result.isInvalid()) return ExprError(); 11792 return S.ImpCastExprToType(Result.take(), Type, 11793 CK_FunctionToPointerDecay, VK_RValue); 11794 } 11795 11796 if (!Type->isFunctionType()) { 11797 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 11798 << VD << E->getSourceRange(); 11799 return ExprError(); 11800 } 11801 11802 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 11803 if (MD->isInstance()) { 11804 ValueKind = VK_RValue; 11805 Type = S.Context.BoundMemberTy; 11806 } 11807 11808 // Function references aren't l-values in C. 11809 if (!S.getLangOpts().CPlusPlus) 11810 ValueKind = VK_RValue; 11811 11812 // - variables 11813 } else if (isa<VarDecl>(VD)) { 11814 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 11815 Type = RefTy->getPointeeType(); 11816 } else if (Type->isFunctionType()) { 11817 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 11818 << VD << E->getSourceRange(); 11819 return ExprError(); 11820 } 11821 11822 // - nothing else 11823 } else { 11824 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 11825 << VD << E->getSourceRange(); 11826 return ExprError(); 11827 } 11828 11829 VD->setType(DestType); 11830 E->setType(Type); 11831 E->setValueKind(ValueKind); 11832 return S.Owned(E); 11833 } 11834 11835 /// Check a cast of an unknown-any type. We intentionally only 11836 /// trigger this for C-style casts. 11837 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 11838 Expr *CastExpr, CastKind &CastKind, 11839 ExprValueKind &VK, CXXCastPath &Path) { 11840 // Rewrite the casted expression from scratch. 11841 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 11842 if (!result.isUsable()) return ExprError(); 11843 11844 CastExpr = result.take(); 11845 VK = CastExpr->getValueKind(); 11846 CastKind = CK_NoOp; 11847 11848 return CastExpr; 11849 } 11850 11851 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 11852 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 11853 } 11854 11855 QualType Sema::checkUnknownAnyArg(Expr *&arg) { 11856 // Filter out placeholders. 11857 ExprResult argR = CheckPlaceholderExpr(arg); 11858 if (argR.isInvalid()) return QualType(); 11859 arg = argR.take(); 11860 11861 // If the argument is an explicit cast, use that exact type as the 11862 // effective parameter type. 11863 if (ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg)) { 11864 return castArg->getTypeAsWritten(); 11865 } 11866 11867 // Otherwise, try to pass by value. 11868 return arg->getType().getUnqualifiedType(); 11869 } 11870 11871 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 11872 Expr *orig = E; 11873 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 11874 while (true) { 11875 E = E->IgnoreParenImpCasts(); 11876 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 11877 E = call->getCallee(); 11878 diagID = diag::err_uncasted_call_of_unknown_any; 11879 } else { 11880 break; 11881 } 11882 } 11883 11884 SourceLocation loc; 11885 NamedDecl *d; 11886 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 11887 loc = ref->getLocation(); 11888 d = ref->getDecl(); 11889 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 11890 loc = mem->getMemberLoc(); 11891 d = mem->getMemberDecl(); 11892 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 11893 diagID = diag::err_uncasted_call_of_unknown_any; 11894 loc = msg->getSelectorStartLoc(); 11895 d = msg->getMethodDecl(); 11896 if (!d) { 11897 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 11898 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 11899 << orig->getSourceRange(); 11900 return ExprError(); 11901 } 11902 } else { 11903 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 11904 << E->getSourceRange(); 11905 return ExprError(); 11906 } 11907 11908 S.Diag(loc, diagID) << d << orig->getSourceRange(); 11909 11910 // Never recoverable. 11911 return ExprError(); 11912 } 11913 11914 /// Check for operands with placeholder types and complain if found. 11915 /// Returns true if there was an error and no recovery was possible. 11916 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 11917 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 11918 if (!placeholderType) return Owned(E); 11919 11920 switch (placeholderType->getKind()) { 11921 11922 // Overloaded expressions. 11923 case BuiltinType::Overload: { 11924 // Try to resolve a single function template specialization. 11925 // This is obligatory. 11926 ExprResult result = Owned(E); 11927 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 11928 return result; 11929 11930 // If that failed, try to recover with a call. 11931 } else { 11932 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 11933 /*complain*/ true); 11934 return result; 11935 } 11936 } 11937 11938 // Bound member functions. 11939 case BuiltinType::BoundMember: { 11940 ExprResult result = Owned(E); 11941 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 11942 /*complain*/ true); 11943 return result; 11944 } 11945 11946 // ARC unbridged casts. 11947 case BuiltinType::ARCUnbridgedCast: { 11948 Expr *realCast = stripARCUnbridgedCast(E); 11949 diagnoseARCUnbridgedCast(realCast); 11950 return Owned(realCast); 11951 } 11952 11953 // Expressions of unknown type. 11954 case BuiltinType::UnknownAny: 11955 return diagnoseUnknownAnyExpr(*this, E); 11956 11957 // Pseudo-objects. 11958 case BuiltinType::PseudoObject: 11959 return checkPseudoObjectRValue(E); 11960 11961 case BuiltinType::BuiltinFn: 11962 Diag(E->getLocStart(), diag::err_builtin_fn_use); 11963 return ExprError(); 11964 11965 // Everything else should be impossible. 11966 #define BUILTIN_TYPE(Id, SingletonId) \ 11967 case BuiltinType::Id: 11968 #define PLACEHOLDER_TYPE(Id, SingletonId) 11969 #include "clang/AST/BuiltinTypes.def" 11970 break; 11971 } 11972 11973 llvm_unreachable("invalid placeholder type!"); 11974 } 11975 11976 bool Sema::CheckCaseExpression(Expr *E) { 11977 if (E->isTypeDependent()) 11978 return true; 11979 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 11980 return E->getType()->isIntegralOrEnumerationType(); 11981 return false; 11982 } 11983 11984 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 11985 ExprResult 11986 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 11987 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 11988 "Unknown Objective-C Boolean value!"); 11989 QualType BoolT = Context.ObjCBuiltinBoolTy; 11990 if (!Context.getBOOLDecl()) { 11991 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 11992 Sema::LookupOrdinaryName); 11993 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 11994 NamedDecl *ND = Result.getFoundDecl(); 11995 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 11996 Context.setBOOLDecl(TD); 11997 } 11998 } 11999 if (Context.getBOOLDecl()) 12000 BoolT = Context.getBOOLType(); 12001 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 12002 BoolT, OpLoc)); 12003 } 12004