SemaStmt.cpp revision d87a0cd2b3e1c9e9f01212875f4cbe5b7bb7ab57
1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===// 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 statements. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Scope.h" 16#include "clang/Sema/ScopeInfo.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/CharUnits.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/ExprObjC.h" 24#include "clang/AST/StmtObjC.h" 25#include "clang/AST/StmtCXX.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/Lex/Preprocessor.h" 28#include "clang/Basic/TargetInfo.h" 29#include "llvm/ADT/ArrayRef.h" 30#include "llvm/ADT/STLExtras.h" 31#include "llvm/ADT/SmallVector.h" 32using namespace clang; 33using namespace sema; 34 35StmtResult Sema::ActOnExprStmt(FullExprArg expr) { 36 Expr *E = expr.get(); 37 if (!E) // FIXME: FullExprArg has no error state? 38 return StmtError(); 39 40 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 41 // void expression for its side effects. Conversion to void allows any 42 // operand, even incomplete types. 43 44 // Same thing in for stmt first clause (when expr) and third clause. 45 return Owned(static_cast<Stmt*>(E)); 46} 47 48 49StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, 50 bool HasLeadingEmptyMacro) { 51 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro)); 52} 53 54StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc, 55 SourceLocation EndLoc) { 56 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 57 58 // If we have an invalid decl, just return an error. 59 if (DG.isNull()) return StmtError(); 60 61 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc)); 62} 63 64void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 65 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 66 67 // If we have an invalid decl, just return. 68 if (DG.isNull() || !DG.isSingleDecl()) return; 69 VarDecl *var = cast<VarDecl>(DG.getSingleDecl()); 70 71 // suppress any potential 'unused variable' warning. 72 var->setUsed(); 73 74 // foreach variables are never actually initialized in the way that 75 // the parser came up with. 76 var->setInit(0); 77 78 // In ARC, we don't need to retain the iteration variable of a fast 79 // enumeration loop. Rather than actually trying to catch that 80 // during declaration processing, we remove the consequences here. 81 if (getLangOptions().ObjCAutoRefCount) { 82 QualType type = var->getType(); 83 84 // Only do this if we inferred the lifetime. Inferred lifetime 85 // will show up as a local qualifier because explicit lifetime 86 // should have shown up as an AttributedType instead. 87 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) { 88 // Add 'const' and mark the variable as pseudo-strong. 89 var->setType(type.withConst()); 90 var->setARCPseudoStrong(true); 91 } 92 } 93} 94 95/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='. 96/// 97/// Adding a cast to void (or other expression wrappers) will prevent the 98/// warning from firing. 99static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) { 100 SourceLocation Loc; 101 bool IsNotEqual, CanAssign; 102 103 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 104 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE) 105 return false; 106 107 Loc = Op->getOperatorLoc(); 108 IsNotEqual = Op->getOpcode() == BO_NE; 109 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue(); 110 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 111 if (Op->getOperator() != OO_EqualEqual && 112 Op->getOperator() != OO_ExclaimEqual) 113 return false; 114 115 Loc = Op->getOperatorLoc(); 116 IsNotEqual = Op->getOperator() == OO_ExclaimEqual; 117 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue(); 118 } else { 119 // Not a typo-prone comparison. 120 return false; 121 } 122 123 // Suppress warnings when the operator, suspicious as it may be, comes from 124 // a macro expansion. 125 if (Loc.isMacroID()) 126 return false; 127 128 S.Diag(Loc, diag::warn_unused_comparison) 129 << (unsigned)IsNotEqual << E->getSourceRange(); 130 131 // If the LHS is a plausible entity to assign to, provide a fixit hint to 132 // correct common typos. 133 if (CanAssign) { 134 if (IsNotEqual) 135 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign) 136 << FixItHint::CreateReplacement(Loc, "|="); 137 else 138 S.Diag(Loc, diag::note_equality_comparison_to_assign) 139 << FixItHint::CreateReplacement(Loc, "="); 140 } 141 142 return true; 143} 144 145void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 146 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 147 return DiagnoseUnusedExprResult(Label->getSubStmt()); 148 149 const Expr *E = dyn_cast_or_null<Expr>(S); 150 if (!E) 151 return; 152 153 SourceLocation Loc; 154 SourceRange R1, R2; 155 if (SourceMgr.isInSystemMacro(E->getExprLoc()) || 156 !E->isUnusedResultAWarning(Loc, R1, R2, Context)) 157 return; 158 159 // Okay, we have an unused result. Depending on what the base expression is, 160 // we might want to make a more specific diagnostic. Check for one of these 161 // cases now. 162 unsigned DiagID = diag::warn_unused_expr; 163 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 164 E = Temps->getSubExpr(); 165 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 166 E = TempExpr->getSubExpr(); 167 168 if (DiagnoseUnusedComparison(*this, E)) 169 return; 170 171 E = E->IgnoreParenImpCasts(); 172 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 173 if (E->getType()->isVoidType()) 174 return; 175 176 // If the callee has attribute pure, const, or warn_unused_result, warn with 177 // a more specific message to make it clear what is happening. 178 if (const Decl *FD = CE->getCalleeDecl()) { 179 if (FD->getAttr<WarnUnusedResultAttr>()) { 180 Diag(Loc, diag::warn_unused_result) << R1 << R2; 181 return; 182 } 183 if (FD->getAttr<PureAttr>()) { 184 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 185 return; 186 } 187 if (FD->getAttr<ConstAttr>()) { 188 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 189 return; 190 } 191 } 192 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 193 if (getLangOptions().ObjCAutoRefCount && ME->isDelegateInitCall()) { 194 Diag(Loc, diag::err_arc_unused_init_message) << R1; 195 return; 196 } 197 const ObjCMethodDecl *MD = ME->getMethodDecl(); 198 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 199 Diag(Loc, diag::warn_unused_result) << R1 << R2; 200 return; 201 } 202 } else if (isa<PseudoObjectExpr>(E)) { 203 DiagID = diag::warn_unused_property_expr; 204 } else if (const CXXFunctionalCastExpr *FC 205 = dyn_cast<CXXFunctionalCastExpr>(E)) { 206 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 207 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 208 return; 209 } 210 // Diagnose "(void*) blah" as a typo for "(void) blah". 211 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 212 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 213 QualType T = TI->getType(); 214 215 // We really do want to use the non-canonical type here. 216 if (T == Context.VoidPtrTy) { 217 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc()); 218 219 Diag(Loc, diag::warn_unused_voidptr) 220 << FixItHint::CreateRemoval(TL.getStarLoc()); 221 return; 222 } 223 } 224 225 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2); 226} 227 228StmtResult 229Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 230 MultiStmtArg elts, bool isStmtExpr) { 231 unsigned NumElts = elts.size(); 232 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release()); 233 // If we're in C89 mode, check that we don't have any decls after stmts. If 234 // so, emit an extension diagnostic. 235 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) { 236 // Note that __extension__ can be around a decl. 237 unsigned i = 0; 238 // Skip over all declarations. 239 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 240 /*empty*/; 241 242 // We found the end of the list or a statement. Scan for another declstmt. 243 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 244 /*empty*/; 245 246 if (i != NumElts) { 247 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 248 Diag(D->getLocation(), diag::ext_mixed_decls_code); 249 } 250 } 251 // Warn about unused expressions in statements. 252 for (unsigned i = 0; i != NumElts; ++i) { 253 // Ignore statements that are last in a statement expression. 254 if (isStmtExpr && i == NumElts - 1) 255 continue; 256 257 DiagnoseUnusedExprResult(Elts[i]); 258 } 259 260 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R)); 261} 262 263StmtResult 264Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 265 SourceLocation DotDotDotLoc, Expr *RHSVal, 266 SourceLocation ColonLoc) { 267 assert((LHSVal != 0) && "missing expression in case statement"); 268 269 // C99 6.8.4.2p3: The expression shall be an integer constant. 270 // However, GCC allows any evaluatable integer expression. 271 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() && 272 VerifyIntegerConstantExpression(LHSVal)) 273 return StmtError(); 274 275 // GCC extension: The expression shall be an integer constant. 276 277 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() && 278 VerifyIntegerConstantExpression(RHSVal)) { 279 RHSVal = 0; // Recover by just forgetting about it. 280 } 281 282 if (getCurFunction()->SwitchStack.empty()) { 283 Diag(CaseLoc, diag::err_case_not_in_switch); 284 return StmtError(); 285 } 286 287 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 288 ColonLoc); 289 getCurFunction()->SwitchStack.back()->addSwitchCase(CS); 290 return Owned(CS); 291} 292 293/// ActOnCaseStmtBody - This installs a statement as the body of a case. 294void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) { 295 DiagnoseUnusedExprResult(SubStmt); 296 297 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 298 CS->setSubStmt(SubStmt); 299} 300 301StmtResult 302Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 303 Stmt *SubStmt, Scope *CurScope) { 304 DiagnoseUnusedExprResult(SubStmt); 305 306 if (getCurFunction()->SwitchStack.empty()) { 307 Diag(DefaultLoc, diag::err_default_not_in_switch); 308 return Owned(SubStmt); 309 } 310 311 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 312 getCurFunction()->SwitchStack.back()->addSwitchCase(DS); 313 return Owned(DS); 314} 315 316StmtResult 317Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 318 SourceLocation ColonLoc, Stmt *SubStmt) { 319 320 // If the label was multiply defined, reject it now. 321 if (TheDecl->getStmt()) { 322 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 323 Diag(TheDecl->getLocation(), diag::note_previous_definition); 324 return Owned(SubStmt); 325 } 326 327 // Otherwise, things are good. Fill in the declaration and return it. 328 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 329 TheDecl->setStmt(LS); 330 if (!TheDecl->isGnuLocal()) 331 TheDecl->setLocation(IdentLoc); 332 return Owned(LS); 333} 334 335StmtResult 336Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 337 Stmt *thenStmt, SourceLocation ElseLoc, 338 Stmt *elseStmt) { 339 ExprResult CondResult(CondVal.release()); 340 341 VarDecl *ConditionVar = 0; 342 if (CondVar) { 343 ConditionVar = cast<VarDecl>(CondVar); 344 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 345 if (CondResult.isInvalid()) 346 return StmtError(); 347 } 348 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 349 if (!ConditionExpr) 350 return StmtError(); 351 352 DiagnoseUnusedExprResult(thenStmt); 353 354 // Warn if the if block has a null body without an else value. 355 // this helps prevent bugs due to typos, such as 356 // if (condition); 357 // do_stuff(); 358 // 359 if (!elseStmt) { 360 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 361 // But do not warn if the body is a macro that expands to nothing, e.g: 362 // 363 // #define CALL(x) 364 // if (condition) 365 // CALL(0); 366 // 367 if (!stmt->hasLeadingEmptyMacro()) 368 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 369 } 370 371 DiagnoseUnusedExprResult(elseStmt); 372 373 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 374 thenStmt, ElseLoc, elseStmt)); 375} 376 377/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 378/// the specified width and sign. If an overflow occurs, detect it and emit 379/// the specified diagnostic. 380void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 381 unsigned NewWidth, bool NewSign, 382 SourceLocation Loc, 383 unsigned DiagID) { 384 // Perform a conversion to the promoted condition type if needed. 385 if (NewWidth > Val.getBitWidth()) { 386 // If this is an extension, just do it. 387 Val = Val.extend(NewWidth); 388 Val.setIsSigned(NewSign); 389 390 // If the input was signed and negative and the output is 391 // unsigned, don't bother to warn: this is implementation-defined 392 // behavior. 393 // FIXME: Introduce a second, default-ignored warning for this case? 394 } else if (NewWidth < Val.getBitWidth()) { 395 // If this is a truncation, check for overflow. 396 llvm::APSInt ConvVal(Val); 397 ConvVal = ConvVal.trunc(NewWidth); 398 ConvVal.setIsSigned(NewSign); 399 ConvVal = ConvVal.extend(Val.getBitWidth()); 400 ConvVal.setIsSigned(Val.isSigned()); 401 if (ConvVal != Val) 402 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 403 404 // Regardless of whether a diagnostic was emitted, really do the 405 // truncation. 406 Val = Val.trunc(NewWidth); 407 Val.setIsSigned(NewSign); 408 } else if (NewSign != Val.isSigned()) { 409 // Convert the sign to match the sign of the condition. This can cause 410 // overflow as well: unsigned(INTMIN) 411 // We don't diagnose this overflow, because it is implementation-defined 412 // behavior. 413 // FIXME: Introduce a second, default-ignored warning for this case? 414 llvm::APSInt OldVal(Val); 415 Val.setIsSigned(NewSign); 416 } 417} 418 419namespace { 420 struct CaseCompareFunctor { 421 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 422 const llvm::APSInt &RHS) { 423 return LHS.first < RHS; 424 } 425 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 426 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 427 return LHS.first < RHS.first; 428 } 429 bool operator()(const llvm::APSInt &LHS, 430 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 431 return LHS < RHS.first; 432 } 433 }; 434} 435 436/// CmpCaseVals - Comparison predicate for sorting case values. 437/// 438static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 439 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 440 if (lhs.first < rhs.first) 441 return true; 442 443 if (lhs.first == rhs.first && 444 lhs.second->getCaseLoc().getRawEncoding() 445 < rhs.second->getCaseLoc().getRawEncoding()) 446 return true; 447 return false; 448} 449 450/// CmpEnumVals - Comparison predicate for sorting enumeration values. 451/// 452static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 453 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 454{ 455 return lhs.first < rhs.first; 456} 457 458/// EqEnumVals - Comparison preficate for uniqing enumeration values. 459/// 460static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 461 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 462{ 463 return lhs.first == rhs.first; 464} 465 466/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 467/// potentially integral-promoted expression @p expr. 468static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) { 469 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr)) 470 expr = cleanups->getSubExpr(); 471 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) { 472 if (impcast->getCastKind() != CK_IntegralCast) break; 473 expr = impcast->getSubExpr(); 474 } 475 return expr->getType(); 476} 477 478StmtResult 479Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 480 Decl *CondVar) { 481 ExprResult CondResult; 482 483 VarDecl *ConditionVar = 0; 484 if (CondVar) { 485 ConditionVar = cast<VarDecl>(CondVar); 486 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 487 if (CondResult.isInvalid()) 488 return StmtError(); 489 490 Cond = CondResult.release(); 491 } 492 493 if (!Cond) 494 return StmtError(); 495 496 CondResult = CheckPlaceholderExpr(Cond); 497 if (CondResult.isInvalid()) 498 return StmtError(); 499 500 CondResult 501 = ConvertToIntegralOrEnumerationType(SwitchLoc, CondResult.take(), 502 PDiag(diag::err_typecheck_statement_requires_integer), 503 PDiag(diag::err_switch_incomplete_class_type) 504 << Cond->getSourceRange(), 505 PDiag(diag::err_switch_explicit_conversion), 506 PDiag(diag::note_switch_conversion), 507 PDiag(diag::err_switch_multiple_conversions), 508 PDiag(diag::note_switch_conversion), 509 PDiag(0)); 510 if (CondResult.isInvalid()) return StmtError(); 511 Cond = CondResult.take(); 512 513 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 514 CondResult = UsualUnaryConversions(Cond); 515 if (CondResult.isInvalid()) return StmtError(); 516 Cond = CondResult.take(); 517 518 if (!CondVar) { 519 CheckImplicitConversions(Cond, SwitchLoc); 520 CondResult = MaybeCreateExprWithCleanups(Cond); 521 if (CondResult.isInvalid()) 522 return StmtError(); 523 Cond = CondResult.take(); 524 } 525 526 getCurFunction()->setHasBranchIntoScope(); 527 528 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 529 getCurFunction()->SwitchStack.push_back(SS); 530 return Owned(SS); 531} 532 533static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 534 if (Val.getBitWidth() < BitWidth) 535 Val = Val.extend(BitWidth); 536 else if (Val.getBitWidth() > BitWidth) 537 Val = Val.trunc(BitWidth); 538 Val.setIsSigned(IsSigned); 539} 540 541StmtResult 542Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 543 Stmt *BodyStmt) { 544 SwitchStmt *SS = cast<SwitchStmt>(Switch); 545 assert(SS == getCurFunction()->SwitchStack.back() && 546 "switch stack missing push/pop!"); 547 548 SS->setBody(BodyStmt, SwitchLoc); 549 getCurFunction()->SwitchStack.pop_back(); 550 551 Expr *CondExpr = SS->getCond(); 552 if (!CondExpr) return StmtError(); 553 554 QualType CondType = CondExpr->getType(); 555 556 Expr *CondExprBeforePromotion = CondExpr; 557 QualType CondTypeBeforePromotion = 558 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); 559 560 // C++ 6.4.2.p2: 561 // Integral promotions are performed (on the switch condition). 562 // 563 // A case value unrepresentable by the original switch condition 564 // type (before the promotion) doesn't make sense, even when it can 565 // be represented by the promoted type. Therefore we need to find 566 // the pre-promotion type of the switch condition. 567 if (!CondExpr->isTypeDependent()) { 568 // We have already converted the expression to an integral or enumeration 569 // type, when we started the switch statement. If we don't have an 570 // appropriate type now, just return an error. 571 if (!CondType->isIntegralOrEnumerationType()) 572 return StmtError(); 573 574 if (CondExpr->isKnownToHaveBooleanValue()) { 575 // switch(bool_expr) {...} is often a programmer error, e.g. 576 // switch(n && mask) { ... } // Doh - should be "n & mask". 577 // One can always use an if statement instead of switch(bool_expr). 578 Diag(SwitchLoc, diag::warn_bool_switch_condition) 579 << CondExpr->getSourceRange(); 580 } 581 } 582 583 // Get the bitwidth of the switched-on value before promotions. We must 584 // convert the integer case values to this width before comparison. 585 bool HasDependentValue 586 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 587 unsigned CondWidth 588 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); 589 bool CondIsSigned 590 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); 591 592 // Accumulate all of the case values in a vector so that we can sort them 593 // and detect duplicates. This vector contains the APInt for the case after 594 // it has been converted to the condition type. 595 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 596 CaseValsTy CaseVals; 597 598 // Keep track of any GNU case ranges we see. The APSInt is the low value. 599 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 600 CaseRangesTy CaseRanges; 601 602 DefaultStmt *TheDefaultStmt = 0; 603 604 bool CaseListIsErroneous = false; 605 606 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 607 SC = SC->getNextSwitchCase()) { 608 609 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 610 if (TheDefaultStmt) { 611 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 612 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 613 614 // FIXME: Remove the default statement from the switch block so that 615 // we'll return a valid AST. This requires recursing down the AST and 616 // finding it, not something we are set up to do right now. For now, 617 // just lop the entire switch stmt out of the AST. 618 CaseListIsErroneous = true; 619 } 620 TheDefaultStmt = DS; 621 622 } else { 623 CaseStmt *CS = cast<CaseStmt>(SC); 624 625 // We already verified that the expression has a i-c-e value (C99 626 // 6.8.4.2p3) - get that value now. 627 Expr *Lo = CS->getLHS(); 628 629 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 630 HasDependentValue = true; 631 break; 632 } 633 634 llvm::APSInt LoVal = Lo->EvaluateKnownConstInt(Context); 635 636 // Convert the value to the same width/sign as the condition. 637 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 638 Lo->getLocStart(), 639 diag::warn_case_value_overflow); 640 641 // If the LHS is not the same type as the condition, insert an implicit 642 // cast. 643 // FIXME: In C++11, the value is a converted constant expression of the 644 // promoted type of the switch condition. 645 Lo = DefaultLvalueConversion(Lo).take(); 646 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take(); 647 CS->setLHS(Lo); 648 649 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 650 if (CS->getRHS()) { 651 if (CS->getRHS()->isTypeDependent() || 652 CS->getRHS()->isValueDependent()) { 653 HasDependentValue = true; 654 break; 655 } 656 CaseRanges.push_back(std::make_pair(LoVal, CS)); 657 } else 658 CaseVals.push_back(std::make_pair(LoVal, CS)); 659 } 660 } 661 662 if (!HasDependentValue) { 663 // If we don't have a default statement, check whether the 664 // condition is constant. 665 llvm::APSInt ConstantCondValue; 666 bool HasConstantCond = false; 667 if (!HasDependentValue && !TheDefaultStmt) { 668 HasConstantCond 669 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context, 670 Expr::SE_AllowSideEffects); 671 assert(!HasConstantCond || 672 (ConstantCondValue.getBitWidth() == CondWidth && 673 ConstantCondValue.isSigned() == CondIsSigned)); 674 } 675 bool ShouldCheckConstantCond = HasConstantCond; 676 677 // Sort all the scalar case values so we can easily detect duplicates. 678 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 679 680 if (!CaseVals.empty()) { 681 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 682 if (ShouldCheckConstantCond && 683 CaseVals[i].first == ConstantCondValue) 684 ShouldCheckConstantCond = false; 685 686 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 687 // If we have a duplicate, report it. 688 Diag(CaseVals[i].second->getLHS()->getLocStart(), 689 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 690 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 691 diag::note_duplicate_case_prev); 692 // FIXME: We really want to remove the bogus case stmt from the 693 // substmt, but we have no way to do this right now. 694 CaseListIsErroneous = true; 695 } 696 } 697 } 698 699 // Detect duplicate case ranges, which usually don't exist at all in 700 // the first place. 701 if (!CaseRanges.empty()) { 702 // Sort all the case ranges by their low value so we can easily detect 703 // overlaps between ranges. 704 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 705 706 // Scan the ranges, computing the high values and removing empty ranges. 707 std::vector<llvm::APSInt> HiVals; 708 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 709 llvm::APSInt &LoVal = CaseRanges[i].first; 710 CaseStmt *CR = CaseRanges[i].second; 711 Expr *Hi = CR->getRHS(); 712 llvm::APSInt HiVal = Hi->EvaluateKnownConstInt(Context); 713 714 // Convert the value to the same width/sign as the condition. 715 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 716 Hi->getLocStart(), 717 diag::warn_case_value_overflow); 718 719 // If the RHS is not the same type as the condition, insert an implicit 720 // cast. 721 // FIXME: In C++11, the value is a converted constant expression of the 722 // promoted type of the switch condition. 723 Hi = DefaultLvalueConversion(Hi).take(); 724 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take(); 725 CR->setRHS(Hi); 726 727 // If the low value is bigger than the high value, the case is empty. 728 if (LoVal > HiVal) { 729 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 730 << SourceRange(CR->getLHS()->getLocStart(), 731 Hi->getLocEnd()); 732 CaseRanges.erase(CaseRanges.begin()+i); 733 --i, --e; 734 continue; 735 } 736 737 if (ShouldCheckConstantCond && 738 LoVal <= ConstantCondValue && 739 ConstantCondValue <= HiVal) 740 ShouldCheckConstantCond = false; 741 742 HiVals.push_back(HiVal); 743 } 744 745 // Rescan the ranges, looking for overlap with singleton values and other 746 // ranges. Since the range list is sorted, we only need to compare case 747 // ranges with their neighbors. 748 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 749 llvm::APSInt &CRLo = CaseRanges[i].first; 750 llvm::APSInt &CRHi = HiVals[i]; 751 CaseStmt *CR = CaseRanges[i].second; 752 753 // Check to see whether the case range overlaps with any 754 // singleton cases. 755 CaseStmt *OverlapStmt = 0; 756 llvm::APSInt OverlapVal(32); 757 758 // Find the smallest value >= the lower bound. If I is in the 759 // case range, then we have overlap. 760 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 761 CaseVals.end(), CRLo, 762 CaseCompareFunctor()); 763 if (I != CaseVals.end() && I->first < CRHi) { 764 OverlapVal = I->first; // Found overlap with scalar. 765 OverlapStmt = I->second; 766 } 767 768 // Find the smallest value bigger than the upper bound. 769 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 770 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 771 OverlapVal = (I-1)->first; // Found overlap with scalar. 772 OverlapStmt = (I-1)->second; 773 } 774 775 // Check to see if this case stmt overlaps with the subsequent 776 // case range. 777 if (i && CRLo <= HiVals[i-1]) { 778 OverlapVal = HiVals[i-1]; // Found overlap with range. 779 OverlapStmt = CaseRanges[i-1].second; 780 } 781 782 if (OverlapStmt) { 783 // If we have a duplicate, report it. 784 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 785 << OverlapVal.toString(10); 786 Diag(OverlapStmt->getLHS()->getLocStart(), 787 diag::note_duplicate_case_prev); 788 // FIXME: We really want to remove the bogus case stmt from the 789 // substmt, but we have no way to do this right now. 790 CaseListIsErroneous = true; 791 } 792 } 793 } 794 795 // Complain if we have a constant condition and we didn't find a match. 796 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 797 // TODO: it would be nice if we printed enums as enums, chars as 798 // chars, etc. 799 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 800 << ConstantCondValue.toString(10) 801 << CondExpr->getSourceRange(); 802 } 803 804 // Check to see if switch is over an Enum and handles all of its 805 // values. We only issue a warning if there is not 'default:', but 806 // we still do the analysis to preserve this information in the AST 807 // (which can be used by flow-based analyes). 808 // 809 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 810 811 // If switch has default case, then ignore it. 812 if (!CaseListIsErroneous && !HasConstantCond && ET) { 813 const EnumDecl *ED = ET->getDecl(); 814 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> 815 EnumValsTy; 816 EnumValsTy EnumVals; 817 818 // Gather all enum values, set their type and sort them, 819 // allowing easier comparison with CaseVals. 820 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 821 EDI != ED->enumerator_end(); ++EDI) { 822 llvm::APSInt Val = EDI->getInitVal(); 823 AdjustAPSInt(Val, CondWidth, CondIsSigned); 824 EnumVals.push_back(std::make_pair(Val, *EDI)); 825 } 826 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 827 EnumValsTy::iterator EIend = 828 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 829 830 // See which case values aren't in enum. 831 // TODO: we might want to check whether case values are out of the 832 // enum even if we don't want to check whether all cases are handled. 833 if (!TheDefaultStmt) { 834 EnumValsTy::const_iterator EI = EnumVals.begin(); 835 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 836 CI != CaseVals.end(); CI++) { 837 while (EI != EIend && EI->first < CI->first) 838 EI++; 839 if (EI == EIend || EI->first > CI->first) 840 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 841 << ED->getDeclName(); 842 } 843 // See which of case ranges aren't in enum 844 EI = EnumVals.begin(); 845 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 846 RI != CaseRanges.end() && EI != EIend; RI++) { 847 while (EI != EIend && EI->first < RI->first) 848 EI++; 849 850 if (EI == EIend || EI->first != RI->first) { 851 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 852 << ED->getDeclName(); 853 } 854 855 llvm::APSInt Hi = 856 RI->second->getRHS()->EvaluateKnownConstInt(Context); 857 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 858 while (EI != EIend && EI->first < Hi) 859 EI++; 860 if (EI == EIend || EI->first != Hi) 861 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 862 << ED->getDeclName(); 863 } 864 } 865 866 // Check which enum vals aren't in switch 867 CaseValsTy::const_iterator CI = CaseVals.begin(); 868 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 869 bool hasCasesNotInSwitch = false; 870 871 SmallVector<DeclarationName,8> UnhandledNames; 872 873 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){ 874 // Drop unneeded case values 875 llvm::APSInt CIVal; 876 while (CI != CaseVals.end() && CI->first < EI->first) 877 CI++; 878 879 if (CI != CaseVals.end() && CI->first == EI->first) 880 continue; 881 882 // Drop unneeded case ranges 883 for (; RI != CaseRanges.end(); RI++) { 884 llvm::APSInt Hi = 885 RI->second->getRHS()->EvaluateKnownConstInt(Context); 886 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 887 if (EI->first <= Hi) 888 break; 889 } 890 891 if (RI == CaseRanges.end() || EI->first < RI->first) { 892 hasCasesNotInSwitch = true; 893 if (!TheDefaultStmt) 894 UnhandledNames.push_back(EI->second->getDeclName()); 895 } 896 } 897 898 // Produce a nice diagnostic if multiple values aren't handled. 899 switch (UnhandledNames.size()) { 900 case 0: break; 901 case 1: 902 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1) 903 << UnhandledNames[0]; 904 break; 905 case 2: 906 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2) 907 << UnhandledNames[0] << UnhandledNames[1]; 908 break; 909 case 3: 910 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3) 911 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 912 break; 913 default: 914 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases) 915 << (unsigned)UnhandledNames.size() 916 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 917 break; 918 } 919 920 if (!hasCasesNotInSwitch) 921 SS->setAllEnumCasesCovered(); 922 } 923 } 924 925 // FIXME: If the case list was broken is some way, we don't have a good system 926 // to patch it up. Instead, just return the whole substmt as broken. 927 if (CaseListIsErroneous) 928 return StmtError(); 929 930 return Owned(SS); 931} 932 933StmtResult 934Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 935 Decl *CondVar, Stmt *Body) { 936 ExprResult CondResult(Cond.release()); 937 938 VarDecl *ConditionVar = 0; 939 if (CondVar) { 940 ConditionVar = cast<VarDecl>(CondVar); 941 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 942 if (CondResult.isInvalid()) 943 return StmtError(); 944 } 945 Expr *ConditionExpr = CondResult.take(); 946 if (!ConditionExpr) 947 return StmtError(); 948 949 DiagnoseUnusedExprResult(Body); 950 951 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 952 Body, WhileLoc)); 953} 954 955StmtResult 956Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 957 SourceLocation WhileLoc, SourceLocation CondLParen, 958 Expr *Cond, SourceLocation CondRParen) { 959 assert(Cond && "ActOnDoStmt(): missing expression"); 960 961 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc); 962 if (CondResult.isInvalid() || CondResult.isInvalid()) 963 return StmtError(); 964 Cond = CondResult.take(); 965 966 CheckImplicitConversions(Cond, DoLoc); 967 CondResult = MaybeCreateExprWithCleanups(Cond); 968 if (CondResult.isInvalid()) 969 return StmtError(); 970 Cond = CondResult.take(); 971 972 DiagnoseUnusedExprResult(Body); 973 974 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 975} 976 977StmtResult 978Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 979 Stmt *First, FullExprArg second, Decl *secondVar, 980 FullExprArg third, 981 SourceLocation RParenLoc, Stmt *Body) { 982 if (!getLangOptions().CPlusPlus) { 983 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 984 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 985 // declare identifiers for objects having storage class 'auto' or 986 // 'register'. 987 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 988 DI!=DE; ++DI) { 989 VarDecl *VD = dyn_cast<VarDecl>(*DI); 990 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 991 VD = 0; 992 if (VD == 0) 993 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 994 // FIXME: mark decl erroneous! 995 } 996 } 997 } 998 999 ExprResult SecondResult(second.release()); 1000 VarDecl *ConditionVar = 0; 1001 if (secondVar) { 1002 ConditionVar = cast<VarDecl>(secondVar); 1003 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 1004 if (SecondResult.isInvalid()) 1005 return StmtError(); 1006 } 1007 1008 Expr *Third = third.release().takeAs<Expr>(); 1009 1010 DiagnoseUnusedExprResult(First); 1011 DiagnoseUnusedExprResult(Third); 1012 DiagnoseUnusedExprResult(Body); 1013 1014 return Owned(new (Context) ForStmt(Context, First, 1015 SecondResult.take(), ConditionVar, 1016 Third, Body, ForLoc, LParenLoc, 1017 RParenLoc)); 1018} 1019 1020/// In an Objective C collection iteration statement: 1021/// for (x in y) 1022/// x can be an arbitrary l-value expression. Bind it up as a 1023/// full-expression. 1024StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 1025 CheckImplicitConversions(E); 1026 ExprResult Result = MaybeCreateExprWithCleanups(E); 1027 if (Result.isInvalid()) return StmtError(); 1028 return Owned(static_cast<Stmt*>(Result.get())); 1029} 1030 1031ExprResult 1032Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { 1033 assert(collection); 1034 1035 // Bail out early if we've got a type-dependent expression. 1036 if (collection->isTypeDependent()) return Owned(collection); 1037 1038 // Perform normal l-value conversion. 1039 ExprResult result = DefaultFunctionArrayLvalueConversion(collection); 1040 if (result.isInvalid()) 1041 return ExprError(); 1042 collection = result.take(); 1043 1044 // The operand needs to have object-pointer type. 1045 // TODO: should we do a contextual conversion? 1046 const ObjCObjectPointerType *pointerType = 1047 collection->getType()->getAs<ObjCObjectPointerType>(); 1048 if (!pointerType) 1049 return Diag(forLoc, diag::err_collection_expr_type) 1050 << collection->getType() << collection->getSourceRange(); 1051 1052 // Check that the operand provides 1053 // - countByEnumeratingWithState:objects:count: 1054 const ObjCObjectType *objectType = pointerType->getObjectType(); 1055 ObjCInterfaceDecl *iface = objectType->getInterface(); 1056 1057 // If we have a forward-declared type, we can't do this check. 1058 // Under ARC, it is an error not to have a forward-declared class. 1059 if (iface && 1060 RequireCompleteType(forLoc, QualType(objectType, 0), 1061 getLangOptions().ObjCAutoRefCount 1062 ? PDiag(diag::err_arc_collection_forward) 1063 << collection->getSourceRange() 1064 : PDiag(0))) { 1065 // Otherwise, if we have any useful type information, check that 1066 // the type declares the appropriate method. 1067 } else if (iface || !objectType->qual_empty()) { 1068 IdentifierInfo *selectorIdents[] = { 1069 &Context.Idents.get("countByEnumeratingWithState"), 1070 &Context.Idents.get("objects"), 1071 &Context.Idents.get("count") 1072 }; 1073 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); 1074 1075 ObjCMethodDecl *method = 0; 1076 1077 // If there's an interface, look in both the public and private APIs. 1078 if (iface) { 1079 method = iface->lookupInstanceMethod(selector); 1080 if (!method) method = LookupPrivateInstanceMethod(selector, iface); 1081 } 1082 1083 // Also check protocol qualifiers. 1084 if (!method) 1085 method = LookupMethodInQualifiedType(selector, pointerType, 1086 /*instance*/ true); 1087 1088 // If we didn't find it anywhere, give up. 1089 if (!method) { 1090 Diag(forLoc, diag::warn_collection_expr_type) 1091 << collection->getType() << selector << collection->getSourceRange(); 1092 } 1093 1094 // TODO: check for an incompatible signature? 1095 } 1096 1097 // Wrap up any cleanups in the expression. 1098 return Owned(MaybeCreateExprWithCleanups(collection)); 1099} 1100 1101StmtResult 1102Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 1103 SourceLocation LParenLoc, 1104 Stmt *First, Expr *Second, 1105 SourceLocation RParenLoc, Stmt *Body) { 1106 if (First) { 1107 QualType FirstType; 1108 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 1109 if (!DS->isSingleDecl()) 1110 return StmtError(Diag((*DS->decl_begin())->getLocation(), 1111 diag::err_toomany_element_decls)); 1112 1113 VarDecl *D = cast<VarDecl>(DS->getSingleDecl()); 1114 FirstType = D->getType(); 1115 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 1116 // declare identifiers for objects having storage class 'auto' or 1117 // 'register'. 1118 if (!D->hasLocalStorage()) 1119 return StmtError(Diag(D->getLocation(), 1120 diag::err_non_variable_decl_in_for)); 1121 } else { 1122 Expr *FirstE = cast<Expr>(First); 1123 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 1124 return StmtError(Diag(First->getLocStart(), 1125 diag::err_selector_element_not_lvalue) 1126 << First->getSourceRange()); 1127 1128 FirstType = static_cast<Expr*>(First)->getType(); 1129 } 1130 if (!FirstType->isDependentType() && 1131 !FirstType->isObjCObjectPointerType() && 1132 !FirstType->isBlockPointerType()) 1133 Diag(ForLoc, diag::err_selector_element_type) 1134 << FirstType << First->getSourceRange(); 1135 } 1136 1137 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 1138 ForLoc, RParenLoc)); 1139} 1140 1141namespace { 1142 1143enum BeginEndFunction { 1144 BEF_begin, 1145 BEF_end 1146}; 1147 1148/// Build a variable declaration for a for-range statement. 1149static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 1150 QualType Type, const char *Name) { 1151 DeclContext *DC = SemaRef.CurContext; 1152 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1153 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1154 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 1155 TInfo, SC_Auto, SC_None); 1156 Decl->setImplicit(); 1157 return Decl; 1158} 1159 1160/// Finish building a variable declaration for a for-range statement. 1161/// \return true if an error occurs. 1162static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 1163 SourceLocation Loc, int diag) { 1164 // Deduce the type for the iterator variable now rather than leaving it to 1165 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 1166 TypeSourceInfo *InitTSI = 0; 1167 if (Init->getType()->isVoidType() || 1168 !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI)) 1169 SemaRef.Diag(Loc, diag) << Init->getType(); 1170 if (!InitTSI) { 1171 Decl->setInvalidDecl(); 1172 return true; 1173 } 1174 Decl->setTypeSourceInfo(InitTSI); 1175 Decl->setType(InitTSI->getType()); 1176 1177 // In ARC, infer lifetime. 1178 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if 1179 // we're doing the equivalent of fast iteration. 1180 if (SemaRef.getLangOptions().ObjCAutoRefCount && 1181 SemaRef.inferObjCARCLifetime(Decl)) 1182 Decl->setInvalidDecl(); 1183 1184 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false, 1185 /*TypeMayContainAuto=*/false); 1186 SemaRef.FinalizeDeclaration(Decl); 1187 SemaRef.CurContext->addHiddenDecl(Decl); 1188 return false; 1189} 1190 1191/// Produce a note indicating which begin/end function was implicitly called 1192/// by a C++0x for-range statement. This is often not obvious from the code, 1193/// nor from the diagnostics produced when analysing the implicit expressions 1194/// required in a for-range statement. 1195void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 1196 BeginEndFunction BEF) { 1197 CallExpr *CE = dyn_cast<CallExpr>(E); 1198 if (!CE) 1199 return; 1200 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1201 if (!D) 1202 return; 1203 SourceLocation Loc = D->getLocation(); 1204 1205 std::string Description; 1206 bool IsTemplate = false; 1207 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 1208 Description = SemaRef.getTemplateArgumentBindingsText( 1209 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 1210 IsTemplate = true; 1211 } 1212 1213 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 1214 << BEF << IsTemplate << Description << E->getType(); 1215} 1216 1217/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the 1218/// given LookupResult is non-empty, it is assumed to describe a member which 1219/// will be invoked. Otherwise, the function will be found via argument 1220/// dependent lookup. 1221static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S, 1222 SourceLocation Loc, 1223 VarDecl *Decl, 1224 BeginEndFunction BEF, 1225 const DeclarationNameInfo &NameInfo, 1226 LookupResult &MemberLookup, 1227 Expr *Range) { 1228 ExprResult CallExpr; 1229 if (!MemberLookup.empty()) { 1230 ExprResult MemberRef = 1231 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc, 1232 /*IsPtr=*/false, CXXScopeSpec(), 1233 /*Qualifier=*/0, MemberLookup, 1234 /*TemplateArgs=*/0); 1235 if (MemberRef.isInvalid()) 1236 return ExprError(); 1237 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), 1238 Loc, 0); 1239 if (CallExpr.isInvalid()) 1240 return ExprError(); 1241 } else { 1242 UnresolvedSet<0> FoundNames; 1243 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace 1244 // std is an associated namespace. 1245 UnresolvedLookupExpr *Fn = 1246 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0, 1247 NestedNameSpecifierLoc(), NameInfo, 1248 /*NeedsADL=*/true, /*Overloaded=*/false, 1249 FoundNames.begin(), FoundNames.end(), 1250 /*LookInStdNamespace=*/true); 1251 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc, 1252 0); 1253 if (CallExpr.isInvalid()) { 1254 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type) 1255 << Range->getType(); 1256 return ExprError(); 1257 } 1258 } 1259 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc, 1260 diag::err_for_range_iter_deduction_failure)) { 1261 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF); 1262 return ExprError(); 1263 } 1264 return CallExpr; 1265} 1266 1267} 1268 1269/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement. 1270/// 1271/// C++0x [stmt.ranged]: 1272/// A range-based for statement is equivalent to 1273/// 1274/// { 1275/// auto && __range = range-init; 1276/// for ( auto __begin = begin-expr, 1277/// __end = end-expr; 1278/// __begin != __end; 1279/// ++__begin ) { 1280/// for-range-declaration = *__begin; 1281/// statement 1282/// } 1283/// } 1284/// 1285/// The body of the loop is not available yet, since it cannot be analysed until 1286/// we have determined the type of the for-range-declaration. 1287StmtResult 1288Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 1289 Stmt *First, SourceLocation ColonLoc, Expr *Range, 1290 SourceLocation RParenLoc) { 1291 if (!First || !Range) 1292 return StmtError(); 1293 1294 DeclStmt *DS = dyn_cast<DeclStmt>(First); 1295 assert(DS && "first part of for range not a decl stmt"); 1296 1297 if (!DS->isSingleDecl()) { 1298 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range); 1299 return StmtError(); 1300 } 1301 if (DS->getSingleDecl()->isInvalidDecl()) 1302 return StmtError(); 1303 1304 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) 1305 return StmtError(); 1306 1307 // Build auto && __range = range-init 1308 SourceLocation RangeLoc = Range->getLocStart(); 1309 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 1310 Context.getAutoRRefDeductType(), 1311 "__range"); 1312 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 1313 diag::err_for_range_deduction_failure)) 1314 return StmtError(); 1315 1316 // Claim the type doesn't contain auto: we've already done the checking. 1317 DeclGroupPtrTy RangeGroup = 1318 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false); 1319 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 1320 if (RangeDecl.isInvalid()) 1321 return StmtError(); 1322 1323 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(), 1324 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS, 1325 RParenLoc); 1326} 1327 1328/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement. 1329StmtResult 1330Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, 1331 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond, 1332 Expr *Inc, Stmt *LoopVarDecl, 1333 SourceLocation RParenLoc) { 1334 Scope *S = getCurScope(); 1335 1336 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 1337 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 1338 QualType RangeVarType = RangeVar->getType(); 1339 1340 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 1341 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 1342 1343 StmtResult BeginEndDecl = BeginEnd; 1344 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 1345 1346 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) { 1347 SourceLocation RangeLoc = RangeVar->getLocation(); 1348 1349 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); 1350 1351 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1352 VK_LValue, ColonLoc); 1353 if (BeginRangeRef.isInvalid()) 1354 return StmtError(); 1355 1356 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1357 VK_LValue, ColonLoc); 1358 if (EndRangeRef.isInvalid()) 1359 return StmtError(); 1360 1361 QualType AutoType = Context.getAutoDeductType(); 1362 Expr *Range = RangeVar->getInit(); 1363 if (!Range) 1364 return StmtError(); 1365 QualType RangeType = Range->getType(); 1366 1367 if (RequireCompleteType(RangeLoc, RangeType, 1368 PDiag(diag::err_for_range_incomplete_type))) 1369 return StmtError(); 1370 1371 // Build auto __begin = begin-expr, __end = end-expr. 1372 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1373 "__begin"); 1374 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1375 "__end"); 1376 1377 // Build begin-expr and end-expr and attach to __begin and __end variables. 1378 ExprResult BeginExpr, EndExpr; 1379 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 1380 // - if _RangeT is an array type, begin-expr and end-expr are __range and 1381 // __range + __bound, respectively, where __bound is the array bound. If 1382 // _RangeT is an array of unknown size or an array of incomplete type, 1383 // the program is ill-formed; 1384 1385 // begin-expr is __range. 1386 BeginExpr = BeginRangeRef; 1387 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, 1388 diag::err_for_range_iter_deduction_failure)) { 1389 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1390 return StmtError(); 1391 } 1392 1393 // Find the array bound. 1394 ExprResult BoundExpr; 1395 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 1396 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(), 1397 Context.getPointerDiffType(), 1398 RangeLoc)); 1399 else if (const VariableArrayType *VAT = 1400 dyn_cast<VariableArrayType>(UnqAT)) 1401 BoundExpr = VAT->getSizeExpr(); 1402 else { 1403 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 1404 // UnqAT is not incomplete and Range is not type-dependent. 1405 llvm_unreachable("Unexpected array type in for-range"); 1406 } 1407 1408 // end-expr is __range + __bound. 1409 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), 1410 BoundExpr.get()); 1411 if (EndExpr.isInvalid()) 1412 return StmtError(); 1413 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 1414 diag::err_for_range_iter_deduction_failure)) { 1415 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1416 return StmtError(); 1417 } 1418 } else { 1419 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"), 1420 ColonLoc); 1421 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"), 1422 ColonLoc); 1423 1424 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName); 1425 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName); 1426 1427 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 1428 // - if _RangeT is a class type, the unqualified-ids begin and end are 1429 // looked up in the scope of class _RangeT as if by class member access 1430 // lookup (3.4.5), and if either (or both) finds at least one 1431 // declaration, begin-expr and end-expr are __range.begin() and 1432 // __range.end(), respectively; 1433 LookupQualifiedName(BeginMemberLookup, D); 1434 LookupQualifiedName(EndMemberLookup, D); 1435 1436 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 1437 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch) 1438 << RangeType << BeginMemberLookup.empty(); 1439 return StmtError(); 1440 } 1441 } else { 1442 // - otherwise, begin-expr and end-expr are begin(__range) and 1443 // end(__range), respectively, where begin and end are looked up with 1444 // argument-dependent lookup (3.4.2). For the purposes of this name 1445 // lookup, namespace std is an associated namespace. 1446 } 1447 1448 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar, 1449 BEF_begin, BeginNameInfo, 1450 BeginMemberLookup, 1451 BeginRangeRef.get()); 1452 if (BeginExpr.isInvalid()) 1453 return StmtError(); 1454 1455 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar, 1456 BEF_end, EndNameInfo, 1457 EndMemberLookup, EndRangeRef.get()); 1458 if (EndExpr.isInvalid()) 1459 return StmtError(); 1460 } 1461 1462 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same. 1463 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 1464 if (!Context.hasSameType(BeginType, EndType)) { 1465 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ) 1466 << BeginType << EndType; 1467 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1468 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1469 } 1470 1471 Decl *BeginEndDecls[] = { BeginVar, EndVar }; 1472 // Claim the type doesn't contain auto: we've already done the checking. 1473 DeclGroupPtrTy BeginEndGroup = 1474 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false); 1475 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc); 1476 1477 const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); 1478 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1479 VK_LValue, ColonLoc); 1480 if (BeginRef.isInvalid()) 1481 return StmtError(); 1482 1483 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 1484 VK_LValue, ColonLoc); 1485 if (EndRef.isInvalid()) 1486 return StmtError(); 1487 1488 // Build and check __begin != __end expression. 1489 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 1490 BeginRef.get(), EndRef.get()); 1491 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get()); 1492 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get()); 1493 if (NotEqExpr.isInvalid()) { 1494 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1495 if (!Context.hasSameType(BeginType, EndType)) 1496 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1497 return StmtError(); 1498 } 1499 1500 // Build and check ++__begin expression. 1501 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1502 VK_LValue, ColonLoc); 1503 if (BeginRef.isInvalid()) 1504 return StmtError(); 1505 1506 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 1507 IncrExpr = ActOnFinishFullExpr(IncrExpr.get()); 1508 if (IncrExpr.isInvalid()) { 1509 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1510 return StmtError(); 1511 } 1512 1513 // Build and check *__begin expression. 1514 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1515 VK_LValue, ColonLoc); 1516 if (BeginRef.isInvalid()) 1517 return StmtError(); 1518 1519 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 1520 if (DerefExpr.isInvalid()) { 1521 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1522 return StmtError(); 1523 } 1524 1525 // Attach *__begin as initializer for VD. 1526 if (!LoopVar->isInvalidDecl()) { 1527 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false, 1528 /*TypeMayContainAuto=*/true); 1529 if (LoopVar->isInvalidDecl()) 1530 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1531 } 1532 } else { 1533 // The range is implicitly used as a placeholder when it is dependent. 1534 RangeVar->setUsed(); 1535 } 1536 1537 return Owned(new (Context) CXXForRangeStmt(RangeDS, 1538 cast_or_null<DeclStmt>(BeginEndDecl.get()), 1539 NotEqExpr.take(), IncrExpr.take(), 1540 LoopVarDS, /*Body=*/0, ForLoc, 1541 ColonLoc, RParenLoc)); 1542} 1543 1544/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 1545/// This is a separate step from ActOnCXXForRangeStmt because analysis of the 1546/// body cannot be performed until after the type of the range variable is 1547/// determined. 1548StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 1549 if (!S || !B) 1550 return StmtError(); 1551 1552 cast<CXXForRangeStmt>(S)->setBody(B); 1553 return S; 1554} 1555 1556StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 1557 SourceLocation LabelLoc, 1558 LabelDecl *TheDecl) { 1559 getCurFunction()->setHasBranchIntoScope(); 1560 TheDecl->setUsed(); 1561 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc)); 1562} 1563 1564StmtResult 1565Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 1566 Expr *E) { 1567 // Convert operand to void* 1568 if (!E->isTypeDependent()) { 1569 QualType ETy = E->getType(); 1570 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 1571 ExprResult ExprRes = Owned(E); 1572 AssignConvertType ConvTy = 1573 CheckSingleAssignmentConstraints(DestTy, ExprRes); 1574 if (ExprRes.isInvalid()) 1575 return StmtError(); 1576 E = ExprRes.take(); 1577 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 1578 return StmtError(); 1579 } 1580 1581 getCurFunction()->setHasIndirectGoto(); 1582 1583 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 1584} 1585 1586StmtResult 1587Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 1588 Scope *S = CurScope->getContinueParent(); 1589 if (!S) { 1590 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 1591 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 1592 } 1593 1594 return Owned(new (Context) ContinueStmt(ContinueLoc)); 1595} 1596 1597StmtResult 1598Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1599 Scope *S = CurScope->getBreakParent(); 1600 if (!S) { 1601 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1602 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1603 } 1604 1605 return Owned(new (Context) BreakStmt(BreakLoc)); 1606} 1607 1608/// \brief Determine whether the given expression is a candidate for 1609/// copy elision in either a return statement or a throw expression. 1610/// 1611/// \param ReturnType If we're determining the copy elision candidate for 1612/// a return statement, this is the return type of the function. If we're 1613/// determining the copy elision candidate for a throw expression, this will 1614/// be a NULL type. 1615/// 1616/// \param E The expression being returned from the function or block, or 1617/// being thrown. 1618/// 1619/// \param AllowFunctionParameter Whether we allow function parameters to 1620/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but 1621/// we re-use this logic to determine whether we should try to move as part of 1622/// a return or throw (which does allow function parameters). 1623/// 1624/// \returns The NRVO candidate variable, if the return statement may use the 1625/// NRVO, or NULL if there is no such candidate. 1626const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 1627 Expr *E, 1628 bool AllowFunctionParameter) { 1629 QualType ExprType = E->getType(); 1630 // - in a return statement in a function with ... 1631 // ... a class return type ... 1632 if (!ReturnType.isNull()) { 1633 if (!ReturnType->isRecordType()) 1634 return 0; 1635 // ... the same cv-unqualified type as the function return type ... 1636 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType)) 1637 return 0; 1638 } 1639 1640 // ... the expression is the name of a non-volatile automatic object 1641 // (other than a function or catch-clause parameter)) ... 1642 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 1643 if (!DR) 1644 return 0; 1645 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1646 if (!VD) 1647 return 0; 1648 1649 // ...object (other than a function or catch-clause parameter)... 1650 if (VD->getKind() != Decl::Var && 1651 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar)) 1652 return 0; 1653 if (VD->isExceptionVariable()) return 0; 1654 1655 // ...automatic... 1656 if (!VD->hasLocalStorage()) return 0; 1657 1658 // ...non-volatile... 1659 if (VD->getType().isVolatileQualified()) return 0; 1660 if (VD->getType()->isReferenceType()) return 0; 1661 1662 // __block variables can't be allocated in a way that permits NRVO. 1663 if (VD->hasAttr<BlocksAttr>()) return 0; 1664 1665 // Variables with higher required alignment than their type's ABI 1666 // alignment cannot use NRVO. 1667 if (VD->hasAttr<AlignedAttr>() && 1668 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())) 1669 return 0; 1670 1671 return VD; 1672} 1673 1674/// \brief Perform the initialization of a potentially-movable value, which 1675/// is the result of return value. 1676/// 1677/// This routine implements C++0x [class.copy]p33, which attempts to treat 1678/// returned lvalues as rvalues in certain cases (to prefer move construction), 1679/// then falls back to treating them as lvalues if that failed. 1680ExprResult 1681Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1682 const VarDecl *NRVOCandidate, 1683 QualType ResultType, 1684 Expr *Value, 1685 bool AllowNRVO) { 1686 // C++0x [class.copy]p33: 1687 // When the criteria for elision of a copy operation are met or would 1688 // be met save for the fact that the source object is a function 1689 // parameter, and the object to be copied is designated by an lvalue, 1690 // overload resolution to select the constructor for the copy is first 1691 // performed as if the object were designated by an rvalue. 1692 ExprResult Res = ExprError(); 1693 if (AllowNRVO && 1694 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) { 1695 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 1696 Value->getType(), CK_LValueToRValue, 1697 Value, VK_XValue); 1698 1699 Expr *InitExpr = &AsRvalue; 1700 InitializationKind Kind 1701 = InitializationKind::CreateCopy(Value->getLocStart(), 1702 Value->getLocStart()); 1703 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1); 1704 1705 // [...] If overload resolution fails, or if the type of the first 1706 // parameter of the selected constructor is not an rvalue reference 1707 // to the object's type (possibly cv-qualified), overload resolution 1708 // is performed again, considering the object as an lvalue. 1709 if (Seq) { 1710 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 1711 StepEnd = Seq.step_end(); 1712 Step != StepEnd; ++Step) { 1713 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization) 1714 continue; 1715 1716 CXXConstructorDecl *Constructor 1717 = cast<CXXConstructorDecl>(Step->Function.Function); 1718 1719 const RValueReferenceType *RRefType 1720 = Constructor->getParamDecl(0)->getType() 1721 ->getAs<RValueReferenceType>(); 1722 1723 // If we don't meet the criteria, break out now. 1724 if (!RRefType || 1725 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 1726 Context.getTypeDeclType(Constructor->getParent()))) 1727 break; 1728 1729 // Promote "AsRvalue" to the heap, since we now need this 1730 // expression node to persist. 1731 Value = ImplicitCastExpr::Create(Context, Value->getType(), 1732 CK_LValueToRValue, Value, 0, 1733 VK_XValue); 1734 1735 // Complete type-checking the initialization of the return type 1736 // using the constructor we found. 1737 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1)); 1738 } 1739 } 1740 } 1741 1742 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 1743 // above, or overload resolution failed. Either way, we need to try 1744 // (again) now with the return value expression as written. 1745 if (Res.isInvalid()) 1746 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 1747 1748 return Res; 1749} 1750 1751/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 1752/// 1753StmtResult 1754Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1755 // If this is the first return we've seen in the block, infer the type of 1756 // the block from it. 1757 BlockScopeInfo *CurBlock = getCurBlock(); 1758 if (CurBlock->TheDecl->blockMissingReturnType()) { 1759 QualType BlockReturnT; 1760 if (RetValExp) { 1761 // Don't call UsualUnaryConversions(), since we don't want to do 1762 // integer promotions here. 1763 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 1764 if (Result.isInvalid()) 1765 return StmtError(); 1766 RetValExp = Result.take(); 1767 1768 if (!RetValExp->isTypeDependent()) { 1769 BlockReturnT = RetValExp->getType(); 1770 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 1771 // We have to remove a 'const' added to copied-in variable which was 1772 // part of the implementation spec. and not the actual qualifier for 1773 // the variable. 1774 if (CDRE->isConstQualAdded()) 1775 CurBlock->ReturnType.removeLocalConst(); // FIXME: local??? 1776 } 1777 } else 1778 BlockReturnT = Context.DependentTy; 1779 } else 1780 BlockReturnT = Context.VoidTy; 1781 if (!CurBlock->ReturnType.isNull() && !CurBlock->ReturnType->isDependentType() 1782 && !BlockReturnT->isDependentType() 1783 // when block's return type is not specified, all return types 1784 // must strictly match. 1785 && !Context.hasSameType(BlockReturnT, CurBlock->ReturnType)) { 1786 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible) 1787 << BlockReturnT << CurBlock->ReturnType; 1788 return StmtError(); 1789 } 1790 CurBlock->ReturnType = BlockReturnT; 1791 } 1792 QualType FnRetType = CurBlock->ReturnType; 1793 1794 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 1795 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr); 1796 return StmtError(); 1797 } 1798 1799 // Otherwise, verify that this result type matches the previous one. We are 1800 // pickier with blocks than for normal functions because we don't have GCC 1801 // compatibility to worry about here. 1802 const VarDecl *NRVOCandidate = 0; 1803 if (FnRetType->isDependentType()) { 1804 // Delay processing for now. TODO: there are lots of dependent 1805 // types we can conclusively prove aren't void. 1806 } else if (FnRetType->isVoidType()) { 1807 if (RetValExp && 1808 !(getLangOptions().CPlusPlus && 1809 (RetValExp->isTypeDependent() || 1810 RetValExp->getType()->isVoidType()))) { 1811 Diag(ReturnLoc, diag::err_return_block_has_expr); 1812 RetValExp = 0; 1813 } 1814 } else if (!RetValExp) { 1815 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 1816 } else if (!RetValExp->isTypeDependent()) { 1817 // we have a non-void block with an expression, continue checking 1818 1819 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1820 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1821 // function return. 1822 1823 // In C++ the return statement is handled via a copy initialization. 1824 // the C version of which boils down to CheckSingleAssignmentConstraints. 1825 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1826 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1827 FnRetType, 1828 NRVOCandidate != 0); 1829 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1830 FnRetType, RetValExp); 1831 if (Res.isInvalid()) { 1832 // FIXME: Cleanup temporaries here, anyway? 1833 return StmtError(); 1834 } 1835 RetValExp = Res.take(); 1836 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1837 } 1838 1839 if (RetValExp) { 1840 CheckImplicitConversions(RetValExp, ReturnLoc); 1841 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1842 } 1843 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 1844 NRVOCandidate); 1845 1846 // If we need to check for the named return value optimization, save the 1847 // return statement in our scope for later processing. 1848 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1849 !CurContext->isDependentContext()) 1850 FunctionScopes.back()->Returns.push_back(Result); 1851 1852 return Owned(Result); 1853} 1854 1855StmtResult 1856Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1857 // Check for unexpanded parameter packs. 1858 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 1859 return StmtError(); 1860 1861 if (getCurBlock()) 1862 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 1863 1864 QualType FnRetType; 1865 QualType DeclaredRetType; 1866 if (const FunctionDecl *FD = getCurFunctionDecl()) { 1867 FnRetType = FD->getResultType(); 1868 DeclaredRetType = FnRetType; 1869 if (FD->hasAttr<NoReturnAttr>() || 1870 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 1871 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 1872 << FD->getDeclName(); 1873 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1874 DeclaredRetType = MD->getResultType(); 1875 if (MD->hasRelatedResultType() && MD->getClassInterface()) { 1876 // In the implementation of a method with a related return type, the 1877 // type used to type-check the validity of return statements within the 1878 // method body is a pointer to the type of the class being implemented. 1879 FnRetType = Context.getObjCInterfaceType(MD->getClassInterface()); 1880 FnRetType = Context.getObjCObjectPointerType(FnRetType); 1881 } else { 1882 FnRetType = DeclaredRetType; 1883 } 1884 } else // If we don't have a function/method context, bail. 1885 return StmtError(); 1886 1887 ReturnStmt *Result = 0; 1888 if (FnRetType->isVoidType()) { 1889 if (RetValExp) { 1890 if (!RetValExp->isTypeDependent()) { 1891 // C99 6.8.6.4p1 (ext_ since GCC warns) 1892 unsigned D = diag::ext_return_has_expr; 1893 if (RetValExp->getType()->isVoidType()) 1894 D = diag::ext_return_has_void_expr; 1895 else { 1896 ExprResult Result = Owned(RetValExp); 1897 Result = IgnoredValueConversions(Result.take()); 1898 if (Result.isInvalid()) 1899 return StmtError(); 1900 RetValExp = Result.take(); 1901 RetValExp = ImpCastExprToType(RetValExp, 1902 Context.VoidTy, CK_ToVoid).take(); 1903 } 1904 1905 // return (some void expression); is legal in C++. 1906 if (D != diag::ext_return_has_void_expr || 1907 !getLangOptions().CPlusPlus) { 1908 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1909 1910 int FunctionKind = 0; 1911 if (isa<ObjCMethodDecl>(CurDecl)) 1912 FunctionKind = 1; 1913 else if (isa<CXXConstructorDecl>(CurDecl)) 1914 FunctionKind = 2; 1915 else if (isa<CXXDestructorDecl>(CurDecl)) 1916 FunctionKind = 3; 1917 1918 Diag(ReturnLoc, D) 1919 << CurDecl->getDeclName() << FunctionKind 1920 << RetValExp->getSourceRange(); 1921 } 1922 } 1923 1924 CheckImplicitConversions(RetValExp, ReturnLoc); 1925 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1926 } 1927 1928 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1929 } else if (!RetValExp && !FnRetType->isDependentType()) { 1930 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 1931 // C99 6.8.6.4p1 (ext_ since GCC warns) 1932 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 1933 1934 if (FunctionDecl *FD = getCurFunctionDecl()) 1935 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 1936 else 1937 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 1938 Result = new (Context) ReturnStmt(ReturnLoc); 1939 } else { 1940 const VarDecl *NRVOCandidate = 0; 1941 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1942 // we have a non-void function with an expression, continue checking 1943 1944 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1945 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1946 // function return. 1947 1948 // In C++ the return statement is handled via a copy initialization, 1949 // the C version of which boils down to CheckSingleAssignmentConstraints. 1950 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1951 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1952 FnRetType, 1953 NRVOCandidate != 0); 1954 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1955 FnRetType, RetValExp); 1956 if (Res.isInvalid()) { 1957 // FIXME: Cleanup temporaries here, anyway? 1958 return StmtError(); 1959 } 1960 1961 RetValExp = Res.takeAs<Expr>(); 1962 if (RetValExp) 1963 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1964 } 1965 1966 if (RetValExp) { 1967 // If we type-checked an Objective-C method's return type based 1968 // on a related return type, we may need to adjust the return 1969 // type again. Do so now. 1970 if (DeclaredRetType != FnRetType) { 1971 ExprResult result = PerformImplicitConversion(RetValExp, 1972 DeclaredRetType, 1973 AA_Returning); 1974 if (result.isInvalid()) return StmtError(); 1975 RetValExp = result.take(); 1976 } 1977 1978 CheckImplicitConversions(RetValExp, ReturnLoc); 1979 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1980 } 1981 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1982 } 1983 1984 // If we need to check for the named return value optimization, save the 1985 // return statement in our scope for later processing. 1986 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1987 !CurContext->isDependentContext()) 1988 FunctionScopes.back()->Returns.push_back(Result); 1989 1990 return Owned(Result); 1991} 1992 1993/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 1994/// ignore "noop" casts in places where an lvalue is required by an inline asm. 1995/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 1996/// provide a strong guidance to not use it. 1997/// 1998/// This method checks to see if the argument is an acceptable l-value and 1999/// returns false if it is a case we can handle. 2000static bool CheckAsmLValue(const Expr *E, Sema &S) { 2001 // Type dependent expressions will be checked during instantiation. 2002 if (E->isTypeDependent()) 2003 return false; 2004 2005 if (E->isLValue()) 2006 return false; // Cool, this is an lvalue. 2007 2008 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 2009 // are supposed to allow. 2010 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 2011 if (E != E2 && E2->isLValue()) { 2012 if (!S.getLangOptions().HeinousExtensions) 2013 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 2014 << E->getSourceRange(); 2015 else 2016 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 2017 << E->getSourceRange(); 2018 // Accept, even if we emitted an error diagnostic. 2019 return false; 2020 } 2021 2022 // None of the above, just randomly invalid non-lvalue. 2023 return true; 2024} 2025 2026/// isOperandMentioned - Return true if the specified operand # is mentioned 2027/// anywhere in the decomposed asm string. 2028static bool isOperandMentioned(unsigned OpNo, 2029 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) { 2030 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { 2031 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; 2032 if (!Piece.isOperand()) continue; 2033 2034 // If this is a reference to the input and if the input was the smaller 2035 // one, then we have to reject this asm. 2036 if (Piece.getOperandNo() == OpNo) 2037 return true; 2038 } 2039 2040 return false; 2041} 2042 2043StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple, 2044 bool IsVolatile, unsigned NumOutputs, 2045 unsigned NumInputs, IdentifierInfo **Names, 2046 MultiExprArg constraints, MultiExprArg exprs, 2047 Expr *asmString, MultiExprArg clobbers, 2048 SourceLocation RParenLoc, bool MSAsm) { 2049 unsigned NumClobbers = clobbers.size(); 2050 StringLiteral **Constraints = 2051 reinterpret_cast<StringLiteral**>(constraints.get()); 2052 Expr **Exprs = exprs.get(); 2053 StringLiteral *AsmString = cast<StringLiteral>(asmString); 2054 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 2055 2056 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 2057 2058 // The parser verifies that there is a string literal here. 2059 if (!AsmString->isAscii()) 2060 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 2061 << AsmString->getSourceRange()); 2062 2063 for (unsigned i = 0; i != NumOutputs; i++) { 2064 StringLiteral *Literal = Constraints[i]; 2065 if (!Literal->isAscii()) 2066 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2067 << Literal->getSourceRange()); 2068 2069 StringRef OutputName; 2070 if (Names[i]) 2071 OutputName = Names[i]->getName(); 2072 2073 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 2074 if (!Context.getTargetInfo().validateOutputConstraint(Info)) 2075 return StmtError(Diag(Literal->getLocStart(), 2076 diag::err_asm_invalid_output_constraint) 2077 << Info.getConstraintStr()); 2078 2079 // Check that the output exprs are valid lvalues. 2080 Expr *OutputExpr = Exprs[i]; 2081 if (CheckAsmLValue(OutputExpr, *this)) { 2082 return StmtError(Diag(OutputExpr->getLocStart(), 2083 diag::err_asm_invalid_lvalue_in_output) 2084 << OutputExpr->getSourceRange()); 2085 } 2086 2087 OutputConstraintInfos.push_back(Info); 2088 } 2089 2090 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 2091 2092 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 2093 StringLiteral *Literal = Constraints[i]; 2094 if (!Literal->isAscii()) 2095 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2096 << Literal->getSourceRange()); 2097 2098 StringRef InputName; 2099 if (Names[i]) 2100 InputName = Names[i]->getName(); 2101 2102 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 2103 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(), 2104 NumOutputs, Info)) { 2105 return StmtError(Diag(Literal->getLocStart(), 2106 diag::err_asm_invalid_input_constraint) 2107 << Info.getConstraintStr()); 2108 } 2109 2110 Expr *InputExpr = Exprs[i]; 2111 2112 // Only allow void types for memory constraints. 2113 if (Info.allowsMemory() && !Info.allowsRegister()) { 2114 if (CheckAsmLValue(InputExpr, *this)) 2115 return StmtError(Diag(InputExpr->getLocStart(), 2116 diag::err_asm_invalid_lvalue_in_input) 2117 << Info.getConstraintStr() 2118 << InputExpr->getSourceRange()); 2119 } 2120 2121 if (Info.allowsRegister()) { 2122 if (InputExpr->getType()->isVoidType()) { 2123 return StmtError(Diag(InputExpr->getLocStart(), 2124 diag::err_asm_invalid_type_in_input) 2125 << InputExpr->getType() << Info.getConstraintStr() 2126 << InputExpr->getSourceRange()); 2127 } 2128 } 2129 2130 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); 2131 if (Result.isInvalid()) 2132 return StmtError(); 2133 2134 Exprs[i] = Result.take(); 2135 InputConstraintInfos.push_back(Info); 2136 } 2137 2138 // Check that the clobbers are valid. 2139 for (unsigned i = 0; i != NumClobbers; i++) { 2140 StringLiteral *Literal = Clobbers[i]; 2141 if (!Literal->isAscii()) 2142 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2143 << Literal->getSourceRange()); 2144 2145 StringRef Clobber = Literal->getString(); 2146 2147 if (!Context.getTargetInfo().isValidClobber(Clobber)) 2148 return StmtError(Diag(Literal->getLocStart(), 2149 diag::err_asm_unknown_register_name) << Clobber); 2150 } 2151 2152 AsmStmt *NS = 2153 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 2154 NumOutputs, NumInputs, Names, Constraints, Exprs, 2155 AsmString, NumClobbers, Clobbers, RParenLoc); 2156 // Validate the asm string, ensuring it makes sense given the operands we 2157 // have. 2158 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 2159 unsigned DiagOffs; 2160 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 2161 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 2162 << AsmString->getSourceRange(); 2163 return StmtError(); 2164 } 2165 2166 // Validate tied input operands for type mismatches. 2167 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 2168 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 2169 2170 // If this is a tied constraint, verify that the output and input have 2171 // either exactly the same type, or that they are int/ptr operands with the 2172 // same size (int/long, int*/long, are ok etc). 2173 if (!Info.hasTiedOperand()) continue; 2174 2175 unsigned TiedTo = Info.getTiedOperand(); 2176 unsigned InputOpNo = i+NumOutputs; 2177 Expr *OutputExpr = Exprs[TiedTo]; 2178 Expr *InputExpr = Exprs[InputOpNo]; 2179 2180 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent()) 2181 continue; 2182 2183 QualType InTy = InputExpr->getType(); 2184 QualType OutTy = OutputExpr->getType(); 2185 if (Context.hasSameType(InTy, OutTy)) 2186 continue; // All types can be tied to themselves. 2187 2188 // Decide if the input and output are in the same domain (integer/ptr or 2189 // floating point. 2190 enum AsmDomain { 2191 AD_Int, AD_FP, AD_Other 2192 } InputDomain, OutputDomain; 2193 2194 if (InTy->isIntegerType() || InTy->isPointerType()) 2195 InputDomain = AD_Int; 2196 else if (InTy->isRealFloatingType()) 2197 InputDomain = AD_FP; 2198 else 2199 InputDomain = AD_Other; 2200 2201 if (OutTy->isIntegerType() || OutTy->isPointerType()) 2202 OutputDomain = AD_Int; 2203 else if (OutTy->isRealFloatingType()) 2204 OutputDomain = AD_FP; 2205 else 2206 OutputDomain = AD_Other; 2207 2208 // They are ok if they are the same size and in the same domain. This 2209 // allows tying things like: 2210 // void* to int* 2211 // void* to int if they are the same size. 2212 // double to long double if they are the same size. 2213 // 2214 uint64_t OutSize = Context.getTypeSize(OutTy); 2215 uint64_t InSize = Context.getTypeSize(InTy); 2216 if (OutSize == InSize && InputDomain == OutputDomain && 2217 InputDomain != AD_Other) 2218 continue; 2219 2220 // If the smaller input/output operand is not mentioned in the asm string, 2221 // then we can promote the smaller one to a larger input and the asm string 2222 // won't notice. 2223 bool SmallerValueMentioned = false; 2224 2225 // If this is a reference to the input and if the input was the smaller 2226 // one, then we have to reject this asm. 2227 if (isOperandMentioned(InputOpNo, Pieces)) { 2228 // This is a use in the asm string of the smaller operand. Since we 2229 // codegen this by promoting to a wider value, the asm will get printed 2230 // "wrong". 2231 SmallerValueMentioned |= InSize < OutSize; 2232 } 2233 if (isOperandMentioned(TiedTo, Pieces)) { 2234 // If this is a reference to the output, and if the output is the larger 2235 // value, then it's ok because we'll promote the input to the larger type. 2236 SmallerValueMentioned |= OutSize < InSize; 2237 } 2238 2239 // If the smaller value wasn't mentioned in the asm string, and if the 2240 // output was a register, just extend the shorter one to the size of the 2241 // larger one. 2242 if (!SmallerValueMentioned && InputDomain != AD_Other && 2243 OutputConstraintInfos[TiedTo].allowsRegister()) 2244 continue; 2245 2246 // Either both of the operands were mentioned or the smaller one was 2247 // mentioned. One more special case that we'll allow: if the tied input is 2248 // integer, unmentioned, and is a constant, then we'll allow truncating it 2249 // down to the size of the destination. 2250 if (InputDomain == AD_Int && OutputDomain == AD_Int && 2251 !isOperandMentioned(InputOpNo, Pieces) && 2252 InputExpr->isEvaluatable(Context)) { 2253 CastKind castKind = 2254 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); 2255 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take(); 2256 Exprs[InputOpNo] = InputExpr; 2257 NS->setInputExpr(i, InputExpr); 2258 continue; 2259 } 2260 2261 Diag(InputExpr->getLocStart(), 2262 diag::err_asm_tying_incompatible_types) 2263 << InTy << OutTy << OutputExpr->getSourceRange() 2264 << InputExpr->getSourceRange(); 2265 return StmtError(); 2266 } 2267 2268 return Owned(NS); 2269} 2270 2271StmtResult 2272Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 2273 SourceLocation RParen, Decl *Parm, 2274 Stmt *Body) { 2275 VarDecl *Var = cast_or_null<VarDecl>(Parm); 2276 if (Var && Var->isInvalidDecl()) 2277 return StmtError(); 2278 2279 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 2280} 2281 2282StmtResult 2283Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 2284 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 2285} 2286 2287StmtResult 2288Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2289 MultiStmtArg CatchStmts, Stmt *Finally) { 2290 if (!getLangOptions().ObjCExceptions) 2291 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 2292 2293 getCurFunction()->setHasBranchProtectedScope(); 2294 unsigned NumCatchStmts = CatchStmts.size(); 2295 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 2296 CatchStmts.release(), 2297 NumCatchStmts, 2298 Finally)); 2299} 2300 2301StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, 2302 Expr *Throw) { 2303 if (Throw) { 2304 Throw = MaybeCreateExprWithCleanups(Throw); 2305 ExprResult Result = DefaultLvalueConversion(Throw); 2306 if (Result.isInvalid()) 2307 return StmtError(); 2308 2309 Throw = Result.take(); 2310 QualType ThrowType = Throw->getType(); 2311 // Make sure the expression type is an ObjC pointer or "void *". 2312 if (!ThrowType->isDependentType() && 2313 !ThrowType->isObjCObjectPointerType()) { 2314 const PointerType *PT = ThrowType->getAs<PointerType>(); 2315 if (!PT || !PT->getPointeeType()->isVoidType()) 2316 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 2317 << Throw->getType() << Throw->getSourceRange()); 2318 } 2319 } 2320 2321 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 2322} 2323 2324StmtResult 2325Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2326 Scope *CurScope) { 2327 if (!getLangOptions().ObjCExceptions) 2328 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 2329 2330 if (!Throw) { 2331 // @throw without an expression designates a rethrow (which much occur 2332 // in the context of an @catch clause). 2333 Scope *AtCatchParent = CurScope; 2334 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 2335 AtCatchParent = AtCatchParent->getParent(); 2336 if (!AtCatchParent) 2337 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 2338 } 2339 2340 return BuildObjCAtThrowStmt(AtLoc, Throw); 2341} 2342 2343ExprResult 2344Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { 2345 ExprResult result = DefaultLvalueConversion(operand); 2346 if (result.isInvalid()) 2347 return ExprError(); 2348 operand = result.take(); 2349 2350 // Make sure the expression type is an ObjC pointer or "void *". 2351 QualType type = operand->getType(); 2352 if (!type->isDependentType() && 2353 !type->isObjCObjectPointerType()) { 2354 const PointerType *pointerType = type->getAs<PointerType>(); 2355 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) 2356 return Diag(atLoc, diag::error_objc_synchronized_expects_object) 2357 << type << operand->getSourceRange(); 2358 } 2359 2360 // The operand to @synchronized is a full-expression. 2361 return MaybeCreateExprWithCleanups(operand); 2362} 2363 2364StmtResult 2365Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 2366 Stmt *SyncBody) { 2367 // We can't jump into or indirect-jump out of a @synchronized block. 2368 getCurFunction()->setHasBranchProtectedScope(); 2369 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 2370} 2371 2372/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 2373/// and creates a proper catch handler from them. 2374StmtResult 2375Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 2376 Stmt *HandlerBlock) { 2377 // There's nothing to test that ActOnExceptionDecl didn't already test. 2378 return Owned(new (Context) CXXCatchStmt(CatchLoc, 2379 cast_or_null<VarDecl>(ExDecl), 2380 HandlerBlock)); 2381} 2382 2383StmtResult 2384Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { 2385 getCurFunction()->setHasBranchProtectedScope(); 2386 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body)); 2387} 2388 2389namespace { 2390 2391class TypeWithHandler { 2392 QualType t; 2393 CXXCatchStmt *stmt; 2394public: 2395 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 2396 : t(type), stmt(statement) {} 2397 2398 // An arbitrary order is fine as long as it places identical 2399 // types next to each other. 2400 bool operator<(const TypeWithHandler &y) const { 2401 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 2402 return true; 2403 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 2404 return false; 2405 else 2406 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 2407 } 2408 2409 bool operator==(const TypeWithHandler& other) const { 2410 return t == other.t; 2411 } 2412 2413 CXXCatchStmt *getCatchStmt() const { return stmt; } 2414 SourceLocation getTypeSpecStartLoc() const { 2415 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 2416 } 2417}; 2418 2419} 2420 2421/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 2422/// handlers and creates a try statement from them. 2423StmtResult 2424Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2425 MultiStmtArg RawHandlers) { 2426 // Don't report an error if 'try' is used in system headers. 2427 if (!getLangOptions().CXXExceptions && 2428 !getSourceManager().isInSystemHeader(TryLoc)) 2429 Diag(TryLoc, diag::err_exceptions_disabled) << "try"; 2430 2431 unsigned NumHandlers = RawHandlers.size(); 2432 assert(NumHandlers > 0 && 2433 "The parser shouldn't call this if there are no handlers."); 2434 Stmt **Handlers = RawHandlers.get(); 2435 2436 SmallVector<TypeWithHandler, 8> TypesWithHandlers; 2437 2438 for (unsigned i = 0; i < NumHandlers; ++i) { 2439 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]); 2440 if (!Handler->getExceptionDecl()) { 2441 if (i < NumHandlers - 1) 2442 return StmtError(Diag(Handler->getLocStart(), 2443 diag::err_early_catch_all)); 2444 2445 continue; 2446 } 2447 2448 const QualType CaughtType = Handler->getCaughtType(); 2449 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 2450 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 2451 } 2452 2453 // Detect handlers for the same type as an earlier one. 2454 if (NumHandlers > 1) { 2455 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 2456 2457 TypeWithHandler prev = TypesWithHandlers[0]; 2458 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 2459 TypeWithHandler curr = TypesWithHandlers[i]; 2460 2461 if (curr == prev) { 2462 Diag(curr.getTypeSpecStartLoc(), 2463 diag::warn_exception_caught_by_earlier_handler) 2464 << curr.getCatchStmt()->getCaughtType().getAsString(); 2465 Diag(prev.getTypeSpecStartLoc(), 2466 diag::note_previous_exception_handler) 2467 << prev.getCatchStmt()->getCaughtType().getAsString(); 2468 } 2469 2470 prev = curr; 2471 } 2472 } 2473 2474 getCurFunction()->setHasBranchProtectedScope(); 2475 2476 // FIXME: We should detect handlers that cannot catch anything because an 2477 // earlier handler catches a superclass. Need to find a method that is not 2478 // quadratic for this. 2479 // Neither of these are explicitly forbidden, but every compiler detects them 2480 // and warns. 2481 2482 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 2483 Handlers, NumHandlers)); 2484} 2485 2486StmtResult 2487Sema::ActOnSEHTryBlock(bool IsCXXTry, 2488 SourceLocation TryLoc, 2489 Stmt *TryBlock, 2490 Stmt *Handler) { 2491 assert(TryBlock && Handler); 2492 2493 getCurFunction()->setHasBranchProtectedScope(); 2494 2495 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler)); 2496} 2497 2498StmtResult 2499Sema::ActOnSEHExceptBlock(SourceLocation Loc, 2500 Expr *FilterExpr, 2501 Stmt *Block) { 2502 assert(FilterExpr && Block); 2503 2504 if(!FilterExpr->getType()->isIntegerType()) { 2505 return StmtError(Diag(FilterExpr->getExprLoc(), 2506 diag::err_filter_expression_integral) 2507 << FilterExpr->getType()); 2508 } 2509 2510 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block)); 2511} 2512 2513StmtResult 2514Sema::ActOnSEHFinallyBlock(SourceLocation Loc, 2515 Stmt *Block) { 2516 assert(Block); 2517 return Owned(SEHFinallyStmt::Create(Context,Loc,Block)); 2518} 2519 2520StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 2521 bool IsIfExists, 2522 NestedNameSpecifierLoc QualifierLoc, 2523 DeclarationNameInfo NameInfo, 2524 Stmt *Nested) 2525{ 2526 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, 2527 QualifierLoc, NameInfo, 2528 cast<CompoundStmt>(Nested)); 2529} 2530 2531 2532StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 2533 bool IsIfExists, 2534 CXXScopeSpec &SS, 2535 UnqualifiedId &Name, 2536 Stmt *Nested) { 2537 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, 2538 SS.getWithLocInContext(Context), 2539 GetNameFromUnqualifiedId(Name), 2540 Nested); 2541} 2542