SemaStmt.cpp revision 80d4b55db94db2172a04617d1a80feca6bbcea5c
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 (!E->isUnusedResultAWarning(Loc, R1, R2, Context)) 156 return; 157 158 // Okay, we have an unused result. Depending on what the base expression is, 159 // we might want to make a more specific diagnostic. Check for one of these 160 // cases now. 161 unsigned DiagID = diag::warn_unused_expr; 162 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 163 E = Temps->getSubExpr(); 164 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 165 E = TempExpr->getSubExpr(); 166 167 if (DiagnoseUnusedComparison(*this, E)) 168 return; 169 170 E = E->IgnoreParenImpCasts(); 171 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 172 if (E->getType()->isVoidType()) 173 return; 174 175 // If the callee has attribute pure, const, or warn_unused_result, warn with 176 // a more specific message to make it clear what is happening. 177 if (const Decl *FD = CE->getCalleeDecl()) { 178 if (FD->getAttr<WarnUnusedResultAttr>()) { 179 Diag(Loc, diag::warn_unused_result) << R1 << R2; 180 return; 181 } 182 if (FD->getAttr<PureAttr>()) { 183 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 184 return; 185 } 186 if (FD->getAttr<ConstAttr>()) { 187 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 188 return; 189 } 190 } 191 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 192 if (getLangOptions().ObjCAutoRefCount && ME->isDelegateInitCall()) { 193 Diag(Loc, diag::err_arc_unused_init_message) << R1; 194 return; 195 } 196 const ObjCMethodDecl *MD = ME->getMethodDecl(); 197 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 198 Diag(Loc, diag::warn_unused_result) << R1 << R2; 199 return; 200 } 201 } else if (isa<PseudoObjectExpr>(E)) { 202 DiagID = diag::warn_unused_property_expr; 203 } else if (const CXXFunctionalCastExpr *FC 204 = dyn_cast<CXXFunctionalCastExpr>(E)) { 205 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 206 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 207 return; 208 } 209 // Diagnose "(void*) blah" as a typo for "(void) blah". 210 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 211 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 212 QualType T = TI->getType(); 213 214 // We really do want to use the non-canonical type here. 215 if (T == Context.VoidPtrTy) { 216 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc()); 217 218 Diag(Loc, diag::warn_unused_voidptr) 219 << FixItHint::CreateRemoval(TL.getStarLoc()); 220 return; 221 } 222 } 223 224 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2); 225} 226 227StmtResult 228Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 229 MultiStmtArg elts, bool isStmtExpr) { 230 unsigned NumElts = elts.size(); 231 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release()); 232 // If we're in C89 mode, check that we don't have any decls after stmts. If 233 // so, emit an extension diagnostic. 234 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) { 235 // Note that __extension__ can be around a decl. 236 unsigned i = 0; 237 // Skip over all declarations. 238 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 239 /*empty*/; 240 241 // We found the end of the list or a statement. Scan for another declstmt. 242 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 243 /*empty*/; 244 245 if (i != NumElts) { 246 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 247 Diag(D->getLocation(), diag::ext_mixed_decls_code); 248 } 249 } 250 // Warn about unused expressions in statements. 251 for (unsigned i = 0; i != NumElts; ++i) { 252 // Ignore statements that are last in a statement expression. 253 if (isStmtExpr && i == NumElts - 1) 254 continue; 255 256 DiagnoseUnusedExprResult(Elts[i]); 257 } 258 259 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R)); 260} 261 262StmtResult 263Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 264 SourceLocation DotDotDotLoc, Expr *RHSVal, 265 SourceLocation ColonLoc) { 266 assert((LHSVal != 0) && "missing expression in case statement"); 267 268 // C99 6.8.4.2p3: The expression shall be an integer constant. 269 // However, GCC allows any evaluatable integer expression. 270 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() && 271 VerifyIntegerConstantExpression(LHSVal)) 272 return StmtError(); 273 274 // GCC extension: The expression shall be an integer constant. 275 276 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() && 277 VerifyIntegerConstantExpression(RHSVal)) { 278 RHSVal = 0; // Recover by just forgetting about it. 279 } 280 281 if (getCurFunction()->SwitchStack.empty()) { 282 Diag(CaseLoc, diag::err_case_not_in_switch); 283 return StmtError(); 284 } 285 286 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 287 ColonLoc); 288 getCurFunction()->SwitchStack.back()->addSwitchCase(CS); 289 return Owned(CS); 290} 291 292/// ActOnCaseStmtBody - This installs a statement as the body of a case. 293void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) { 294 DiagnoseUnusedExprResult(SubStmt); 295 296 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 297 CS->setSubStmt(SubStmt); 298} 299 300StmtResult 301Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 302 Stmt *SubStmt, Scope *CurScope) { 303 DiagnoseUnusedExprResult(SubStmt); 304 305 if (getCurFunction()->SwitchStack.empty()) { 306 Diag(DefaultLoc, diag::err_default_not_in_switch); 307 return Owned(SubStmt); 308 } 309 310 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 311 getCurFunction()->SwitchStack.back()->addSwitchCase(DS); 312 return Owned(DS); 313} 314 315StmtResult 316Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 317 SourceLocation ColonLoc, Stmt *SubStmt) { 318 319 // If the label was multiply defined, reject it now. 320 if (TheDecl->getStmt()) { 321 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 322 Diag(TheDecl->getLocation(), diag::note_previous_definition); 323 return Owned(SubStmt); 324 } 325 326 // Otherwise, things are good. Fill in the declaration and return it. 327 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 328 TheDecl->setStmt(LS); 329 if (!TheDecl->isGnuLocal()) 330 TheDecl->setLocation(IdentLoc); 331 return Owned(LS); 332} 333 334StmtResult 335Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 336 Stmt *thenStmt, SourceLocation ElseLoc, 337 Stmt *elseStmt) { 338 ExprResult CondResult(CondVal.release()); 339 340 VarDecl *ConditionVar = 0; 341 if (CondVar) { 342 ConditionVar = cast<VarDecl>(CondVar); 343 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 344 if (CondResult.isInvalid()) 345 return StmtError(); 346 } 347 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 348 if (!ConditionExpr) 349 return StmtError(); 350 351 DiagnoseUnusedExprResult(thenStmt); 352 353 // Warn if the if block has a null body without an else value. 354 // this helps prevent bugs due to typos, such as 355 // if (condition); 356 // do_stuff(); 357 // 358 if (!elseStmt) { 359 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 360 // But do not warn if the body is a macro that expands to nothing, e.g: 361 // 362 // #define CALL(x) 363 // if (condition) 364 // CALL(0); 365 // 366 if (!stmt->hasLeadingEmptyMacro()) 367 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 368 } 369 370 DiagnoseUnusedExprResult(elseStmt); 371 372 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 373 thenStmt, ElseLoc, elseStmt)); 374} 375 376/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 377/// the specified width and sign. If an overflow occurs, detect it and emit 378/// the specified diagnostic. 379void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 380 unsigned NewWidth, bool NewSign, 381 SourceLocation Loc, 382 unsigned DiagID) { 383 // Perform a conversion to the promoted condition type if needed. 384 if (NewWidth > Val.getBitWidth()) { 385 // If this is an extension, just do it. 386 Val = Val.extend(NewWidth); 387 Val.setIsSigned(NewSign); 388 389 // If the input was signed and negative and the output is 390 // unsigned, don't bother to warn: this is implementation-defined 391 // behavior. 392 // FIXME: Introduce a second, default-ignored warning for this case? 393 } else if (NewWidth < Val.getBitWidth()) { 394 // If this is a truncation, check for overflow. 395 llvm::APSInt ConvVal(Val); 396 ConvVal = ConvVal.trunc(NewWidth); 397 ConvVal.setIsSigned(NewSign); 398 ConvVal = ConvVal.extend(Val.getBitWidth()); 399 ConvVal.setIsSigned(Val.isSigned()); 400 if (ConvVal != Val) 401 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 402 403 // Regardless of whether a diagnostic was emitted, really do the 404 // truncation. 405 Val = Val.trunc(NewWidth); 406 Val.setIsSigned(NewSign); 407 } else if (NewSign != Val.isSigned()) { 408 // Convert the sign to match the sign of the condition. This can cause 409 // overflow as well: unsigned(INTMIN) 410 // We don't diagnose this overflow, because it is implementation-defined 411 // behavior. 412 // FIXME: Introduce a second, default-ignored warning for this case? 413 llvm::APSInt OldVal(Val); 414 Val.setIsSigned(NewSign); 415 } 416} 417 418namespace { 419 struct CaseCompareFunctor { 420 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 421 const llvm::APSInt &RHS) { 422 return LHS.first < RHS; 423 } 424 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 425 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 426 return LHS.first < RHS.first; 427 } 428 bool operator()(const llvm::APSInt &LHS, 429 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 430 return LHS < RHS.first; 431 } 432 }; 433} 434 435/// CmpCaseVals - Comparison predicate for sorting case values. 436/// 437static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 438 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 439 if (lhs.first < rhs.first) 440 return true; 441 442 if (lhs.first == rhs.first && 443 lhs.second->getCaseLoc().getRawEncoding() 444 < rhs.second->getCaseLoc().getRawEncoding()) 445 return true; 446 return false; 447} 448 449/// CmpEnumVals - Comparison predicate for sorting enumeration values. 450/// 451static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 452 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 453{ 454 return lhs.first < rhs.first; 455} 456 457/// EqEnumVals - Comparison preficate for uniqing enumeration values. 458/// 459static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 460 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 461{ 462 return lhs.first == rhs.first; 463} 464 465/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 466/// potentially integral-promoted expression @p expr. 467static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) { 468 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr)) 469 expr = cleanups->getSubExpr(); 470 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) { 471 if (impcast->getCastKind() != CK_IntegralCast) break; 472 expr = impcast->getSubExpr(); 473 } 474 return expr->getType(); 475} 476 477StmtResult 478Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 479 Decl *CondVar) { 480 ExprResult CondResult; 481 482 VarDecl *ConditionVar = 0; 483 if (CondVar) { 484 ConditionVar = cast<VarDecl>(CondVar); 485 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 486 if (CondResult.isInvalid()) 487 return StmtError(); 488 489 Cond = CondResult.release(); 490 } 491 492 if (!Cond) 493 return StmtError(); 494 495 CondResult = CheckPlaceholderExpr(Cond); 496 if (CondResult.isInvalid()) 497 return StmtError(); 498 499 CondResult 500 = ConvertToIntegralOrEnumerationType(SwitchLoc, CondResult.take(), 501 PDiag(diag::err_typecheck_statement_requires_integer), 502 PDiag(diag::err_switch_incomplete_class_type) 503 << Cond->getSourceRange(), 504 PDiag(diag::err_switch_explicit_conversion), 505 PDiag(diag::note_switch_conversion), 506 PDiag(diag::err_switch_multiple_conversions), 507 PDiag(diag::note_switch_conversion), 508 PDiag(0)); 509 if (CondResult.isInvalid()) return StmtError(); 510 Cond = CondResult.take(); 511 512 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 513 CondResult = UsualUnaryConversions(Cond); 514 if (CondResult.isInvalid()) return StmtError(); 515 Cond = CondResult.take(); 516 517 if (!CondVar) { 518 CheckImplicitConversions(Cond, SwitchLoc); 519 CondResult = MaybeCreateExprWithCleanups(Cond); 520 if (CondResult.isInvalid()) 521 return StmtError(); 522 Cond = CondResult.take(); 523 } 524 525 getCurFunction()->setHasBranchIntoScope(); 526 527 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 528 getCurFunction()->SwitchStack.push_back(SS); 529 return Owned(SS); 530} 531 532static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 533 if (Val.getBitWidth() < BitWidth) 534 Val = Val.extend(BitWidth); 535 else if (Val.getBitWidth() > BitWidth) 536 Val = Val.trunc(BitWidth); 537 Val.setIsSigned(IsSigned); 538} 539 540StmtResult 541Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 542 Stmt *BodyStmt) { 543 SwitchStmt *SS = cast<SwitchStmt>(Switch); 544 assert(SS == getCurFunction()->SwitchStack.back() && 545 "switch stack missing push/pop!"); 546 547 SS->setBody(BodyStmt, SwitchLoc); 548 getCurFunction()->SwitchStack.pop_back(); 549 550 Expr *CondExpr = SS->getCond(); 551 if (!CondExpr) return StmtError(); 552 553 QualType CondType = CondExpr->getType(); 554 555 Expr *CondExprBeforePromotion = CondExpr; 556 QualType CondTypeBeforePromotion = 557 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); 558 559 // C++ 6.4.2.p2: 560 // Integral promotions are performed (on the switch condition). 561 // 562 // A case value unrepresentable by the original switch condition 563 // type (before the promotion) doesn't make sense, even when it can 564 // be represented by the promoted type. Therefore we need to find 565 // the pre-promotion type of the switch condition. 566 if (!CondExpr->isTypeDependent()) { 567 // We have already converted the expression to an integral or enumeration 568 // type, when we started the switch statement. If we don't have an 569 // appropriate type now, just return an error. 570 if (!CondType->isIntegralOrEnumerationType()) 571 return StmtError(); 572 573 if (CondExpr->isKnownToHaveBooleanValue()) { 574 // switch(bool_expr) {...} is often a programmer error, e.g. 575 // switch(n && mask) { ... } // Doh - should be "n & mask". 576 // One can always use an if statement instead of switch(bool_expr). 577 Diag(SwitchLoc, diag::warn_bool_switch_condition) 578 << CondExpr->getSourceRange(); 579 } 580 } 581 582 // Get the bitwidth of the switched-on value before promotions. We must 583 // convert the integer case values to this width before comparison. 584 bool HasDependentValue 585 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 586 unsigned CondWidth 587 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); 588 bool CondIsSigned 589 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); 590 591 // Accumulate all of the case values in a vector so that we can sort them 592 // and detect duplicates. This vector contains the APInt for the case after 593 // it has been converted to the condition type. 594 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 595 CaseValsTy CaseVals; 596 597 // Keep track of any GNU case ranges we see. The APSInt is the low value. 598 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 599 CaseRangesTy CaseRanges; 600 601 DefaultStmt *TheDefaultStmt = 0; 602 603 bool CaseListIsErroneous = false; 604 605 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 606 SC = SC->getNextSwitchCase()) { 607 608 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 609 if (TheDefaultStmt) { 610 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 611 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 612 613 // FIXME: Remove the default statement from the switch block so that 614 // we'll return a valid AST. This requires recursing down the AST and 615 // finding it, not something we are set up to do right now. For now, 616 // just lop the entire switch stmt out of the AST. 617 CaseListIsErroneous = true; 618 } 619 TheDefaultStmt = DS; 620 621 } else { 622 CaseStmt *CS = cast<CaseStmt>(SC); 623 624 // We already verified that the expression has a i-c-e value (C99 625 // 6.8.4.2p3) - get that value now. 626 Expr *Lo = CS->getLHS(); 627 628 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 629 HasDependentValue = true; 630 break; 631 } 632 633 llvm::APSInt LoVal = Lo->EvaluateKnownConstInt(Context); 634 635 // Convert the value to the same width/sign as the condition. 636 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 637 Lo->getLocStart(), 638 diag::warn_case_value_overflow); 639 640 // If the LHS is not the same type as the condition, insert an implicit 641 // cast. 642 // FIXME: In C++11, the value is a converted constant expression of the 643 // promoted type of the switch condition. 644 Lo = DefaultLvalueConversion(Lo).take(); 645 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take(); 646 CS->setLHS(Lo); 647 648 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 649 if (CS->getRHS()) { 650 if (CS->getRHS()->isTypeDependent() || 651 CS->getRHS()->isValueDependent()) { 652 HasDependentValue = true; 653 break; 654 } 655 CaseRanges.push_back(std::make_pair(LoVal, CS)); 656 } else 657 CaseVals.push_back(std::make_pair(LoVal, CS)); 658 } 659 } 660 661 if (!HasDependentValue) { 662 // If we don't have a default statement, check whether the 663 // condition is constant. 664 llvm::APSInt ConstantCondValue; 665 bool HasConstantCond = false; 666 if (!HasDependentValue && !TheDefaultStmt) { 667 HasConstantCond 668 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context, 669 Expr::SE_AllowSideEffects); 670 assert(!HasConstantCond || 671 (ConstantCondValue.getBitWidth() == CondWidth && 672 ConstantCondValue.isSigned() == CondIsSigned)); 673 } 674 bool ShouldCheckConstantCond = HasConstantCond; 675 676 // Sort all the scalar case values so we can easily detect duplicates. 677 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 678 679 if (!CaseVals.empty()) { 680 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 681 if (ShouldCheckConstantCond && 682 CaseVals[i].first == ConstantCondValue) 683 ShouldCheckConstantCond = false; 684 685 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 686 // If we have a duplicate, report it. 687 Diag(CaseVals[i].second->getLHS()->getLocStart(), 688 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 689 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 690 diag::note_duplicate_case_prev); 691 // FIXME: We really want to remove the bogus case stmt from the 692 // substmt, but we have no way to do this right now. 693 CaseListIsErroneous = true; 694 } 695 } 696 } 697 698 // Detect duplicate case ranges, which usually don't exist at all in 699 // the first place. 700 if (!CaseRanges.empty()) { 701 // Sort all the case ranges by their low value so we can easily detect 702 // overlaps between ranges. 703 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 704 705 // Scan the ranges, computing the high values and removing empty ranges. 706 std::vector<llvm::APSInt> HiVals; 707 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 708 llvm::APSInt &LoVal = CaseRanges[i].first; 709 CaseStmt *CR = CaseRanges[i].second; 710 Expr *Hi = CR->getRHS(); 711 llvm::APSInt HiVal = Hi->EvaluateKnownConstInt(Context); 712 713 // Convert the value to the same width/sign as the condition. 714 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 715 Hi->getLocStart(), 716 diag::warn_case_value_overflow); 717 718 // If the RHS is not the same type as the condition, insert an implicit 719 // cast. 720 // FIXME: In C++11, the value is a converted constant expression of the 721 // promoted type of the switch condition. 722 Hi = DefaultLvalueConversion(Hi).take(); 723 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take(); 724 CR->setRHS(Hi); 725 726 // If the low value is bigger than the high value, the case is empty. 727 if (LoVal > HiVal) { 728 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 729 << SourceRange(CR->getLHS()->getLocStart(), 730 Hi->getLocEnd()); 731 CaseRanges.erase(CaseRanges.begin()+i); 732 --i, --e; 733 continue; 734 } 735 736 if (ShouldCheckConstantCond && 737 LoVal <= ConstantCondValue && 738 ConstantCondValue <= HiVal) 739 ShouldCheckConstantCond = false; 740 741 HiVals.push_back(HiVal); 742 } 743 744 // Rescan the ranges, looking for overlap with singleton values and other 745 // ranges. Since the range list is sorted, we only need to compare case 746 // ranges with their neighbors. 747 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 748 llvm::APSInt &CRLo = CaseRanges[i].first; 749 llvm::APSInt &CRHi = HiVals[i]; 750 CaseStmt *CR = CaseRanges[i].second; 751 752 // Check to see whether the case range overlaps with any 753 // singleton cases. 754 CaseStmt *OverlapStmt = 0; 755 llvm::APSInt OverlapVal(32); 756 757 // Find the smallest value >= the lower bound. If I is in the 758 // case range, then we have overlap. 759 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 760 CaseVals.end(), CRLo, 761 CaseCompareFunctor()); 762 if (I != CaseVals.end() && I->first < CRHi) { 763 OverlapVal = I->first; // Found overlap with scalar. 764 OverlapStmt = I->second; 765 } 766 767 // Find the smallest value bigger than the upper bound. 768 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 769 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 770 OverlapVal = (I-1)->first; // Found overlap with scalar. 771 OverlapStmt = (I-1)->second; 772 } 773 774 // Check to see if this case stmt overlaps with the subsequent 775 // case range. 776 if (i && CRLo <= HiVals[i-1]) { 777 OverlapVal = HiVals[i-1]; // Found overlap with range. 778 OverlapStmt = CaseRanges[i-1].second; 779 } 780 781 if (OverlapStmt) { 782 // If we have a duplicate, report it. 783 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 784 << OverlapVal.toString(10); 785 Diag(OverlapStmt->getLHS()->getLocStart(), 786 diag::note_duplicate_case_prev); 787 // FIXME: We really want to remove the bogus case stmt from the 788 // substmt, but we have no way to do this right now. 789 CaseListIsErroneous = true; 790 } 791 } 792 } 793 794 // Complain if we have a constant condition and we didn't find a match. 795 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 796 // TODO: it would be nice if we printed enums as enums, chars as 797 // chars, etc. 798 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 799 << ConstantCondValue.toString(10) 800 << CondExpr->getSourceRange(); 801 } 802 803 // Check to see if switch is over an Enum and handles all of its 804 // values. We only issue a warning if there is not 'default:', but 805 // we still do the analysis to preserve this information in the AST 806 // (which can be used by flow-based analyes). 807 // 808 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 809 810 // If switch has default case, then ignore it. 811 if (!CaseListIsErroneous && !HasConstantCond && ET) { 812 const EnumDecl *ED = ET->getDecl(); 813 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> 814 EnumValsTy; 815 EnumValsTy EnumVals; 816 817 // Gather all enum values, set their type and sort them, 818 // allowing easier comparison with CaseVals. 819 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 820 EDI != ED->enumerator_end(); ++EDI) { 821 llvm::APSInt Val = EDI->getInitVal(); 822 AdjustAPSInt(Val, CondWidth, CondIsSigned); 823 EnumVals.push_back(std::make_pair(Val, *EDI)); 824 } 825 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 826 EnumValsTy::iterator EIend = 827 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 828 829 // See which case values aren't in enum. 830 // TODO: we might want to check whether case values are out of the 831 // enum even if we don't want to check whether all cases are handled. 832 if (!TheDefaultStmt) { 833 EnumValsTy::const_iterator EI = EnumVals.begin(); 834 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 835 CI != CaseVals.end(); CI++) { 836 while (EI != EIend && EI->first < CI->first) 837 EI++; 838 if (EI == EIend || EI->first > CI->first) 839 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 840 << ED->getDeclName(); 841 } 842 // See which of case ranges aren't in enum 843 EI = EnumVals.begin(); 844 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 845 RI != CaseRanges.end() && EI != EIend; RI++) { 846 while (EI != EIend && EI->first < RI->first) 847 EI++; 848 849 if (EI == EIend || EI->first != RI->first) { 850 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 851 << ED->getDeclName(); 852 } 853 854 llvm::APSInt Hi = 855 RI->second->getRHS()->EvaluateKnownConstInt(Context); 856 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 857 while (EI != EIend && EI->first < Hi) 858 EI++; 859 if (EI == EIend || EI->first != Hi) 860 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 861 << ED->getDeclName(); 862 } 863 } 864 865 // Check which enum vals aren't in switch 866 CaseValsTy::const_iterator CI = CaseVals.begin(); 867 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 868 bool hasCasesNotInSwitch = false; 869 870 SmallVector<DeclarationName,8> UnhandledNames; 871 872 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){ 873 // Drop unneeded case values 874 llvm::APSInt CIVal; 875 while (CI != CaseVals.end() && CI->first < EI->first) 876 CI++; 877 878 if (CI != CaseVals.end() && CI->first == EI->first) 879 continue; 880 881 // Drop unneeded case ranges 882 for (; RI != CaseRanges.end(); RI++) { 883 llvm::APSInt Hi = 884 RI->second->getRHS()->EvaluateKnownConstInt(Context); 885 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 886 if (EI->first <= Hi) 887 break; 888 } 889 890 if (RI == CaseRanges.end() || EI->first < RI->first) { 891 hasCasesNotInSwitch = true; 892 if (!TheDefaultStmt) 893 UnhandledNames.push_back(EI->second->getDeclName()); 894 } 895 } 896 897 // Produce a nice diagnostic if multiple values aren't handled. 898 switch (UnhandledNames.size()) { 899 case 0: break; 900 case 1: 901 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1) 902 << UnhandledNames[0]; 903 break; 904 case 2: 905 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2) 906 << UnhandledNames[0] << UnhandledNames[1]; 907 break; 908 case 3: 909 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3) 910 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 911 break; 912 default: 913 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases) 914 << (unsigned)UnhandledNames.size() 915 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 916 break; 917 } 918 919 if (!hasCasesNotInSwitch) 920 SS->setAllEnumCasesCovered(); 921 } 922 } 923 924 // FIXME: If the case list was broken is some way, we don't have a good system 925 // to patch it up. Instead, just return the whole substmt as broken. 926 if (CaseListIsErroneous) 927 return StmtError(); 928 929 return Owned(SS); 930} 931 932StmtResult 933Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 934 Decl *CondVar, Stmt *Body) { 935 ExprResult CondResult(Cond.release()); 936 937 VarDecl *ConditionVar = 0; 938 if (CondVar) { 939 ConditionVar = cast<VarDecl>(CondVar); 940 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 941 if (CondResult.isInvalid()) 942 return StmtError(); 943 } 944 Expr *ConditionExpr = CondResult.take(); 945 if (!ConditionExpr) 946 return StmtError(); 947 948 DiagnoseUnusedExprResult(Body); 949 950 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 951 Body, WhileLoc)); 952} 953 954StmtResult 955Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 956 SourceLocation WhileLoc, SourceLocation CondLParen, 957 Expr *Cond, SourceLocation CondRParen) { 958 assert(Cond && "ActOnDoStmt(): missing expression"); 959 960 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc); 961 if (CondResult.isInvalid() || CondResult.isInvalid()) 962 return StmtError(); 963 Cond = CondResult.take(); 964 965 CheckImplicitConversions(Cond, DoLoc); 966 CondResult = MaybeCreateExprWithCleanups(Cond); 967 if (CondResult.isInvalid()) 968 return StmtError(); 969 Cond = CondResult.take(); 970 971 DiagnoseUnusedExprResult(Body); 972 973 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 974} 975 976StmtResult 977Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 978 Stmt *First, FullExprArg second, Decl *secondVar, 979 FullExprArg third, 980 SourceLocation RParenLoc, Stmt *Body) { 981 if (!getLangOptions().CPlusPlus) { 982 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 983 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 984 // declare identifiers for objects having storage class 'auto' or 985 // 'register'. 986 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 987 DI!=DE; ++DI) { 988 VarDecl *VD = dyn_cast<VarDecl>(*DI); 989 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 990 VD = 0; 991 if (VD == 0) 992 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 993 // FIXME: mark decl erroneous! 994 } 995 } 996 } 997 998 ExprResult SecondResult(second.release()); 999 VarDecl *ConditionVar = 0; 1000 if (secondVar) { 1001 ConditionVar = cast<VarDecl>(secondVar); 1002 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 1003 if (SecondResult.isInvalid()) 1004 return StmtError(); 1005 } 1006 1007 Expr *Third = third.release().takeAs<Expr>(); 1008 1009 DiagnoseUnusedExprResult(First); 1010 DiagnoseUnusedExprResult(Third); 1011 DiagnoseUnusedExprResult(Body); 1012 1013 return Owned(new (Context) ForStmt(Context, First, 1014 SecondResult.take(), ConditionVar, 1015 Third, Body, ForLoc, LParenLoc, 1016 RParenLoc)); 1017} 1018 1019/// In an Objective C collection iteration statement: 1020/// for (x in y) 1021/// x can be an arbitrary l-value expression. Bind it up as a 1022/// full-expression. 1023StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 1024 CheckImplicitConversions(E); 1025 ExprResult Result = MaybeCreateExprWithCleanups(E); 1026 if (Result.isInvalid()) return StmtError(); 1027 return Owned(static_cast<Stmt*>(Result.get())); 1028} 1029 1030ExprResult 1031Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { 1032 assert(collection); 1033 1034 // Bail out early if we've got a type-dependent expression. 1035 if (collection->isTypeDependent()) return Owned(collection); 1036 1037 // Perform normal l-value conversion. 1038 ExprResult result = DefaultFunctionArrayLvalueConversion(collection); 1039 if (result.isInvalid()) 1040 return ExprError(); 1041 collection = result.take(); 1042 1043 // The operand needs to have object-pointer type. 1044 // TODO: should we do a contextual conversion? 1045 const ObjCObjectPointerType *pointerType = 1046 collection->getType()->getAs<ObjCObjectPointerType>(); 1047 if (!pointerType) 1048 return Diag(forLoc, diag::err_collection_expr_type) 1049 << collection->getType() << collection->getSourceRange(); 1050 1051 // Check that the operand provides 1052 // - countByEnumeratingWithState:objects:count: 1053 const ObjCObjectType *objectType = pointerType->getObjectType(); 1054 ObjCInterfaceDecl *iface = objectType->getInterface(); 1055 1056 // If we have a forward-declared type, we can't do this check. 1057 // Under ARC, it is an error not to have a forward-declared class. 1058 if (iface && 1059 RequireCompleteType(forLoc, QualType(objectType, 0), 1060 getLangOptions().ObjCAutoRefCount 1061 ? PDiag(diag::err_arc_collection_forward) 1062 << collection->getSourceRange() 1063 : PDiag(0))) { 1064 // Otherwise, if we have any useful type information, check that 1065 // the type declares the appropriate method. 1066 } else if (iface || !objectType->qual_empty()) { 1067 IdentifierInfo *selectorIdents[] = { 1068 &Context.Idents.get("countByEnumeratingWithState"), 1069 &Context.Idents.get("objects"), 1070 &Context.Idents.get("count") 1071 }; 1072 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); 1073 1074 ObjCMethodDecl *method = 0; 1075 1076 // If there's an interface, look in both the public and private APIs. 1077 if (iface) { 1078 method = iface->lookupInstanceMethod(selector); 1079 if (!method) method = LookupPrivateInstanceMethod(selector, iface); 1080 } 1081 1082 // Also check protocol qualifiers. 1083 if (!method) 1084 method = LookupMethodInQualifiedType(selector, pointerType, 1085 /*instance*/ true); 1086 1087 // If we didn't find it anywhere, give up. 1088 if (!method) { 1089 Diag(forLoc, diag::warn_collection_expr_type) 1090 << collection->getType() << selector << collection->getSourceRange(); 1091 } 1092 1093 // TODO: check for an incompatible signature? 1094 } 1095 1096 // Wrap up any cleanups in the expression. 1097 return Owned(MaybeCreateExprWithCleanups(collection)); 1098} 1099 1100StmtResult 1101Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 1102 SourceLocation LParenLoc, 1103 Stmt *First, Expr *Second, 1104 SourceLocation RParenLoc, Stmt *Body) { 1105 if (First) { 1106 QualType FirstType; 1107 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 1108 if (!DS->isSingleDecl()) 1109 return StmtError(Diag((*DS->decl_begin())->getLocation(), 1110 diag::err_toomany_element_decls)); 1111 1112 VarDecl *D = cast<VarDecl>(DS->getSingleDecl()); 1113 FirstType = D->getType(); 1114 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 1115 // declare identifiers for objects having storage class 'auto' or 1116 // 'register'. 1117 if (!D->hasLocalStorage()) 1118 return StmtError(Diag(D->getLocation(), 1119 diag::err_non_variable_decl_in_for)); 1120 } else { 1121 Expr *FirstE = cast<Expr>(First); 1122 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 1123 return StmtError(Diag(First->getLocStart(), 1124 diag::err_selector_element_not_lvalue) 1125 << First->getSourceRange()); 1126 1127 FirstType = static_cast<Expr*>(First)->getType(); 1128 } 1129 if (!FirstType->isDependentType() && 1130 !FirstType->isObjCObjectPointerType() && 1131 !FirstType->isBlockPointerType()) 1132 Diag(ForLoc, diag::err_selector_element_type) 1133 << FirstType << First->getSourceRange(); 1134 } 1135 1136 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 1137 ForLoc, RParenLoc)); 1138} 1139 1140namespace { 1141 1142enum BeginEndFunction { 1143 BEF_begin, 1144 BEF_end 1145}; 1146 1147/// Build a variable declaration for a for-range statement. 1148static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 1149 QualType Type, const char *Name) { 1150 DeclContext *DC = SemaRef.CurContext; 1151 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1152 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1153 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 1154 TInfo, SC_Auto, SC_None); 1155 Decl->setImplicit(); 1156 return Decl; 1157} 1158 1159/// Finish building a variable declaration for a for-range statement. 1160/// \return true if an error occurs. 1161static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 1162 SourceLocation Loc, int diag) { 1163 // Deduce the type for the iterator variable now rather than leaving it to 1164 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 1165 TypeSourceInfo *InitTSI = 0; 1166 if (Init->getType()->isVoidType() || 1167 !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI)) 1168 SemaRef.Diag(Loc, diag) << Init->getType(); 1169 if (!InitTSI) { 1170 Decl->setInvalidDecl(); 1171 return true; 1172 } 1173 Decl->setTypeSourceInfo(InitTSI); 1174 Decl->setType(InitTSI->getType()); 1175 1176 // In ARC, infer lifetime. 1177 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if 1178 // we're doing the equivalent of fast iteration. 1179 if (SemaRef.getLangOptions().ObjCAutoRefCount && 1180 SemaRef.inferObjCARCLifetime(Decl)) 1181 Decl->setInvalidDecl(); 1182 1183 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false, 1184 /*TypeMayContainAuto=*/false); 1185 SemaRef.FinalizeDeclaration(Decl); 1186 SemaRef.CurContext->addHiddenDecl(Decl); 1187 return false; 1188} 1189 1190/// Produce a note indicating which begin/end function was implicitly called 1191/// by a C++0x for-range statement. This is often not obvious from the code, 1192/// nor from the diagnostics produced when analysing the implicit expressions 1193/// required in a for-range statement. 1194void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 1195 BeginEndFunction BEF) { 1196 CallExpr *CE = dyn_cast<CallExpr>(E); 1197 if (!CE) 1198 return; 1199 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1200 if (!D) 1201 return; 1202 SourceLocation Loc = D->getLocation(); 1203 1204 std::string Description; 1205 bool IsTemplate = false; 1206 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 1207 Description = SemaRef.getTemplateArgumentBindingsText( 1208 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 1209 IsTemplate = true; 1210 } 1211 1212 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 1213 << BEF << IsTemplate << Description << E->getType(); 1214} 1215 1216/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the 1217/// given LookupResult is non-empty, it is assumed to describe a member which 1218/// will be invoked. Otherwise, the function will be found via argument 1219/// dependent lookup. 1220static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S, 1221 SourceLocation Loc, 1222 VarDecl *Decl, 1223 BeginEndFunction BEF, 1224 const DeclarationNameInfo &NameInfo, 1225 LookupResult &MemberLookup, 1226 Expr *Range) { 1227 ExprResult CallExpr; 1228 if (!MemberLookup.empty()) { 1229 ExprResult MemberRef = 1230 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc, 1231 /*IsPtr=*/false, CXXScopeSpec(), 1232 /*Qualifier=*/0, MemberLookup, 1233 /*TemplateArgs=*/0); 1234 if (MemberRef.isInvalid()) 1235 return ExprError(); 1236 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), 1237 Loc, 0); 1238 if (CallExpr.isInvalid()) 1239 return ExprError(); 1240 } else { 1241 UnresolvedSet<0> FoundNames; 1242 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace 1243 // std is an associated namespace. 1244 UnresolvedLookupExpr *Fn = 1245 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0, 1246 NestedNameSpecifierLoc(), NameInfo, 1247 /*NeedsADL=*/true, /*Overloaded=*/false, 1248 FoundNames.begin(), FoundNames.end(), 1249 /*LookInStdNamespace=*/true); 1250 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc, 1251 0); 1252 if (CallExpr.isInvalid()) { 1253 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type) 1254 << Range->getType(); 1255 return ExprError(); 1256 } 1257 } 1258 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc, 1259 diag::err_for_range_iter_deduction_failure)) { 1260 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF); 1261 return ExprError(); 1262 } 1263 return CallExpr; 1264} 1265 1266} 1267 1268/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement. 1269/// 1270/// C++0x [stmt.ranged]: 1271/// A range-based for statement is equivalent to 1272/// 1273/// { 1274/// auto && __range = range-init; 1275/// for ( auto __begin = begin-expr, 1276/// __end = end-expr; 1277/// __begin != __end; 1278/// ++__begin ) { 1279/// for-range-declaration = *__begin; 1280/// statement 1281/// } 1282/// } 1283/// 1284/// The body of the loop is not available yet, since it cannot be analysed until 1285/// we have determined the type of the for-range-declaration. 1286StmtResult 1287Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 1288 Stmt *First, SourceLocation ColonLoc, Expr *Range, 1289 SourceLocation RParenLoc) { 1290 if (!First || !Range) 1291 return StmtError(); 1292 1293 DeclStmt *DS = dyn_cast<DeclStmt>(First); 1294 assert(DS && "first part of for range not a decl stmt"); 1295 1296 if (!DS->isSingleDecl()) { 1297 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range); 1298 return StmtError(); 1299 } 1300 if (DS->getSingleDecl()->isInvalidDecl()) 1301 return StmtError(); 1302 1303 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) 1304 return StmtError(); 1305 1306 // Build auto && __range = range-init 1307 SourceLocation RangeLoc = Range->getLocStart(); 1308 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 1309 Context.getAutoRRefDeductType(), 1310 "__range"); 1311 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 1312 diag::err_for_range_deduction_failure)) 1313 return StmtError(); 1314 1315 // Claim the type doesn't contain auto: we've already done the checking. 1316 DeclGroupPtrTy RangeGroup = 1317 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false); 1318 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 1319 if (RangeDecl.isInvalid()) 1320 return StmtError(); 1321 1322 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(), 1323 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS, 1324 RParenLoc); 1325} 1326 1327/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement. 1328StmtResult 1329Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, 1330 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond, 1331 Expr *Inc, Stmt *LoopVarDecl, 1332 SourceLocation RParenLoc) { 1333 Scope *S = getCurScope(); 1334 1335 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 1336 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 1337 QualType RangeVarType = RangeVar->getType(); 1338 1339 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 1340 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 1341 1342 StmtResult BeginEndDecl = BeginEnd; 1343 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 1344 1345 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) { 1346 SourceLocation RangeLoc = RangeVar->getLocation(); 1347 1348 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); 1349 1350 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1351 VK_LValue, ColonLoc); 1352 if (BeginRangeRef.isInvalid()) 1353 return StmtError(); 1354 1355 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1356 VK_LValue, ColonLoc); 1357 if (EndRangeRef.isInvalid()) 1358 return StmtError(); 1359 1360 QualType AutoType = Context.getAutoDeductType(); 1361 Expr *Range = RangeVar->getInit(); 1362 if (!Range) 1363 return StmtError(); 1364 QualType RangeType = Range->getType(); 1365 1366 if (RequireCompleteType(RangeLoc, RangeType, 1367 PDiag(diag::err_for_range_incomplete_type))) 1368 return StmtError(); 1369 1370 // Build auto __begin = begin-expr, __end = end-expr. 1371 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1372 "__begin"); 1373 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1374 "__end"); 1375 1376 // Build begin-expr and end-expr and attach to __begin and __end variables. 1377 ExprResult BeginExpr, EndExpr; 1378 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 1379 // - if _RangeT is an array type, begin-expr and end-expr are __range and 1380 // __range + __bound, respectively, where __bound is the array bound. If 1381 // _RangeT is an array of unknown size or an array of incomplete type, 1382 // the program is ill-formed; 1383 1384 // begin-expr is __range. 1385 BeginExpr = BeginRangeRef; 1386 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, 1387 diag::err_for_range_iter_deduction_failure)) { 1388 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1389 return StmtError(); 1390 } 1391 1392 // Find the array bound. 1393 ExprResult BoundExpr; 1394 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 1395 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(), 1396 Context.getPointerDiffType(), 1397 RangeLoc)); 1398 else if (const VariableArrayType *VAT = 1399 dyn_cast<VariableArrayType>(UnqAT)) 1400 BoundExpr = VAT->getSizeExpr(); 1401 else { 1402 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 1403 // UnqAT is not incomplete and Range is not type-dependent. 1404 llvm_unreachable("Unexpected array type in for-range"); 1405 } 1406 1407 // end-expr is __range + __bound. 1408 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), 1409 BoundExpr.get()); 1410 if (EndExpr.isInvalid()) 1411 return StmtError(); 1412 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 1413 diag::err_for_range_iter_deduction_failure)) { 1414 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1415 return StmtError(); 1416 } 1417 } else { 1418 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"), 1419 ColonLoc); 1420 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"), 1421 ColonLoc); 1422 1423 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName); 1424 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName); 1425 1426 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 1427 // - if _RangeT is a class type, the unqualified-ids begin and end are 1428 // looked up in the scope of class _RangeT as if by class member access 1429 // lookup (3.4.5), and if either (or both) finds at least one 1430 // declaration, begin-expr and end-expr are __range.begin() and 1431 // __range.end(), respectively; 1432 LookupQualifiedName(BeginMemberLookup, D); 1433 LookupQualifiedName(EndMemberLookup, D); 1434 1435 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 1436 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch) 1437 << RangeType << BeginMemberLookup.empty(); 1438 return StmtError(); 1439 } 1440 } else { 1441 // - otherwise, begin-expr and end-expr are begin(__range) and 1442 // end(__range), respectively, where begin and end are looked up with 1443 // argument-dependent lookup (3.4.2). For the purposes of this name 1444 // lookup, namespace std is an associated namespace. 1445 } 1446 1447 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar, 1448 BEF_begin, BeginNameInfo, 1449 BeginMemberLookup, 1450 BeginRangeRef.get()); 1451 if (BeginExpr.isInvalid()) 1452 return StmtError(); 1453 1454 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar, 1455 BEF_end, EndNameInfo, 1456 EndMemberLookup, EndRangeRef.get()); 1457 if (EndExpr.isInvalid()) 1458 return StmtError(); 1459 } 1460 1461 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same. 1462 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 1463 if (!Context.hasSameType(BeginType, EndType)) { 1464 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ) 1465 << BeginType << EndType; 1466 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1467 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1468 } 1469 1470 Decl *BeginEndDecls[] = { BeginVar, EndVar }; 1471 // Claim the type doesn't contain auto: we've already done the checking. 1472 DeclGroupPtrTy BeginEndGroup = 1473 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false); 1474 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc); 1475 1476 const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); 1477 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1478 VK_LValue, ColonLoc); 1479 if (BeginRef.isInvalid()) 1480 return StmtError(); 1481 1482 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 1483 VK_LValue, ColonLoc); 1484 if (EndRef.isInvalid()) 1485 return StmtError(); 1486 1487 // Build and check __begin != __end expression. 1488 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 1489 BeginRef.get(), EndRef.get()); 1490 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get()); 1491 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get()); 1492 if (NotEqExpr.isInvalid()) { 1493 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1494 if (!Context.hasSameType(BeginType, EndType)) 1495 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1496 return StmtError(); 1497 } 1498 1499 // Build and check ++__begin expression. 1500 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1501 VK_LValue, ColonLoc); 1502 if (BeginRef.isInvalid()) 1503 return StmtError(); 1504 1505 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 1506 IncrExpr = ActOnFinishFullExpr(IncrExpr.get()); 1507 if (IncrExpr.isInvalid()) { 1508 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1509 return StmtError(); 1510 } 1511 1512 // Build and check *__begin expression. 1513 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1514 VK_LValue, ColonLoc); 1515 if (BeginRef.isInvalid()) 1516 return StmtError(); 1517 1518 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 1519 if (DerefExpr.isInvalid()) { 1520 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1521 return StmtError(); 1522 } 1523 1524 // Attach *__begin as initializer for VD. 1525 if (!LoopVar->isInvalidDecl()) { 1526 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false, 1527 /*TypeMayContainAuto=*/true); 1528 if (LoopVar->isInvalidDecl()) 1529 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1530 } 1531 } else { 1532 // The range is implicitly used as a placeholder when it is dependent. 1533 RangeVar->setUsed(); 1534 } 1535 1536 return Owned(new (Context) CXXForRangeStmt(RangeDS, 1537 cast_or_null<DeclStmt>(BeginEndDecl.get()), 1538 NotEqExpr.take(), IncrExpr.take(), 1539 LoopVarDS, /*Body=*/0, ForLoc, 1540 ColonLoc, RParenLoc)); 1541} 1542 1543/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 1544/// This is a separate step from ActOnCXXForRangeStmt because analysis of the 1545/// body cannot be performed until after the type of the range variable is 1546/// determined. 1547StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 1548 if (!S || !B) 1549 return StmtError(); 1550 1551 cast<CXXForRangeStmt>(S)->setBody(B); 1552 return S; 1553} 1554 1555StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 1556 SourceLocation LabelLoc, 1557 LabelDecl *TheDecl) { 1558 getCurFunction()->setHasBranchIntoScope(); 1559 TheDecl->setUsed(); 1560 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc)); 1561} 1562 1563StmtResult 1564Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 1565 Expr *E) { 1566 // Convert operand to void* 1567 if (!E->isTypeDependent()) { 1568 QualType ETy = E->getType(); 1569 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 1570 ExprResult ExprRes = Owned(E); 1571 AssignConvertType ConvTy = 1572 CheckSingleAssignmentConstraints(DestTy, ExprRes); 1573 if (ExprRes.isInvalid()) 1574 return StmtError(); 1575 E = ExprRes.take(); 1576 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 1577 return StmtError(); 1578 } 1579 1580 getCurFunction()->setHasIndirectGoto(); 1581 1582 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 1583} 1584 1585StmtResult 1586Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 1587 Scope *S = CurScope->getContinueParent(); 1588 if (!S) { 1589 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 1590 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 1591 } 1592 1593 return Owned(new (Context) ContinueStmt(ContinueLoc)); 1594} 1595 1596StmtResult 1597Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1598 Scope *S = CurScope->getBreakParent(); 1599 if (!S) { 1600 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1601 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1602 } 1603 1604 return Owned(new (Context) BreakStmt(BreakLoc)); 1605} 1606 1607/// \brief Determine whether the given expression is a candidate for 1608/// copy elision in either a return statement or a throw expression. 1609/// 1610/// \param ReturnType If we're determining the copy elision candidate for 1611/// a return statement, this is the return type of the function. If we're 1612/// determining the copy elision candidate for a throw expression, this will 1613/// be a NULL type. 1614/// 1615/// \param E The expression being returned from the function or block, or 1616/// being thrown. 1617/// 1618/// \param AllowFunctionParameter Whether we allow function parameters to 1619/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but 1620/// we re-use this logic to determine whether we should try to move as part of 1621/// a return or throw (which does allow function parameters). 1622/// 1623/// \returns The NRVO candidate variable, if the return statement may use the 1624/// NRVO, or NULL if there is no such candidate. 1625const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 1626 Expr *E, 1627 bool AllowFunctionParameter) { 1628 QualType ExprType = E->getType(); 1629 // - in a return statement in a function with ... 1630 // ... a class return type ... 1631 if (!ReturnType.isNull()) { 1632 if (!ReturnType->isRecordType()) 1633 return 0; 1634 // ... the same cv-unqualified type as the function return type ... 1635 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType)) 1636 return 0; 1637 } 1638 1639 // ... the expression is the name of a non-volatile automatic object 1640 // (other than a function or catch-clause parameter)) ... 1641 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 1642 if (!DR) 1643 return 0; 1644 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1645 if (!VD) 1646 return 0; 1647 1648 // ...object (other than a function or catch-clause parameter)... 1649 if (VD->getKind() != Decl::Var && 1650 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar)) 1651 return 0; 1652 if (VD->isExceptionVariable()) return 0; 1653 1654 // ...automatic... 1655 if (!VD->hasLocalStorage()) return 0; 1656 1657 // ...non-volatile... 1658 if (VD->getType().isVolatileQualified()) return 0; 1659 if (VD->getType()->isReferenceType()) return 0; 1660 1661 // __block variables can't be allocated in a way that permits NRVO. 1662 if (VD->hasAttr<BlocksAttr>()) return 0; 1663 1664 // Variables with higher required alignment than their type's ABI 1665 // alignment cannot use NRVO. 1666 if (VD->hasAttr<AlignedAttr>() && 1667 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())) 1668 return 0; 1669 1670 return VD; 1671} 1672 1673/// \brief Perform the initialization of a potentially-movable value, which 1674/// is the result of return value. 1675/// 1676/// This routine implements C++0x [class.copy]p33, which attempts to treat 1677/// returned lvalues as rvalues in certain cases (to prefer move construction), 1678/// then falls back to treating them as lvalues if that failed. 1679ExprResult 1680Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1681 const VarDecl *NRVOCandidate, 1682 QualType ResultType, 1683 Expr *Value, 1684 bool AllowNRVO) { 1685 // C++0x [class.copy]p33: 1686 // When the criteria for elision of a copy operation are met or would 1687 // be met save for the fact that the source object is a function 1688 // parameter, and the object to be copied is designated by an lvalue, 1689 // overload resolution to select the constructor for the copy is first 1690 // performed as if the object were designated by an rvalue. 1691 ExprResult Res = ExprError(); 1692 if (AllowNRVO && 1693 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) { 1694 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 1695 Value->getType(), CK_LValueToRValue, 1696 Value, VK_XValue); 1697 1698 Expr *InitExpr = &AsRvalue; 1699 InitializationKind Kind 1700 = InitializationKind::CreateCopy(Value->getLocStart(), 1701 Value->getLocStart()); 1702 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1); 1703 1704 // [...] If overload resolution fails, or if the type of the first 1705 // parameter of the selected constructor is not an rvalue reference 1706 // to the object's type (possibly cv-qualified), overload resolution 1707 // is performed again, considering the object as an lvalue. 1708 if (Seq) { 1709 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 1710 StepEnd = Seq.step_end(); 1711 Step != StepEnd; ++Step) { 1712 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization) 1713 continue; 1714 1715 CXXConstructorDecl *Constructor 1716 = cast<CXXConstructorDecl>(Step->Function.Function); 1717 1718 const RValueReferenceType *RRefType 1719 = Constructor->getParamDecl(0)->getType() 1720 ->getAs<RValueReferenceType>(); 1721 1722 // If we don't meet the criteria, break out now. 1723 if (!RRefType || 1724 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 1725 Context.getTypeDeclType(Constructor->getParent()))) 1726 break; 1727 1728 // Promote "AsRvalue" to the heap, since we now need this 1729 // expression node to persist. 1730 Value = ImplicitCastExpr::Create(Context, Value->getType(), 1731 CK_LValueToRValue, Value, 0, 1732 VK_XValue); 1733 1734 // Complete type-checking the initialization of the return type 1735 // using the constructor we found. 1736 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1)); 1737 } 1738 } 1739 } 1740 1741 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 1742 // above, or overload resolution failed. Either way, we need to try 1743 // (again) now with the return value expression as written. 1744 if (Res.isInvalid()) 1745 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 1746 1747 return Res; 1748} 1749 1750/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 1751/// 1752StmtResult 1753Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1754 // If this is the first return we've seen in the block, infer the type of 1755 // the block from it. 1756 BlockScopeInfo *CurBlock = getCurBlock(); 1757 if (CurBlock->TheDecl->blockMissingReturnType()) { 1758 QualType BlockReturnT; 1759 if (RetValExp) { 1760 // Don't call UsualUnaryConversions(), since we don't want to do 1761 // integer promotions here. 1762 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 1763 if (Result.isInvalid()) 1764 return StmtError(); 1765 RetValExp = Result.take(); 1766 1767 if (!RetValExp->isTypeDependent()) { 1768 BlockReturnT = RetValExp->getType(); 1769 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 1770 // We have to remove a 'const' added to copied-in variable which was 1771 // part of the implementation spec. and not the actual qualifier for 1772 // the variable. 1773 if (CDRE->isConstQualAdded()) 1774 CurBlock->ReturnType.removeLocalConst(); // FIXME: local??? 1775 } 1776 } else 1777 BlockReturnT = Context.DependentTy; 1778 } else 1779 BlockReturnT = Context.VoidTy; 1780 if (!CurBlock->ReturnType.isNull() && !CurBlock->ReturnType->isDependentType() 1781 && !BlockReturnT->isDependentType() 1782 // when block's return type is not specified, all return types 1783 // must strictly match. 1784 && !Context.hasSameType(BlockReturnT, CurBlock->ReturnType)) { 1785 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible) 1786 << BlockReturnT << CurBlock->ReturnType; 1787 return StmtError(); 1788 } 1789 CurBlock->ReturnType = BlockReturnT; 1790 } 1791 QualType FnRetType = CurBlock->ReturnType; 1792 1793 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 1794 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr) 1795 << getCurFunctionOrMethodDecl()->getDeclName(); 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 << getCurFunctionOrMethodDecl()->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