SemaStmt.cpp revision 4b9c2d235fb9449e249d74f48ecfec601650de93
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/APValue.h" 20#include "clang/AST/ASTContext.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 bool ShouldCheckConstantCond = false; 667 if (!HasDependentValue && !TheDefaultStmt) { 668 Expr::EvalResult Result; 669 HasConstantCond 670 = CondExprBeforePromotion->EvaluateAsRValue(Result, Context); 671 if (HasConstantCond) { 672 assert(Result.Val.isInt() && "switch condition evaluated to non-int"); 673 ConstantCondValue = Result.Val.getInt(); 674 ShouldCheckConstantCond = true; 675 676 assert(ConstantCondValue.getBitWidth() == CondWidth && 677 ConstantCondValue.isSigned() == CondIsSigned); 678 } 679 } 680 681 // Sort all the scalar case values so we can easily detect duplicates. 682 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 683 684 if (!CaseVals.empty()) { 685 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 686 if (ShouldCheckConstantCond && 687 CaseVals[i].first == ConstantCondValue) 688 ShouldCheckConstantCond = false; 689 690 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 691 // If we have a duplicate, report it. 692 Diag(CaseVals[i].second->getLHS()->getLocStart(), 693 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 694 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 695 diag::note_duplicate_case_prev); 696 // FIXME: We really want to remove the bogus case stmt from the 697 // substmt, but we have no way to do this right now. 698 CaseListIsErroneous = true; 699 } 700 } 701 } 702 703 // Detect duplicate case ranges, which usually don't exist at all in 704 // the first place. 705 if (!CaseRanges.empty()) { 706 // Sort all the case ranges by their low value so we can easily detect 707 // overlaps between ranges. 708 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 709 710 // Scan the ranges, computing the high values and removing empty ranges. 711 std::vector<llvm::APSInt> HiVals; 712 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 713 llvm::APSInt &LoVal = CaseRanges[i].first; 714 CaseStmt *CR = CaseRanges[i].second; 715 Expr *Hi = CR->getRHS(); 716 llvm::APSInt HiVal = Hi->EvaluateKnownConstInt(Context); 717 718 // Convert the value to the same width/sign as the condition. 719 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 720 Hi->getLocStart(), 721 diag::warn_case_value_overflow); 722 723 // If the RHS is not the same type as the condition, insert an implicit 724 // cast. 725 // FIXME: In C++11, the value is a converted constant expression of the 726 // promoted type of the switch condition. 727 Hi = DefaultLvalueConversion(Hi).take(); 728 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take(); 729 CR->setRHS(Hi); 730 731 // If the low value is bigger than the high value, the case is empty. 732 if (LoVal > HiVal) { 733 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 734 << SourceRange(CR->getLHS()->getLocStart(), 735 Hi->getLocEnd()); 736 CaseRanges.erase(CaseRanges.begin()+i); 737 --i, --e; 738 continue; 739 } 740 741 if (ShouldCheckConstantCond && 742 LoVal <= ConstantCondValue && 743 ConstantCondValue <= HiVal) 744 ShouldCheckConstantCond = false; 745 746 HiVals.push_back(HiVal); 747 } 748 749 // Rescan the ranges, looking for overlap with singleton values and other 750 // ranges. Since the range list is sorted, we only need to compare case 751 // ranges with their neighbors. 752 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 753 llvm::APSInt &CRLo = CaseRanges[i].first; 754 llvm::APSInt &CRHi = HiVals[i]; 755 CaseStmt *CR = CaseRanges[i].second; 756 757 // Check to see whether the case range overlaps with any 758 // singleton cases. 759 CaseStmt *OverlapStmt = 0; 760 llvm::APSInt OverlapVal(32); 761 762 // Find the smallest value >= the lower bound. If I is in the 763 // case range, then we have overlap. 764 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 765 CaseVals.end(), CRLo, 766 CaseCompareFunctor()); 767 if (I != CaseVals.end() && I->first < CRHi) { 768 OverlapVal = I->first; // Found overlap with scalar. 769 OverlapStmt = I->second; 770 } 771 772 // Find the smallest value bigger than the upper bound. 773 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 774 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 775 OverlapVal = (I-1)->first; // Found overlap with scalar. 776 OverlapStmt = (I-1)->second; 777 } 778 779 // Check to see if this case stmt overlaps with the subsequent 780 // case range. 781 if (i && CRLo <= HiVals[i-1]) { 782 OverlapVal = HiVals[i-1]; // Found overlap with range. 783 OverlapStmt = CaseRanges[i-1].second; 784 } 785 786 if (OverlapStmt) { 787 // If we have a duplicate, report it. 788 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 789 << OverlapVal.toString(10); 790 Diag(OverlapStmt->getLHS()->getLocStart(), 791 diag::note_duplicate_case_prev); 792 // FIXME: We really want to remove the bogus case stmt from the 793 // substmt, but we have no way to do this right now. 794 CaseListIsErroneous = true; 795 } 796 } 797 } 798 799 // Complain if we have a constant condition and we didn't find a match. 800 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 801 // TODO: it would be nice if we printed enums as enums, chars as 802 // chars, etc. 803 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 804 << ConstantCondValue.toString(10) 805 << CondExpr->getSourceRange(); 806 } 807 808 // Check to see if switch is over an Enum and handles all of its 809 // values. We only issue a warning if there is not 'default:', but 810 // we still do the analysis to preserve this information in the AST 811 // (which can be used by flow-based analyes). 812 // 813 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 814 815 // If switch has default case, then ignore it. 816 if (!CaseListIsErroneous && !HasConstantCond && ET) { 817 const EnumDecl *ED = ET->getDecl(); 818 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> 819 EnumValsTy; 820 EnumValsTy EnumVals; 821 822 // Gather all enum values, set their type and sort them, 823 // allowing easier comparison with CaseVals. 824 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 825 EDI != ED->enumerator_end(); ++EDI) { 826 llvm::APSInt Val = EDI->getInitVal(); 827 AdjustAPSInt(Val, CondWidth, CondIsSigned); 828 EnumVals.push_back(std::make_pair(Val, *EDI)); 829 } 830 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 831 EnumValsTy::iterator EIend = 832 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 833 834 // See which case values aren't in enum. 835 // TODO: we might want to check whether case values are out of the 836 // enum even if we don't want to check whether all cases are handled. 837 if (!TheDefaultStmt) { 838 EnumValsTy::const_iterator EI = EnumVals.begin(); 839 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 840 CI != CaseVals.end(); CI++) { 841 while (EI != EIend && EI->first < CI->first) 842 EI++; 843 if (EI == EIend || EI->first > CI->first) 844 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 845 << ED->getDeclName(); 846 } 847 // See which of case ranges aren't in enum 848 EI = EnumVals.begin(); 849 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 850 RI != CaseRanges.end() && EI != EIend; RI++) { 851 while (EI != EIend && EI->first < RI->first) 852 EI++; 853 854 if (EI == EIend || EI->first != RI->first) { 855 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 856 << ED->getDeclName(); 857 } 858 859 llvm::APSInt Hi = 860 RI->second->getRHS()->EvaluateKnownConstInt(Context); 861 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 862 while (EI != EIend && EI->first < Hi) 863 EI++; 864 if (EI == EIend || EI->first != Hi) 865 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 866 << ED->getDeclName(); 867 } 868 } 869 870 // Check which enum vals aren't in switch 871 CaseValsTy::const_iterator CI = CaseVals.begin(); 872 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 873 bool hasCasesNotInSwitch = false; 874 875 SmallVector<DeclarationName,8> UnhandledNames; 876 877 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){ 878 // Drop unneeded case values 879 llvm::APSInt CIVal; 880 while (CI != CaseVals.end() && CI->first < EI->first) 881 CI++; 882 883 if (CI != CaseVals.end() && CI->first == EI->first) 884 continue; 885 886 // Drop unneeded case ranges 887 for (; RI != CaseRanges.end(); RI++) { 888 llvm::APSInt Hi = 889 RI->second->getRHS()->EvaluateKnownConstInt(Context); 890 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 891 if (EI->first <= Hi) 892 break; 893 } 894 895 if (RI == CaseRanges.end() || EI->first < RI->first) { 896 hasCasesNotInSwitch = true; 897 if (!TheDefaultStmt) 898 UnhandledNames.push_back(EI->second->getDeclName()); 899 } 900 } 901 902 // Produce a nice diagnostic if multiple values aren't handled. 903 switch (UnhandledNames.size()) { 904 case 0: break; 905 case 1: 906 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1) 907 << UnhandledNames[0]; 908 break; 909 case 2: 910 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2) 911 << UnhandledNames[0] << UnhandledNames[1]; 912 break; 913 case 3: 914 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3) 915 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 916 break; 917 default: 918 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases) 919 << (unsigned)UnhandledNames.size() 920 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 921 break; 922 } 923 924 if (!hasCasesNotInSwitch) 925 SS->setAllEnumCasesCovered(); 926 } 927 } 928 929 // FIXME: If the case list was broken is some way, we don't have a good system 930 // to patch it up. Instead, just return the whole substmt as broken. 931 if (CaseListIsErroneous) 932 return StmtError(); 933 934 return Owned(SS); 935} 936 937StmtResult 938Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 939 Decl *CondVar, Stmt *Body) { 940 ExprResult CondResult(Cond.release()); 941 942 VarDecl *ConditionVar = 0; 943 if (CondVar) { 944 ConditionVar = cast<VarDecl>(CondVar); 945 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 946 if (CondResult.isInvalid()) 947 return StmtError(); 948 } 949 Expr *ConditionExpr = CondResult.take(); 950 if (!ConditionExpr) 951 return StmtError(); 952 953 DiagnoseUnusedExprResult(Body); 954 955 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 956 Body, WhileLoc)); 957} 958 959StmtResult 960Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 961 SourceLocation WhileLoc, SourceLocation CondLParen, 962 Expr *Cond, SourceLocation CondRParen) { 963 assert(Cond && "ActOnDoStmt(): missing expression"); 964 965 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc); 966 if (CondResult.isInvalid() || CondResult.isInvalid()) 967 return StmtError(); 968 Cond = CondResult.take(); 969 970 CheckImplicitConversions(Cond, DoLoc); 971 CondResult = MaybeCreateExprWithCleanups(Cond); 972 if (CondResult.isInvalid()) 973 return StmtError(); 974 Cond = CondResult.take(); 975 976 DiagnoseUnusedExprResult(Body); 977 978 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 979} 980 981StmtResult 982Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 983 Stmt *First, FullExprArg second, Decl *secondVar, 984 FullExprArg third, 985 SourceLocation RParenLoc, Stmt *Body) { 986 if (!getLangOptions().CPlusPlus) { 987 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 988 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 989 // declare identifiers for objects having storage class 'auto' or 990 // 'register'. 991 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 992 DI!=DE; ++DI) { 993 VarDecl *VD = dyn_cast<VarDecl>(*DI); 994 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 995 VD = 0; 996 if (VD == 0) 997 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 998 // FIXME: mark decl erroneous! 999 } 1000 } 1001 } 1002 1003 ExprResult SecondResult(second.release()); 1004 VarDecl *ConditionVar = 0; 1005 if (secondVar) { 1006 ConditionVar = cast<VarDecl>(secondVar); 1007 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 1008 if (SecondResult.isInvalid()) 1009 return StmtError(); 1010 } 1011 1012 Expr *Third = third.release().takeAs<Expr>(); 1013 1014 DiagnoseUnusedExprResult(First); 1015 DiagnoseUnusedExprResult(Third); 1016 DiagnoseUnusedExprResult(Body); 1017 1018 return Owned(new (Context) ForStmt(Context, First, 1019 SecondResult.take(), ConditionVar, 1020 Third, Body, ForLoc, LParenLoc, 1021 RParenLoc)); 1022} 1023 1024/// In an Objective C collection iteration statement: 1025/// for (x in y) 1026/// x can be an arbitrary l-value expression. Bind it up as a 1027/// full-expression. 1028StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 1029 CheckImplicitConversions(E); 1030 ExprResult Result = MaybeCreateExprWithCleanups(E); 1031 if (Result.isInvalid()) return StmtError(); 1032 return Owned(static_cast<Stmt*>(Result.get())); 1033} 1034 1035ExprResult 1036Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { 1037 assert(collection); 1038 1039 // Bail out early if we've got a type-dependent expression. 1040 if (collection->isTypeDependent()) return Owned(collection); 1041 1042 // Perform normal l-value conversion. 1043 ExprResult result = DefaultFunctionArrayLvalueConversion(collection); 1044 if (result.isInvalid()) 1045 return ExprError(); 1046 collection = result.take(); 1047 1048 // The operand needs to have object-pointer type. 1049 // TODO: should we do a contextual conversion? 1050 const ObjCObjectPointerType *pointerType = 1051 collection->getType()->getAs<ObjCObjectPointerType>(); 1052 if (!pointerType) 1053 return Diag(forLoc, diag::err_collection_expr_type) 1054 << collection->getType() << collection->getSourceRange(); 1055 1056 // Check that the operand provides 1057 // - countByEnumeratingWithState:objects:count: 1058 const ObjCObjectType *objectType = pointerType->getObjectType(); 1059 ObjCInterfaceDecl *iface = objectType->getInterface(); 1060 1061 // If we have a forward-declared type, we can't do this check. 1062 if (iface && iface->isForwardDecl()) { 1063 // This is ill-formed under ARC. 1064 if (getLangOptions().ObjCAutoRefCount) { 1065 Diag(forLoc, diag::err_arc_collection_forward) 1066 << pointerType->getPointeeType() << collection->getSourceRange(); 1067 } 1068 1069 // Otherwise, if we have any useful type information, check that 1070 // the type declares the appropriate method. 1071 } else if (iface || !objectType->qual_empty()) { 1072 IdentifierInfo *selectorIdents[] = { 1073 &Context.Idents.get("countByEnumeratingWithState"), 1074 &Context.Idents.get("objects"), 1075 &Context.Idents.get("count") 1076 }; 1077 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); 1078 1079 ObjCMethodDecl *method = 0; 1080 1081 // If there's an interface, look in both the public and private APIs. 1082 if (iface) { 1083 method = iface->lookupInstanceMethod(selector); 1084 if (!method) method = LookupPrivateInstanceMethod(selector, iface); 1085 } 1086 1087 // Also check protocol qualifiers. 1088 if (!method) 1089 method = LookupMethodInQualifiedType(selector, pointerType, 1090 /*instance*/ true); 1091 1092 // If we didn't find it anywhere, give up. 1093 if (!method) { 1094 Diag(forLoc, diag::warn_collection_expr_type) 1095 << collection->getType() << selector << collection->getSourceRange(); 1096 } 1097 1098 // TODO: check for an incompatible signature? 1099 } 1100 1101 // Wrap up any cleanups in the expression. 1102 return Owned(MaybeCreateExprWithCleanups(collection)); 1103} 1104 1105StmtResult 1106Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 1107 SourceLocation LParenLoc, 1108 Stmt *First, Expr *Second, 1109 SourceLocation RParenLoc, Stmt *Body) { 1110 if (First) { 1111 QualType FirstType; 1112 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 1113 if (!DS->isSingleDecl()) 1114 return StmtError(Diag((*DS->decl_begin())->getLocation(), 1115 diag::err_toomany_element_decls)); 1116 1117 VarDecl *D = cast<VarDecl>(DS->getSingleDecl()); 1118 FirstType = D->getType(); 1119 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 1120 // declare identifiers for objects having storage class 'auto' or 1121 // 'register'. 1122 if (!D->hasLocalStorage()) 1123 return StmtError(Diag(D->getLocation(), 1124 diag::err_non_variable_decl_in_for)); 1125 } else { 1126 Expr *FirstE = cast<Expr>(First); 1127 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 1128 return StmtError(Diag(First->getLocStart(), 1129 diag::err_selector_element_not_lvalue) 1130 << First->getSourceRange()); 1131 1132 FirstType = static_cast<Expr*>(First)->getType(); 1133 } 1134 if (!FirstType->isDependentType() && 1135 !FirstType->isObjCObjectPointerType() && 1136 !FirstType->isBlockPointerType()) 1137 Diag(ForLoc, diag::err_selector_element_type) 1138 << FirstType << First->getSourceRange(); 1139 } 1140 1141 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 1142 ForLoc, RParenLoc)); 1143} 1144 1145namespace { 1146 1147enum BeginEndFunction { 1148 BEF_begin, 1149 BEF_end 1150}; 1151 1152/// Build a variable declaration for a for-range statement. 1153static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 1154 QualType Type, const char *Name) { 1155 DeclContext *DC = SemaRef.CurContext; 1156 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1157 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1158 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 1159 TInfo, SC_Auto, SC_None); 1160 Decl->setImplicit(); 1161 return Decl; 1162} 1163 1164/// Finish building a variable declaration for a for-range statement. 1165/// \return true if an error occurs. 1166static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 1167 SourceLocation Loc, int diag) { 1168 // Deduce the type for the iterator variable now rather than leaving it to 1169 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 1170 TypeSourceInfo *InitTSI = 0; 1171 if (Init->getType()->isVoidType() || 1172 !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI)) 1173 SemaRef.Diag(Loc, diag) << Init->getType(); 1174 if (!InitTSI) { 1175 Decl->setInvalidDecl(); 1176 return true; 1177 } 1178 Decl->setTypeSourceInfo(InitTSI); 1179 Decl->setType(InitTSI->getType()); 1180 1181 // In ARC, infer lifetime. 1182 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if 1183 // we're doing the equivalent of fast iteration. 1184 if (SemaRef.getLangOptions().ObjCAutoRefCount && 1185 SemaRef.inferObjCARCLifetime(Decl)) 1186 Decl->setInvalidDecl(); 1187 1188 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false, 1189 /*TypeMayContainAuto=*/false); 1190 SemaRef.FinalizeDeclaration(Decl); 1191 SemaRef.CurContext->addHiddenDecl(Decl); 1192 return false; 1193} 1194 1195/// Produce a note indicating which begin/end function was implicitly called 1196/// by a C++0x for-range statement. This is often not obvious from the code, 1197/// nor from the diagnostics produced when analysing the implicit expressions 1198/// required in a for-range statement. 1199void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 1200 BeginEndFunction BEF) { 1201 CallExpr *CE = dyn_cast<CallExpr>(E); 1202 if (!CE) 1203 return; 1204 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1205 if (!D) 1206 return; 1207 SourceLocation Loc = D->getLocation(); 1208 1209 std::string Description; 1210 bool IsTemplate = false; 1211 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 1212 Description = SemaRef.getTemplateArgumentBindingsText( 1213 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 1214 IsTemplate = true; 1215 } 1216 1217 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 1218 << BEF << IsTemplate << Description << E->getType(); 1219} 1220 1221/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the 1222/// given LookupResult is non-empty, it is assumed to describe a member which 1223/// will be invoked. Otherwise, the function will be found via argument 1224/// dependent lookup. 1225static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S, 1226 SourceLocation Loc, 1227 VarDecl *Decl, 1228 BeginEndFunction BEF, 1229 const DeclarationNameInfo &NameInfo, 1230 LookupResult &MemberLookup, 1231 Expr *Range) { 1232 ExprResult CallExpr; 1233 if (!MemberLookup.empty()) { 1234 ExprResult MemberRef = 1235 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc, 1236 /*IsPtr=*/false, CXXScopeSpec(), 1237 /*Qualifier=*/0, MemberLookup, 1238 /*TemplateArgs=*/0); 1239 if (MemberRef.isInvalid()) 1240 return ExprError(); 1241 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), 1242 Loc, 0); 1243 if (CallExpr.isInvalid()) 1244 return ExprError(); 1245 } else { 1246 UnresolvedSet<0> FoundNames; 1247 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace 1248 // std is an associated namespace. 1249 UnresolvedLookupExpr *Fn = 1250 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0, 1251 NestedNameSpecifierLoc(), NameInfo, 1252 /*NeedsADL=*/true, /*Overloaded=*/false, 1253 FoundNames.begin(), FoundNames.end(), 1254 /*LookInStdNamespace=*/true); 1255 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc, 1256 0); 1257 if (CallExpr.isInvalid()) { 1258 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type) 1259 << Range->getType(); 1260 return ExprError(); 1261 } 1262 } 1263 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc, 1264 diag::err_for_range_iter_deduction_failure)) { 1265 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF); 1266 return ExprError(); 1267 } 1268 return CallExpr; 1269} 1270 1271} 1272 1273/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement. 1274/// 1275/// C++0x [stmt.ranged]: 1276/// A range-based for statement is equivalent to 1277/// 1278/// { 1279/// auto && __range = range-init; 1280/// for ( auto __begin = begin-expr, 1281/// __end = end-expr; 1282/// __begin != __end; 1283/// ++__begin ) { 1284/// for-range-declaration = *__begin; 1285/// statement 1286/// } 1287/// } 1288/// 1289/// The body of the loop is not available yet, since it cannot be analysed until 1290/// we have determined the type of the for-range-declaration. 1291StmtResult 1292Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 1293 Stmt *First, SourceLocation ColonLoc, Expr *Range, 1294 SourceLocation RParenLoc) { 1295 if (!First || !Range) 1296 return StmtError(); 1297 1298 DeclStmt *DS = dyn_cast<DeclStmt>(First); 1299 assert(DS && "first part of for range not a decl stmt"); 1300 1301 if (!DS->isSingleDecl()) { 1302 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range); 1303 return StmtError(); 1304 } 1305 if (DS->getSingleDecl()->isInvalidDecl()) 1306 return StmtError(); 1307 1308 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) 1309 return StmtError(); 1310 1311 // Build auto && __range = range-init 1312 SourceLocation RangeLoc = Range->getLocStart(); 1313 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 1314 Context.getAutoRRefDeductType(), 1315 "__range"); 1316 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 1317 diag::err_for_range_deduction_failure)) 1318 return StmtError(); 1319 1320 // Claim the type doesn't contain auto: we've already done the checking. 1321 DeclGroupPtrTy RangeGroup = 1322 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false); 1323 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 1324 if (RangeDecl.isInvalid()) 1325 return StmtError(); 1326 1327 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(), 1328 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS, 1329 RParenLoc); 1330} 1331 1332/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement. 1333StmtResult 1334Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, 1335 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond, 1336 Expr *Inc, Stmt *LoopVarDecl, 1337 SourceLocation RParenLoc) { 1338 Scope *S = getCurScope(); 1339 1340 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 1341 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 1342 QualType RangeVarType = RangeVar->getType(); 1343 1344 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 1345 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 1346 1347 StmtResult BeginEndDecl = BeginEnd; 1348 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 1349 1350 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) { 1351 SourceLocation RangeLoc = RangeVar->getLocation(); 1352 1353 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); 1354 1355 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1356 VK_LValue, ColonLoc); 1357 if (BeginRangeRef.isInvalid()) 1358 return StmtError(); 1359 1360 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1361 VK_LValue, ColonLoc); 1362 if (EndRangeRef.isInvalid()) 1363 return StmtError(); 1364 1365 QualType AutoType = Context.getAutoDeductType(); 1366 Expr *Range = RangeVar->getInit(); 1367 if (!Range) 1368 return StmtError(); 1369 QualType RangeType = Range->getType(); 1370 1371 if (RequireCompleteType(RangeLoc, RangeType, 1372 PDiag(diag::err_for_range_incomplete_type))) 1373 return StmtError(); 1374 1375 // Build auto __begin = begin-expr, __end = end-expr. 1376 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1377 "__begin"); 1378 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1379 "__end"); 1380 1381 // Build begin-expr and end-expr and attach to __begin and __end variables. 1382 ExprResult BeginExpr, EndExpr; 1383 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 1384 // - if _RangeT is an array type, begin-expr and end-expr are __range and 1385 // __range + __bound, respectively, where __bound is the array bound. If 1386 // _RangeT is an array of unknown size or an array of incomplete type, 1387 // the program is ill-formed; 1388 1389 // begin-expr is __range. 1390 BeginExpr = BeginRangeRef; 1391 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, 1392 diag::err_for_range_iter_deduction_failure)) { 1393 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1394 return StmtError(); 1395 } 1396 1397 // Find the array bound. 1398 ExprResult BoundExpr; 1399 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 1400 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(), 1401 Context.getPointerDiffType(), 1402 RangeLoc)); 1403 else if (const VariableArrayType *VAT = 1404 dyn_cast<VariableArrayType>(UnqAT)) 1405 BoundExpr = VAT->getSizeExpr(); 1406 else { 1407 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 1408 // UnqAT is not incomplete and Range is not type-dependent. 1409 llvm_unreachable("Unexpected array type in for-range"); 1410 } 1411 1412 // end-expr is __range + __bound. 1413 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), 1414 BoundExpr.get()); 1415 if (EndExpr.isInvalid()) 1416 return StmtError(); 1417 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 1418 diag::err_for_range_iter_deduction_failure)) { 1419 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1420 return StmtError(); 1421 } 1422 } else { 1423 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"), 1424 ColonLoc); 1425 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"), 1426 ColonLoc); 1427 1428 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName); 1429 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName); 1430 1431 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 1432 // - if _RangeT is a class type, the unqualified-ids begin and end are 1433 // looked up in the scope of class _RangeT as if by class member access 1434 // lookup (3.4.5), and if either (or both) finds at least one 1435 // declaration, begin-expr and end-expr are __range.begin() and 1436 // __range.end(), respectively; 1437 LookupQualifiedName(BeginMemberLookup, D); 1438 LookupQualifiedName(EndMemberLookup, D); 1439 1440 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 1441 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch) 1442 << RangeType << BeginMemberLookup.empty(); 1443 return StmtError(); 1444 } 1445 } else { 1446 // - otherwise, begin-expr and end-expr are begin(__range) and 1447 // end(__range), respectively, where begin and end are looked up with 1448 // argument-dependent lookup (3.4.2). For the purposes of this name 1449 // lookup, namespace std is an associated namespace. 1450 } 1451 1452 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar, 1453 BEF_begin, BeginNameInfo, 1454 BeginMemberLookup, 1455 BeginRangeRef.get()); 1456 if (BeginExpr.isInvalid()) 1457 return StmtError(); 1458 1459 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar, 1460 BEF_end, EndNameInfo, 1461 EndMemberLookup, EndRangeRef.get()); 1462 if (EndExpr.isInvalid()) 1463 return StmtError(); 1464 } 1465 1466 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same. 1467 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 1468 if (!Context.hasSameType(BeginType, EndType)) { 1469 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ) 1470 << BeginType << EndType; 1471 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1472 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1473 } 1474 1475 Decl *BeginEndDecls[] = { BeginVar, EndVar }; 1476 // Claim the type doesn't contain auto: we've already done the checking. 1477 DeclGroupPtrTy BeginEndGroup = 1478 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false); 1479 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc); 1480 1481 const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); 1482 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1483 VK_LValue, ColonLoc); 1484 if (BeginRef.isInvalid()) 1485 return StmtError(); 1486 1487 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 1488 VK_LValue, ColonLoc); 1489 if (EndRef.isInvalid()) 1490 return StmtError(); 1491 1492 // Build and check __begin != __end expression. 1493 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 1494 BeginRef.get(), EndRef.get()); 1495 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get()); 1496 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get()); 1497 if (NotEqExpr.isInvalid()) { 1498 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1499 if (!Context.hasSameType(BeginType, EndType)) 1500 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1501 return StmtError(); 1502 } 1503 1504 // Build and check ++__begin expression. 1505 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1506 VK_LValue, ColonLoc); 1507 if (BeginRef.isInvalid()) 1508 return StmtError(); 1509 1510 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 1511 IncrExpr = ActOnFinishFullExpr(IncrExpr.get()); 1512 if (IncrExpr.isInvalid()) { 1513 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1514 return StmtError(); 1515 } 1516 1517 // Build and check *__begin expression. 1518 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1519 VK_LValue, ColonLoc); 1520 if (BeginRef.isInvalid()) 1521 return StmtError(); 1522 1523 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 1524 if (DerefExpr.isInvalid()) { 1525 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1526 return StmtError(); 1527 } 1528 1529 // Attach *__begin as initializer for VD. 1530 if (!LoopVar->isInvalidDecl()) { 1531 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false, 1532 /*TypeMayContainAuto=*/true); 1533 if (LoopVar->isInvalidDecl()) 1534 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1535 } 1536 } else { 1537 // The range is implicitly used as a placeholder when it is dependent. 1538 RangeVar->setUsed(); 1539 } 1540 1541 return Owned(new (Context) CXXForRangeStmt(RangeDS, 1542 cast_or_null<DeclStmt>(BeginEndDecl.get()), 1543 NotEqExpr.take(), IncrExpr.take(), 1544 LoopVarDS, /*Body=*/0, ForLoc, 1545 ColonLoc, RParenLoc)); 1546} 1547 1548/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 1549/// This is a separate step from ActOnCXXForRangeStmt because analysis of the 1550/// body cannot be performed until after the type of the range variable is 1551/// determined. 1552StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 1553 if (!S || !B) 1554 return StmtError(); 1555 1556 cast<CXXForRangeStmt>(S)->setBody(B); 1557 return S; 1558} 1559 1560StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 1561 SourceLocation LabelLoc, 1562 LabelDecl *TheDecl) { 1563 getCurFunction()->setHasBranchIntoScope(); 1564 TheDecl->setUsed(); 1565 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc)); 1566} 1567 1568StmtResult 1569Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 1570 Expr *E) { 1571 // Convert operand to void* 1572 if (!E->isTypeDependent()) { 1573 QualType ETy = E->getType(); 1574 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 1575 ExprResult ExprRes = Owned(E); 1576 AssignConvertType ConvTy = 1577 CheckSingleAssignmentConstraints(DestTy, ExprRes); 1578 if (ExprRes.isInvalid()) 1579 return StmtError(); 1580 E = ExprRes.take(); 1581 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 1582 return StmtError(); 1583 } 1584 1585 getCurFunction()->setHasIndirectGoto(); 1586 1587 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 1588} 1589 1590StmtResult 1591Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 1592 Scope *S = CurScope->getContinueParent(); 1593 if (!S) { 1594 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 1595 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 1596 } 1597 1598 return Owned(new (Context) ContinueStmt(ContinueLoc)); 1599} 1600 1601StmtResult 1602Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1603 Scope *S = CurScope->getBreakParent(); 1604 if (!S) { 1605 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1606 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1607 } 1608 1609 return Owned(new (Context) BreakStmt(BreakLoc)); 1610} 1611 1612/// \brief Determine whether the given expression is a candidate for 1613/// copy elision in either a return statement or a throw expression. 1614/// 1615/// \param ReturnType If we're determining the copy elision candidate for 1616/// a return statement, this is the return type of the function. If we're 1617/// determining the copy elision candidate for a throw expression, this will 1618/// be a NULL type. 1619/// 1620/// \param E The expression being returned from the function or block, or 1621/// being thrown. 1622/// 1623/// \param AllowFunctionParameter Whether we allow function parameters to 1624/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but 1625/// we re-use this logic to determine whether we should try to move as part of 1626/// a return or throw (which does allow function parameters). 1627/// 1628/// \returns The NRVO candidate variable, if the return statement may use the 1629/// NRVO, or NULL if there is no such candidate. 1630const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 1631 Expr *E, 1632 bool AllowFunctionParameter) { 1633 QualType ExprType = E->getType(); 1634 // - in a return statement in a function with ... 1635 // ... a class return type ... 1636 if (!ReturnType.isNull()) { 1637 if (!ReturnType->isRecordType()) 1638 return 0; 1639 // ... the same cv-unqualified type as the function return type ... 1640 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType)) 1641 return 0; 1642 } 1643 1644 // ... the expression is the name of a non-volatile automatic object 1645 // (other than a function or catch-clause parameter)) ... 1646 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 1647 if (!DR) 1648 return 0; 1649 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1650 if (!VD) 1651 return 0; 1652 1653 if (VD->hasLocalStorage() && !VD->isExceptionVariable() && 1654 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() && 1655 !VD->getType().isVolatileQualified() && 1656 ((VD->getKind() == Decl::Var) || 1657 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar))) 1658 return VD; 1659 1660 return 0; 1661} 1662 1663/// \brief Perform the initialization of a potentially-movable value, which 1664/// is the result of return value. 1665/// 1666/// This routine implements C++0x [class.copy]p33, which attempts to treat 1667/// returned lvalues as rvalues in certain cases (to prefer move construction), 1668/// then falls back to treating them as lvalues if that failed. 1669ExprResult 1670Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1671 const VarDecl *NRVOCandidate, 1672 QualType ResultType, 1673 Expr *Value, 1674 bool AllowNRVO) { 1675 // C++0x [class.copy]p33: 1676 // When the criteria for elision of a copy operation are met or would 1677 // be met save for the fact that the source object is a function 1678 // parameter, and the object to be copied is designated by an lvalue, 1679 // overload resolution to select the constructor for the copy is first 1680 // performed as if the object were designated by an rvalue. 1681 ExprResult Res = ExprError(); 1682 if (AllowNRVO && 1683 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) { 1684 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 1685 Value->getType(), CK_LValueToRValue, 1686 Value, VK_XValue); 1687 1688 Expr *InitExpr = &AsRvalue; 1689 InitializationKind Kind 1690 = InitializationKind::CreateCopy(Value->getLocStart(), 1691 Value->getLocStart()); 1692 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1); 1693 1694 // [...] If overload resolution fails, or if the type of the first 1695 // parameter of the selected constructor is not an rvalue reference 1696 // to the object's type (possibly cv-qualified), overload resolution 1697 // is performed again, considering the object as an lvalue. 1698 if (Seq) { 1699 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 1700 StepEnd = Seq.step_end(); 1701 Step != StepEnd; ++Step) { 1702 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization) 1703 continue; 1704 1705 CXXConstructorDecl *Constructor 1706 = cast<CXXConstructorDecl>(Step->Function.Function); 1707 1708 const RValueReferenceType *RRefType 1709 = Constructor->getParamDecl(0)->getType() 1710 ->getAs<RValueReferenceType>(); 1711 1712 // If we don't meet the criteria, break out now. 1713 if (!RRefType || 1714 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 1715 Context.getTypeDeclType(Constructor->getParent()))) 1716 break; 1717 1718 // Promote "AsRvalue" to the heap, since we now need this 1719 // expression node to persist. 1720 Value = ImplicitCastExpr::Create(Context, Value->getType(), 1721 CK_LValueToRValue, Value, 0, 1722 VK_XValue); 1723 1724 // Complete type-checking the initialization of the return type 1725 // using the constructor we found. 1726 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1)); 1727 } 1728 } 1729 } 1730 1731 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 1732 // above, or overload resolution failed. Either way, we need to try 1733 // (again) now with the return value expression as written. 1734 if (Res.isInvalid()) 1735 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 1736 1737 return Res; 1738} 1739 1740/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 1741/// 1742StmtResult 1743Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1744 // If this is the first return we've seen in the block, infer the type of 1745 // the block from it. 1746 BlockScopeInfo *CurBlock = getCurBlock(); 1747 if (CurBlock->ReturnType.isNull()) { 1748 if (RetValExp) { 1749 // Don't call UsualUnaryConversions(), since we don't want to do 1750 // integer promotions here. 1751 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 1752 if (Result.isInvalid()) 1753 return StmtError(); 1754 RetValExp = Result.take(); 1755 1756 if (!RetValExp->isTypeDependent()) { 1757 CurBlock->ReturnType = RetValExp->getType(); 1758 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 1759 // We have to remove a 'const' added to copied-in variable which was 1760 // part of the implementation spec. and not the actual qualifier for 1761 // the variable. 1762 if (CDRE->isConstQualAdded()) 1763 CurBlock->ReturnType.removeLocalConst(); // FIXME: local??? 1764 } 1765 } else 1766 CurBlock->ReturnType = Context.DependentTy; 1767 } else 1768 CurBlock->ReturnType = Context.VoidTy; 1769 } 1770 QualType FnRetType = CurBlock->ReturnType; 1771 1772 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 1773 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr) 1774 << getCurFunctionOrMethodDecl()->getDeclName(); 1775 return StmtError(); 1776 } 1777 1778 // Otherwise, verify that this result type matches the previous one. We are 1779 // pickier with blocks than for normal functions because we don't have GCC 1780 // compatibility to worry about here. 1781 const VarDecl *NRVOCandidate = 0; 1782 if (FnRetType->isDependentType()) { 1783 // Delay processing for now. TODO: there are lots of dependent 1784 // types we can conclusively prove aren't void. 1785 } else if (FnRetType->isVoidType()) { 1786 if (RetValExp && 1787 !(getLangOptions().CPlusPlus && 1788 (RetValExp->isTypeDependent() || 1789 RetValExp->getType()->isVoidType()))) { 1790 Diag(ReturnLoc, diag::err_return_block_has_expr); 1791 RetValExp = 0; 1792 } 1793 } else if (!RetValExp) { 1794 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 1795 } else if (!RetValExp->isTypeDependent()) { 1796 // we have a non-void block with an expression, continue checking 1797 1798 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1799 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1800 // function return. 1801 1802 // In C++ the return statement is handled via a copy initialization. 1803 // the C version of which boils down to CheckSingleAssignmentConstraints. 1804 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1805 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1806 FnRetType, 1807 NRVOCandidate != 0); 1808 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1809 FnRetType, RetValExp); 1810 if (Res.isInvalid()) { 1811 // FIXME: Cleanup temporaries here, anyway? 1812 return StmtError(); 1813 } 1814 RetValExp = Res.take(); 1815 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1816 } 1817 1818 if (RetValExp) { 1819 CheckImplicitConversions(RetValExp, ReturnLoc); 1820 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1821 } 1822 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 1823 NRVOCandidate); 1824 1825 // If we need to check for the named return value optimization, save the 1826 // return statement in our scope for later processing. 1827 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1828 !CurContext->isDependentContext()) 1829 FunctionScopes.back()->Returns.push_back(Result); 1830 1831 return Owned(Result); 1832} 1833 1834StmtResult 1835Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1836 // Check for unexpanded parameter packs. 1837 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 1838 return StmtError(); 1839 1840 if (getCurBlock()) 1841 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 1842 1843 QualType FnRetType; 1844 QualType DeclaredRetType; 1845 if (const FunctionDecl *FD = getCurFunctionDecl()) { 1846 FnRetType = FD->getResultType(); 1847 DeclaredRetType = FnRetType; 1848 if (FD->hasAttr<NoReturnAttr>() || 1849 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 1850 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 1851 << getCurFunctionOrMethodDecl()->getDeclName(); 1852 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1853 DeclaredRetType = MD->getResultType(); 1854 if (MD->hasRelatedResultType() && MD->getClassInterface()) { 1855 // In the implementation of a method with a related return type, the 1856 // type used to type-check the validity of return statements within the 1857 // method body is a pointer to the type of the class being implemented. 1858 FnRetType = Context.getObjCInterfaceType(MD->getClassInterface()); 1859 FnRetType = Context.getObjCObjectPointerType(FnRetType); 1860 } else { 1861 FnRetType = DeclaredRetType; 1862 } 1863 } else // If we don't have a function/method context, bail. 1864 return StmtError(); 1865 1866 ReturnStmt *Result = 0; 1867 if (FnRetType->isVoidType()) { 1868 if (RetValExp) { 1869 if (!RetValExp->isTypeDependent()) { 1870 // C99 6.8.6.4p1 (ext_ since GCC warns) 1871 unsigned D = diag::ext_return_has_expr; 1872 if (RetValExp->getType()->isVoidType()) 1873 D = diag::ext_return_has_void_expr; 1874 else { 1875 ExprResult Result = Owned(RetValExp); 1876 Result = IgnoredValueConversions(Result.take()); 1877 if (Result.isInvalid()) 1878 return StmtError(); 1879 RetValExp = Result.take(); 1880 RetValExp = ImpCastExprToType(RetValExp, 1881 Context.VoidTy, CK_ToVoid).take(); 1882 } 1883 1884 // return (some void expression); is legal in C++. 1885 if (D != diag::ext_return_has_void_expr || 1886 !getLangOptions().CPlusPlus) { 1887 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1888 1889 int FunctionKind = 0; 1890 if (isa<ObjCMethodDecl>(CurDecl)) 1891 FunctionKind = 1; 1892 else if (isa<CXXConstructorDecl>(CurDecl)) 1893 FunctionKind = 2; 1894 else if (isa<CXXDestructorDecl>(CurDecl)) 1895 FunctionKind = 3; 1896 1897 Diag(ReturnLoc, D) 1898 << CurDecl->getDeclName() << FunctionKind 1899 << RetValExp->getSourceRange(); 1900 } 1901 } 1902 1903 CheckImplicitConversions(RetValExp, ReturnLoc); 1904 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1905 } 1906 1907 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1908 } else if (!RetValExp && !FnRetType->isDependentType()) { 1909 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 1910 // C99 6.8.6.4p1 (ext_ since GCC warns) 1911 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 1912 1913 if (FunctionDecl *FD = getCurFunctionDecl()) 1914 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 1915 else 1916 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 1917 Result = new (Context) ReturnStmt(ReturnLoc); 1918 } else { 1919 const VarDecl *NRVOCandidate = 0; 1920 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1921 // we have a non-void function with an expression, continue checking 1922 1923 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1924 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1925 // function return. 1926 1927 // In C++ the return statement is handled via a copy initialization, 1928 // the C version of which boils down to CheckSingleAssignmentConstraints. 1929 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1930 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1931 FnRetType, 1932 NRVOCandidate != 0); 1933 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1934 FnRetType, RetValExp); 1935 if (Res.isInvalid()) { 1936 // FIXME: Cleanup temporaries here, anyway? 1937 return StmtError(); 1938 } 1939 1940 RetValExp = Res.takeAs<Expr>(); 1941 if (RetValExp) 1942 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1943 } 1944 1945 if (RetValExp) { 1946 // If we type-checked an Objective-C method's return type based 1947 // on a related return type, we may need to adjust the return 1948 // type again. Do so now. 1949 if (DeclaredRetType != FnRetType) { 1950 ExprResult result = PerformImplicitConversion(RetValExp, 1951 DeclaredRetType, 1952 AA_Returning); 1953 if (result.isInvalid()) return StmtError(); 1954 RetValExp = result.take(); 1955 } 1956 1957 CheckImplicitConversions(RetValExp, ReturnLoc); 1958 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1959 } 1960 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1961 } 1962 1963 // If we need to check for the named return value optimization, save the 1964 // return statement in our scope for later processing. 1965 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1966 !CurContext->isDependentContext()) 1967 FunctionScopes.back()->Returns.push_back(Result); 1968 1969 return Owned(Result); 1970} 1971 1972/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 1973/// ignore "noop" casts in places where an lvalue is required by an inline asm. 1974/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 1975/// provide a strong guidance to not use it. 1976/// 1977/// This method checks to see if the argument is an acceptable l-value and 1978/// returns false if it is a case we can handle. 1979static bool CheckAsmLValue(const Expr *E, Sema &S) { 1980 // Type dependent expressions will be checked during instantiation. 1981 if (E->isTypeDependent()) 1982 return false; 1983 1984 if (E->isLValue()) 1985 return false; // Cool, this is an lvalue. 1986 1987 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 1988 // are supposed to allow. 1989 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 1990 if (E != E2 && E2->isLValue()) { 1991 if (!S.getLangOptions().HeinousExtensions) 1992 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 1993 << E->getSourceRange(); 1994 else 1995 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 1996 << E->getSourceRange(); 1997 // Accept, even if we emitted an error diagnostic. 1998 return false; 1999 } 2000 2001 // None of the above, just randomly invalid non-lvalue. 2002 return true; 2003} 2004 2005/// isOperandMentioned - Return true if the specified operand # is mentioned 2006/// anywhere in the decomposed asm string. 2007static bool isOperandMentioned(unsigned OpNo, 2008 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) { 2009 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { 2010 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; 2011 if (!Piece.isOperand()) continue; 2012 2013 // If this is a reference to the input and if the input was the smaller 2014 // one, then we have to reject this asm. 2015 if (Piece.getOperandNo() == OpNo) 2016 return true; 2017 } 2018 2019 return false; 2020} 2021 2022StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple, 2023 bool IsVolatile, unsigned NumOutputs, 2024 unsigned NumInputs, IdentifierInfo **Names, 2025 MultiExprArg constraints, MultiExprArg exprs, 2026 Expr *asmString, MultiExprArg clobbers, 2027 SourceLocation RParenLoc, bool MSAsm) { 2028 unsigned NumClobbers = clobbers.size(); 2029 StringLiteral **Constraints = 2030 reinterpret_cast<StringLiteral**>(constraints.get()); 2031 Expr **Exprs = exprs.get(); 2032 StringLiteral *AsmString = cast<StringLiteral>(asmString); 2033 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 2034 2035 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 2036 2037 // The parser verifies that there is a string literal here. 2038 if (!AsmString->isAscii()) 2039 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 2040 << AsmString->getSourceRange()); 2041 2042 for (unsigned i = 0; i != NumOutputs; i++) { 2043 StringLiteral *Literal = Constraints[i]; 2044 if (!Literal->isAscii()) 2045 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2046 << Literal->getSourceRange()); 2047 2048 StringRef OutputName; 2049 if (Names[i]) 2050 OutputName = Names[i]->getName(); 2051 2052 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 2053 if (!Context.getTargetInfo().validateOutputConstraint(Info)) 2054 return StmtError(Diag(Literal->getLocStart(), 2055 diag::err_asm_invalid_output_constraint) 2056 << Info.getConstraintStr()); 2057 2058 // Check that the output exprs are valid lvalues. 2059 Expr *OutputExpr = Exprs[i]; 2060 if (CheckAsmLValue(OutputExpr, *this)) { 2061 return StmtError(Diag(OutputExpr->getLocStart(), 2062 diag::err_asm_invalid_lvalue_in_output) 2063 << OutputExpr->getSourceRange()); 2064 } 2065 2066 OutputConstraintInfos.push_back(Info); 2067 } 2068 2069 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 2070 2071 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 2072 StringLiteral *Literal = Constraints[i]; 2073 if (!Literal->isAscii()) 2074 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2075 << Literal->getSourceRange()); 2076 2077 StringRef InputName; 2078 if (Names[i]) 2079 InputName = Names[i]->getName(); 2080 2081 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 2082 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(), 2083 NumOutputs, Info)) { 2084 return StmtError(Diag(Literal->getLocStart(), 2085 diag::err_asm_invalid_input_constraint) 2086 << Info.getConstraintStr()); 2087 } 2088 2089 Expr *InputExpr = Exprs[i]; 2090 2091 // Only allow void types for memory constraints. 2092 if (Info.allowsMemory() && !Info.allowsRegister()) { 2093 if (CheckAsmLValue(InputExpr, *this)) 2094 return StmtError(Diag(InputExpr->getLocStart(), 2095 diag::err_asm_invalid_lvalue_in_input) 2096 << Info.getConstraintStr() 2097 << InputExpr->getSourceRange()); 2098 } 2099 2100 if (Info.allowsRegister()) { 2101 if (InputExpr->getType()->isVoidType()) { 2102 return StmtError(Diag(InputExpr->getLocStart(), 2103 diag::err_asm_invalid_type_in_input) 2104 << InputExpr->getType() << Info.getConstraintStr() 2105 << InputExpr->getSourceRange()); 2106 } 2107 } 2108 2109 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); 2110 if (Result.isInvalid()) 2111 return StmtError(); 2112 2113 Exprs[i] = Result.take(); 2114 InputConstraintInfos.push_back(Info); 2115 } 2116 2117 // Check that the clobbers are valid. 2118 for (unsigned i = 0; i != NumClobbers; i++) { 2119 StringLiteral *Literal = Clobbers[i]; 2120 if (!Literal->isAscii()) 2121 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2122 << Literal->getSourceRange()); 2123 2124 StringRef Clobber = Literal->getString(); 2125 2126 if (!Context.getTargetInfo().isValidClobber(Clobber)) 2127 return StmtError(Diag(Literal->getLocStart(), 2128 diag::err_asm_unknown_register_name) << Clobber); 2129 } 2130 2131 AsmStmt *NS = 2132 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 2133 NumOutputs, NumInputs, Names, Constraints, Exprs, 2134 AsmString, NumClobbers, Clobbers, RParenLoc); 2135 // Validate the asm string, ensuring it makes sense given the operands we 2136 // have. 2137 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 2138 unsigned DiagOffs; 2139 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 2140 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 2141 << AsmString->getSourceRange(); 2142 return StmtError(); 2143 } 2144 2145 // Validate tied input operands for type mismatches. 2146 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 2147 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 2148 2149 // If this is a tied constraint, verify that the output and input have 2150 // either exactly the same type, or that they are int/ptr operands with the 2151 // same size (int/long, int*/long, are ok etc). 2152 if (!Info.hasTiedOperand()) continue; 2153 2154 unsigned TiedTo = Info.getTiedOperand(); 2155 unsigned InputOpNo = i+NumOutputs; 2156 Expr *OutputExpr = Exprs[TiedTo]; 2157 Expr *InputExpr = Exprs[InputOpNo]; 2158 2159 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent()) 2160 continue; 2161 2162 QualType InTy = InputExpr->getType(); 2163 QualType OutTy = OutputExpr->getType(); 2164 if (Context.hasSameType(InTy, OutTy)) 2165 continue; // All types can be tied to themselves. 2166 2167 // Decide if the input and output are in the same domain (integer/ptr or 2168 // floating point. 2169 enum AsmDomain { 2170 AD_Int, AD_FP, AD_Other 2171 } InputDomain, OutputDomain; 2172 2173 if (InTy->isIntegerType() || InTy->isPointerType()) 2174 InputDomain = AD_Int; 2175 else if (InTy->isRealFloatingType()) 2176 InputDomain = AD_FP; 2177 else 2178 InputDomain = AD_Other; 2179 2180 if (OutTy->isIntegerType() || OutTy->isPointerType()) 2181 OutputDomain = AD_Int; 2182 else if (OutTy->isRealFloatingType()) 2183 OutputDomain = AD_FP; 2184 else 2185 OutputDomain = AD_Other; 2186 2187 // They are ok if they are the same size and in the same domain. This 2188 // allows tying things like: 2189 // void* to int* 2190 // void* to int if they are the same size. 2191 // double to long double if they are the same size. 2192 // 2193 uint64_t OutSize = Context.getTypeSize(OutTy); 2194 uint64_t InSize = Context.getTypeSize(InTy); 2195 if (OutSize == InSize && InputDomain == OutputDomain && 2196 InputDomain != AD_Other) 2197 continue; 2198 2199 // If the smaller input/output operand is not mentioned in the asm string, 2200 // then we can promote the smaller one to a larger input and the asm string 2201 // won't notice. 2202 bool SmallerValueMentioned = false; 2203 2204 // If this is a reference to the input and if the input was the smaller 2205 // one, then we have to reject this asm. 2206 if (isOperandMentioned(InputOpNo, Pieces)) { 2207 // This is a use in the asm string of the smaller operand. Since we 2208 // codegen this by promoting to a wider value, the asm will get printed 2209 // "wrong". 2210 SmallerValueMentioned |= InSize < OutSize; 2211 } 2212 if (isOperandMentioned(TiedTo, Pieces)) { 2213 // If this is a reference to the output, and if the output is the larger 2214 // value, then it's ok because we'll promote the input to the larger type. 2215 SmallerValueMentioned |= OutSize < InSize; 2216 } 2217 2218 // If the smaller value wasn't mentioned in the asm string, and if the 2219 // output was a register, just extend the shorter one to the size of the 2220 // larger one. 2221 if (!SmallerValueMentioned && InputDomain != AD_Other && 2222 OutputConstraintInfos[TiedTo].allowsRegister()) 2223 continue; 2224 2225 // Either both of the operands were mentioned or the smaller one was 2226 // mentioned. One more special case that we'll allow: if the tied input is 2227 // integer, unmentioned, and is a constant, then we'll allow truncating it 2228 // down to the size of the destination. 2229 if (InputDomain == AD_Int && OutputDomain == AD_Int && 2230 !isOperandMentioned(InputOpNo, Pieces) && 2231 InputExpr->isEvaluatable(Context)) { 2232 CastKind castKind = 2233 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); 2234 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take(); 2235 Exprs[InputOpNo] = InputExpr; 2236 NS->setInputExpr(i, InputExpr); 2237 continue; 2238 } 2239 2240 Diag(InputExpr->getLocStart(), 2241 diag::err_asm_tying_incompatible_types) 2242 << InTy << OutTy << OutputExpr->getSourceRange() 2243 << InputExpr->getSourceRange(); 2244 return StmtError(); 2245 } 2246 2247 return Owned(NS); 2248} 2249 2250StmtResult 2251Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 2252 SourceLocation RParen, Decl *Parm, 2253 Stmt *Body) { 2254 VarDecl *Var = cast_or_null<VarDecl>(Parm); 2255 if (Var && Var->isInvalidDecl()) 2256 return StmtError(); 2257 2258 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 2259} 2260 2261StmtResult 2262Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 2263 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 2264} 2265 2266StmtResult 2267Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2268 MultiStmtArg CatchStmts, Stmt *Finally) { 2269 if (!getLangOptions().ObjCExceptions) 2270 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 2271 2272 getCurFunction()->setHasBranchProtectedScope(); 2273 unsigned NumCatchStmts = CatchStmts.size(); 2274 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 2275 CatchStmts.release(), 2276 NumCatchStmts, 2277 Finally)); 2278} 2279 2280StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, 2281 Expr *Throw) { 2282 if (Throw) { 2283 Throw = MaybeCreateExprWithCleanups(Throw); 2284 ExprResult Result = DefaultLvalueConversion(Throw); 2285 if (Result.isInvalid()) 2286 return StmtError(); 2287 2288 Throw = Result.take(); 2289 QualType ThrowType = Throw->getType(); 2290 // Make sure the expression type is an ObjC pointer or "void *". 2291 if (!ThrowType->isDependentType() && 2292 !ThrowType->isObjCObjectPointerType()) { 2293 const PointerType *PT = ThrowType->getAs<PointerType>(); 2294 if (!PT || !PT->getPointeeType()->isVoidType()) 2295 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 2296 << Throw->getType() << Throw->getSourceRange()); 2297 } 2298 } 2299 2300 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 2301} 2302 2303StmtResult 2304Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2305 Scope *CurScope) { 2306 if (!getLangOptions().ObjCExceptions) 2307 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 2308 2309 if (!Throw) { 2310 // @throw without an expression designates a rethrow (which much occur 2311 // in the context of an @catch clause). 2312 Scope *AtCatchParent = CurScope; 2313 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 2314 AtCatchParent = AtCatchParent->getParent(); 2315 if (!AtCatchParent) 2316 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 2317 } 2318 2319 return BuildObjCAtThrowStmt(AtLoc, Throw); 2320} 2321 2322ExprResult 2323Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { 2324 ExprResult result = DefaultLvalueConversion(operand); 2325 if (result.isInvalid()) 2326 return ExprError(); 2327 operand = result.take(); 2328 2329 // Make sure the expression type is an ObjC pointer or "void *". 2330 QualType type = operand->getType(); 2331 if (!type->isDependentType() && 2332 !type->isObjCObjectPointerType()) { 2333 const PointerType *pointerType = type->getAs<PointerType>(); 2334 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) 2335 return Diag(atLoc, diag::error_objc_synchronized_expects_object) 2336 << type << operand->getSourceRange(); 2337 } 2338 2339 // The operand to @synchronized is a full-expression. 2340 return MaybeCreateExprWithCleanups(operand); 2341} 2342 2343StmtResult 2344Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 2345 Stmt *SyncBody) { 2346 // We can't jump into or indirect-jump out of a @synchronized block. 2347 getCurFunction()->setHasBranchProtectedScope(); 2348 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 2349} 2350 2351/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 2352/// and creates a proper catch handler from them. 2353StmtResult 2354Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 2355 Stmt *HandlerBlock) { 2356 // There's nothing to test that ActOnExceptionDecl didn't already test. 2357 return Owned(new (Context) CXXCatchStmt(CatchLoc, 2358 cast_or_null<VarDecl>(ExDecl), 2359 HandlerBlock)); 2360} 2361 2362StmtResult 2363Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { 2364 getCurFunction()->setHasBranchProtectedScope(); 2365 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body)); 2366} 2367 2368namespace { 2369 2370class TypeWithHandler { 2371 QualType t; 2372 CXXCatchStmt *stmt; 2373public: 2374 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 2375 : t(type), stmt(statement) {} 2376 2377 // An arbitrary order is fine as long as it places identical 2378 // types next to each other. 2379 bool operator<(const TypeWithHandler &y) const { 2380 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 2381 return true; 2382 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 2383 return false; 2384 else 2385 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 2386 } 2387 2388 bool operator==(const TypeWithHandler& other) const { 2389 return t == other.t; 2390 } 2391 2392 CXXCatchStmt *getCatchStmt() const { return stmt; } 2393 SourceLocation getTypeSpecStartLoc() const { 2394 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 2395 } 2396}; 2397 2398} 2399 2400/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 2401/// handlers and creates a try statement from them. 2402StmtResult 2403Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2404 MultiStmtArg RawHandlers) { 2405 // Don't report an error if 'try' is used in system headers. 2406 if (!getLangOptions().CXXExceptions && 2407 !getSourceManager().isInSystemHeader(TryLoc)) 2408 Diag(TryLoc, diag::err_exceptions_disabled) << "try"; 2409 2410 unsigned NumHandlers = RawHandlers.size(); 2411 assert(NumHandlers > 0 && 2412 "The parser shouldn't call this if there are no handlers."); 2413 Stmt **Handlers = RawHandlers.get(); 2414 2415 SmallVector<TypeWithHandler, 8> TypesWithHandlers; 2416 2417 for (unsigned i = 0; i < NumHandlers; ++i) { 2418 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]); 2419 if (!Handler->getExceptionDecl()) { 2420 if (i < NumHandlers - 1) 2421 return StmtError(Diag(Handler->getLocStart(), 2422 diag::err_early_catch_all)); 2423 2424 continue; 2425 } 2426 2427 const QualType CaughtType = Handler->getCaughtType(); 2428 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 2429 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 2430 } 2431 2432 // Detect handlers for the same type as an earlier one. 2433 if (NumHandlers > 1) { 2434 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 2435 2436 TypeWithHandler prev = TypesWithHandlers[0]; 2437 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 2438 TypeWithHandler curr = TypesWithHandlers[i]; 2439 2440 if (curr == prev) { 2441 Diag(curr.getTypeSpecStartLoc(), 2442 diag::warn_exception_caught_by_earlier_handler) 2443 << curr.getCatchStmt()->getCaughtType().getAsString(); 2444 Diag(prev.getTypeSpecStartLoc(), 2445 diag::note_previous_exception_handler) 2446 << prev.getCatchStmt()->getCaughtType().getAsString(); 2447 } 2448 2449 prev = curr; 2450 } 2451 } 2452 2453 getCurFunction()->setHasBranchProtectedScope(); 2454 2455 // FIXME: We should detect handlers that cannot catch anything because an 2456 // earlier handler catches a superclass. Need to find a method that is not 2457 // quadratic for this. 2458 // Neither of these are explicitly forbidden, but every compiler detects them 2459 // and warns. 2460 2461 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 2462 Handlers, NumHandlers)); 2463} 2464 2465StmtResult 2466Sema::ActOnSEHTryBlock(bool IsCXXTry, 2467 SourceLocation TryLoc, 2468 Stmt *TryBlock, 2469 Stmt *Handler) { 2470 assert(TryBlock && Handler); 2471 2472 getCurFunction()->setHasBranchProtectedScope(); 2473 2474 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler)); 2475} 2476 2477StmtResult 2478Sema::ActOnSEHExceptBlock(SourceLocation Loc, 2479 Expr *FilterExpr, 2480 Stmt *Block) { 2481 assert(FilterExpr && Block); 2482 2483 if(!FilterExpr->getType()->isIntegerType()) { 2484 return StmtError(Diag(FilterExpr->getExprLoc(), 2485 diag::err_filter_expression_integral) 2486 << FilterExpr->getType()); 2487 } 2488 2489 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block)); 2490} 2491 2492StmtResult 2493Sema::ActOnSEHFinallyBlock(SourceLocation Loc, 2494 Stmt *Block) { 2495 assert(Block); 2496 return Owned(SEHFinallyStmt::Create(Context,Loc,Block)); 2497} 2498 2499StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 2500 bool IsIfExists, 2501 NestedNameSpecifierLoc QualifierLoc, 2502 DeclarationNameInfo NameInfo, 2503 Stmt *Nested) 2504{ 2505 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, 2506 QualifierLoc, NameInfo, 2507 cast<CompoundStmt>(Nested)); 2508} 2509 2510 2511StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 2512 bool IsIfExists, 2513 CXXScopeSpec &SS, 2514 UnqualifiedId &Name, 2515 Stmt *Nested) { 2516 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, 2517 SS.getWithLocInContext(Context), 2518 GetNameFromUnqualifiedId(Name), 2519 Nested); 2520} 2521