Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Sema/SemaStmt.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements semantic analysis for statements.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Sema/Ownership.h"
14
#include "clang/Sema/SemaInternal.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTDiagnostic.h"
17
#include "clang/AST/ASTLambda.h"
18
#include "clang/AST/CharUnits.h"
19
#include "clang/AST/CXXInheritance.h"
20
#include "clang/AST/DeclObjC.h"
21
#include "clang/AST/EvaluatedExprVisitor.h"
22
#include "clang/AST/ExprCXX.h"
23
#include "clang/AST/ExprObjC.h"
24
#include "clang/AST/RecursiveASTVisitor.h"
25
#include "clang/AST/StmtCXX.h"
26
#include "clang/AST/StmtObjC.h"
27
#include "clang/AST/TypeLoc.h"
28
#include "clang/AST/TypeOrdering.h"
29
#include "clang/Basic/TargetInfo.h"
30
#include "clang/Lex/Preprocessor.h"
31
#include "clang/Sema/Initialization.h"
32
#include "clang/Sema/Lookup.h"
33
#include "clang/Sema/Scope.h"
34
#include "clang/Sema/ScopeInfo.h"
35
#include "llvm/ADT/ArrayRef.h"
36
#include "llvm/ADT/DenseMap.h"
37
#include "llvm/ADT/STLExtras.h"
38
#include "llvm/ADT/SmallPtrSet.h"
39
#include "llvm/ADT/SmallString.h"
40
#include "llvm/ADT/SmallVector.h"
41
42
using namespace clang;
43
using namespace sema;
44
45
3.24M
StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
46
3.24M
  if (FE.isInvalid())
47
499
    return StmtError();
48
3.24M
49
3.24M
  FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
50
3.24M
  if (FE.isInvalid())
51
225
    return StmtError();
52
3.24M
53
3.24M
  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54
3.24M
  // void expression for its side effects.  Conversion to void allows any
55
3.24M
  // operand, even incomplete types.
56
3.24M
57
3.24M
  // Same thing in for stmt first clause (when expr) and third clause.
58
3.24M
  return StmtResult(FE.getAs<Stmt>());
59
3.24M
}
60
61
62
11.8k
StmtResult Sema::ActOnExprStmtError() {
63
11.8k
  DiscardCleanupsInEvaluationContext();
64
11.8k
  return StmtError();
65
11.8k
}
66
67
StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
68
110k
                               bool HasLeadingEmptyMacro) {
69
110k
  return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
70
110k
}
71
72
StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73
2.09M
                               SourceLocation EndLoc) {
74
2.09M
  DeclGroupRef DG = dg.get();
75
2.09M
76
2.09M
  // If we have an invalid decl, just return an error.
77
2.09M
  if (DG.isNull()) 
return StmtError()300
;
78
2.09M
79
2.09M
  return new (Context) DeclStmt(DG, StartLoc, EndLoc);
80
2.09M
}
81
82
197
void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
83
197
  DeclGroupRef DG = dg.get();
84
197
85
197
  // If we don't have a declaration, or we have an invalid declaration,
86
197
  // just return.
87
197
  if (DG.isNull() || !DG.isSingleDecl())
88
1
    return;
89
196
90
196
  Decl *decl = DG.getSingleDecl();
91
196
  if (!decl || decl->isInvalidDecl())
92
0
    return;
93
196
94
196
  // Only variable declarations are permitted.
95
196
  VarDecl *var = dyn_cast<VarDecl>(decl);
96
196
  if (!var) {
97
1
    Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98
1
    decl->setInvalidDecl();
99
1
    return;
100
1
  }
101
195
102
195
  // foreach variables are never actually initialized in the way that
103
195
  // the parser came up with.
104
195
  var->setInit(nullptr);
105
195
106
195
  // In ARC, we don't need to retain the iteration variable of a fast
107
195
  // enumeration loop.  Rather than actually trying to catch that
108
195
  // during declaration processing, we remove the consequences here.
109
195
  if (getLangOpts().ObjCAutoRefCount) {
110
54
    QualType type = var->getType();
111
54
112
54
    // Only do this if we inferred the lifetime.  Inferred lifetime
113
54
    // will show up as a local qualifier because explicit lifetime
114
54
    // should have shown up as an AttributedType instead.
115
54
    if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116
33
      // Add 'const' and mark the variable as pseudo-strong.
117
33
      var->setType(type.withConst());
118
33
      var->setARCPseudoStrong(true);
119
33
    }
120
54
  }
121
195
}
122
123
/// Diagnose unused comparisons, both builtin and overloaded operators.
124
/// For '==' and '!=', suggest fixits for '=' or '|='.
125
///
126
/// Adding a cast to void (or other expression wrappers) will prevent the
127
/// warning from firing.
128
8.50k
static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
129
8.50k
  SourceLocation Loc;
130
8.50k
  bool CanAssign;
131
8.50k
  enum { Equality, Inequality, Relational, ThreeWay } Kind;
132
8.50k
133
8.50k
  if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
134
1.00k
    if (!Op->isComparisonOp())
135
780
      return false;
136
228
137
228
    if (Op->getOpcode() == BO_EQ)
138
85
      Kind = Equality;
139
143
    else if (Op->getOpcode() == BO_NE)
140
12
      Kind = Inequality;
141
131
    else if (Op->getOpcode() == BO_Cmp)
142
1
      Kind = ThreeWay;
143
130
    else {
144
130
      assert(Op->isRelationalOp());
145
130
      Kind = Relational;
146
130
    }
147
228
    Loc = Op->getOperatorLoc();
148
228
    CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
149
7.49k
  } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
150
22
    switch (Op->getOperator()) {
151
22
    case OO_EqualEqual:
152
6
      Kind = Equality;
153
6
      break;
154
22
    case OO_ExclaimEqual:
155
2
      Kind = Inequality;
156
2
      break;
157
22
    case OO_Less:
158
5
    case OO_Greater:
159
5
    case OO_GreaterEqual:
160
5
    case OO_LessEqual:
161
5
      Kind = Relational;
162
5
      break;
163
5
    case OO_Spaceship:
164
0
      Kind = ThreeWay;
165
0
      break;
166
9
    default:
167
9
      return false;
168
13
    }
169
13
170
13
    Loc = Op->getOperatorLoc();
171
13
    CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
172
7.47k
  } else {
173
7.47k
    // Not a typo-prone comparison.
174
7.47k
    return false;
175
7.47k
  }
176
241
177
241
  // Suppress warnings when the operator, suspicious as it may be, comes from
178
241
  // a macro expansion.
179
241
  if (S.SourceMgr.isMacroBodyExpansion(Loc))
180
3
    return false;
181
238
182
238
  S.Diag(Loc, diag::warn_unused_comparison)
183
238
    << (unsigned)Kind << E->getSourceRange();
184
238
185
238
  // If the LHS is a plausible entity to assign to, provide a fixit hint to
186
238
  // correct common typos.
187
238
  if (CanAssign) {
188
221
    if (Kind == Inequality)
189
13
      S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
190
13
        << FixItHint::CreateReplacement(Loc, "|=");
191
208
    else if (Kind == Equality)
192
75
      S.Diag(Loc, diag::note_equality_comparison_to_assign)
193
75
        << FixItHint::CreateReplacement(Loc, "=");
194
221
  }
195
238
196
238
  return true;
197
238
}
198
199
3.51M
void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
200
3.51M
  if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
201
0
    return DiagnoseUnusedExprResult(Label->getSubStmt());
202
3.51M
203
3.51M
  const Expr *E = dyn_cast_or_null<Expr>(S);
204
3.51M
  if (!E)
205
0
    return;
206
3.51M
207
3.51M
  // If we are in an unevaluated expression context, then there can be no unused
208
3.51M
  // results because the results aren't expected to be used in the first place.
209
3.51M
  if (isUnevaluatedContext())
210
4.06k
    return;
211
3.51M
212
3.51M
  SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
213
3.51M
  // In most cases, we don't want to warn if the expression is written in a
214
3.51M
  // macro body, or if the macro comes from a system header. If the offending
215
3.51M
  // expression is a call to a function with the warn_unused_result attribute,
216
3.51M
  // we warn no matter the location. Because of the order in which the various
217
3.51M
  // checks need to happen, we factor out the macro-related test here.
218
3.51M
  bool ShouldSuppress =
219
3.51M
      SourceMgr.isMacroBodyExpansion(ExprLoc) ||
220
3.51M
      
SourceMgr.isInSystemMacro(ExprLoc)3.14M
;
221
3.51M
222
3.51M
  const Expr *WarnExpr;
223
3.51M
  SourceLocation Loc;
224
3.51M
  SourceRange R1, R2;
225
3.51M
  if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
226
3.50M
    return;
227
8.50k
228
8.50k
  // If this is a GNU statement expression expanded from a macro, it is probably
229
8.50k
  // unused because it is a function-like macro that can be used as either an
230
8.50k
  // expression or statement.  Don't warn, because it is almost certainly a
231
8.50k
  // false positive.
232
8.50k
  if (isa<StmtExpr>(E) && 
Loc.isMacroID()11
)
233
3
    return;
234
8.50k
235
8.50k
  // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
236
8.50k
  // That macro is frequently used to suppress "unused parameter" warnings,
237
8.50k
  // but its implementation makes clang's -Wunused-value fire.  Prevent this.
238
8.50k
  if (isa<ParenExpr>(E->IgnoreImpCasts()) && 
Loc.isMacroID()324
) {
239
286
    SourceLocation SpellLoc = Loc;
240
286
    if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
241
1
      return;
242
8.50k
  }
243
8.50k
244
8.50k
  // Okay, we have an unused result.  Depending on what the base expression is,
245
8.50k
  // we might want to make a more specific diagnostic.  Check for one of these
246
8.50k
  // cases now.
247
8.50k
  unsigned DiagID = diag::warn_unused_expr;
248
8.50k
  if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
249
0
    E = Temps->getSubExpr();
250
8.50k
  if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
251
11
    E = TempExpr->getSubExpr();
252
8.50k
253
8.50k
  if (DiagnoseUnusedComparison(*this, E))
254
238
    return;
255
8.26k
256
8.26k
  E = WarnExpr;
257
8.26k
  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
258
4.88k
    if (E->getType()->isVoidType())
259
557
      return;
260
4.33k
261
4.33k
    if (const auto *A = cast_or_null<WarnUnusedResultAttr>(
262
85
            CE->getUnusedResultAttr(Context))) {
263
85
      StringRef Msg = A->getMessage();
264
85
      if (!Msg.empty())
265
13
        Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
266
72
      else
267
72
        Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
268
85
      return;
269
85
    }
270
4.24k
271
4.24k
    // If the callee has attribute pure, const, or warn_unused_result, warn with
272
4.24k
    // a more specific message to make it clear what is happening. If the call
273
4.24k
    // is written in a macro body, only warn if it has the warn_unused_result
274
4.24k
    // attribute.
275
4.24k
    if (const Decl *FD = CE->getCalleeDecl()) {
276
4.24k
      if (ShouldSuppress)
277
5
        return;
278
4.24k
      if (FD->hasAttr<PureAttr>()) {
279
58
        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
280
58
        return;
281
58
      }
282
4.18k
      if (FD->hasAttr<ConstAttr>()) {
283
4.18k
        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
284
4.18k
        return;
285
4.18k
      }
286
3.37k
    }
287
3.37k
  } else if (ShouldSuppress)
288
633
    return;
289
2.74k
290
2.74k
  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
291
25
    if (getLangOpts().ObjCAutoRefCount && 
ME->isDelegateInitCall()23
) {
292
6
      Diag(Loc, diag::err_arc_unused_init_message) << R1;
293
6
      return;
294
6
    }
295
19
    const ObjCMethodDecl *MD = ME->getMethodDecl();
296
19
    if (MD) {
297
19
      if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
298
2
        StringRef Msg = A->getMessage();
299
2
        if (!Msg.empty())
300
0
          Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
301
2
        else
302
2
          Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
303
2
        return;
304
2
      }
305
2.72k
    }
306
2.72k
  } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
307
91
    const Expr *Source = POE->getSyntacticForm();
308
91
    if (isa<ObjCSubscriptRefExpr>(Source))
309
2
      DiagID = diag::warn_unused_container_subscript_expr;
310
89
    else
311
89
      DiagID = diag::warn_unused_property_expr;
312
2.63k
  } else if (const CXXFunctionalCastExpr *FC
313
54
                                       = dyn_cast<CXXFunctionalCastExpr>(E)) {
314
54
    const Expr *E = FC->getSubExpr();
315
54
    if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
316
5
      E = TE->getSubExpr();
317
54
    if (isa<CXXTemporaryObjectExpr>(E))
318
0
      return;
319
54
    if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
320
6
      if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
321
6
        if (!RD->getAttr<WarnUnusedAttr>())
322
4
          return;
323
2.57k
  }
324
2.57k
  // Diagnose "(void*) blah" as a typo for "(void) blah".
325
2.57k
  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
326
181
    TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
327
181
    QualType T = TI->getType();
328
181
329
181
    // We really do want to use the non-canonical type here.
330
181
    if (T == Context.VoidPtrTy) {
331
5
      PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
332
5
333
5
      Diag(Loc, diag::warn_unused_voidptr)
334
5
        << FixItHint::CreateRemoval(TL.getStarLoc());
335
5
      return;
336
5
    }
337
2.73k
  }
338
2.73k
339
2.73k
  if (E->isGLValue() && 
E->getType().isVolatileQualified()743
) {
340
122
    Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
341
122
    return;
342
122
  }
343
2.60k
344
2.60k
  DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
345
2.60k
}
346
347
4.70M
void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
348
4.70M
  PushCompoundScope(IsStmtExpr);
349
4.70M
}
350
351
4.70M
void Sema::ActOnFinishOfCompoundStmt() {
352
4.70M
  PopCompoundScope();
353
4.70M
}
354
355
3.86M
sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
356
3.86M
  return getCurFunction()->CompoundScopes.back();
357
3.86M
}
358
359
StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
360
4.49M
                                   ArrayRef<Stmt *> Elts, bool isStmtExpr) {
361
4.49M
  const unsigned NumElts = Elts.size();
362
4.49M
363
4.49M
  // If we're in C89 mode, check that we don't have any decls after stmts.  If
364
4.49M
  // so, emit an extension diagnostic.
365
4.49M
  if (!getLangOpts().C99 && 
!getLangOpts().CPlusPlus3.23M
) {
366
11.1k
    // Note that __extension__ can be around a decl.
367
11.1k
    unsigned i = 0;
368
11.1k
    // Skip over all declarations.
369
18.1k
    for (; i != NumElts && 
isa<DeclStmt>(Elts[i])18.0k
;
++i7.03k
)
370
7.03k
      /*empty*/;
371
11.1k
372
11.1k
    // We found the end of the list or a statement.  Scan for another declstmt.
373
33.4k
    for (; i != NumElts && 
!isa<DeclStmt>(Elts[i])23.9k
;
++i22.2k
)
374
22.2k
      /*empty*/;
375
11.1k
376
11.1k
    if (i != NumElts) {
377
1.66k
      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
378
1.66k
      Diag(D->getLocation(), diag::ext_mixed_decls_code);
379
1.66k
    }
380
11.1k
  }
381
4.49M
382
4.49M
  // Check for suspicious empty body (null statement) in `for' and `while'
383
4.49M
  // statements.  Don't do anything for template instantiations, this just adds
384
4.49M
  // noise.
385
4.49M
  if (NumElts != 0 && 
!CurrentInstantiationScope4.23M
&&
386
4.49M
      
getCurCompoundScope().HasEmptyLoopBodies3.85M
) {
387
23.5k
    for (unsigned i = 0; i != NumElts - 1; 
++i19.6k
)
388
19.6k
      DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
389
3.82k
  }
390
4.49M
391
4.49M
  return CompoundStmt::Create(Context, Elts, L, R);
392
4.49M
}
393
394
ExprResult
395
169k
Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
396
169k
  if (!Val.get())
397
53.1k
    return Val;
398
115k
399
115k
  if (DiagnoseUnexpandedParameterPack(Val.get()))
400
1
    return ExprError();
401
115k
402
115k
  // If we're not inside a switch, let the 'case' statement handling diagnose
403
115k
  // this. Just clean up after the expression as best we can.
404
115k
  if (!getCurFunction()->SwitchStack.empty()) {
405
115k
    Expr *CondExpr =
406
115k
        getCurFunction()->SwitchStack.back().getPointer()->getCond();
407
115k
    if (!CondExpr)
408
4
      return ExprError();
409
115k
    QualType CondType = CondExpr->getType();
410
115k
411
115k
    auto CheckAndFinish = [&](Expr *E) {
412
115k
      if (CondType->isDependentType() || 
E->isTypeDependent()107k
)
413
8.42k
        return ExprResult(E);
414
107k
415
107k
      if (getLangOpts().CPlusPlus11) {
416
95.7k
        // C++11 [stmt.switch]p2: the constant-expression shall be a converted
417
95.7k
        // constant expression of the promoted type of the switch condition.
418
95.7k
        llvm::APSInt TempVal;
419
95.7k
        return CheckConvertedConstantExpression(E, CondType, TempVal,
420
95.7k
                                                CCEK_CaseValue);
421
95.7k
      }
422
11.6k
423
11.6k
      ExprResult ER = E;
424
11.6k
      if (!E->isValueDependent())
425
11.6k
        ER = VerifyIntegerConstantExpression(E);
426
11.6k
      if (!ER.isInvalid())
427
11.6k
        ER = DefaultLvalueConversion(ER.get());
428
11.6k
      if (!ER.isInvalid())
429
11.6k
        ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
430
11.6k
      return ER;
431
11.6k
    };
432
115k
433
115k
    ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
434
115k
    if (Converted.get() == Val.get())
435
115k
      Converted = CheckAndFinish(Val.get());
436
115k
    if (Converted.isInvalid())
437
51
      return ExprError();
438
115k
    Val = Converted;
439
115k
  }
440
115k
441
115k
  return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
442
115k
                             getLangOpts().CPlusPlus11);
443
115k
}
444
445
StmtResult
446
Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
447
                    SourceLocation DotDotDotLoc, ExprResult RHSVal,
448
115k
                    SourceLocation ColonLoc) {
449
115k
  assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
450
115k
  assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
451
115k
                                   : RHSVal.isInvalid() || RHSVal.get()) &&
452
115k
         "missing RHS value");
453
115k
454
115k
  if (getCurFunction()->SwitchStack.empty()) {
455
3
    Diag(CaseLoc, diag::err_case_not_in_switch);
456
3
    return StmtError();
457
3
  }
458
115k
459
115k
  if (LHSVal.isInvalid() || 
RHSVal.isInvalid()115k
) {
460
63
    getCurFunction()->SwitchStack.back().setInt(true);
461
63
    return StmtError();
462
63
  }
463
115k
464
115k
  auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
465
115k
                              CaseLoc, DotDotDotLoc, ColonLoc);
466
115k
  getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
467
115k
  return CS;
468
115k
}
469
470
/// ActOnCaseStmtBody - This installs a statement as the body of a case.
471
115k
void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
472
115k
  cast<CaseStmt>(S)->setSubStmt(SubStmt);
473
115k
}
474
475
StmtResult
476
Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
477
4.70k
                       Stmt *SubStmt, Scope *CurScope) {
478
4.70k
  if (getCurFunction()->SwitchStack.empty()) {
479
4
    Diag(DefaultLoc, diag::err_default_not_in_switch);
480
4
    return SubStmt;
481
4
  }
482
4.70k
483
4.70k
  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
484
4.70k
  getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
485
4.70k
  return DS;
486
4.70k
}
487
488
StmtResult
489
Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
490
4.12k
                     SourceLocation ColonLoc, Stmt *SubStmt) {
491
4.12k
  // If the label was multiply defined, reject it now.
492
4.12k
  if (TheDecl->getStmt()) {
493
4
    Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
494
4
    Diag(TheDecl->getLocation(), diag::note_previous_definition);
495
4
    return SubStmt;
496
4
  }
497
4.11k
498
4.11k
  // Otherwise, things are good.  Fill in the declaration and return it.
499
4.11k
  LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
500
4.11k
  TheDecl->setStmt(LS);
501
4.11k
  if (!TheDecl->isGnuLocal()) {
502
4.10k
    TheDecl->setLocStart(IdentLoc);
503
4.10k
    if (!TheDecl->isMSAsmLabel()) {
504
4.10k
      // Don't update the location of MS ASM labels.  These will result in
505
4.10k
      // a diagnostic, and changing the location here will mess that up.
506
4.10k
      TheDecl->setLocation(IdentLoc);
507
4.10k
    }
508
4.10k
  }
509
4.11k
  return LS;
510
4.11k
}
511
512
StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
513
                                     ArrayRef<const Attr*> Attrs,
514
1.04k
                                     Stmt *SubStmt) {
515
1.04k
  // Fill in the declaration and return it.
516
1.04k
  AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
517
1.04k
  return LS;
518
1.04k
}
519
520
namespace {
521
class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
522
  typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
523
  Sema &SemaRef;
524
public:
525
182
  CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
526
180
  void VisitBinaryOperator(BinaryOperator *E) {
527
180
    if (E->getOpcode() == BO_Comma)
528
35
      SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
529
180
    EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
530
180
  }
531
};
532
}
533
534
StmtResult
535
Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
536
                  ConditionResult Cond,
537
                  Stmt *thenStmt, SourceLocation ElseLoc,
538
1.05M
                  Stmt *elseStmt) {
539
1.05M
  if (Cond.isInvalid())
540
132
    Cond = ConditionResult(
541
132
        *this, nullptr,
542
132
        MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
543
132
                                                   Context.BoolTy, VK_RValue),
544
132
                     IfLoc),
545
132
        false);
546
1.05M
547
1.05M
  Expr *CondExpr = Cond.get().second;
548
1.05M
  // Only call the CommaVisitor when not C89 due to differences in scope flags.
549
1.05M
  if ((getLangOpts().C99 || 
getLangOpts().CPlusPlus938k
) &&
550
1.05M
      
!Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc())1.04M
)
551
15
    CommaVisitor(*this).Visit(CondExpr);
552
1.05M
553
1.05M
  if (!elseStmt)
554
844k
    DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
555
844k
                          diag::warn_empty_if_body);
556
1.05M
557
1.05M
  return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
558
1.05M
                     elseStmt);
559
1.05M
}
560
561
StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
562
                             Stmt *InitStmt, ConditionResult Cond,
563
                             Stmt *thenStmt, SourceLocation ElseLoc,
564
1.05M
                             Stmt *elseStmt) {
565
1.05M
  if (Cond.isInvalid())
566
0
    return StmtError();
567
1.05M
568
1.05M
  if (IsConstexpr || 
isa<ObjCAvailabilityCheckExpr>(Cond.get().second)1.05M
)
569
184
    setFunctionHasBranchProtectedScope();
570
1.05M
571
1.05M
  return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
572
1.05M
                        Cond.get().second, thenStmt, ElseLoc, elseStmt);
573
1.05M
}
574
575
namespace {
576
  struct CaseCompareFunctor {
577
    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
578
72
                    const llvm::APSInt &RHS) {
579
72
      return LHS.first < RHS;
580
72
    }
581
    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
582
0
                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
583
0
      return LHS.first < RHS.first;
584
0
    }
585
    bool operator()(const llvm::APSInt &LHS,
586
21
                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
587
21
      return LHS < RHS.first;
588
21
    }
589
  };
590
}
591
592
/// CmpCaseVals - Comparison predicate for sorting case values.
593
///
594
static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
595
291k
                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
596
291k
  if (lhs.first < rhs.first)
597
254k
    return true;
598
36.2k
599
36.2k
  if (lhs.first == rhs.first &&
600
36.2k
      lhs.second->getCaseLoc().getRawEncoding()
601
20
       < rhs.second->getCaseLoc().getRawEncoding())
602
20
    return true;
603
36.2k
  return false;
604
36.2k
}
605
606
/// CmpEnumVals - Comparison predicate for sorting enumeration values.
607
///
608
static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
609
                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
610
222k
{
611
222k
  return lhs.first < rhs.first;
612
222k
}
613
614
/// EqEnumVals - Comparison preficate for uniqing enumeration values.
615
///
616
static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
617
                       const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
618
75.8k
{
619
75.8k
  return lhs.first == rhs.first;
620
75.8k
}
621
622
/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
623
/// potentially integral-promoted expression @p expr.
624
118k
static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
625
118k
  if (const auto *FE = dyn_cast<FullExpr>(E))
626
101k
    E = FE->getSubExpr();
627
208k
  while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
628
99.0k
    if (ImpCast->getCastKind() != CK_IntegralCast) 
break9.18k
;
629
89.8k
    E = ImpCast->getSubExpr();
630
89.8k
  }
631
118k
  return E->getType();
632
118k
}
633
634
14.9k
ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
635
14.9k
  class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
636
14.9k
    Expr *Cond;
637
14.9k
638
14.9k
  public:
639
14.9k
    SwitchConvertDiagnoser(Expr *Cond)
640
14.9k
        : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
641
14.9k
          Cond(Cond) {}
642
14.9k
643
14.9k
    SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
644
14.9k
                                         QualType T) override {
645
22
      return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
646
22
    }
647
14.9k
648
14.9k
    SemaDiagnosticBuilder diagnoseIncomplete(
649
14.9k
        Sema &S, SourceLocation Loc, QualType T) override {
650
1
      return S.Diag(Loc, diag::err_switch_incomplete_class_type)
651
1
               << T << Cond->getSourceRange();
652
1
    }
653
14.9k
654
14.9k
    SemaDiagnosticBuilder diagnoseExplicitConv(
655
14.9k
        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
656
6
      return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
657
6
    }
658
14.9k
659
14.9k
    SemaDiagnosticBuilder noteExplicitConv(
660
14.9k
        Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
661
6
      return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
662
6
        << ConvTy->isEnumeralType() << ConvTy;
663
6
    }
664
14.9k
665
14.9k
    SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
666
14.9k
                                            QualType T) override {
667
2
      return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
668
2
    }
669
14.9k
670
14.9k
    SemaDiagnosticBuilder noteAmbiguous(
671
14.9k
        Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
672
4
      return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
673
4
      << ConvTy->isEnumeralType() << ConvTy;
674
4
    }
675
14.9k
676
14.9k
    SemaDiagnosticBuilder diagnoseConversion(
677
14.9k
        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
678
0
      llvm_unreachable("conversion functions are permitted");
679
0
    }
680
14.9k
  } SwitchDiagnoser(Cond);
681
14.9k
682
14.9k
  ExprResult CondResult =
683
14.9k
      PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
684
14.9k
  if (CondResult.isInvalid())
685
5
    return ExprError();
686
14.9k
687
14.9k
  // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
688
14.9k
  // failed and produced a diagnostic.
689
14.9k
  Cond = CondResult.get();
690
14.9k
  if (!Cond->isTypeDependent() &&
691
14.9k
      
!Cond->getType()->isIntegralOrEnumerationType()12.9k
)
692
25
    return ExprError();
693
14.9k
694
14.9k
  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
695
14.9k
  return UsualUnaryConversions(Cond);
696
14.9k
}
697
698
StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
699
14.9k
                                        Stmt *InitStmt, ConditionResult Cond) {
700
14.9k
  Expr *CondExpr = Cond.get().second;
701
14.9k
  assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
702
14.9k
703
14.9k
  if (CondExpr && 
!CondExpr->isTypeDependent()14.9k
) {
704
12.8k
    // We have already converted the expression to an integral or enumeration
705
12.8k
    // type, when we parsed the switch condition. If we don't have an
706
12.8k
    // appropriate type now, enter the switch scope but remember that it's
707
12.8k
    // invalid.
708
12.8k
    assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
709
12.8k
           "invalid condition type");
710
12.8k
    if (CondExpr->isKnownToHaveBooleanValue()) {
711
20
      // switch(bool_expr) {...} is often a programmer error, e.g.
712
20
      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
713
20
      // One can always use an if statement instead of switch(bool_expr).
714
20
      Diag(SwitchLoc, diag::warn_bool_switch_condition)
715
20
          << CondExpr->getSourceRange();
716
20
    }
717
12.8k
  }
718
14.9k
719
14.9k
  setFunctionHasBranchIntoScope();
720
14.9k
721
14.9k
  auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
722
14.9k
  getCurFunction()->SwitchStack.push_back(
723
14.9k
      FunctionScopeInfo::SwitchInfo(SS, false));
724
14.9k
  return SS;
725
14.9k
}
726
727
189k
static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
728
189k
  Val = Val.extOrTrunc(BitWidth);
729
189k
  Val.setIsSigned(IsSigned);
730
189k
}
731
732
/// Check the specified case value is in range for the given unpromoted switch
733
/// type.
734
static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
735
103k
                           unsigned UnpromotedWidth, bool UnpromotedSign) {
736
103k
  // In C++11 onwards, this is checked by the language rules.
737
103k
  if (S.getLangOpts().CPlusPlus11)
738
92.2k
    return;
739
11.6k
740
11.6k
  // If the case value was signed and negative and the switch expression is
741
11.6k
  // unsigned, don't bother to warn: this is implementation-defined behavior.
742
11.6k
  // FIXME: Introduce a second, default-ignored warning for this case?
743
11.6k
  if (UnpromotedWidth < Val.getBitWidth()) {
744
3.07k
    llvm::APSInt ConvVal(Val);
745
3.07k
    AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
746
3.07k
    AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
747
3.07k
    // FIXME: Use different diagnostics for overflow  in conversion to promoted
748
3.07k
    // type versus "switch expression cannot have this value". Use proper
749
3.07k
    // IntRange checking rather than just looking at the unpromoted type here.
750
3.07k
    if (ConvVal != Val)
751
7
      S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
752
7
                                                  << ConvVal.toString(10);
753
3.07k
  }
754
11.6k
}
755
756
typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
757
758
/// Returns true if we should emit a diagnostic about this case expression not
759
/// being a part of the enum used in the switch controlling expression.
760
static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
761
                                              const EnumDecl *ED,
762
                                              const Expr *CaseExpr,
763
                                              EnumValsTy::iterator &EI,
764
                                              EnumValsTy::iterator &EIEnd,
765
21.6k
                                              const llvm::APSInt &Val) {
766
21.6k
  if (!ED->isClosed())
767
18
    return false;
768
21.5k
769
21.5k
  if (const DeclRefExpr *DRE =
770
21.5k
          dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
771
21.5k
    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
772
46
      QualType VarType = VD->getType();
773
46
      QualType EnumType = S.Context.getTypeDeclType(ED);
774
46
      if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
775
46
          S.Context.hasSameUnqualifiedType(EnumType, VarType))
776
45
        return false;
777
21.5k
    }
778
21.5k
  }
779
21.5k
780
21.5k
  if (ED->hasAttr<FlagEnumAttr>())
781
31
    return !S.IsValueInFlagEnum(ED, Val, false);
782
21.5k
783
55.0k
  
while (21.5k
EI != EIEnd &&
EI->first < Val55.0k
)
784
33.5k
    EI++;
785
21.5k
786
21.5k
  if (EI != EIEnd && 
EI->first == Val21.4k
)
787
21.4k
    return false;
788
34
789
34
  return true;
790
34
}
791
792
static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
793
103k
                                       const Expr *Case) {
794
103k
  QualType CondType = Cond->getType();
795
103k
  QualType CaseType = Case->getType();
796
103k
797
103k
  const EnumType *CondEnumType = CondType->getAs<EnumType>();
798
103k
  const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
799
103k
  if (!CondEnumType || 
!CaseEnumType21.6k
)
800
83.3k
    return;
801
20.4k
802
20.4k
  // Ignore anonymous enums.
803
20.4k
  if (!CondEnumType->getDecl()->getIdentifier() &&
804
20.4k
      
!CondEnumType->getDecl()->getTypedefNameForAnonDecl()1.56k
)
805
1
    return;
806
20.4k
  if (!CaseEnumType->getDecl()->getIdentifier() &&
807
20.4k
      
!CaseEnumType->getDecl()->getTypedefNameForAnonDecl()1.56k
)
808
6
    return;
809
20.4k
810
20.4k
  if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
811
20.4k
    return;
812
15
813
15
  S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
814
15
      << CondType << CaseType << Cond->getSourceRange()
815
15
      << Case->getSourceRange();
816
15
}
817
818
StmtResult
819
Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
820
14.9k
                            Stmt *BodyStmt) {
821
14.9k
  SwitchStmt *SS = cast<SwitchStmt>(Switch);
822
14.9k
  bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
823
14.9k
  assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
824
14.9k
         "switch stack missing push/pop!");
825
14.9k
826
14.9k
  getCurFunction()->SwitchStack.pop_back();
827
14.9k
828
14.9k
  if (!BodyStmt) 
return StmtError()7
;
829
14.9k
  SS->setBody(BodyStmt, SwitchLoc);
830
14.9k
831
14.9k
  Expr *CondExpr = SS->getCond();
832
14.9k
  if (!CondExpr) 
return StmtError()44
;
833
14.9k
834
14.9k
  QualType CondType = CondExpr->getType();
835
14.9k
836
14.9k
  // C++ 6.4.2.p2:
837
14.9k
  // Integral promotions are performed (on the switch condition).
838
14.9k
  //
839
14.9k
  // A case value unrepresentable by the original switch condition
840
14.9k
  // type (before the promotion) doesn't make sense, even when it can
841
14.9k
  // be represented by the promoted type.  Therefore we need to find
842
14.9k
  // the pre-promotion type of the switch condition.
843
14.9k
  const Expr *CondExprBeforePromotion = CondExpr;
844
14.9k
  QualType CondTypeBeforePromotion =
845
14.9k
      GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
846
14.9k
847
14.9k
  // Get the bitwidth of the switched-on value after promotions. We must
848
14.9k
  // convert the integer case values to this width before comparison.
849
14.9k
  bool HasDependentValue
850
14.9k
    = CondExpr->isTypeDependent() || 
CondExpr->isValueDependent()12.8k
;
851
14.9k
  unsigned CondWidth = HasDependentValue ? 
02.28k
:
Context.getIntWidth(CondType)12.6k
;
852
14.9k
  bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
853
14.9k
854
14.9k
  // Get the width and signedness that the condition might actually have, for
855
14.9k
  // warning purposes.
856
14.9k
  // FIXME: Grab an IntRange for the condition rather than using the unpromoted
857
14.9k
  // type.
858
14.9k
  unsigned CondWidthBeforePromotion
859
14.9k
    = HasDependentValue ? 
02.28k
:
Context.getIntWidth(CondTypeBeforePromotion)12.6k
;
860
14.9k
  bool CondIsSignedBeforePromotion
861
14.9k
    = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
862
14.9k
863
14.9k
  // Accumulate all of the case values in a vector so that we can sort them
864
14.9k
  // and detect duplicates.  This vector contains the APInt for the case after
865
14.9k
  // it has been converted to the condition type.
866
14.9k
  typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
867
14.9k
  CaseValsTy CaseVals;
868
14.9k
869
14.9k
  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
870
14.9k
  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
871
14.9k
  CaseRangesTy CaseRanges;
872
14.9k
873
14.9k
  DefaultStmt *TheDefaultStmt = nullptr;
874
14.9k
875
14.9k
  bool CaseListIsErroneous = false;
876
14.9k
877
123k
  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && 
!HasDependentValue110k
;
878
108k
       
SC = SC->getNextSwitchCase()108k
) {
879
108k
880
108k
    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
881
4.57k
      if (TheDefaultStmt) {
882
2
        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
883
2
        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
884
2
885
2
        // FIXME: Remove the default statement from the switch block so that
886
2
        // we'll return a valid AST.  This requires recursing down the AST and
887
2
        // finding it, not something we are set up to do right now.  For now,
888
2
        // just lop the entire switch stmt out of the AST.
889
2
        CaseListIsErroneous = true;
890
2
      }
891
4.57k
      TheDefaultStmt = DS;
892
4.57k
893
103k
    } else {
894
103k
      CaseStmt *CS = cast<CaseStmt>(SC);
895
103k
896
103k
      Expr *Lo = CS->getLHS();
897
103k
898
103k
      if (Lo->isValueDependent()) {
899
7
        HasDependentValue = true;
900
7
        break;
901
7
      }
902
103k
903
103k
      // We already verified that the expression has a constant value;
904
103k
      // get that value (prior to conversions).
905
103k
      const Expr *LoBeforePromotion = Lo;
906
103k
      GetTypeBeforeIntegralPromotion(LoBeforePromotion);
907
103k
      llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
908
103k
909
103k
      // Check the unconverted value is within the range of possible values of
910
103k
      // the switch expression.
911
103k
      checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
912
103k
                     CondIsSignedBeforePromotion);
913
103k
914
103k
      // FIXME: This duplicates the check performed for warn_not_in_enum below.
915
103k
      checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
916
103k
                                 LoBeforePromotion);
917
103k
918
103k
      // Convert the value to the same width/sign as the condition.
919
103k
      AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
920
103k
921
103k
      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
922
103k
      if (CS->getRHS()) {
923
92
        if (CS->getRHS()->isValueDependent()) {
924
0
          HasDependentValue = true;
925
0
          break;
926
0
        }
927
92
        CaseRanges.push_back(std::make_pair(LoVal, CS));
928
92
      } else
929
103k
        CaseVals.push_back(std::make_pair(LoVal, CS));
930
103k
    }
931
108k
  }
932
14.9k
933
14.9k
  if (!HasDependentValue) {
934
12.6k
    // If we don't have a default statement, check whether the
935
12.6k
    // condition is constant.
936
12.6k
    llvm::APSInt ConstantCondValue;
937
12.6k
    bool HasConstantCond = false;
938
12.6k
    if (!HasDependentValue && !TheDefaultStmt) {
939
8.04k
      Expr::EvalResult Result;
940
8.04k
      HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
941
8.04k
                                                Expr::SE_AllowSideEffects);
942
8.04k
      if (Result.Val.isInt())
943
3.55k
        ConstantCondValue = Result.Val.getInt();
944
8.04k
      assert(!HasConstantCond ||
945
8.04k
             (ConstantCondValue.getBitWidth() == CondWidth &&
946
8.04k
              ConstantCondValue.isSigned() == CondIsSigned));
947
8.04k
    }
948
12.6k
    bool ShouldCheckConstantCond = HasConstantCond;
949
12.6k
950
12.6k
    // Sort all the scalar case values so we can easily detect duplicates.
951
12.6k
    llvm::stable_sort(CaseVals, CmpCaseVals);
952
12.6k
953
12.6k
    if (!CaseVals.empty()) {
954
116k
      for (unsigned i = 0, e = CaseVals.size(); i != e; 
++i103k
) {
955
103k
        if (ShouldCheckConstantCond &&
956
103k
            
CaseVals[i].first == ConstantCondValue27.1k
)
957
3.53k
          ShouldCheckConstantCond = false;
958
103k
959
103k
        if (i != 0 && 
CaseVals[i].first == CaseVals[i-1].first91.3k
) {
960
16
          // If we have a duplicate, report it.
961
16
          // First, determine if either case value has a name
962
16
          StringRef PrevString, CurrString;
963
16
          Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
964
16
          Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
965
16
          if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
966
4
            PrevString = DeclRef->getDecl()->getName();
967
4
          }
968
16
          if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
969
6
            CurrString = DeclRef->getDecl()->getName();
970
6
          }
971
16
          SmallString<16> CaseValStr;
972
16
          CaseVals[i-1].first.toString(CaseValStr);
973
16
974
16
          if (PrevString == CurrString)
975
13
            Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
976
13
                 diag::err_duplicate_case)
977
13
                << (PrevString.empty() ? 
StringRef(CaseValStr)10
:
PrevString3
);
978
3
          else
979
3
            Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
980
3
                 diag::err_duplicate_case_differing_expr)
981
3
                << (PrevString.empty() ? 
StringRef(CaseValStr)2
:
PrevString1
)
982
3
                << (CurrString.empty() ? 
StringRef(CaseValStr)0
: CurrString)
983
3
                << CaseValStr;
984
16
985
16
          Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
986
16
               diag::note_duplicate_case_prev);
987
16
          // FIXME: We really want to remove the bogus case stmt from the
988
16
          // substmt, but we have no way to do this right now.
989
16
          CaseListIsErroneous = true;
990
16
        }
991
103k
      }
992
12.3k
    }
993
12.6k
994
12.6k
    // Detect duplicate case ranges, which usually don't exist at all in
995
12.6k
    // the first place.
996
12.6k
    if (!CaseRanges.empty()) {
997
65
      // Sort all the case ranges by their low value so we can easily detect
998
65
      // overlaps between ranges.
999
65
      llvm::stable_sort(CaseRanges);
1000
65
1001
65
      // Scan the ranges, computing the high values and removing empty ranges.
1002
65
      std::vector<llvm::APSInt> HiVals;
1003
157
      for (unsigned i = 0, e = CaseRanges.size(); i != e; 
++i92
) {
1004
92
        llvm::APSInt &LoVal = CaseRanges[i].first;
1005
92
        CaseStmt *CR = CaseRanges[i].second;
1006
92
        Expr *Hi = CR->getRHS();
1007
92
1008
92
        const Expr *HiBeforePromotion = Hi;
1009
92
        GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1010
92
        llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
1011
92
1012
92
        // Check the unconverted value is within the range of possible values of
1013
92
        // the switch expression.
1014
92
        checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
1015
92
                       CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1016
92
1017
92
        // Convert the value to the same width/sign as the condition.
1018
92
        AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1019
92
1020
92
        // If the low value is bigger than the high value, the case is empty.
1021
92
        if (LoVal > HiVal) {
1022
5
          Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1023
5
              << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1024
5
          CaseRanges.erase(CaseRanges.begin()+i);
1025
5
          --i;
1026
5
          --e;
1027
5
          continue;
1028
5
        }
1029
87
1030
87
        if (ShouldCheckConstantCond &&
1031
87
            
LoVal <= ConstantCondValue1
&&
1032
87
            
ConstantCondValue <= HiVal1
)
1033
0
          ShouldCheckConstantCond = false;
1034
87
1035
87
        HiVals.push_back(HiVal);
1036
87
      }
1037
65
1038
65
      // Rescan the ranges, looking for overlap with singleton values and other
1039
65
      // ranges.  Since the range list is sorted, we only need to compare case
1040
65
      // ranges with their neighbors.
1041
152
      for (unsigned i = 0, e = CaseRanges.size(); i != e; 
++i87
) {
1042
87
        llvm::APSInt &CRLo = CaseRanges[i].first;
1043
87
        llvm::APSInt &CRHi = HiVals[i];
1044
87
        CaseStmt *CR = CaseRanges[i].second;
1045
87
1046
87
        // Check to see whether the case range overlaps with any
1047
87
        // singleton cases.
1048
87
        CaseStmt *OverlapStmt = nullptr;
1049
87
        llvm::APSInt OverlapVal(32);
1050
87
1051
87
        // Find the smallest value >= the lower bound.  If I is in the
1052
87
        // case range, then we have overlap.
1053
87
        CaseValsTy::iterator I =
1054
87
            llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
1055
87
        if (I != CaseVals.end() && 
I->first < CRHi18
) {
1056
1
          OverlapVal  = I->first;   // Found overlap with scalar.
1057
1
          OverlapStmt = I->second;
1058
1
        }
1059
87
1060
87
        // Find the smallest value bigger than the upper bound.
1061
87
        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1062
87
        if (I != CaseVals.begin() && 
(I-1)->first >= CRLo42
) {
1063
1
          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
1064
1
          OverlapStmt = (I-1)->second;
1065
1
        }
1066
87
1067
87
        // Check to see if this case stmt overlaps with the subsequent
1068
87
        // case range.
1069
87
        if (i && 
CRLo <= HiVals[i-1]26
) {
1070
1
          OverlapVal  = HiVals[i-1];       // Found overlap with range.
1071
1
          OverlapStmt = CaseRanges[i-1].second;
1072
1
        }
1073
87
1074
87
        if (OverlapStmt) {
1075
2
          // If we have a duplicate, report it.
1076
2
          Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1077
2
              << OverlapVal.toString(10);
1078
2
          Diag(OverlapStmt->getLHS()->getBeginLoc(),
1079
2
               diag::note_duplicate_case_prev);
1080
2
          // FIXME: We really want to remove the bogus case stmt from the
1081
2
          // substmt, but we have no way to do this right now.
1082
2
          CaseListIsErroneous = true;
1083
2
        }
1084
87
      }
1085
65
    }
1086
12.6k
1087
12.6k
    // Complain if we have a constant condition and we didn't find a match.
1088
12.6k
    if (!CaseListIsErroneous && 
!CaseListIsIncomplete12.6k
&&
1089
12.6k
        
ShouldCheckConstantCond12.5k
) {
1090
21
      // TODO: it would be nice if we printed enums as enums, chars as
1091
21
      // chars, etc.
1092
21
      Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1093
21
        << ConstantCondValue.toString(10)
1094
21
        << CondExpr->getSourceRange();
1095
21
    }
1096
12.6k
1097
12.6k
    // Check to see if switch is over an Enum and handles all of its
1098
12.6k
    // values.  We only issue a warning if there is not 'default:', but
1099
12.6k
    // we still do the analysis to preserve this information in the AST
1100
12.6k
    // (which can be used by flow-based analyes).
1101
12.6k
    //
1102
12.6k
    const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1103
12.6k
1104
12.6k
    // If switch has default case, then ignore it.
1105
12.6k
    if (!CaseListIsErroneous && 
!CaseListIsIncomplete12.6k
&&
!HasConstantCond12.5k
&&
1106
12.6k
        
ET9.01k
&&
ET->getDecl()->isCompleteDefinition()3.46k
) {
1107
3.46k
      const EnumDecl *ED = ET->getDecl();
1108
3.46k
      EnumValsTy EnumVals;
1109
3.46k
1110
3.46k
      // Gather all enum values, set their type and sort them,
1111
3.46k
      // allowing easier comparison with CaseVals.
1112
79.3k
      for (auto *EDI : ED->enumerators()) {
1113
79.3k
        llvm::APSInt Val = EDI->getInitVal();
1114
79.3k
        AdjustAPSInt(Val, CondWidth, CondIsSigned);
1115
79.3k
        EnumVals.push_back(std::make_pair(Val, EDI));
1116
79.3k
      }
1117
3.46k
      llvm::stable_sort(EnumVals, CmpEnumVals);
1118
3.46k
      auto EI = EnumVals.begin(), EIEnd =
1119
3.46k
        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1120
3.46k
1121
3.46k
      // See which case values aren't in enum.
1122
3.46k
      for (CaseValsTy::const_iterator CI = CaseVals.begin();
1123
25.0k
          CI != CaseVals.end(); 
CI++21.5k
) {
1124
21.5k
        Expr *CaseExpr = CI->second->getLHS();
1125
21.5k
        if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1126
21.5k
                                              CI->first))
1127
33
          Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1128
33
            << CondTypeBeforePromotion;
1129
21.5k
      }
1130
3.46k
1131
3.46k
      // See which of case ranges aren't in enum
1132
3.46k
      EI = EnumVals.begin();
1133
3.46k
      for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1134
3.47k
          RI != CaseRanges.end(); 
RI++13
) {
1135
13
        Expr *CaseExpr = RI->second->getLHS();
1136
13
        if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1137
13
                                              RI->first))
1138
6
          Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1139
6
            << CondTypeBeforePromotion;
1140
13
1141
13
        llvm::APSInt Hi =
1142
13
          RI->second->getRHS()->EvaluateKnownConstInt(Context);
1143
13
        AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1144
13
1145
13
        CaseExpr = RI->second->getRHS();
1146
13
        if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1147
13
                                              Hi))
1148
6
          Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1149
6
            << CondTypeBeforePromotion;
1150
13
      }
1151
3.46k
1152
3.46k
      // Check which enum vals aren't in switch
1153
3.46k
      auto CI = CaseVals.begin();
1154
3.46k
      auto RI = CaseRanges.begin();
1155
3.46k
      bool hasCasesNotInSwitch = false;
1156
3.46k
1157
3.46k
      SmallVector<DeclarationName,8> UnhandledNames;
1158
3.46k
1159
82.6k
      for (EI = EnumVals.begin(); EI != EIEnd; 
EI++79.2k
) {
1160
79.2k
        // Don't warn about omitted unavailable EnumConstantDecls.
1161
79.2k
        switch (EI->second->getAvailability()) {
1162
79.2k
        case AR_Deprecated:
1163
6
          // Omitting a deprecated constant is ok; it should never materialize.
1164
6
        case AR_Unavailable:
1165
6
          continue;
1166
6
1167
79.2k
        case AR_NotYetIntroduced:
1168
79.2k
          // Partially available enum constants should be present. Note that we
1169
79.2k
          // suppress -Wunguarded-availability diagnostics for such uses.
1170
79.2k
        case AR_Available:
1171
79.2k
          break;
1172
79.2k
        }
1173
79.2k
1174
79.2k
        if (EI->second->hasAttr<UnusedAttr>())
1175
4
          continue;
1176
79.2k
1177
79.2k
        // Drop unneeded case values
1178
97.9k
        
while (79.2k
CI != CaseVals.end() &&
CI->first < EI->first55.7k
)
1179
18.7k
          CI++;
1180
79.2k
1181
79.2k
        if (CI != CaseVals.end() && 
CI->first == EI->first37.0k
)
1182
21.5k
          continue;
1183
57.6k
1184
57.6k
        // Drop unneeded case ranges
1185
57.6k
        
for (; 57.6k
RI != CaseRanges.end();
RI++3
) {
1186
21
          llvm::APSInt Hi =
1187
21
            RI->second->getRHS()->EvaluateKnownConstInt(Context);
1188
21
          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1189
21
          if (EI->first <= Hi)
1190
18
            break;
1191
21
        }
1192
57.6k
1193
57.6k
        if (RI == CaseRanges.end() || 
EI->first < RI->first18
) {
1194
57.6k
          hasCasesNotInSwitch = true;
1195
57.6k
          UnhandledNames.push_back(EI->second->getDeclName());
1196
57.6k
        }
1197
57.6k
      }
1198
3.46k
1199
3.46k
      if (TheDefaultStmt && 
UnhandledNames.empty()1.31k
&&
ED->isClosedNonFlag()468
)
1200
460
        Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1201
3.46k
1202
3.46k
      // Produce a nice diagnostic if multiple values aren't handled.
1203
3.46k
      if (!UnhandledNames.empty()) {
1204
903
        DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1205
903
                                    TheDefaultStmt ? 
diag::warn_def_missing_case848
1206
903
                                                   : 
diag::warn_missing_case55
)
1207
903
                               << (int)UnhandledNames.size();
1208
903
1209
903
        for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1210
2.94k
             I != E; 
++I2.04k
)
1211
2.04k
          DB << UnhandledNames[I];
1212
903
      }
1213
3.46k
1214
3.46k
      if (!hasCasesNotInSwitch)
1215
2.56k
        SS->setAllEnumCasesCovered();
1216
3.46k
    }
1217
12.6k
  }
1218
14.9k
1219
14.9k
  if (BodyStmt)
1220
14.9k
    DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
1221
14.9k
                          diag::warn_empty_switch_body);
1222
14.9k
1223
14.9k
  // FIXME: If the case list was broken is some way, we don't have a good system
1224
14.9k
  // to patch it up.  Instead, just return the whole substmt as broken.
1225
14.9k
  if (CaseListIsErroneous)
1226
11
    return StmtError();
1227
14.8k
1228
14.8k
  return SS;
1229
14.8k
}
1230
1231
void
1232
Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1233
6.93M
                             Expr *SrcExpr) {
1234
6.93M
  if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1235
6.93M
    return;
1236
407
1237
407
  if (const EnumType *ET = DstType->getAs<EnumType>())
1238
52
    if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1239
52
        
SrcType->isIntegerType()43
) {
1240
43
      if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1241
43
          SrcExpr->isIntegerConstantExpr(Context)) {
1242
43
        // Get the bitwidth of the enum value before promotions.
1243
43
        unsigned DstWidth = Context.getIntWidth(DstType);
1244
43
        bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1245
43
1246
43
        llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1247
43
        AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1248
43
        const EnumDecl *ED = ET->getDecl();
1249
43
1250
43
        if (!ED->isClosed())
1251
4
          return;
1252
39
1253
39
        if (ED->hasAttr<FlagEnumAttr>()) {
1254
19
          if (!IsValueInFlagEnum(ED, RhsVal, true))
1255
6
            Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1256
6
              << DstType.getUnqualifiedType();
1257
20
        } else {
1258
20
          typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1259
20
              EnumValsTy;
1260
20
          EnumValsTy EnumVals;
1261
20
1262
20
          // Gather all enum values, set their type and sort them,
1263
20
          // allowing easier comparison with rhs constant.
1264
50
          for (auto *EDI : ED->enumerators()) {
1265
50
            llvm::APSInt Val = EDI->getInitVal();
1266
50
            AdjustAPSInt(Val, DstWidth, DstIsSigned);
1267
50
            EnumVals.push_back(std::make_pair(Val, EDI));
1268
50
          }
1269
20
          if (EnumVals.empty())
1270
0
            return;
1271
20
          llvm::stable_sort(EnumVals, CmpEnumVals);
1272
20
          EnumValsTy::iterator EIend =
1273
20
              std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1274
20
1275
20
          // See which values aren't in the enum.
1276
20
          EnumValsTy::const_iterator EI = EnumVals.begin();
1277
58
          while (EI != EIend && 
EI->first < RhsVal45
)
1278
38
            EI++;
1279
20
          if (EI == EIend || 
EI->first != RhsVal7
) {
1280
15
            Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1281
15
                << DstType.getUnqualifiedType();
1282
15
          }
1283
20
        }
1284
39
      }
1285
43
    }
1286
407
}
1287
1288
StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1289
58.2k
                                Stmt *Body) {
1290
58.2k
  if (Cond.isInvalid())
1291
0
    return StmtError();
1292
58.2k
1293
58.2k
  auto CondVal = Cond.get();
1294
58.2k
  CheckBreakContinueBinding(CondVal.second);
1295
58.2k
1296
58.2k
  if (CondVal.second &&
1297
58.2k
      !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1298
6
    CommaVisitor(*this).Visit(CondVal.second);
1299
58.2k
1300
58.2k
  if (isa<NullStmt>(Body))
1301
2.77k
    getCurCompoundScope().setHasEmptyLoopBodies();
1302
58.2k
1303
58.2k
  return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1304
58.2k
                           WhileLoc);
1305
58.2k
}
1306
1307
StmtResult
1308
Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1309
                  SourceLocation WhileLoc, SourceLocation CondLParen,
1310
146k
                  Expr *Cond, SourceLocation CondRParen) {
1311
146k
  assert(Cond && "ActOnDoStmt(): missing expression");
1312
146k
1313
146k
  CheckBreakContinueBinding(Cond);
1314
146k
  ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1315
146k
  if (CondResult.isInvalid())
1316
2
    return StmtError();
1317
146k
  Cond = CondResult.get();
1318
146k
1319
146k
  CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
1320
146k
  if (CondResult.isInvalid())
1321
1
    return StmtError();
1322
146k
  Cond = CondResult.get();
1323
146k
1324
146k
  // Only call the CommaVisitor for C89 due to differences in scope flags.
1325
146k
  if (Cond && !getLangOpts().C99 && 
!getLangOpts().CPlusPlus144k
&&
1326
146k
      
!Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc())106
)
1327
1
    CommaVisitor(*this).Visit(Cond);
1328
146k
1329
146k
  return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1330
146k
}
1331
1332
namespace {
1333
  // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1334
  using DeclSetVector =
1335
      llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1336
                      llvm::SmallPtrSet<VarDecl *, 8>>;
1337
1338
  // This visitor will traverse a conditional statement and store all
1339
  // the evaluated decls into a vector.  Simple is set to true if none
1340
  // of the excluded constructs are used.
1341
  class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1342
    DeclSetVector &Decls;
1343
    SmallVectorImpl<SourceRange> &Ranges;
1344
    bool Simple;
1345
  public:
1346
    typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1347
1348
    DeclExtractor(Sema &S, DeclSetVector &Decls,
1349
                  SmallVectorImpl<SourceRange> &Ranges) :
1350
        Inherited(S.Context),
1351
        Decls(Decls),
1352
        Ranges(Ranges),
1353
53.3k
        Simple(true) {}
1354
1355
53.3k
    bool isSimple() { return Simple; }
1356
1357
    // Replaces the method in EvaluatedExprVisitor.
1358
4.68k
    void VisitMemberExpr(MemberExpr* E) {
1359
4.68k
      Simple = false;
1360
4.68k
    }
1361
1362
    // Any Stmt not whitelisted will cause the condition to be marked complex.
1363
3.44k
    void VisitStmt(Stmt *S) {
1364
3.44k
      Simple = false;
1365
3.44k
    }
1366
1367
59.6k
    void VisitBinaryOperator(BinaryOperator *E) {
1368
59.6k
      Visit(E->getLHS());
1369
59.6k
      Visit(E->getRHS());
1370
59.6k
    }
1371
1372
98.2k
    void VisitCastExpr(CastExpr *E) {
1373
98.2k
      Visit(E->getSubExpr());
1374
98.2k
    }
1375
1376
116
    void VisitUnaryOperator(UnaryOperator *E) {
1377
116
      // Skip checking conditionals with derefernces.
1378
116
      if (E->getOpcode() == UO_Deref)
1379
105
        Simple = false;
1380
11
      else
1381
11
        Visit(E->getSubExpr());
1382
116
    }
1383
1384
12
    void VisitConditionalOperator(ConditionalOperator *E) {
1385
12
      Visit(E->getCond());
1386
12
      Visit(E->getTrueExpr());
1387
12
      Visit(E->getFalseExpr());
1388
12
    }
1389
1390
902
    void VisitParenExpr(ParenExpr *E) {
1391
902
      Visit(E->getSubExpr());
1392
902
    }
1393
1394
3
    void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1395
3
      Visit(E->getOpaqueValue()->getSourceExpr());
1396
3
      Visit(E->getFalseExpr());
1397
3
    }
1398
1399
6.67k
    void VisitIntegerLiteral(IntegerLiteral *E) { }
1400
2
    void VisitFloatingLiteral(FloatingLiteral *E) { }
1401
2
    void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1402
42
    void VisitCharacterLiteral(CharacterLiteral *E) { }
1403
2
    void VisitGNUNullExpr(GNUNullExpr *E) { }
1404
2
    void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1405
1406
96.2k
    void VisitDeclRefExpr(DeclRefExpr *E) {
1407
96.2k
      VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1408
96.2k
      if (!VD) {
1409
4.21k
        // Don't allow unhandled Decl types.
1410
4.21k
        Simple = false;
1411
4.21k
        return;
1412
4.21k
      }
1413
92.0k
1414
92.0k
      Ranges.push_back(E->getSourceRange());
1415
92.0k
1416
92.0k
      Decls.insert(VD);
1417
92.0k
    }
1418
1419
  }; // end class DeclExtractor
1420
1421
  // DeclMatcher checks to see if the decls are used in a non-evaluated
1422
  // context.
1423
  class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1424
    DeclSetVector &Decls;
1425
    bool FoundDecl;
1426
1427
  public:
1428
    typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1429
1430
    DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1431
49.3k
        Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1432
49.3k
      if (!Statement) 
return60
;
1433
49.3k
1434
49.3k
      Visit(Statement);
1435
49.3k
    }
1436
1437
1
    void VisitReturnStmt(ReturnStmt *S) {
1438
1
      FoundDecl = true;
1439
1
    }
1440
1441
25
    void VisitBreakStmt(BreakStmt *S) {
1442
25
      FoundDecl = true;
1443
25
    }
1444
1445
1
    void VisitGotoStmt(GotoStmt *S) {
1446
1
      FoundDecl = true;
1447
1
    }
1448
1449
58.6k
    void VisitCastExpr(CastExpr *E) {
1450
58.6k
      if (E->getCastKind() == CK_LValueToRValue)
1451
53.8k
        CheckLValueToRValueCast(E->getSubExpr());
1452
4.75k
      else
1453
4.75k
        Visit(E->getSubExpr());
1454
58.6k
    }
1455
1456
53.8k
    void CheckLValueToRValueCast(Expr *E) {
1457
53.8k
      E = E->IgnoreParenImpCasts();
1458
53.8k
1459
53.8k
      if (isa<DeclRefExpr>(E)) {
1460
53.6k
        return;
1461
53.6k
      }
1462
194
1463
194
      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1464
7
        Visit(CO->getCond());
1465
7
        CheckLValueToRValueCast(CO->getTrueExpr());
1466
7
        CheckLValueToRValueCast(CO->getFalseExpr());
1467
7
        return;
1468
7
      }
1469
187
1470
187
      if (BinaryConditionalOperator *BCO =
1471
4
              dyn_cast<BinaryConditionalOperator>(E)) {
1472
4
        CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1473
4
        CheckLValueToRValueCast(BCO->getFalseExpr());
1474
4
        return;
1475
4
      }
1476
183
1477
183
      Visit(E);
1478
183
    }
1479
1480
25.8k
    void VisitDeclRefExpr(DeclRefExpr *E) {
1481
25.8k
      if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1482
25.7k
        if (Decls.count(VD))
1483
24.6k
          FoundDecl = true;
1484
25.8k
    }
1485
1486
1
    void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1487
1
      // Only need to visit the semantics for POE.
1488
1
      // SyntaticForm doesn't really use the Decal.
1489
3
      for (auto *S : POE->semantics()) {
1490
3
        if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1491
2
          // Look past the OVE into the expression it binds.
1492
2
          Visit(OVE->getSourceExpr());
1493
1
        else
1494
1
          Visit(S);
1495
3
      }
1496
1
    }
1497
1498
49.3k
    bool FoundDeclInUse() { return FoundDecl; }
1499
1500
  };  // end class DeclMatcher
1501
1502
  void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1503
252k
                                        Expr *Third, Stmt *Body) {
1504
252k
    // Condition is empty
1505
252k
    if (!Second) 
return11.2k
;
1506
241k
1507
241k
    if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1508
241k
                          Second->getBeginLoc()))
1509
187k
      return;
1510
53.3k
1511
53.3k
    PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1512
53.3k
    DeclSetVector Decls;
1513
53.3k
    SmallVector<SourceRange, 10> Ranges;
1514
53.3k
    DeclExtractor DE(S, Decls, Ranges);
1515
53.3k
    DE.Visit(Second);
1516
53.3k
1517
53.3k
    // Don't analyze complex conditionals.
1518
53.3k
    if (!DE.isSimple()) 
return12.3k
;
1519
41.0k
1520
41.0k
    // No decls found.
1521
41.0k
    if (Decls.size() == 0) 
return0
;
1522
41.0k
1523
41.0k
    // Don't warn on volatile, static, or global variables.
1524
41.0k
    for (auto *VD : Decls)
1525
79.6k
      if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1526
16.3k
        return;
1527
41.0k
1528
41.0k
    
if (24.6k
DeclMatcher(S, Decls, Second).FoundDeclInUse()24.6k
||
1529
24.6k
        
DeclMatcher(S, Decls, Third).FoundDeclInUse()24.6k
||
1530
24.6k
        
DeclMatcher(S, Decls, Body).FoundDeclInUse()86
)
1531
24.6k
      return;
1532
35
1533
35
    // Load decl names into diagnostic.
1534
35
    if (Decls.size() > 4) {
1535
2
      PDiag << 0;
1536
33
    } else {
1537
33
      PDiag << (unsigned)Decls.size();
1538
33
      for (auto *VD : Decls)
1539
51
        PDiag << VD->getDeclName();
1540
33
    }
1541
35
1542
35
    for (auto Range : Ranges)
1543
129
      PDiag << Range;
1544
35
1545
35
    S.Diag(Ranges.begin()->getBegin(), PDiag);
1546
35
  }
1547
1548
  // If Statement is an incemement or decrement, return true and sets the
1549
  // variables Increment and DRE.
1550
  bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1551
68.9k
                            DeclRefExpr *&DRE) {
1552
68.9k
    if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1553
24
      if (!Cleanups->cleanupsHaveSideEffects())
1554
12
        Statement = Cleanups->getSubExpr();
1555
68.9k
1556
68.9k
    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1557
30.9k
      switch (UO->getOpcode()) {
1558
30.9k
        
default: return false0
;
1559
30.9k
        case UO_PostInc:
1560
27.5k
        case UO_PreInc:
1561
27.5k
          Increment = true;
1562
27.5k
          break;
1563
27.5k
        case UO_PostDec:
1564
3.45k
        case UO_PreDec:
1565
3.45k
          Increment = false;
1566
3.45k
          break;
1567
30.9k
      }
1568
30.9k
      DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1569
30.9k
      return DRE;
1570
30.9k
    }
1571
37.9k
1572
37.9k
    if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1573
38
      FunctionDecl *FD = Call->getDirectCallee();
1574
38
      if (!FD || !FD->isOverloadedOperator()) 
return false0
;
1575
38
      switch (FD->getOverloadedOperator()) {
1576
38
        
default: return false0
;
1577
38
        case OO_PlusPlus:
1578
26
          Increment = true;
1579
26
          break;
1580
38
        case OO_MinusMinus:
1581
12
          Increment = false;
1582
12
          break;
1583
38
      }
1584
38
      DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1585
38
      return DRE;
1586
38
    }
1587
37.9k
1588
37.9k
    return false;
1589
37.9k
  }
1590
1591
  // A visitor to determine if a continue or break statement is a
1592
  // subexpression.
1593
  class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1594
    SourceLocation BreakLoc;
1595
    SourceLocation ContinueLoc;
1596
    bool InSwitch = false;
1597
1598
  public:
1599
    BreakContinueFinder(Sema &S, const Stmt* Body) :
1600
54.5k
        Inherited(S.Context) {
1601
54.5k
      Visit(Body);
1602
54.5k
    }
1603
1604
    typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
1605
1606
17
    void VisitContinueStmt(const ContinueStmt* E) {
1607
17
      ContinueLoc = E->getContinueLoc();
1608
17
    }
1609
1610
29
    void VisitBreakStmt(const BreakStmt* E) {
1611
29
      if (!InSwitch)
1612
28
        BreakLoc = E->getBreakLoc();
1613
29
    }
1614
1615
2
    void VisitSwitchStmt(const SwitchStmt* S) {
1616
2
      if (const Stmt *Init = S->getInit())
1617
0
        Visit(Init);
1618
2
      if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1619
0
        Visit(CondVar);
1620
2
      if (const Stmt *Cond = S->getCond())
1621
2
        Visit(Cond);
1622
2
1623
2
      // Don't return break statements from the body of a switch.
1624
2
      InSwitch = true;
1625
2
      if (const Stmt *Body = S->getBody())
1626
2
        Visit(Body);
1627
2
      InSwitch = false;
1628
2
    }
1629
1630
4
    void VisitForStmt(const ForStmt *S) {
1631
4
      // Only visit the init statement of a for loop; the body
1632
4
      // has a different break/continue scope.
1633
4
      if (const Stmt *Init = S->getInit())
1634
3
        Visit(Init);
1635
4
    }
1636
1637
7
    void VisitWhileStmt(const WhileStmt *) {
1638
7
      // Do nothing; the children of a while loop have a different
1639
7
      // break/continue scope.
1640
7
    }
1641
1642
8
    void VisitDoStmt(const DoStmt *) {
1643
8
      // Do nothing; the children of a while loop have a different
1644
8
      // break/continue scope.
1645
8
    }
1646
1647
0
    void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1648
0
      // Only visit the initialization of a for loop; the body
1649
0
      // has a different break/continue scope.
1650
0
      if (const Stmt *Init = S->getInit())
1651
0
        Visit(Init);
1652
0
      if (const Stmt *Range = S->getRangeStmt())
1653
0
        Visit(Range);
1654
0
      if (const Stmt *Begin = S->getBeginStmt())
1655
0
        Visit(Begin);
1656
0
      if (const Stmt *End = S->getEndStmt())
1657
0
        Visit(End);
1658
0
    }
1659
1660
0
    void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1661
0
      // Only visit the initialization of a for loop; the body
1662
0
      // has a different break/continue scope.
1663
0
      if (const Stmt *Element = S->getElement())
1664
0
        Visit(Element);
1665
0
      if (const Stmt *Collection = S->getCollection())
1666
0
        Visit(Collection);
1667
0
    }
1668
1669
54.5k
    bool ContinueFound() { return ContinueLoc.isValid(); }
1670
54.5k
    bool BreakFound() { return BreakLoc.isValid(); }
1671
7
    SourceLocation GetContinueLoc() { return ContinueLoc; }
1672
17
    SourceLocation GetBreakLoc() { return BreakLoc; }
1673
1674
  };  // end class BreakContinueFinder
1675
1676
  // Emit a warning when a loop increment/decrement appears twice per loop
1677
  // iteration.  The conditions which trigger this warning are:
1678
  // 1) The last statement in the loop body and the third expression in the
1679
  //    for loop are both increment or both decrement of the same variable
1680
  // 2) No continue statements in the loop body.
1681
252k
  void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1682
252k
    // Return when there is nothing to check.
1683
252k
    if (!Body || !Third) 
return9.14k
;
1684
243k
1685
243k
    if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1686
243k
                          Third->getBeginLoc()))
1687
184k
      return;
1688
58.5k
1689
58.5k
    // Get the last statement from the loop body.
1690
58.5k
    CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1691
58.5k
    if (!CS || 
CS->body_empty()38.2k
)
return20.4k
;
1692
38.1k
    Stmt *LastStmt = CS->body_back();
1693
38.1k
    if (!LastStmt) 
return0
;
1694
38.1k
1695
38.1k
    bool LoopIncrement, LastIncrement;
1696
38.1k
    DeclRefExpr *LoopDRE, *LastDRE;
1697
38.1k
1698
38.1k
    if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) 
return7.29k
;
1699
30.8k
    if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) 
return30.7k
;
1700
86
1701
86
    // Check that the two statements are both increments or both decrements
1702
86
    // on the same variable.
1703
86
    if (LoopIncrement != LastIncrement ||
1704
86
        
LoopDRE->getDecl() != LastDRE->getDecl()70
)
return64
;
1705
22
1706
22
    if (BreakContinueFinder(S, Body).ContinueFound()) 
return4
;
1707
18
1708
18
    S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1709
18
         << LastDRE->getDecl() << LastIncrement;
1710
18
    S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1711
18
         << LoopIncrement;
1712
18
  }
1713
1714
} // end namespace
1715
1716
1717
709k
void Sema::CheckBreakContinueBinding(Expr *E) {
1718
709k
  if (!E || 
getLangOpts().CPlusPlus689k
)
1719
654k
    return;
1720
54.5k
  BreakContinueFinder BCFinder(*this, E);
1721
54.5k
  Scope *BreakParent = CurScope->getBreakParent();
1722
54.5k
  if (BCFinder.BreakFound() && 
BreakParent24
) {
1723
17
    if (BreakParent->getFlags() & Scope::SwitchScope) {
1724
5
      Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1725
12
    } else {
1726
12
      Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1727
12
          << "break";
1728
12
    }
1729
54.5k
  } else if (BCFinder.ContinueFound() && 
CurScope->getContinueParent()13
) {
1730
7
    Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1731
7
        << "continue";
1732
7
  }
1733
54.5k
}
1734
1735
StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1736
                              Stmt *First, ConditionResult Second,
1737
                              FullExprArg third, SourceLocation RParenLoc,
1738
252k
                              Stmt *Body) {
1739
252k
  if (Second.isInvalid())
1740
32
    return StmtError();
1741
252k
1742
252k
  if (!getLangOpts().CPlusPlus) {
1743
24.4k
    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1744
2.78k
      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1745
2.78k
      // declare identifiers for objects having storage class 'auto' or
1746
2.78k
      // 'register'.
1747
2.80k
      for (auto *DI : DS->decls()) {
1748
2.80k
        VarDecl *VD = dyn_cast<VarDecl>(DI);
1749
2.80k
        if (VD && 
VD->isLocalVarDecl()2.80k
&&
!VD->hasLocalStorage()2.80k
)
1750
1
          VD = nullptr;
1751
2.80k
        if (!VD) {
1752
3
          Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1753
3
          DI->setInvalidDecl();
1754
3
        }
1755
2.80k
      }
1756
2.78k
    }
1757
24.4k
  }
1758
252k
1759
252k
  CheckBreakContinueBinding(Second.get().second);
1760
252k
  CheckBreakContinueBinding(third.get());
1761
252k
1762
252k
  if (!Second.get().first)
1763
252k
    CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1764
252k
                                     Body);
1765
252k
  CheckForRedundantIteration(*this, third.get(), Body);
1766
252k
1767
252k
  if (Second.get().second &&
1768
252k
      !Diags.isIgnored(diag::warn_comma_operator,
1769
241k
                       Second.get().second->getExprLoc()))
1770
160
    CommaVisitor(*this).Visit(Second.get().second);
1771
252k
1772
252k
  Expr *Third  = third.release().getAs<Expr>();
1773
252k
  if (isa<NullStmt>(Body))
1774
11.2k
    getCurCompoundScope().setHasEmptyLoopBodies();
1775
252k
1776
252k
  return new (Context)
1777
252k
      ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1778
252k
              Body, ForLoc, LParenLoc, RParenLoc);
1779
252k
}
1780
1781
/// In an Objective C collection iteration statement:
1782
///   for (x in y)
1783
/// x can be an arbitrary l-value expression.  Bind it up as a
1784
/// full-expression.
1785
49
StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1786
49
  // Reduce placeholder expressions here.  Note that this rejects the
1787
49
  // use of pseudo-object l-values in this position.
1788
49
  ExprResult result = CheckPlaceholderExpr(E);
1789
49
  if (result.isInvalid()) 
return StmtError()0
;
1790
49
  E = result.get();
1791
49
1792
49
  ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
1793
49
  if (FullExpr.isInvalid())
1794
0
    return StmtError();
1795
49
  return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1796
49
}
1797
1798
ExprResult
1799
265
Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1800
265
  if (!collection)
1801
0
    return ExprError();
1802
265
1803
265
  ExprResult result = CorrectDelayedTyposInExpr(collection);
1804
265
  if (!result.isUsable())
1805
2
    return ExprError();
1806
263
  collection = result.get();
1807
263
1808
263
  // Bail out early if we've got a type-dependent expression.
1809
263
  if (collection->isTypeDependent()) 
return collection6
;
1810
257
1811
257
  // Perform normal l-value conversion.
1812
257
  result = DefaultFunctionArrayLvalueConversion(collection);
1813
257
  if (result.isInvalid())
1814
0
    return ExprError();
1815
257
  collection = result.get();
1816
257
1817
257
  // The operand needs to have object-pointer type.
1818
257
  // TODO: should we do a contextual conversion?
1819
257
  const ObjCObjectPointerType *pointerType =
1820
257
    collection->getType()->getAs<ObjCObjectPointerType>();
1821
257
  if (!pointerType)
1822
6
    return Diag(forLoc, diag::err_collection_expr_type)
1823
6
             << collection->getType() << collection->getSourceRange();
1824
251
1825
251
  // Check that the operand provides
1826
251
  //   - countByEnumeratingWithState:objects:count:
1827
251
  const ObjCObjectType *objectType = pointerType->getObjectType();
1828
251
  ObjCInterfaceDecl *iface = objectType->getInterface();
1829
251
1830
251
  // If we have a forward-declared type, we can't do this check.
1831
251
  // Under ARC, it is an error not to have a forward-declared class.
1832
251
  if (iface &&
1833
251
      (getLangOpts().ObjCAutoRefCount
1834
127
           ? RequireCompleteType(forLoc, QualType(objectType, 0),
1835
19
                                 diag::err_arc_collection_forward, collection)
1836
127
           : 
!isCompleteType(forLoc, QualType(objectType, 0))108
)) {
1837
20
    // Otherwise, if we have any useful type information, check that
1838
20
    // the type declares the appropriate method.
1839
231
  } else if (iface || 
!objectType->qual_empty()124
) {
1840
107
    IdentifierInfo *selectorIdents[] = {
1841
107
      &Context.Idents.get("countByEnumeratingWithState"),
1842
107
      &Context.Idents.get("objects"),
1843
107
      &Context.Idents.get("count")
1844
107
    };
1845
107
    Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1846
107
1847
107
    ObjCMethodDecl *method = nullptr;
1848
107
1849
107
    // If there's an interface, look in both the public and private APIs.
1850
107
    if (iface) {
1851
107
      method = iface->lookupInstanceMethod(selector);
1852
107
      if (!method) 
method = iface->lookupPrivateMethod(selector)30
;
1853
107
    }
1854
107
1855
107
    // Also check protocol qualifiers.
1856
107
    if (!method)
1857
13
      method = LookupMethodInQualifiedType(selector, pointerType,
1858
13
                                           /*instance*/ true);
1859
107
1860
107
    // If we didn't find it anywhere, give up.
1861
107
    if (!method) {
1862
8
      Diag(forLoc, diag::warn_collection_expr_type)
1863
8
        << collection->getType() << selector << collection->getSourceRange();
1864
8
    }
1865
107
1866
107
    // TODO: check for an incompatible signature?
1867
107
  }
1868
251
1869
251
  // Wrap up any cleanups in the expression.
1870
251
  return collection;
1871
251
}
1872
1873
StmtResult
1874
Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1875
                                 Stmt *First, Expr *collection,
1876
265
                                 SourceLocation RParenLoc) {
1877
265
  setFunctionHasBranchProtectedScope();
1878
265
1879
265
  ExprResult CollectionExprResult =
1880
265
    CheckObjCForCollectionOperand(ForLoc, collection);
1881
265
1882
265
  if (First) {
1883
265
    QualType FirstType;
1884
265
    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1885
210
      if (!DS->isSingleDecl())
1886
1
        return StmtError(Diag((*DS->decl_begin())->getLocation(),
1887
1
                         diag::err_toomany_element_decls));
1888
209
1889
209
      VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1890
209
      if (!D || 
D->isInvalidDecl()208
)
1891
1
        return StmtError();
1892
208
1893
208
      FirstType = D->getType();
1894
208
      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1895
208
      // declare identifiers for objects having storage class 'auto' or
1896
208
      // 'register'.
1897
208
      if (!D->hasLocalStorage())
1898
0
        return StmtError(Diag(D->getLocation(),
1899
0
                              diag::err_non_local_variable_decl_in_for));
1900
208
1901
208
      // If the type contained 'auto', deduce the 'auto' to 'id'.
1902
208
      if (FirstType->getContainedAutoType()) {
1903
2
        OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1904
2
                                 VK_RValue);
1905
2
        Expr *DeducedInit = &OpaqueId;
1906
2
        if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1907
2
                DAR_Failed)
1908
0
          DiagnoseAutoDeductionFailure(D, DeducedInit);
1909
2
        if (FirstType.isNull()) {
1910
0
          D->setInvalidDecl();
1911
0
          return StmtError();
1912
0
        }
1913
2
1914
2
        D->setType(FirstType);
1915
2
1916
2
        if (!inTemplateInstantiation()) {
1917
1
          SourceLocation Loc =
1918
1
              D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1919
1
          Diag(Loc, diag::warn_auto_var_is_id)
1920
1
            << D->getDeclName();
1921
1
        }
1922
2
      }
1923
208
1924
208
    } else {
1925
55
      Expr *FirstE = cast<Expr>(First);
1926
55
      if (!FirstE->isTypeDependent() && 
!FirstE->isLValue()54
)
1927
3
        return StmtError(
1928
3
            Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1929
3
            << First->getSourceRange());
1930
52
1931
52
      FirstType = static_cast<Expr*>(First)->getType();
1932
52
      if (FirstType.isConstQualified())
1933
2
        Diag(ForLoc, diag::err_selector_element_const_type)
1934
2
          << FirstType << First->getSourceRange();
1935
52
    }
1936
265
    
if (260
!FirstType->isDependentType()260
&&
1937
260
        
!FirstType->isObjCObjectPointerType()258
&&
1938
260
        
!FirstType->isBlockPointerType()10
)
1939
7
        return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1940
7
                           << FirstType << First->getSourceRange());
1941
253
  }
1942
253
1943
253
  if (CollectionExprResult.isInvalid())
1944
6
    return StmtError();
1945
247
1946
247
  CollectionExprResult =
1947
247
      ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
1948
247
  if (CollectionExprResult.isInvalid())
1949
1
    return StmtError();
1950
246
1951
246
  return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1952
246
                                             nullptr, ForLoc, RParenLoc);
1953
246
}
1954
1955
/// Finish building a variable declaration for a for-range statement.
1956
/// \return true if an error occurs.
1957
static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1958
8.47k
                                  SourceLocation Loc, int DiagID) {
1959
8.47k
  if (Decl->getType()->isUndeducedType()) {
1960
8.47k
    ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1961
8.47k
    if (!Res.isUsable()) {
1962
0
      Decl->setInvalidDecl();
1963
0
      return true;
1964
0
    }
1965
8.47k
    Init = Res.get();
1966
8.47k
  }
1967
8.47k
1968
8.47k
  // Deduce the type for the iterator variable now rather than leaving it to
1969
8.47k
  // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1970
8.47k
  QualType InitType;
1971
8.47k
  if ((!isa<InitListExpr>(Init) && 
Init->getType()->isVoidType()8.46k
) ||
1972
8.47k
      SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1973
8.46k
          Sema::DAR_Failed)
1974
12
    SemaRef.Diag(Loc, DiagID) << Init->getType();
1975
8.47k
  if (InitType.isNull()) {
1976
13
    Decl->setInvalidDecl();
1977
13
    return true;
1978
13
  }
1979
8.46k
  Decl->setType(InitType);
1980
8.46k
1981
8.46k
  // In ARC, infer lifetime.
1982
8.46k
  // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1983
8.46k
  // we're doing the equivalent of fast iteration.
1984
8.46k
  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1985
8.46k
      
SemaRef.inferObjCARCLifetime(Decl)6
)
1986
0
    Decl->setInvalidDecl();
1987
8.46k
1988
8.46k
  SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
1989
8.46k
  SemaRef.FinalizeDeclaration(Decl);
1990
8.46k
  SemaRef.CurContext->addHiddenDecl(Decl);
1991
8.46k
  return false;
1992
8.46k
}
1993
1994
namespace {
1995
// An enum to represent whether something is dealing with a call to begin()
1996
// or a call to end() in a range-based for loop.
1997
enum BeginEndFunction {
1998
  BEF_begin,
1999
  BEF_end
2000
};
2001
2002
/// Produce a note indicating which begin/end function was implicitly called
2003
/// by a C++11 for-range statement. This is often not obvious from the code,
2004
/// nor from the diagnostics produced when analysing the implicit expressions
2005
/// required in a for-range statement.
2006
void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2007
40
                                  BeginEndFunction BEF) {
2008
40
  CallExpr *CE = dyn_cast<CallExpr>(E);
2009
40
  if (!CE)
2010
6
    return;
2011
34
  FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2012
34
  if (!D)
2013
0
    return;
2014
34
  SourceLocation Loc = D->getLocation();
2015
34
2016
34
  std::string Description;
2017
34
  bool IsTemplate = false;
2018
34
  if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2019
3
    Description = SemaRef.getTemplateArgumentBindingsText(
2020
3
      FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2021
3
    IsTemplate = true;
2022
3
  }
2023
34
2024
34
  SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2025
34
    << BEF << IsTemplate << Description << E->getType();
2026
34
}
2027
2028
/// Build a variable declaration for a for-range statement.
2029
VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2030
8.61k
                              QualType Type, StringRef Name) {
2031
8.61k
  DeclContext *DC = SemaRef.CurContext;
2032
8.61k
  IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2033
8.61k
  TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2034
8.61k
  VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2035
8.61k
                                  TInfo, SC_None);
2036
8.61k
  Decl->setImplicit();
2037
8.61k
  return Decl;
2038
8.61k
}
2039
2040
}
2041
2042
2.87k
static bool ObjCEnumerationCollection(Expr *Collection) {
2043
2.87k
  return !Collection->isTypeDependent()
2044
2.87k
          && 
Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr2.84k
;
2045
2.87k
}
2046
2047
/// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2048
///
2049
/// C++11 [stmt.ranged]:
2050
///   A range-based for statement is equivalent to
2051
///
2052
///   {
2053
///     auto && __range = range-init;
2054
///     for ( auto __begin = begin-expr,
2055
///           __end = end-expr;
2056
///           __begin != __end;
2057
///           ++__begin ) {
2058
///       for-range-declaration = *__begin;
2059
///       statement
2060
///     }
2061
///   }
2062
///
2063
/// The body of the loop is not available yet, since it cannot be analysed until
2064
/// we have determined the type of the for-range-declaration.
2065
StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2066
                                      SourceLocation CoawaitLoc, Stmt *InitStmt,
2067
                                      Stmt *First, SourceLocation ColonLoc,
2068
                                      Expr *Range, SourceLocation RParenLoc,
2069
2.89k
                                      BuildForRangeKind Kind) {
2070
2.89k
  if (!First)
2071
2
    return StmtError();
2072
2.89k
2073
2.89k
  if (Range && 
ObjCEnumerationCollection(Range)2.87k
) {
2074
6
    // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2075
6
    if (InitStmt)
2076
1
      return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2077
1
                 << InitStmt->getSourceRange();
2078
5
    return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2079
5
  }
2080
2.88k
2081
2.88k
  DeclStmt *DS = dyn_cast<DeclStmt>(First);
2082
2.88k
  assert(DS && "first part of for range not a decl stmt");
2083
2.88k
2084
2.88k
  if (!DS->isSingleDecl()) {
2085
3
    Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2086
3
    return StmtError();
2087
3
  }
2088
2.88k
2089
2.88k
  Decl *LoopVar = DS->getSingleDecl();
2090
2.88k
  if (LoopVar->isInvalidDecl() || 
!Range2.86k
||
2091
2.88k
      
DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)2.85k
) {
2092
27
    LoopVar->setInvalidDecl();
2093
27
    return StmtError();
2094
27
  }
2095
2.85k
2096
2.85k
  // Build the coroutine state immediately and not later during template
2097
2.85k
  // instantiation
2098
2.85k
  if (!CoawaitLoc.isInvalid()) {
2099
8
    if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2100
1
      return StmtError();
2101
2.85k
  }
2102
2.85k
2103
2.85k
  // Build  auto && __range = range-init
2104
2.85k
  // Divide by 2, since the variables are in the inner scope (loop body).
2105
2.85k
  const auto DepthStr = std::to_string(S->getDepth() / 2);
2106
2.85k
  SourceLocation RangeLoc = Range->getBeginLoc();
2107
2.85k
  VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2108
2.85k
                                           Context.getAutoRRefDeductType(),
2109
2.85k
                                           std::string("__range") + DepthStr);
2110
2.85k
  if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2111
2.85k
                            diag::err_for_range_deduction_failure)) {
2112
7
    LoopVar->setInvalidDecl();
2113
7
    return StmtError();
2114
7
  }
2115
2.84k
2116
2.84k
  // Claim the type doesn't contain auto: we've already done the checking.
2117
2.84k
  DeclGroupPtrTy RangeGroup =
2118
2.84k
      BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2119
2.84k
  StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2120
2.84k
  if (RangeDecl.isInvalid()) {
2121
0
    LoopVar->setInvalidDecl();
2122
0
    return StmtError();
2123
0
  }
2124
2.84k
2125
2.84k
  return BuildCXXForRangeStmt(
2126
2.84k
      ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2127
2.84k
      /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2128
2.84k
      /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
2129
2.84k
}
2130
2131
/// Create the initialization, compare, and increment steps for
2132
/// the range-based for loop expression.
2133
/// This function does not handle array-based for loops,
2134
/// which are created in Sema::BuildCXXForRangeStmt.
2135
///
2136
/// \returns a ForRangeStatus indicating success or what kind of error occurred.
2137
/// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2138
/// CandidateSet and BEF are set and some non-success value is returned on
2139
/// failure.
2140
static Sema::ForRangeStatus
2141
BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2142
                      QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2143
                      SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2144
                      OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2145
2.61k
                      ExprResult *EndExpr, BeginEndFunction *BEF) {
2146
2.61k
  DeclarationNameInfo BeginNameInfo(
2147
2.61k
      &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2148
2.61k
  DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2149
2.61k
                                  ColonLoc);
2150
2.61k
2151
2.61k
  LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2152
2.61k
                                 Sema::LookupMemberName);
2153
2.61k
  LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2154
2.61k
2155
2.61k
  auto BuildBegin = [&] {
2156
2.60k
    *BEF = BEF_begin;
2157
2.60k
    Sema::ForRangeStatus RangeStatus =
2158
2.60k
        SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2159
2.60k
                                          BeginMemberLookup, CandidateSet,
2160
2.60k
                                          BeginRange, BeginExpr);
2161
2.60k
2162
2.60k
    if (RangeStatus != Sema::FRS_Success) {
2163
54
      if (RangeStatus == Sema::FRS_DiagnosticIssued)
2164
4
        SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2165
4
            << ColonLoc << BEF_begin << BeginRange->getType();
2166
54
      return RangeStatus;
2167
54
    }
2168
2.55k
    if (!CoawaitLoc.isInvalid()) {
2169
6
      // FIXME: getCurScope() should not be used during template instantiation.
2170
6
      // We should pick up the set of unqualified lookup results for operator
2171
6
      // co_await during the initial parse.
2172
6
      *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2173
6
                                            BeginExpr->get());
2174
6
      if (BeginExpr->isInvalid())
2175
3
        return Sema::FRS_DiagnosticIssued;
2176
2.54k
    }
2177
2.54k
    if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2178
2.54k
                              diag::err_for_range_iter_deduction_failure)) {
2179
6
      NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2180
6
      return Sema::FRS_DiagnosticIssued;
2181
6
    }
2182
2.54k
    return Sema::FRS_Success;
2183
2.54k
  };
2184
2.61k
2185
2.61k
  auto BuildEnd = [&] {
2186
2.55k
    *BEF = BEF_end;
2187
2.55k
    Sema::ForRangeStatus RangeStatus =
2188
2.55k
        SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2189
2.55k
                                          EndMemberLookup, CandidateSet,
2190
2.55k
                                          EndRange, EndExpr);
2191
2.55k
    if (RangeStatus != Sema::FRS_Success) {
2192
16
      if (RangeStatus == Sema::FRS_DiagnosticIssued)
2193
2
        SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2194
2
            << ColonLoc << BEF_end << EndRange->getType();
2195
16
      return RangeStatus;
2196
16
    }
2197
2.53k
    if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2198
2.53k
                              diag::err_for_range_iter_deduction_failure)) {
2199
0
      NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2200
0
      return Sema::FRS_DiagnosticIssued;
2201
0
    }
2202
2.53k
    return Sema::FRS_Success;
2203
2.53k
  };
2204
2.61k
2205
2.61k
  if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2206
2.58k
    // - if _RangeT is a class type, the unqualified-ids begin and end are
2207
2.58k
    //   looked up in the scope of class _RangeT as if by class member access
2208
2.58k
    //   lookup (3.4.5), and if either (or both) finds at least one
2209
2.58k
    //   declaration, begin-expr and end-expr are __range.begin() and
2210
2.58k
    //   __range.end(), respectively;
2211
2.58k
    SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2212
2.58k
    if (BeginMemberLookup.isAmbiguous())
2213
0
      return Sema::FRS_DiagnosticIssued;
2214
2.58k
2215
2.58k
    SemaRef.LookupQualifiedName(EndMemberLookup, D);
2216
2.58k
    if (EndMemberLookup.isAmbiguous())
2217
0
      return Sema::FRS_DiagnosticIssued;
2218
2.58k
2219
2.58k
    if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2220
26
      // Look up the non-member form of the member we didn't find, first.
2221
26
      // This way we prefer a "no viable 'end'" diagnostic over a "i found
2222
26
      // a 'begin' but ignored it because there was no member 'end'"
2223
26
      // diagnostic.
2224
26
      auto BuildNonmember = [&](
2225
26
          BeginEndFunction BEFFound, LookupResult &Found,
2226
26
          llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2227
26
          llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2228
26
        LookupResult OldFound = std::move(Found);
2229
26
        Found.clear();
2230
26
2231
26
        if (Sema::ForRangeStatus Result = BuildNotFound())
2232
14
          return Result;
2233
12
2234
12
        switch (BuildFound()) {
2235
12
        case Sema::FRS_Success:
2236
6
          return Sema::FRS_Success;
2237
12
2238
12
        case Sema::FRS_NoViableFunction:
2239
6
          CandidateSet->NoteCandidates(
2240
6
              PartialDiagnosticAt(BeginRange->getBeginLoc(),
2241
6
                                  SemaRef.PDiag(diag::err_for_range_invalid)
2242
6
                                      << BeginRange->getType() << BEFFound),
2243
6
              SemaRef, OCD_AllCandidates, BeginRange);
2244
6
          LLVM_FALLTHROUGH;
2245
6
2246
6
        case Sema::FRS_DiagnosticIssued:
2247
6
          for (NamedDecl *D : OldFound) {
2248
6
            SemaRef.Diag(D->getLocation(),
2249
6
                         diag::note_for_range_member_begin_end_ignored)
2250
6
                << BeginRange->getType() << BEFFound;
2251
6
          }
2252
6
          return Sema::FRS_DiagnosticIssued;
2253
0
        }
2254
0
        llvm_unreachable("unexpected ForRangeStatus");
2255
0
      };
2256
26
      if (BeginMemberLookup.empty())
2257
14
        return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2258
12
      return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2259
12
    }
2260
24
  } else {
2261
24
    // - otherwise, begin-expr and end-expr are begin(__range) and
2262
24
    //   end(__range), respectively, where begin and end are looked up with
2263
24
    //   argument-dependent lookup (3.4.2). For the purposes of this name
2264
24
    //   lookup, namespace std is an associated namespace.
2265
24
  }
2266
2.61k
2267
2.61k
  
if (Sema::ForRangeStatus 2.58k
Result2.58k
= BuildBegin())
2268
52
    return Result;
2269
2.53k
  return BuildEnd();
2270
2.53k
}
2271
2272
/// Speculatively attempt to dereference an invalid range expression.
2273
/// If the attempt fails, this function will return a valid, null StmtResult
2274
/// and emit no diagnostics.
2275
static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2276
                                                 SourceLocation ForLoc,
2277
                                                 SourceLocation CoawaitLoc,
2278
                                                 Stmt *InitStmt,
2279
                                                 Stmt *LoopVarDecl,
2280
                                                 SourceLocation ColonLoc,
2281
                                                 Expr *Range,
2282
                                                 SourceLocation RangeLoc,
2283
39
                                                 SourceLocation RParenLoc) {
2284
39
  // Determine whether we can rebuild the for-range statement with a
2285
39
  // dereferenced range expression.
2286
39
  ExprResult AdjustedRange;
2287
39
  {
2288
39
    Sema::SFINAETrap Trap(SemaRef);
2289
39
2290
39
    AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2291
39
    if (AdjustedRange.isInvalid())
2292
29
      return StmtResult();
2293
10
2294
10
    StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2295
10
        S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2296
10
        AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
2297
10
    if (SR.isInvalid())
2298
5
      return StmtResult();
2299
5
  }
2300
5
2301
5
  // The attempt to dereference worked well enough that it could produce a valid
2302
5
  // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2303
5
  // case there are any other (non-fatal) problems with it.
2304
5
  SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2305
5
    << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2306
5
  return SemaRef.ActOnCXXForRangeStmt(
2307
5
      S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2308
5
      AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
2309
5
}
2310
2311
namespace {
2312
/// RAII object to automatically invalidate a declaration if an error occurs.
2313
struct InvalidateOnErrorScope {
2314
  InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2315
2.94k
      : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2316
2.94k
  ~InvalidateOnErrorScope() {
2317
2.94k
    if (Enabled && 
Trap.hasErrorOccurred()2.46k
)
2318
93
      D->setInvalidDecl();
2319
2.94k
  }
2320
2321
  DiagnosticErrorTrap Trap;
2322
  Decl *D;
2323
  bool Enabled;
2324
};
2325
}
2326
2327
/// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2328
StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
2329
                                      SourceLocation CoawaitLoc, Stmt *InitStmt,
2330
                                      SourceLocation ColonLoc, Stmt *RangeDecl,
2331
                                      Stmt *Begin, Stmt *End, Expr *Cond,
2332
                                      Expr *Inc, Stmt *LoopVarDecl,
2333
                                      SourceLocation RParenLoc,
2334
2.94k
                                      BuildForRangeKind Kind) {
2335
2.94k
  // FIXME: This should not be used during template instantiation. We should
2336
2.94k
  // pick up the set of unqualified lookup results for the != and + operators
2337
2.94k
  // in the initial parse.
2338
2.94k
  //
2339
2.94k
  // Testcase (accepts-invalid):
2340
2.94k
  //   template<typename T> void f() { for (auto x : T()) {} }
2341
2.94k
  //   namespace N { struct X { X begin(); X end(); int operator*(); }; }
2342
2.94k
  //   bool operator!=(N::X, N::X); void operator++(N::X);
2343
2.94k
  //   void g() { f<N::X>(); }
2344
2.94k
  Scope *S = getCurScope();
2345
2.94k
2346
2.94k
  DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2347
2.94k
  VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2348
2.94k
  QualType RangeVarType = RangeVar->getType();
2349
2.94k
2350
2.94k
  DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2351
2.94k
  VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2352
2.94k
2353
2.94k
  // If we hit any errors, mark the loop variable as invalid if its type
2354
2.94k
  // contains 'auto'.
2355
2.94k
  InvalidateOnErrorScope Invalidate(*this, LoopVar,
2356
2.94k
                                    LoopVar->getType()->isUndeducedType());
2357
2.94k
2358
2.94k
  StmtResult BeginDeclStmt = Begin;
2359
2.94k
  StmtResult EndDeclStmt = End;
2360
2.94k
  ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2361
2.94k
2362
2.94k
  if (RangeVarType->isDependentType()) {
2363
36
    // The range is implicitly used as a placeholder when it is dependent.
2364
36
    RangeVar->markUsed(Context);
2365
36
2366
36
    // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2367
36
    // them in properly when we instantiate the loop.
2368
36
    if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2369
36
      if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2370
4
        for (auto *Binding : DD->bindings())
2371
6
          Binding->setType(Context.DependentTy);
2372
36
      LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2373
36
    }
2374
2.91k
  } else if (!BeginDeclStmt.get()) {
2375
2.88k
    SourceLocation RangeLoc = RangeVar->getLocation();
2376
2.88k
2377
2.88k
    const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2378
2.88k
2379
2.88k
    ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2380
2.88k
                                                VK_LValue, ColonLoc);
2381
2.88k
    if (BeginRangeRef.isInvalid())
2382
0
      return StmtError();
2383
2.88k
2384
2.88k
    ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2385
2.88k
                                              VK_LValue, ColonLoc);
2386
2.88k
    if (EndRangeRef.isInvalid())
2387
0
      return StmtError();
2388
2.88k
2389
2.88k
    QualType AutoType = Context.getAutoDeductType();
2390
2.88k
    Expr *Range = RangeVar->getInit();
2391
2.88k
    if (!Range)
2392
0
      return StmtError();
2393
2.88k
    QualType RangeType = Range->getType();
2394
2.88k
2395
2.88k
    if (RequireCompleteType(RangeLoc, RangeType,
2396
2.88k
                            diag::err_for_range_incomplete_type))
2397
9
      return StmtError();
2398
2.88k
2399
2.88k
    // Build auto __begin = begin-expr, __end = end-expr.
2400
2.88k
    // Divide by 2, since the variables are in the inner scope (loop body).
2401
2.88k
    const auto DepthStr = std::to_string(S->getDepth() / 2);
2402
2.88k
    VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2403
2.88k
                                             std::string("__begin") + DepthStr);
2404
2.88k
    VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2405
2.88k
                                           std::string("__end") + DepthStr);
2406
2.88k
2407
2.88k
    // Build begin-expr and end-expr and attach to __begin and __end variables.
2408
2.88k
    ExprResult BeginExpr, EndExpr;
2409
2.88k
    if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2410
269
      // - if _RangeT is an array type, begin-expr and end-expr are __range and
2411
269
      //   __range + __bound, respectively, where __bound is the array bound. If
2412
269
      //   _RangeT is an array of unknown size or an array of incomplete type,
2413
269
      //   the program is ill-formed;
2414
269
2415
269
      // begin-expr is __range.
2416
269
      BeginExpr = BeginRangeRef;
2417
269
      if (!CoawaitLoc.isInvalid()) {
2418
1
        BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2419
1
        if (BeginExpr.isInvalid())
2420
1
          return StmtError();
2421
268
      }
2422
268
      if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2423
268
                                diag::err_for_range_iter_deduction_failure)) {
2424
0
        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2425
0
        return StmtError();
2426
0
      }
2427
268
2428
268
      // Find the array bound.
2429
268
      ExprResult BoundExpr;
2430
268
      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2431
257
        BoundExpr = IntegerLiteral::Create(
2432
257
            Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2433
11
      else if (const VariableArrayType *VAT =
2434
11
               dyn_cast<VariableArrayType>(UnqAT)) {
2435
11
        // For a variably modified type we can't just use the expression within
2436
11
        // the array bounds, since we don't want that to be re-evaluated here.
2437
11
        // Rather, we need to determine what it was when the array was first
2438
11
        // created - so we resort to using sizeof(vla)/sizeof(element).
2439
11
        // For e.g.
2440
11
        //  void f(int b) {
2441
11
        //    int vla[b];
2442
11
        //    b = -1;   <-- This should not affect the num of iterations below
2443
11
        //    for (int &c : vla) { .. }
2444
11
        //  }
2445
11
2446
11
        // FIXME: This results in codegen generating IR that recalculates the
2447
11
        // run-time number of elements (as opposed to just using the IR Value
2448
11
        // that corresponds to the run-time value of each bound that was
2449
11
        // generated when the array was created.) If this proves too embarrassing
2450
11
        // even for unoptimized IR, consider passing a magic-value/cookie to
2451
11
        // codegen that then knows to simply use that initial llvm::Value (that
2452
11
        // corresponds to the bound at time of array creation) within
2453
11
        // getelementptr.  But be prepared to pay the price of increasing a
2454
11
        // customized form of coupling between the two components - which  could
2455
11
        // be hard to maintain as the codebase evolves.
2456
11
2457
11
        ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2458
11
            EndVar->getLocation(), UETT_SizeOf,
2459
11
            /*IsType=*/true,
2460
11
            CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2461
11
                                                 VAT->desugar(), RangeLoc))
2462
11
                .getAsOpaquePtr(),
2463
11
            EndVar->getSourceRange());
2464
11
        if (SizeOfVLAExprR.isInvalid())
2465
0
          return StmtError();
2466
11
2467
11
        ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2468
11
            EndVar->getLocation(), UETT_SizeOf,
2469
11
            /*IsType=*/true,
2470
11
            CreateParsedType(VAT->desugar(),
2471
11
                             Context.getTrivialTypeSourceInfo(
2472
11
                                 VAT->getElementType(), RangeLoc))
2473
11
                .getAsOpaquePtr(),
2474
11
            EndVar->getSourceRange());
2475
11
        if (SizeOfEachElementExprR.isInvalid())
2476
0
          return StmtError();
2477
11
2478
11
        BoundExpr =
2479
11
            ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2480
11
                       SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2481
11
        if (BoundExpr.isInvalid())
2482
0
          return StmtError();
2483
0
2484
0
      } else {
2485
0
        // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2486
0
        // UnqAT is not incomplete and Range is not type-dependent.
2487
0
        llvm_unreachable("Unexpected array type in for-range");
2488
0
      }
2489
268
2490
268
      // end-expr is __range + __bound.
2491
268
      EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2492
268
                           BoundExpr.get());
2493
268
      if (EndExpr.isInvalid())
2494
0
        return StmtError();
2495
268
      if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2496
268
                                diag::err_for_range_iter_deduction_failure)) {
2497
0
        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2498
0
        return StmtError();
2499
0
      }
2500
2.61k
    } else {
2501
2.61k
      OverloadCandidateSet CandidateSet(RangeLoc,
2502
2.61k
                                        OverloadCandidateSet::CSK_Normal);
2503
2.61k
      BeginEndFunction BEFFailure;
2504
2.61k
      ForRangeStatus RangeStatus = BuildNonArrayForRange(
2505
2.61k
          *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2506
2.61k
          EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2507
2.61k
          &BEFFailure);
2508
2.61k
2509
2.61k
      if (Kind == BFRK_Build && 
RangeStatus == FRS_NoViableFunction2.55k
&&
2510
2.61k
          
BEFFailure == BEF_begin51
) {
2511
41
        // If the range is being built from an array parameter, emit a
2512
41
        // a diagnostic that it is being treated as a pointer.
2513
41
        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2514
20
          if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2515
8
            QualType ArrayTy = PVD->getOriginalType();
2516
8
            QualType PointerTy = PVD->getType();
2517
8
            if (PointerTy->isPointerType() && 
ArrayTy->isArrayType()2
) {
2518
2
              Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2519
2
                  << RangeLoc << PVD << ArrayTy << PointerTy;
2520
2
              Diag(PVD->getLocation(), diag::note_declared_at);
2521
2
              return StmtError();
2522
2
            }
2523
39
          }
2524
20
        }
2525
39
2526
39
        // If building the range failed, try dereferencing the range expression
2527
39
        // unless a diagnostic was issued or the end function is problematic.
2528
39
        StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2529
39
                                                       CoawaitLoc, InitStmt,
2530
39
                                                       LoopVarDecl, ColonLoc,
2531
39
                                                       Range, RangeLoc,
2532
39
                                                       RParenLoc);
2533
39
        if (SR.isInvalid() || SR.isUsable())
2534
5
          return SR;
2535
2.60k
      }
2536
2.60k
2537
2.60k
      // Otherwise, emit diagnostics if we haven't already.
2538
2.60k
      if (RangeStatus == FRS_NoViableFunction) {
2539
51
        Expr *Range = BEFFailure ? 
EndRangeRef.get()11
:
BeginRangeRef.get()40
;
2540
51
        CandidateSet.NoteCandidates(
2541
51
            PartialDiagnosticAt(Range->getBeginLoc(),
2542
51
                                PDiag(diag::err_for_range_invalid)
2543
51
                                    << RangeLoc << Range->getType()
2544
51
                                    << BEFFailure),
2545
51
            *this, OCD_AllCandidates, Range);
2546
51
      }
2547
2.60k
      // Return an error if no fix was discovered.
2548
2.60k
      if (RangeStatus != FRS_Success)
2549
72
        return StmtError();
2550
2.80k
    }
2551
2.80k
2552
2.80k
    assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2553
2.80k
           "invalid range expression in for loop");
2554
2.80k
2555
2.80k
    // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2556
2.80k
    // C++1z removes this restriction.
2557
2.80k
    QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2558
2.80k
    if (!Context.hasSameType(BeginType, EndType)) {
2559
3
      Diag(RangeLoc, getLangOpts().CPlusPlus17
2560
3
                         ? 
diag::warn_for_range_begin_end_types_differ1
2561
3
                         : 
diag::ext_for_range_begin_end_types_differ2
)
2562
3
          << BeginType << EndType;
2563
3
      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2564
3
      NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2565
3
    }
2566
2.80k
2567
2.80k
    BeginDeclStmt =
2568
2.80k
        ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2569
2.80k
    EndDeclStmt =
2570
2.80k
        ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2571
2.80k
2572
2.80k
    const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2573
2.80k
    ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2574
2.80k
                                           VK_LValue, ColonLoc);
2575
2.80k
    if (BeginRef.isInvalid())
2576
0
      return StmtError();
2577
2.80k
2578
2.80k
    ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2579
2.80k
                                         VK_LValue, ColonLoc);
2580
2.80k
    if (EndRef.isInvalid())
2581
0
      return StmtError();
2582
2.80k
2583
2.80k
    // Build and check __begin != __end expression.
2584
2.80k
    NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2585
2.80k
                           BeginRef.get(), EndRef.get());
2586
2.80k
    if (!NotEqExpr.isInvalid())
2587
2.79k
      NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2588
2.80k
    if (!NotEqExpr.isInvalid())
2589
2.79k
      NotEqExpr =
2590
2.79k
          ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
2591
2.80k
    if (NotEqExpr.isInvalid()) {
2592
3
      Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2593
3
        << RangeLoc << 0 << BeginRangeRef.get()->getType();
2594
3
      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2595
3
      if (!Context.hasSameType(BeginType, EndType))
2596
0
        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2597
3
      return StmtError();
2598
3
    }
2599
2.79k
2600
2.79k
    // Build and check ++__begin expression.
2601
2.79k
    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2602
2.79k
                                VK_LValue, ColonLoc);
2603
2.79k
    if (BeginRef.isInvalid())
2604
0
      return StmtError();
2605
2.79k
2606
2.79k
    IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2607
2.79k
    if (!IncrExpr.isInvalid() && 
CoawaitLoc.isValid()2.79k
)
2608
3
      // FIXME: getCurScope() should not be used during template instantiation.
2609
3
      // We should pick up the set of unqualified lookup results for operator
2610
3
      // co_await during the initial parse.
2611
3
      IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2612
2.79k
    if (!IncrExpr.isInvalid())
2613
2.79k
      IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
2614
2.79k
    if (IncrExpr.isInvalid()) {
2615
5
      Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2616
5
        << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2617
5
      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2618
5
      return StmtError();
2619
5
    }
2620
2.79k
2621
2.79k
    // Build and check *__begin  expression.
2622
2.79k
    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2623
2.79k
                                VK_LValue, ColonLoc);
2624
2.79k
    if (BeginRef.isInvalid())
2625
0
      return StmtError();
2626
2.79k
2627
2.79k
    ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2628
2.79k
    if (DerefExpr.isInvalid()) {
2629
3
      Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2630
3
        << RangeLoc << 1 << BeginRangeRef.get()->getType();
2631
3
      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2632
3
      return StmtError();
2633
3
    }
2634
2.78k
2635
2.78k
    // Attach  *__begin  as initializer for VD. Don't touch it if we're just
2636
2.78k
    // trying to determine whether this would be a valid range.
2637
2.78k
    if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2638
2.78k
      AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2639
2.78k
      if (LoopVar->isInvalidDecl())
2640
17
        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2641
2.78k
    }
2642
2.78k
  }
2643
2.94k
2644
2.94k
  // Don't bother to actually allocate the result if we're just trying to
2645
2.94k
  // determine whether it would be valid.
2646
2.94k
  
if (2.84k
Kind == BFRK_Check2.84k
)
2647
5
    return StmtResult();
2648
2.84k
2649
2.84k
  return new (Context) CXXForRangeStmt(
2650
2.84k
      InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2651
2.84k
      cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2652
2.84k
      IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2653
2.84k
      ColonLoc, RParenLoc);
2654
2.84k
}
2655
2656
/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2657
/// statement.
2658
258
StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2659
258
  if (!S || 
!B246
)
2660
12
    return StmtError();
2661
246
  ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2662
246
2663
246
  ForStmt->setBody(B);
2664
246
  return S;
2665
246
}
2666
2667
// Warn when the loop variable is a const reference that creates a copy.
2668
// Suggest using the non-reference type for copies.  If a copy can be prevented
2669
// suggest the const reference type that would do so.
2670
// For instance, given "for (const &Foo : Range)", suggest
2671
// "for (const Foo : Range)" to denote a copy is made for the loop.  If
2672
// possible, also suggest "for (const &Bar : Range)" if this type prevents
2673
// the copy altogether.
2674
static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2675
                                                    const VarDecl *VD,
2676
52
                                                    QualType RangeInitType) {
2677
52
  const Expr *InitExpr = VD->getInit();
2678
52
  if (!InitExpr)
2679
0
    return;
2680
52
2681
52
  QualType VariableType = VD->getType();
2682
52
2683
52
  if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2684
32
    if (!Cleanups->cleanupsHaveSideEffects())
2685
32
      InitExpr = Cleanups->getSubExpr();
2686
52
2687
52
  const MaterializeTemporaryExpr *MTE =
2688
52
      dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2689
52
2690
52
  // No copy made.
2691
52
  if (!MTE)
2692
20
    return;
2693
32
2694
32
  const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2695
32
2696
32
  // Searching for either UnaryOperator for dereference of a pointer or
2697
32
  // CXXOperatorCallExpr for handling iterators.
2698
60
  while (!isa<CXXOperatorCallExpr>(E) && 
!isa<UnaryOperator>(E)36
) {
2699
28
    if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2700
18
      E = CCE->getArg(0);
2701
18
    } else 
if (const CXXMemberCallExpr *10
Call10
= dyn_cast<CXXMemberCallExpr>(E)) {
2702
6
      const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2703
6
      E = ME->getBase();
2704
6
    } else {
2705
4
      const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2706
4
      E = MTE->GetTemporaryExpr();
2707
4
    }
2708
28
    E = E->IgnoreImpCasts();
2709
28
  }
2710
32
2711
32
  bool ReturnsReference = false;
2712
32
  if (isa<UnaryOperator>(E)) {
2713
8
    ReturnsReference = true;
2714
24
  } else {
2715
24
    const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2716
24
    const FunctionDecl *FD = Call->getDirectCallee();
2717
24
    QualType ReturnType = FD->getReturnType();
2718
24
    ReturnsReference = ReturnType->isReferenceType();
2719
24
  }
2720
32
2721
32
  if (ReturnsReference) {
2722
18
    // Loop variable creates a temporary.  Suggest either to go with
2723
18
    // non-reference loop variable to indicate a copy is made, or
2724
18
    // the correct time to bind a const reference.
2725
18
    SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2726
18
        << VD << VariableType << E->getType();
2727
18
    QualType NonReferenceType = VariableType.getNonReferenceType();
2728
18
    NonReferenceType.removeLocalConst();
2729
18
    QualType NewReferenceType =
2730
18
        SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2731
18
    SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
2732
18
        << NonReferenceType << NewReferenceType << VD->getSourceRange();
2733
18
  } else {
2734
14
    // The range always returns a copy, so a temporary is always created.
2735
14
    // Suggest removing the reference from the loop variable.
2736
14
    SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2737
14
        << VD << RangeInitType;
2738
14
    QualType NonReferenceType = VariableType.getNonReferenceType();
2739
14
    NonReferenceType.removeLocalConst();
2740
14
    SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
2741
14
        << NonReferenceType << VD->getSourceRange();
2742
14
  }
2743
32
}
2744
2745
// Warns when the loop variable can be changed to a reference type to
2746
// prevent a copy.  For instance, if given "for (const Foo x : Range)" suggest
2747
// "for (const Foo &x : Range)" if this form does not make a copy.
2748
static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2749
40
                                                const VarDecl *VD) {
2750
40
  const Expr *InitExpr = VD->getInit();
2751
40
  if (!InitExpr)
2752
0
    return;
2753
40
2754
40
  QualType VariableType = VD->getType();
2755
40
2756
40
  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2757
8
    if (!CE->getConstructor()->isCopyConstructor())
2758
0
      return;
2759
32
  } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2760
14
    if (CE->getCastKind() != CK_LValueToRValue)
2761
10
      return;
2762
18
  } else {
2763
18
    return;
2764
18
  }
2765
12
2766
12
  // TODO: Determine a maximum size that a POD type can be before a diagnostic
2767
12
  // should be emitted.  Also, only ignore POD types with trivial copy
2768
12
  // constructors.
2769
12
  if (VariableType.isPODType(SemaRef.Context))
2770
6
    return;
2771
6
2772
6
  // Suggest changing from a const variable to a const reference variable
2773
6
  // if doing so will prevent a copy.
2774
6
  SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2775
6
      << VD << VariableType << InitExpr->getType();
2776
6
  SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
2777
6
      << SemaRef.Context.getLValueReferenceType(VariableType)
2778
6
      << VD->getSourceRange();
2779
6
}
2780
2781
/// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2782
/// 1) for (const foo &x : foos) where foos only returns a copy.  Suggest
2783
///    using "const foo x" to show that a copy is made
2784
/// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
2785
///    Suggest either "const bar x" to keep the copying or "const foo& x" to
2786
///    prevent the copy.
2787
/// 3) for (const foo x : foos) where x is constructed from a reference foo.
2788
///    Suggest "const foo &x" to prevent the copy.
2789
static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2790
2.83k
                                           const CXXForRangeStmt *ForStmt) {
2791
2.83k
  if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2792
2.83k
                              ForStmt->getBeginLoc()) &&
2793
2.83k
      SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2794
2.70k
                              ForStmt->getBeginLoc()) &&
2795
2.83k
      SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2796
2.70k
                              ForStmt->getBeginLoc())) {
2797
2.70k
    return;
2798
2.70k
  }
2799
130
2800
130
  const VarDecl *VD = ForStmt->getLoopVariable();
2801
130
  if (!VD)
2802
0
    return;
2803
130
2804
130
  QualType VariableType = VD->getType();
2805
130
2806
130
  if (VariableType->isIncompleteType())
2807
0
    return;
2808
130
2809
130
  const Expr *InitExpr = VD->getInit();
2810
130
  if (!InitExpr)
2811
0
    return;
2812
130
2813
130
  if (VariableType->isReferenceType()) {
2814
52
    DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2815
52
                                            ForStmt->getRangeInit()->getType());
2816
78
  } else if (VariableType.isConstQualified()) {
2817
40
    DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2818
40
  }
2819
130
}
2820
2821
/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2822
/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2823
/// body cannot be performed until after the type of the range variable is
2824
/// determined.
2825
2.96k
StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2826
2.96k
  if (!S || 
!B2.84k
)
2827
117
    return StmtError();
2828
2.84k
2829
2.84k
  if (isa<ObjCForCollectionStmt>(S))
2830
6
    return FinishObjCForCollectionStmt(S, B);
2831
2.83k
2832
2.83k
  CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2833
2.83k
  ForStmt->setBody(B);
2834
2.83k
2835
2.83k
  DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2836
2.83k
                        diag::warn_empty_range_based_for_body);
2837
2.83k
2838
2.83k
  DiagnoseForRangeVariableCopies(*this, ForStmt);
2839
2.83k
2840
2.83k
  return S;
2841
2.83k
}
2842
2843
StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2844
                               SourceLocation LabelLoc,
2845
8.49k
                               LabelDecl *TheDecl) {
2846
8.49k
  setFunctionHasBranchIntoScope();
2847
8.49k
  TheDecl->markUsed(Context);
2848
8.49k
  return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2849
8.49k
}
2850
2851
StmtResult
2852
Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2853
146
                            Expr *E) {
2854
146
  // Convert operand to void*
2855
146
  if (!E->isTypeDependent()) {
2856
144
    QualType ETy = E->getType();
2857
144
    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2858
144
    ExprResult ExprRes = E;
2859
144
    AssignConvertType ConvTy =
2860
144
      CheckSingleAssignmentConstraints(DestTy, ExprRes);
2861
144
    if (ExprRes.isInvalid())
2862
1
      return StmtError();
2863
143
    E = ExprRes.get();
2864
143
    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2865
1
      return StmtError();
2866
144
  }
2867
144
2868
144
  ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
2869
144
  if (ExprRes.isInvalid())
2870
1
    return StmtError();
2871
143
  E = ExprRes.get();
2872
143
2873
143
  setFunctionHasIndirectGoto();
2874
143
2875
143
  return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2876
143
}
2877
2878
static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2879
2.82M
                                     const Scope &DestScope) {
2880
2.82M
  if (!S.CurrentSEHFinally.empty() &&
2881
2.82M
      
DestScope.Contains(*S.CurrentSEHFinally.back())32
) {
2882
22
    S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2883
22
  }
2884
2.82M
}
2885
2886
StmtResult
2887
7.50k
Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2888
7.50k
  Scope *S = CurScope->getContinueParent();
2889
7.50k
  if (!S) {
2890
20
    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2891
20
    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2892
20
  }
2893
7.48k
  CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2894
7.48k
2895
7.48k
  return new (Context) ContinueStmt(ContinueLoc);
2896
7.48k
}
2897
2898
StmtResult
2899
61.7k
Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2900
61.7k
  Scope *S = CurScope->getBreakParent();
2901
61.7k
  if (!S) {
2902
23
    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2903
23
    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2904
23
  }
2905
61.7k
  if (S->isOpenMPLoopScope())
2906
110
    return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2907
110
                     << "break");
2908
61.6k
  CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2909
61.6k
2910
61.6k
  return new (Context) BreakStmt(BreakLoc);
2911
61.6k
}
2912
2913
/// Determine whether the given expression is a candidate for
2914
/// copy elision in either a return statement or a throw expression.
2915
///
2916
/// \param ReturnType If we're determining the copy elision candidate for
2917
/// a return statement, this is the return type of the function. If we're
2918
/// determining the copy elision candidate for a throw expression, this will
2919
/// be a NULL type.
2920
///
2921
/// \param E The expression being returned from the function or block, or
2922
/// being thrown.
2923
///
2924
/// \param CESK Whether we allow function parameters or
2925
/// id-expressions that could be moved out of the function to be considered NRVO
2926
/// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2927
/// determine whether we should try to move as part of a return or throw (which
2928
/// does allow function parameters).
2929
///
2930
/// \returns The NRVO candidate variable, if the return statement may use the
2931
/// NRVO, or NULL if there is no such candidate.
2932
VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2933
5.40M
                                       CopyElisionSemanticsKind CESK) {
2934
5.40M
  // - in a return statement in a function [where] ...
2935
5.40M
  // ... the expression is the name of a non-volatile automatic object ...
2936
5.40M
  DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2937
5.40M
  if (!DR || 
DR->refersToEnclosingVariableOrCapture()974k
)
2938
4.43M
    return nullptr;
2939
974k
  VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2940
974k
  if (!VD)
2941
32.0k
    return nullptr;
2942
942k
2943
942k
  if (isCopyElisionCandidate(ReturnType, VD, CESK))
2944
87.4k
    return VD;
2945
854k
  return nullptr;
2946
854k
}
2947
2948
bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2949
949k
                                  CopyElisionSemanticsKind CESK) {
2950
949k
  QualType VDType = VD->getType();
2951
949k
  // - in a return statement in a function with ...
2952
949k
  // ... a class return type ...
2953
949k
  if (!ReturnType.isNull() && 
!ReturnType->isDependentType()858k
) {
2954
763k
    if (!ReturnType->isRecordType())
2955
744k
      return false;
2956
19.6k
    // ... the same cv-unqualified type as the function return type ...
2957
19.6k
    // When considering moving this expression out, allow dissimilar types.
2958
19.6k
    if (!(CESK & CES_AllowDifferentTypes) && 
!VDType->isDependentType()15.7k
&&
2959
19.6k
        
!Context.hasSameUnqualifiedType(ReturnType, VDType)15.7k
)
2960
1.01k
      return false;
2961
204k
  }
2962
204k
2963
204k
  // ...object (other than a function or catch-clause parameter)...
2964
204k
  if (VD->getKind() != Decl::Var &&
2965
204k
      
!(68.5k
(CESK & CES_AllowParameters)68.5k
&&
VD->getKind() == Decl::ParmVar11.4k
))
2966
57.1k
    return false;
2967
147k
  if (!(CESK & CES_AllowExceptionVariables) && 
VD->isExceptionVariable()56.2k
)
2968
168
    return false;
2969
147k
2970
147k
  // ...automatic...
2971
147k
  if (!VD->hasLocalStorage()) 
return false58.3k
;
2972
88.7k
2973
88.7k
  // Return false if VD is a __block variable. We don't want to implicitly move
2974
88.7k
  // out of a __block variable during a return because we cannot assume the
2975
88.7k
  // variable will no longer be used.
2976
88.7k
  if (VD->hasAttr<BlocksAttr>()) 
return false27
;
2977
88.7k
2978
88.7k
  if (CESK & CES_AllowDifferentTypes)
2979
40.1k
    return true;
2980
48.5k
2981
48.5k
  // ...non-volatile...
2982
48.5k
  if (VD->getType().isVolatileQualified()) 
return false0
;
2983
48.5k
2984
48.5k
  // Variables with higher required alignment than their type's ABI
2985
48.5k
  // alignment cannot use NRVO.
2986
48.5k
  if (!VD->getType()->isDependentType() && 
VD->hasAttr<AlignedAttr>()12.1k
&&
2987
48.5k
      
Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())3
)
2988
3
    return false;
2989
48.5k
2990
48.5k
  return true;
2991
48.5k
}
2992
2993
/// Try to perform the initialization of a potentially-movable value,
2994
/// which is the operand to a return or throw statement.
2995
///
2996
/// This routine implements C++14 [class.copy]p32, which attempts to treat
2997
/// returned lvalues as rvalues in certain cases (to prefer move construction),
2998
/// then falls back to treating them as lvalues if that failed.
2999
///
3000
/// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
3001
/// resolutions that find non-constructors, such as derived-to-base conversions
3002
/// or `operator T()&&` member functions. If false, do consider such
3003
/// conversion sequences.
3004
///
3005
/// \param Res We will fill this in if move-initialization was possible.
3006
/// If move-initialization is not possible, such that we must fall back to
3007
/// treating the operand as an lvalue, we will leave Res in its original
3008
/// invalid state.
3009
static void TryMoveInitialization(Sema& S,
3010
                                  const InitializedEntity &Entity,
3011
                                  const VarDecl *NRVOCandidate,
3012
                                  QualType ResultType,
3013
                                  Expr *&Value,
3014
                                  bool ConvertingConstructorsOnly,
3015
14.5k
                                  ExprResult &Res) {
3016
14.5k
  ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3017
14.5k
                            CK_NoOp, Value, VK_XValue);
3018
14.5k
3019
14.5k
  Expr *InitExpr = &AsRvalue;
3020
14.5k
3021
14.5k
  InitializationKind Kind = InitializationKind::CreateCopy(
3022
14.5k
      Value->getBeginLoc(), Value->getBeginLoc());
3023
14.5k
3024
14.5k
  InitializationSequence Seq(S, Entity, Kind, InitExpr);
3025
14.5k
3026
14.5k
  if (!Seq)
3027
26
    return;
3028
14.5k
3029
14.6k
  
for (const InitializationSequence::Step &Step : Seq.steps())14.5k
{
3030
14.6k
    if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
3031
14.6k
        
Step.Kind != InitializationSequence::SK_UserConversion6.59k
)
3032
6.39k
      continue;
3033
8.23k
3034
8.23k
    FunctionDecl *FD = Step.Function.Function;
3035
8.23k
    if (ConvertingConstructorsOnly) {
3036
8.18k
      if (isa<CXXConstructorDecl>(FD)) {
3037
8.12k
        // C++14 [class.copy]p32:
3038
8.12k
        // [...] If the first overload resolution fails or was not performed,
3039
8.12k
        // or if the type of the first parameter of the selected constructor
3040
8.12k
        // is not an rvalue reference to the object's type (possibly
3041
8.12k
        // cv-qualified), overload resolution is performed again, considering
3042
8.12k
        // the object as an lvalue.
3043
8.12k
        const RValueReferenceType *RRefType =
3044
8.12k
            FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
3045
8.12k
        if (!RRefType)
3046
2.10k
          break;
3047
6.01k
        if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3048
6.01k
                                              NRVOCandidate->getType()))
3049
62
          break;
3050
58
      } else {
3051
58
        continue;
3052
58
      }
3053
50
    } else {
3054
50
      if (isa<CXXConstructorDecl>(FD)) {
3055
34
        // Check that overload resolution selected a constructor taking an
3056
34
        // rvalue reference. If it selected an lvalue reference, then we
3057
34
        // didn't need to cast this thing to an rvalue in the first place.
3058
34
        if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3059
6
          break;
3060
16
      } else if (isa<CXXMethodDecl>(FD)) {
3061
16
        // Check that overload resolution selected a conversion operator
3062
16
        // taking an rvalue reference.
3063
16
        if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3064
0
          break;
3065
0
      } else {
3066
0
        continue;
3067
0
      }
3068
6.00k
    }
3069
6.00k
3070
6.00k
    // Promote "AsRvalue" to the heap, since we now need this
3071
6.00k
    // expression node to persist.
3072
6.00k
    Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3073
6.00k
                                     Value, nullptr, VK_XValue);
3074
6.00k
3075
6.00k
    // Complete type-checking the initialization of the return type
3076
6.00k
    // using the constructor we found.
3077
6.00k
    Res = Seq.Perform(S, Entity, Kind, Value);
3078
6.00k
  }
3079
14.5k
}
3080
3081
/// Perform the initialization of a potentially-movable value, which
3082
/// is the result of return value.
3083
///
3084
/// This routine implements C++14 [class.copy]p32, which attempts to treat
3085
/// returned lvalues as rvalues in certain cases (to prefer move construction),
3086
/// then falls back to treating them as lvalues if that failed.
3087
ExprResult
3088
Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3089
                                      const VarDecl *NRVOCandidate,
3090
                                      QualType ResultType,
3091
                                      Expr *Value,
3092
2.10M
                                      bool AllowNRVO) {
3093
2.10M
  // C++14 [class.copy]p32:
3094
2.10M
  // When the criteria for elision of a copy/move operation are met, but not for
3095
2.10M
  // an exception-declaration, and the object to be copied is designated by an
3096
2.10M
  // lvalue, or when the expression in a return statement is a (possibly
3097
2.10M
  // parenthesized) id-expression that names an object with automatic storage
3098
2.10M
  // duration declared in the body or parameter-declaration-clause of the
3099
2.10M
  // innermost enclosing function or lambda-expression, overload resolution to
3100
2.10M
  // select the constructor for the copy is first performed as if the object
3101
2.10M
  // were designated by an rvalue.
3102
2.10M
  ExprResult Res = ExprError();
3103
2.10M
3104
2.10M
  if (AllowNRVO) {
3105
2.10M
    bool AffectedByCWG1579 = false;
3106
2.10M
3107
2.10M
    if (!NRVOCandidate) {
3108
2.09M
      NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
3109
2.09M
      if (NRVOCandidate &&
3110
2.09M
          !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3111
3.76k
                                      Value->getExprLoc())) {
3112
88
        const VarDecl *NRVOCandidateInCXX11 =
3113
88
            getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3114
88
        AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3115
88
      }
3116
2.09M
    }
3117
2.10M
3118
2.10M
    if (NRVOCandidate) {
3119
14.4k
      TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
3120
14.4k
                            true, Res);
3121
14.4k
    }
3122
2.10M
3123
2.10M
    if (!Res.isInvalid() && 
AffectedByCWG15795.95k
) {
3124
8
      QualType QT = NRVOCandidate->getType();
3125
8
      if (QT.getNonReferenceType()
3126
8
                     .getUnqualifiedType()
3127
8
                     .isTriviallyCopyableType(Context)) {
3128
2
        // Adding 'std::move' around a trivially copyable variable is probably
3129
2
        // pointless. Don't suggest it.
3130
6
      } else {
3131
6
        // Common cases for this are returning unique_ptr<Derived> from a
3132
6
        // function of return type unique_ptr<Base>, or returning T from a
3133
6
        // function of return type Expected<T>. This is totally fine in a
3134
6
        // post-CWG1579 world, but was not fine before.
3135
6
        assert(!ResultType.isNull());
3136
6
        SmallString<32> Str;
3137
6
        Str += "std::move(";
3138
6
        Str += NRVOCandidate->getDeclName().getAsString();
3139
6
        Str += ")";
3140
6
        Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3141
6
            << Value->getSourceRange()
3142
6
            << NRVOCandidate->getDeclName() << ResultType << QT;
3143
6
        Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3144
6
            << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3145
6
      }
3146
2.10M
    } else if (Res.isInvalid() &&
3147
2.10M
               !getDiagnostics().isIgnored(diag::warn_return_std_move,
3148
2.09M
                                           Value->getExprLoc())) {
3149
360k
      const VarDecl *FakeNRVOCandidate =
3150
360k
          getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3151
360k
      if (FakeNRVOCandidate) {
3152
36.3k
        QualType QT = FakeNRVOCandidate->getType();
3153
36.3k
        if (QT->isLValueReferenceType()) {
3154
100
          // Adding 'std::move' around an lvalue reference variable's name is
3155
100
          // dangerous. Don't suggest it.
3156
36.2k
        } else if (QT.getNonReferenceType()
3157
36.2k
                       .getUnqualifiedType()
3158
36.2k
                       .isTriviallyCopyableType(Context)) {
3159
36.1k
          // Adding 'std::move' around a trivially copyable variable is probably
3160
36.1k
          // pointless. Don't suggest it.
3161
36.1k
        } else {
3162
59
          ExprResult FakeRes = ExprError();
3163
59
          Expr *FakeValue = Value;
3164
59
          TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3165
59
                                FakeValue, false, FakeRes);
3166
59
          if (!FakeRes.isInvalid()) {
3167
44
            bool IsThrow =
3168
44
                (Entity.getKind() == InitializedEntity::EK_Exception);
3169
44
            SmallString<32> Str;
3170
44
            Str += "std::move(";
3171
44
            Str += FakeNRVOCandidate->getDeclName().getAsString();
3172
44
            Str += ")";
3173
44
            Diag(Value->getExprLoc(), diag::warn_return_std_move)
3174
44
                << Value->getSourceRange()
3175
44
                << FakeNRVOCandidate->getDeclName() << IsThrow;
3176
44
            Diag(Value->getExprLoc(), diag::note_add_std_move)
3177
44
                << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3178
44
          }
3179
59
        }
3180
36.3k
      }
3181
360k
    }
3182
2.10M
  }
3183
2.10M
3184
2.10M
  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3185
2.10M
  // above, or overload resolution failed. Either way, we need to try
3186
2.10M
  // (again) now with the return value expression as written.
3187
2.10M
  if (Res.isInvalid())
3188
2.10M
    Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
3189
2.10M
3190
2.10M
  return Res;
3191
2.10M
}
3192
3193
/// Determine whether the declared return type of the specified function
3194
/// contains 'auto'.
3195
4.07k
static bool hasDeducedReturnType(FunctionDecl *FD) {
3196
4.07k
  const FunctionProtoType *FPT =
3197
4.07k
      FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3198
4.07k
  return FPT->getReturnType()->isUndeducedType();
3199
4.07k
}
3200
3201
/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3202
/// for capturing scopes.
3203
///
3204
StmtResult
3205
4.92k
Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3206
4.92k
  // If this is the first return we've seen, infer the return type.
3207
4.92k
  // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3208
4.92k
  CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3209
4.92k
  QualType FnRetType = CurCap->ReturnType;
3210
4.92k
  LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3211
4.92k
  bool HasDeducedReturnType =
3212
4.92k
      CurLambda && 
hasDeducedReturnType(CurLambda->CallOperator)4.07k
;
3213
4.92k
3214
4.92k
  if (ExprEvalContexts.back().Context ==
3215
4.92k
          ExpressionEvaluationContext::DiscardedStatement &&
3216
4.92k
      
(1
HasDeducedReturnType1
||
CurCap->HasImplicitReturnType0
)) {
3217
1
    if (RetValExp) {
3218
1
      ExprResult ER =
3219
1
          ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3220
1
      if (ER.isInvalid())
3221
0
        return StmtError();
3222
1
      RetValExp = ER.get();
3223
1
    }
3224
1
    return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3225
1
                              /* NRVOCandidate=*/nullptr);
3226
4.92k
  }
3227
4.92k
3228
4.92k
  if (HasDeducedReturnType) {
3229
2.53k
    // In C++1y, the return type may involve 'auto'.
3230
2.53k
    // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3231
2.53k
    FunctionDecl *FD = CurLambda->CallOperator;
3232
2.53k
    if (CurCap->ReturnType.isNull())
3233
1.70k
      CurCap->ReturnType = FD->getReturnType();
3234
2.53k
3235
2.53k
    AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3236
2.53k
    assert(AT && "lost auto type from lambda return type");
3237
2.53k
    if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3238
4
      FD->setInvalidDecl();
3239
4
      return StmtError();
3240
4
    }
3241
2.53k
    CurCap->ReturnType = FnRetType = FD->getReturnType();
3242
2.53k
  } else 
if (2.38k
CurCap->HasImplicitReturnType2.38k
) {
3243
1.35k
    // For blocks/lambdas with implicit return types, we check each return
3244
1.35k
    // statement individually, and deduce the common return type when the block
3245
1.35k
    // or lambda is completed.
3246
1.35k
    // FIXME: Fold this into the 'auto' codepath above.
3247
1.35k
    if (RetValExp && 
!isa<InitListExpr>(RetValExp)1.20k
) {
3248
1.20k
      ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3249
1.20k
      if (Result.isInvalid())
3250
0
        return StmtError();
3251
1.20k
      RetValExp = Result.get();
3252
1.20k
3253
1.20k
      // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3254
1.20k
      // when deducing a return type for a lambda-expression (or by extension
3255
1.20k
      // for a block). These rules differ from the stated C++11 rules only in
3256
1.20k
      // that they remove top-level cv-qualifiers.
3257
1.20k
      if (!CurContext->isDependentContext())
3258
1.14k
        FnRetType = RetValExp->getType().getUnqualifiedType();
3259
58
      else
3260
58
        FnRetType = CurCap->ReturnType = Context.DependentTy;
3261
1.20k
    } else {
3262
148
      if (RetValExp) {
3263
1
        // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3264
1
        // initializer list, because it is not an expression (even
3265
1
        // though we represent it as one). We still deduce 'void'.
3266
1
        Diag(ReturnLoc, diag::err_lambda_return_init_list)
3267
1
          << RetValExp->getSourceRange();
3268
1
      }
3269
148
3270
148
      FnRetType = Context.VoidTy;
3271
148
    }
3272
1.35k
3273
1.35k
    // Although we'll properly infer the type of the block once it's completed,
3274
1.35k
    // make sure we provide a return type now for better error recovery.
3275
1.35k
    if (CurCap->ReturnType.isNull())
3276
1.16k
      CurCap->ReturnType = FnRetType;
3277
1.35k
  }
3278
4.92k
  assert(!FnRetType.isNull());
3279
4.92k
3280
4.92k
  if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3281
725
    if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3282
2
      Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3283
2
      return StmtError();
3284
2
    }
3285
4.19k
  } else if (CapturedRegionScopeInfo *CurRegion =
3286
125
                 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3287
125
    Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3288
125
    return StmtError();
3289
4.07k
  } else {
3290
4.07k
    assert(CurLambda && "unknown kind of captured scope");
3291
4.07k
    if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3292
4.07k
            ->getNoReturnAttr()) {
3293
0
      Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3294
0
      return StmtError();
3295
0
    }
3296
4.79k
  }
3297
4.79k
3298
4.79k
  // Otherwise, verify that this result type matches the previous one.  We are
3299
4.79k
  // pickier with blocks than for normal functions because we don't have GCC
3300
4.79k
  // compatibility to worry about here.
3301
4.79k
  const VarDecl *NRVOCandidate = nullptr;
3302
4.79k
  if (FnRetType->isDependentType()) {
3303
1.37k
    // Delay processing for now.  TODO: there are lots of dependent
3304
1.37k
    // types we can conclusively prove aren't void.
3305
3.41k
  } else if (FnRetType->isVoidType()) {
3306
172
    if (RetValExp && 
!isa<InitListExpr>(RetValExp)17
&&
3307
172
        
!(16
getLangOpts().CPlusPlus16
&&
3308
16
          
(13
RetValExp->isTypeDependent()13
||
3309
13
           RetValExp->getType()->isVoidType()))) {
3310
3
      if (!getLangOpts().CPlusPlus &&
3311
3
          RetValExp->getType()->isVoidType())
3312
3
        Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3313
0
      else {
3314
0
        Diag(ReturnLoc, diag::err_return_block_has_expr);
3315
0
        RetValExp = nullptr;
3316
0
      }
3317
3
    }
3318
3.24k
  } else if (!RetValExp) {
3319
0
    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3320
3.24k
  } else if (!RetValExp->isTypeDependent()) {
3321
3.19k
    // we have a non-void block with an expression, continue checking
3322
3.19k
3323
3.19k
    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3324
3.19k
    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3325
3.19k
    // function return.
3326
3.19k
3327
3.19k
    // In C++ the return statement is handled via a copy initialization.
3328
3.19k
    // the C version of which boils down to CheckSingleAssignmentConstraints.
3329
3.19k
    NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3330
3.19k
    InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3331
3.19k
                                                                   FnRetType,
3332
3.19k
                                                      NRVOCandidate != nullptr);
3333
3.19k
    ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3334
3.19k
                                                     FnRetType, RetValExp);
3335
3.19k
    if (Res.isInvalid()) {
3336
13
      // FIXME: Cleanup temporaries here, anyway?
3337
13
      return StmtError();
3338
13
    }
3339
3.18k
    RetValExp = Res.get();
3340
3.18k
    CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3341
3.18k
  } else {
3342
54
    NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3343
54
  }
3344
4.79k
3345
4.79k
  
if (4.78k
RetValExp4.78k
) {
3346
4.62k
    ExprResult ER =
3347
4.62k
        ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3348
4.62k
    if (ER.isInvalid())
3349
0
      return StmtError();
3350
4.62k
    RetValExp = ER.get();
3351
4.62k
  }
3352
4.78k
  auto *Result =
3353
4.78k
      ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3354
4.78k
3355
4.78k
  // If we need to check for the named return value optimization,
3356
4.78k
  // or if we need to infer the return type,
3357
4.78k
  // save the return statement in our scope for later processing.
3358
4.78k
  if (CurCap->HasImplicitReturnType || 
NRVOCandidate1.63k
)
3359
3.17k
    FunctionScopes.back()->Returns.push_back(Result);
3360
4.78k
3361
4.78k
  if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3362
4.45k
    FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3363
4.78k
3364
4.78k
  return Result;
3365
4.78k
}
3366
3367
namespace {
3368
/// Marks all typedefs in all local classes in a type referenced.
3369
///
3370
/// In a function like
3371
/// auto f() {
3372
///   struct S { typedef int a; };
3373
///   return S();
3374
/// }
3375
///
3376
/// the local type escapes and could be referenced in some TUs but not in
3377
/// others. Pretend that all local typedefs are always referenced, to not warn
3378
/// on this. This isn't necessary if f has internal linkage, or the typedef
3379
/// is private.
3380
class LocalTypedefNameReferencer
3381
    : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3382
public:
3383
1.91k
  LocalTypedefNameReferencer(Sema &S) : S(S) {}
3384
  bool VisitRecordType(const RecordType *RT);
3385
private:
3386
  Sema &S;
3387
};
3388
734
bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3389
734
  auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3390
734
  if (!R || !R->isLocalClass() || 
!R->isLocalClass()->isExternallyVisible()622
||
3391
734
      
R->isDependentType()360
)
3392
374
    return true;
3393
360
  for (auto *TmpD : R->decls())
3394
1.53k
    if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3395
9
      if (T->getAccess() != AS_private || 
R->hasFriends()2
)
3396
8
        S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3397
360
  return true;
3398
360
}
3399
}
3400
3401
4.21k
TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3402
4.21k
  return FD->getTypeSourceInfo()
3403
4.21k
      ->getTypeLoc()
3404
4.21k
      .getAsAdjusted<FunctionProtoTypeLoc>()
3405
4.21k
      .getReturnLoc();
3406
4.21k
}
3407
3408
/// Deduce the return type for a function from a returned expression, per
3409
/// C++1y [dcl.spec.auto]p6.
3410
bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3411
                                            SourceLocation ReturnLoc,
3412
                                            Expr *&RetExpr,
3413
3.40k
                                            AutoType *AT) {
3414
3.40k
  // If this is the conversion function for a lambda, we choose to deduce it
3415
3.40k
  // type from the corresponding call operator, not from the synthesized return
3416
3.40k
  // statement within it. See Sema::DeduceReturnType.
3417
3.40k
  if (isLambdaConversionOperator(FD))
3418
140
    return false;
3419
3.26k
3420
3.26k
  TypeLoc OrigResultType = getReturnTypeLoc(FD);
3421
3.26k
  QualType Deduced;
3422
3.26k
3423
3.26k
  if (RetExpr && 
isa<InitListExpr>(RetExpr)3.25k
) {
3424
5
    //  If the deduction is for a return statement and the initializer is
3425
5
    //  a braced-init-list, the program is ill-formed.
3426
5
    Diag(RetExpr->getExprLoc(),
3427
5
         getCurLambda() ? 
diag::err_lambda_return_init_list1
3428
5
                        : 
diag::err_auto_fn_return_init_list4
)
3429
5
        << RetExpr->getSourceRange();
3430
5
    return true;
3431
5
  }
3432
3.25k
3433
3.25k
  if (FD->isDependentContext()) {
3434
1.33k
    // C++1y [dcl.spec.auto]p12:
3435
1.33k
    //   Return type deduction [...] occurs when the definition is
3436
1.33k
    //   instantiated even if the function body contains a return
3437
1.33k
    //   statement with a non-type-dependent operand.
3438
1.33k
    assert(AT->isDeduced() && "should have deduced to dependent type");
3439
1.33k
    return false;
3440
1.33k
  }
3441
1.92k
3442
1.92k
  if (RetExpr) {
3443
1.91k
    //  Otherwise, [...] deduce a value for U using the rules of template
3444
1.91k
    //  argument deduction.
3445
1.91k
    DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3446
1.91k
3447
1.91k
    if (DAR == DAR_Failed && 
!FD->isInvalidDecl()2
)
3448
2
      Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3449
2
        << OrigResultType.getType() << RetExpr->getType();
3450
1.91k
3451
1.91k
    if (DAR != DAR_Succeeded)
3452
2
      return true;
3453
1.91k
3454
1.91k
    // If a local type is part of the returned type, mark its fields as
3455
1.91k
    // referenced.
3456
1.91k
    LocalTypedefNameReferencer Referencer(*this);
3457
1.91k
    Referencer.TraverseType(RetExpr->getType());
3458
1.91k
  } else {
3459
8
    //  In the case of a return with no operand, the initializer is considered
3460
8
    //  to be void().
3461
8
    //
3462
8
    // Deduction here can only succeed if the return type is exactly 'cv auto'
3463
8
    // or 'decltype(auto)', so just check for that case directly.
3464
8
    if (!OrigResultType.getType()->getAs<AutoType>()) {
3465
0
      Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3466
0
        << OrigResultType.getType();
3467
0
      return true;
3468
0
    }
3469
8
    // We always deduce U = void in this case.
3470
8
    Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3471
8
    if (Deduced.isNull())
3472
0
      return true;
3473
1.91k
  }
3474
1.91k
3475
1.91k
  //  If a function with a declared return type that contains a placeholder type
3476
1.91k
  //  has multiple return statements, the return type is deduced for each return
3477
1.91k
  //  statement. [...] if the type deduced is not the same in each deduction,
3478
1.91k
  //  the program is ill-formed.
3479
1.91k
  QualType DeducedT = AT->getDeducedType();
3480
1.91k
  if (!DeducedT.isNull() && 
!FD->isInvalidDecl()111
) {
3481
111
    AutoType *NewAT = Deduced->getContainedAutoType();
3482
111
    // It is possible that NewAT->getDeducedType() is null. When that happens,
3483
111
    // we should not crash, instead we ignore this deduction.
3484
111
    if (NewAT->getDeducedType().isNull())
3485
0
      return false;
3486
111
3487
111
    CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3488
111
                                   DeducedT);
3489
111
    CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3490
111
                                   NewAT->getDeducedType());
3491
111
    if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3492
7
      const LambdaScopeInfo *LambdaSI = getCurLambda();
3493
7
      if (LambdaSI && 
LambdaSI->HasImplicitReturnType3
) {
3494
2
        Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3495
2
          << NewAT->getDeducedType() << DeducedT
3496
2
          << true /*IsLambda*/;
3497
5
      } else {
3498
5
        Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3499
5
          << (AT->isDecltypeAuto() ? 
10
: 0)
3500
5
          << NewAT->getDeducedType() << DeducedT;
3501
5
      }
3502
7
      return true;
3503
7
    }
3504
1.80k
  } else if (!FD->isInvalidDecl()) {
3505
1.80k
    // Update all declarations of the function to have the deduced return type.
3506
1.80k
    Context.adjustDeducedFunctionResultType(FD, Deduced);
3507
1.80k
  }
3508
1.91k
3509
1.91k
  
return false1.91k
;
3510
1.91k
}
3511
3512
StmtResult
3513
Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3514
2.75M
                      Scope *CurScope) {
3515
2.75M
  // Correct typos, in case the containing function returns 'auto' and
3516
2.75M
  // RetValExp should determine the deduced type.
3517
2.75M
  ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp);
3518
2.75M
  if (RetVal.isInvalid())
3519
36
    return StmtError();
3520
2.75M
  StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());
3521
2.75M
  if (R.isInvalid() || ExprEvalContexts.back().Context ==
3522
2.75M
                           ExpressionEvaluationContext::DiscardedStatement)
3523
351
    return R;
3524
2.75M
3525
2.75M
  if (VarDecl *VD =
3526
45.7k
      const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3527
45.7k
    CurScope->addNRVOCandidate(VD);
3528
2.70M
  } else {
3529
2.70M
    CurScope->setNoNRVO();
3530
2.70M
  }
3531
2.75M
3532
2.75M
  CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3533
2.75M
3534
2.75M
  return R;
3535
2.75M
}
3536
3537
3.01M
StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3538
3.01M
  // Check for unexpanded parameter packs.
3539
3.01M
  if (RetValExp && 
DiagnoseUnexpandedParameterPack(RetValExp)2.96M
)
3540
3
    return StmtError();
3541
3.01M
3542
3.01M
  if (isa<CapturingScopeInfo>(getCurFunction()))
3543
4.92k
    return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3544
3.00M
3545
3.00M
  QualType FnRetType;
3546
3.00M
  QualType RelatedRetType;
3547
3.00M
  const AttrVec *Attrs = nullptr;
3548
3.00M
  bool isObjCMethod = false;
3549
3.00M
3550
3.00M
  if (const FunctionDecl *FD = getCurFunctionDecl()) {
3551
3.00M
    FnRetType = FD->getReturnType();
3552
3.00M
    if (FD->hasAttrs())
3553
2.07M
      Attrs = &FD->getAttrs();
3554
3.00M
    if (FD->isNoReturn())
3555
15
      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3556
15
        << FD->getDeclName();
3557
3.00M
    if (FD->isMain() && 
RetValExp7.30k
)
3558
7.30k
      if (isa<CXXBoolLiteralExpr>(RetValExp))
3559
1
        Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3560
1
          << RetValExp->getSourceRange();
3561
3.00M
  } else 
if (ObjCMethodDecl *2.92k
MD2.92k
= getCurMethodDecl()) {
3562
2.92k
    FnRetType = MD->getReturnType();
3563
2.92k
    isObjCMethod = true;
3564
2.92k
    if (MD->hasAttrs())
3565
276
      Attrs = &MD->getAttrs();
3566
2.92k
    if (MD->hasRelatedResultType() && 
MD->getClassInterface()639
) {
3567
639
      // In the implementation of a method with a related return type, the
3568
639
      // type used to type-check the validity of return statements within the
3569
639
      // method body is a pointer to the type of the class being implemented.
3570
639
      RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3571
639
      RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3572
639
    }
3573
2.92k
  } else // If we don't have a function/method context, bail.
3574
0
    return StmtError();
3575
3.00M
3576
3.00M
  // C++1z: discarded return statements are not considered when deducing a
3577
3.00M
  // return type.
3578
3.00M
  if (ExprEvalContexts.back().Context ==
3579
3.00M
          ExpressionEvaluationContext::DiscardedStatement &&
3580
3.00M
      
FnRetType->getContainedAutoType()23
) {
3581
20
    if (RetValExp) {
3582
20
      ExprResult ER =
3583
20
          ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3584
20
      if (ER.isInvalid())
3585
0
        return StmtError();
3586
20
      RetValExp = ER.get();
3587
20
    }
3588
20
    return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3589
20
                              /* NRVOCandidate=*/nullptr);
3590
3.00M
  }
3591
3.00M
3592
3.00M
  // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3593
3.00M
  // deduction.
3594
3.00M
  if (getLangOpts().CPlusPlus14) {
3595
640k
    if (AutoType *AT = FnRetType->getContainedAutoType()) {
3596
862
      FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3597
862
      if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3598
10
        FD->setInvalidDecl();
3599
10
        return StmtError();
3600
852
      } else {
3601
852
        FnRetType = FD->getReturnType();
3602
852
      }
3603
862
    }
3604
640k
  }
3605
3.00M
3606
3.00M
  bool HasDependentReturnType = FnRetType->isDependentType();
3607
3.00M
3608
3.00M
  ReturnStmt *Result = nullptr;
3609
3.00M
  if (FnRetType->isVoidType()) {
3610
57.9k
    if (RetValExp) {
3611
8.73k
      if (isa<InitListExpr>(RetValExp)) {
3612
0
        // We simply never allow init lists as the return value of void
3613
0
        // functions. This is compatible because this was never allowed before,
3614
0
        // so there's no legacy code to deal with.
3615
0
        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3616
0
        int FunctionKind = 0;
3617
0
        if (isa<ObjCMethodDecl>(CurDecl))
3618
0
          FunctionKind = 1;
3619
0
        else if (isa<CXXConstructorDecl>(CurDecl))
3620
0
          FunctionKind = 2;
3621
0
        else if (isa<CXXDestructorDecl>(CurDecl))
3622
0
          FunctionKind = 3;
3623
0
3624
0
        Diag(ReturnLoc, diag::err_return_init_list)
3625
0
          << CurDecl->getDeclName() << FunctionKind
3626
0
          << RetValExp->getSourceRange();
3627
0
3628
0
        // Drop the expression.
3629
0
        RetValExp = nullptr;
3630
8.73k
      } else if (!RetValExp->isTypeDependent()) {
3631
7.06k
        // C99 6.8.6.4p1 (ext_ since GCC warns)
3632
7.06k
        unsigned D = diag::ext_return_has_expr;
3633
7.06k
        if (RetValExp->getType()->isVoidType()) {
3634
7.05k
          NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3635
7.05k
          if (isa<CXXConstructorDecl>(CurDecl) ||
3636
7.05k
              
isa<CXXDestructorDecl>(CurDecl)7.04k
)
3637
2
            D = diag::err_ctor_dtor_returns_void;
3638
7.04k
          else
3639
7.04k
            D = diag::ext_return_has_void_expr;
3640
7.05k
        }
3641
15
        else {
3642
15
          ExprResult Result = RetValExp;
3643
15
          Result = IgnoredValueConversions(Result.get());
3644
15
          if (Result.isInvalid())
3645
0
            return StmtError();
3646
15
          RetValExp = Result.get();
3647
15
          RetValExp = ImpCastExprToType(RetValExp,
3648
15
                                        Context.VoidTy, CK_ToVoid).get();
3649
15
        }
3650
7.06k
        // return of void in constructor/destructor is illegal in C++.
3651
7.06k
        if (D == diag::err_ctor_dtor_returns_void) {
3652
2
          NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3653
2
          Diag(ReturnLoc, D)
3654
2
            << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3655
2
            << RetValExp->getSourceRange();
3656
2
        }
3657
7.06k
        // return (some void expression); is legal in C++.
3658
7.06k
        else if (D != diag::ext_return_has_void_expr ||
3659
7.06k
                 
!getLangOpts().CPlusPlus7.04k
) {
3660
3.35k
          NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3661
3.35k
3662
3.35k
          int FunctionKind = 0;
3663
3.35k
          if (isa<ObjCMethodDecl>(CurDecl))
3664
0
            FunctionKind = 1;
3665
3.35k
          else if (isa<CXXConstructorDecl>(CurDecl))
3666
1
            FunctionKind = 2;
3667
3.35k
          else if (isa<CXXDestructorDecl>(CurDecl))
3668
1
            FunctionKind = 3;
3669
3.35k
3670
3.35k
          Diag(ReturnLoc, D)
3671
3.35k
            << CurDecl->getDeclName() << FunctionKind
3672
3.35k
            << RetValExp->getSourceRange();
3673
3.35k
        }
3674
7.06k
      }
3675
8.73k
3676
8.73k
      if (RetValExp) {
3677
8.73k
        ExprResult ER =
3678
8.73k
            ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3679
8.73k
        if (ER.isInvalid())
3680
0
          return StmtError();
3681
8.73k
        RetValExp = ER.get();
3682
8.73k
      }
3683
8.73k
    }
3684
57.9k
3685
57.9k
    Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3686
57.9k
                                /* NRVOCandidate=*/nullptr);
3687
2.95M
  } else if (!RetValExp && 
!HasDependentReturnType10
) {
3688
9
    FunctionDecl *FD = getCurFunctionDecl();
3689
9
3690
9
    unsigned DiagID;
3691
9
    if (getLangOpts().CPlusPlus11 && 
FD3
&&
FD->isConstexpr()3
) {
3692
1
      // C++11 [stmt.return]p2
3693
1
      DiagID = diag::err_constexpr_return_missing_expr;
3694
1
      FD->setInvalidDecl();
3695
8
    } else if (getLangOpts().C99) {
3696
6
      // C99 6.8.6.4p1 (ext_ since GCC warns)
3697
6
      DiagID = diag::ext_return_missing_expr;
3698
6
    } else {
3699
2
      // C90 6.6.6.4p4
3700
2
      DiagID = diag::warn_return_missing_expr;
3701
2
    }
3702
9
3703
9
    if (FD)
3704
9
      Diag(ReturnLoc, DiagID)
3705
9
          << FD->getIdentifier() << 0 /*fn*/ << FD->isConsteval();
3706
0
    else
3707
0
      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3708
9
3709
9
    Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3710
9
                                /* NRVOCandidate=*/nullptr);
3711
2.95M
  } else {
3712
2.95M
    assert(RetValExp || HasDependentReturnType);
3713
2.95M
    const VarDecl *NRVOCandidate = nullptr;
3714
2.95M
3715
2.95M
    QualType RetType = RelatedRetType.isNull() ? 
FnRetType2.95M
:
RelatedRetType639
;
3716
2.95M
3717
2.95M
    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3718
2.95M
    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3719
2.95M
    // function return.
3720
2.95M
3721
2.95M
    // In C++ the return statement is handled via a copy initialization,
3722
2.95M
    // the C version of which boils down to CheckSingleAssignmentConstraints.
3723
2.95M
    if (RetValExp)
3724
2.95M
      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3725
2.95M
    if (!HasDependentReturnType && 
!RetValExp->isTypeDependent()2.29M
) {
3726
2.09M
      // we have a non-void function with an expression, continue checking
3727
2.09M
      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3728
2.09M
                                                                     RetType,
3729
2.09M
                                                      NRVOCandidate != nullptr);
3730
2.09M
      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3731
2.09M
                                                       RetType, RetValExp);
3732
2.09M
      if (Res.isInvalid()) {
3733
219
        // FIXME: Clean up temporaries here anyway?
3734
219
        return StmtError();
3735
219
      }
3736
2.09M
      RetValExp = Res.getAs<Expr>();
3737
2.09M
3738
2.09M
      // If we have a related result type, we need to implicitly
3739
2.09M
      // convert back to the formal result type.  We can't pretend to
3740
2.09M
      // initialize the result again --- we might end double-retaining
3741
2.09M
      // --- so instead we initialize a notional temporary.
3742
2.09M
      if (!RelatedRetType.isNull()) {
3743
635
        Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3744
635
                                                            FnRetType);
3745
635
        Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3746
635
        if (Res.isInvalid()) {
3747
0
          // FIXME: Clean up temporaries here anyway?
3748
0
          return StmtError();
3749
0
        }
3750
635
        RetValExp = Res.getAs<Expr>();
3751
635
      }
3752
2.09M
3753
2.09M
      CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3754
2.09M
                         getCurFunctionDecl());
3755
2.09M
    }
3756
2.95M
3757
2.95M
    
if (2.95M
RetValExp2.95M
) {
3758
2.95M
      ExprResult ER =
3759
2.95M
          ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3760
2.95M
      if (ER.isInvalid())
3761
0
        return StmtError();
3762
2.95M
      RetValExp = ER.get();
3763
2.95M
    }
3764
2.95M
    Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3765
2.95M
  }
3766
3.00M
3767
3.00M
  // If we need to check for the named return value optimization, save the
3768
3.00M
  // return statement in our scope for later processing.
3769
3.00M
  
if (3.00M
Result->getNRVOCandidate()3.00M
)
3770
47.2k
    FunctionScopes.back()->Returns.push_back(Result);
3771
3.00M
3772
3.00M
  if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3773
2.70M
    FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3774
3.00M
3775
3.00M
  return Result;
3776
3.00M
}
3777
3778
StmtResult
3779
Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3780
                           SourceLocation RParen, Decl *Parm,
3781
333
                           Stmt *Body) {
3782
333
  VarDecl *Var = cast_or_null<VarDecl>(Parm);
3783
333
  if (Var && 
Var->isInvalidDecl()257
)
3784
12
    return StmtError();
3785
321
3786
321
  return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3787
321
}
3788
3789
StmtResult
3790
67
Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3791
67
  return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3792
67
}
3793
3794
StmtResult
3795
Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3796
287
                         MultiStmtArg CatchStmts, Stmt *Finally) {
3797
287
  if (!getLangOpts().ObjCExceptions)
3798
1
    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3799
287
3800
287
  setFunctionHasBranchProtectedScope();
3801
287
  unsigned NumCatchStmts = CatchStmts.size();
3802
287
  return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3803
287
                               NumCatchStmts, Finally);
3804
287
}
3805
3806
70
StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3807
70
  if (Throw) {
3808
52
    ExprResult Result = DefaultLvalueConversion(Throw);
3809
52
    if (Result.isInvalid())
3810
0
      return StmtError();
3811
52
3812
52
    Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
3813
52
    if (Result.isInvalid())
3814
1
      return StmtError();
3815
51
    Throw = Result.get();
3816
51
3817
51
    QualType ThrowType = Throw->getType();
3818
51
    // Make sure the expression type is an ObjC pointer or "void *".
3819
51
    if (!ThrowType->isDependentType() &&
3820
51
        
!ThrowType->isObjCObjectPointerType()50
) {
3821
10
      const PointerType *PT = ThrowType->getAs<PointerType>();
3822
10
      if (!PT || 
!PT->getPointeeType()->isVoidType()5
)
3823
6
        return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3824
6
                         << Throw->getType() << Throw->getSourceRange());
3825
63
    }
3826
51
  }
3827
63
3828
63
  return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3829
63
}
3830
3831
StmtResult
3832
Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3833
69
                           Scope *CurScope) {
3834
69
  if (!getLangOpts().ObjCExceptions)
3835
1
    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3836
69
3837
69
  if (!Throw) {
3838
19
    // @throw without an expression designates a rethrow (which must occur
3839
19
    // in the context of an @catch clause).
3840
19
    Scope *AtCatchParent = CurScope;
3841
22
    while (AtCatchParent && 
!AtCatchParent->isAtCatchScope()21
)
3842
3
      AtCatchParent = AtCatchParent->getParent();
3843
19
    if (!AtCatchParent)
3844
1
      return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3845
68
  }
3846
68
  return BuildObjCAtThrowStmt(AtLoc, Throw);
3847
68
}
3848
3849
ExprResult
3850
64
Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3851
64
  ExprResult result = DefaultLvalueConversion(operand);
3852
64
  if (result.isInvalid())
3853
0
    return ExprError();
3854
64
  operand = result.get();
3855
64
3856
64
  // Make sure the expression type is an ObjC pointer or "void *".
3857
64
  QualType type = operand->getType();
3858
64
  if (!type->isDependentType() &&
3859
64
      
!type->isObjCObjectPointerType()62
) {
3860
15
    const PointerType *pointerType = type->getAs<PointerType>();
3861
15
    if (!pointerType || 
!pointerType->getPointeeType()->isVoidType()0
) {
3862
15
      if (getLangOpts().CPlusPlus) {
3863
3
        if (RequireCompleteType(atLoc, type,
3864
3
                                diag::err_incomplete_receiver_type))
3865
0
          return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3866
0
                   << type << operand->getSourceRange();
3867
3
3868
3
        ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3869
3
        if (result.isInvalid())
3870
0
          return ExprError();
3871
3
        if (!result.isUsable())
3872
2
          return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3873
2
                   << type << operand->getSourceRange();
3874
1
3875
1
        operand = result.get();
3876
12
      } else {
3877
12
          return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3878
12
                   << type << operand->getSourceRange();
3879
12
      }
3880
50
    }
3881
15
  }
3882
50
3883
50
  // The operand to @synchronized is a full-expression.
3884
50
  return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
3885
50
}
3886
3887
StmtResult
3888
Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3889
49
                                  Stmt *SyncBody) {
3890
49
  // We can't jump into or indirect-jump out of a @synchronized block.
3891
49
  setFunctionHasBranchProtectedScope();
3892
49
  return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3893
49
}
3894
3895
/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3896
/// and creates a proper catch handler from them.
3897
StmtResult
3898
Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3899
11.5k
                         Stmt *HandlerBlock) {
3900
11.5k
  // There's nothing to test that ActOnExceptionDecl didn't already test.
3901
11.5k
  return new (Context)
3902
11.5k
      CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3903
11.5k
}
3904
3905
StmtResult
3906
88
Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3907
88
  setFunctionHasBranchProtectedScope();
3908
88
  return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3909
88
}
3910
3911
namespace {
3912
class CatchHandlerType {
3913
  QualType QT;
3914
  unsigned IsPointer : 1;
3915
3916
  // This is a special constructor to be used only with DenseMapInfo's
3917
  // getEmptyKey() and getTombstoneKey() functions.
3918
  friend struct llvm::DenseMapInfo<CatchHandlerType>;
3919
  enum Unique { ForDenseMap };
3920
3.82k
  CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3921
3922
public:
3923
  /// Used when creating a CatchHandlerType from a handler type; will determine
3924
  /// whether the type is a pointer or reference and will strip off the top
3925
  /// level pointer and cv-qualifiers.
3926
1.31k
  CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3927
1.31k
    if (QT->isPointerType())
3928
268
      IsPointer = true;
3929
1.31k
3930
1.31k
    if (IsPointer || 
QT->isReferenceType()1.04k
)
3931
658
      QT = QT->getPointeeType();
3932
1.31k
    QT = QT.getUnqualifiedType();
3933
1.31k
  }
3934
3935
  /// Used when creating a CatchHandlerType from a base class type; pretends the
3936
  /// type passed in had the pointer qualifier, does not need to get an
3937
  /// unqualified type.
3938
  CatchHandlerType(QualType QT, bool IsPointer)
3939
129
      : QT(QT), IsPointer(IsPointer) {}
3940
3941
1.36k
  QualType underlying() const { return QT; }
3942
272
  bool isPointer() const { return IsPointer; }
3943
3944
  friend bool operator==(const CatchHandlerType &LHS,
3945
40.0k
                         const CatchHandlerType &RHS) {
3946
40.0k
    // If the pointer qualification does not match, we can return early.
3947
40.0k
    if (LHS.IsPointer != RHS.IsPointer)
3948
417
      return false;
3949
39.6k
    // Otherwise, check the underlying type without cv-qualifiers.
3950
39.6k
    return LHS.QT == RHS.QT;
3951
39.6k
  }
3952
};
3953
} // namespace
3954
3955
namespace llvm {
3956
template <> struct DenseMapInfo<CatchHandlerType> {
3957
2.53k
  static CatchHandlerType getEmptyKey() {
3958
2.53k
    return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3959
2.53k
                       CatchHandlerType::ForDenseMap);
3960
2.53k
  }
3961
3962
1.29k
  static CatchHandlerType getTombstoneKey() {
3963
1.29k
    return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3964
1.29k
                       CatchHandlerType::ForDenseMap);
3965
1.29k
  }
3966
3967
708
  static unsigned getHashValue(const CatchHandlerType &Base) {
3968
708
    return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3969
708
  }
3970
3971
  static bool isEqual(const CatchHandlerType &LHS,
3972
40.0k
                      const CatchHandlerType &RHS) {
3973
40.0k
    return LHS == RHS;
3974
40.0k
  }
3975
};
3976
}
3977
3978
namespace {
3979
class CatchTypePublicBases {
3980
  ASTContext &Ctx;
3981
  const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3982
  const bool CheckAgainstPointer;
3983
3984
  CXXCatchStmt *FoundHandler;
3985
  CanQualType FoundHandlerType;
3986
3987
public:
3988
  CatchTypePublicBases(
3989
      ASTContext &Ctx,
3990
      const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3991
      : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3992
272
        FoundHandler(nullptr) {}
3993
3994
24
  CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3995
24
  CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3996
3997
129
  bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3998
129
    if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3999
129
      CatchHandlerType Check(S->getType(), CheckAgainstPointer);
4000
129
      const auto &M = TypesToCheck;
4001
129
      auto I = M.find(Check);
4002
129
      if (I != M.end()) {
4003
24
        FoundHandler = I->second;
4004
24
        FoundHandlerType = Ctx.getCanonicalType(S->getType());
4005
24
        return true;
4006
24
      }
4007
105
    }
4008
105
    return false;
4009
105
  }
4010
};
4011
}
4012
4013
/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4014
/// handlers and creates a try statement from them.
4015
StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4016
11.6k
                                  ArrayRef<Stmt *> Handlers) {
4017
11.6k
  // Don't report an error if 'try' is used in system headers.
4018
11.6k
  if (!getLangOpts().CXXExceptions &&
4019
11.6k
      
!getSourceManager().isInSystemHeader(TryLoc)5
&&
!getLangOpts().CUDA5
) {
4020
5
    // Delay error emission for the OpenMP device code.
4021
5
    targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
4022
5
  }
4023
11.6k
4024
11.6k
  // Exceptions aren't allowed in CUDA device code.
4025
11.6k
  if (getLangOpts().CUDA)
4026
12
    CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4027
12
        << "try" << CurrentCUDATarget();
4028
11.6k
4029
11.6k
  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4030
26
    Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4031
11.6k
4032
11.6k
  sema::FunctionScopeInfo *FSI = getCurFunction();
4033
11.6k
4034
11.6k
  // C++ try is incompatible with SEH __try.
4035
11.6k
  if (!getLangOpts().Borland && 
FSI->FirstSEHTryLoc.isValid()11.6k
) {
4036
2
    Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4037
2
    Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4038
2
  }
4039
11.6k
4040
11.6k
  const unsigned NumHandlers = Handlers.size();
4041
11.6k
  assert(!Handlers.empty() &&
4042
11.6k
         "The parser shouldn't call this if there are no handlers.");
4043
11.6k
4044
11.6k
  llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4045
23.4k
  for (unsigned i = 0; i < NumHandlers; 
++i11.8k
) {
4046
11.8k
    CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4047
11.8k
4048
11.8k
    // Diagnose when the handler is a catch-all handler, but it isn't the last
4049
11.8k
    // handler for the try block. [except.handle]p5. Also, skip exception
4050
11.8k
    // declarations that are invalid, since we can't usefully report on them.
4051
11.8k
    if (!H->getExceptionDecl()) {
4052
11.1k
      if (i < NumHandlers - 1)
4053
3
        return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4054
11.1k
      continue;
4055
11.1k
    } else 
if (713
H->getExceptionDecl()->isInvalidDecl()713
)
4056
55
      continue;
4057
658
4058
658
    // Walk the type hierarchy to diagnose when this type has already been
4059
658
    // handled (duplication), or cannot be handled (derivation inversion). We
4060
658
    // ignore top-level cv-qualifiers, per [except.handle]p3
4061
658
    CatchHandlerType HandlerCHT =
4062
658
        (QualType)Context.getCanonicalType(H->getCaughtType());
4063
658
4064
658
    // We can ignore whether the type is a reference or a pointer; we need the
4065
658
    // underlying declaration type in order to get at the underlying record
4066
658
    // decl, if there is one.
4067
658
    QualType Underlying = HandlerCHT.underlying();
4068
658
    if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4069
272
      if (!RD->hasDefinition())
4070
0
        continue;
4071
272
      // Check that none of the public, unambiguous base classes are in the
4072
272
      // map ([except.handle]p1). Give the base classes the same pointer
4073
272
      // qualification as the original type we are basing off of. This allows
4074
272
      // comparison against the handler type using the same top-level pointer
4075
272
      // as the original type.
4076
272
      CXXBasePaths Paths;
4077
272
      Paths.setOrigin(RD);
4078
272
      CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
4079
272
      if (RD->lookupInBases(CTPB, Paths)) {
4080
24
        const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4081
24
        if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4082
24
          Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4083
24
               diag::warn_exception_caught_by_earlier_handler)
4084
24
              << H->getCaughtType();
4085
24
          Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4086
24
                diag::note_previous_exception_handler)
4087
24
              << Problem->getCaughtType();
4088
24
        }
4089
24
      }
4090
272
    }
4091
658
4092
658
    // Add the type the list of ones we have handled; diagnose if we've already
4093
658
    // handled it.
4094
658
    auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4095
658
    if (!R.second) {
4096
0
      const CXXCatchStmt *Problem = R.first->second;
4097
0
      Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4098
0
           diag::warn_exception_caught_by_earlier_handler)
4099
0
          << H->getCaughtType();
4100
0
      Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4101
0
           diag::note_previous_exception_handler)
4102
0
          << Problem->getCaughtType();
4103
0
    }
4104
658
  }
4105
11.6k
4106
11.6k
  FSI->setHasCXXTry(TryLoc);
4107
11.6k
4108
11.6k
  return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
4109
11.6k
}
4110
4111
StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4112
258
                                  Stmt *TryBlock, Stmt *Handler) {
4113
258
  assert(TryBlock && Handler);
4114
258
4115
258
  sema::FunctionScopeInfo *FSI = getCurFunction();
4116
258
4117
258
  // SEH __try is incompatible with C++ try. Borland appears to support this,
4118
258
  // however.
4119
258
  if (!getLangOpts().Borland) {
4120
224
    if (FSI->FirstCXXTryLoc.isValid()) {
4121
2
      Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4122
2
      Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4123
2
    }
4124
224
  }
4125
258
4126
258
  FSI->setHasSEHTry(TryLoc);
4127
258
4128
258
  // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4129
258
  // track if they use SEH.
4130
258
  DeclContext *DC = CurContext;
4131
258
  while (DC && !DC->isFunctionOrMethod())
4132
0
    DC = DC->getParent();
4133
258
  FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4134
258
  if (FD)
4135
254
    FD->setUsesSEHTry(true);
4136
4
  else
4137
4
    Diag(TryLoc, diag::err_seh_try_outside_functions);
4138
258
4139
258
  // Reject __try on unsupported targets.
4140
258
  if (!Context.getTargetInfo().isSEHTrySupported())
4141
0
    Diag(TryLoc, diag::err_seh_try_unsupported);
4142
258
4143
258
  return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4144
258
}
4145
4146
StmtResult
4147
Sema::ActOnSEHExceptBlock(SourceLocation Loc,
4148
                          Expr *FilterExpr,
4149
120
                          Stmt *Block) {
4150
120
  assert(FilterExpr && Block);
4151
120
4152
120
  if(!FilterExpr->getType()->isIntegerType()) {
4153
2
    return StmtError(Diag(FilterExpr->getExprLoc(),
4154
2
                     diag::err_filter_expression_integral)
4155
2
                     << FilterExpr->getType());
4156
2
  }
4157
118
4158
118
  return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
4159
118
}
4160
4161
139
void Sema::ActOnStartSEHFinallyBlock() {
4162
139
  CurrentSEHFinally.push_back(CurScope);
4163
139
}
4164
4165
0
void Sema::ActOnAbortSEHFinallyBlock() {
4166
0
  CurrentSEHFinally.pop_back();
4167
0
}
4168
4169
139
StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4170
139
  assert(Block);
4171
139
  CurrentSEHFinally.pop_back();
4172
139
  return SEHFinallyStmt::Create(Context, Loc, Block);
4173
139
}
4174
4175
StmtResult
4176
33
Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4177
33
  Scope *SEHTryParent = CurScope;
4178
74
  while (SEHTryParent && 
!SEHTryParent->isSEHTryScope()65
)
4179
41
    SEHTryParent = SEHTryParent->getParent();
4180
33
  if (!SEHTryParent)
4181
9
    return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4182
24
  CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4183
24
4184
24
  return new (Context) SEHLeaveStmt(Loc);
4185
24
}
4186
4187
StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4188
                                            bool IsIfExists,
4189
                                            NestedNameSpecifierLoc QualifierLoc,
4190
                                            DeclarationNameInfo NameInfo,
4191
                                            Stmt *Nested)
4192
6
{
4193
6
  return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4194
6
                                             QualifierLoc, NameInfo,
4195
6
                                             cast<CompoundStmt>(Nested));
4196
6
}
4197
4198
4199
StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4200
                                            bool IsIfExists,
4201
                                            CXXScopeSpec &SS,
4202
                                            UnqualifiedId &Name,
4203
6
                                            Stmt *Nested) {
4204
6
  return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4205
6
                                    SS.getWithLocInContext(Context),
4206
6
                                    GetNameFromUnqualifiedId(Name),
4207
6
                                    Nested);
4208
6
}
4209
4210
RecordDecl*
4211
Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4212
295k
                                   unsigned NumParams) {
4213
295k
  DeclContext *DC = CurContext;
4214
295k
  while (!(DC->isFunctionOrMethod() || 
DC->isRecord()0
||
DC->isFileContext()0
))
4215
0
    DC = DC->getParent();
4216
295k
4217
295k
  RecordDecl *RD = nullptr;
4218
295k
  if (getLangOpts().CPlusPlus)
4219
286k
    RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4220
286k
                               /*Id=*/nullptr);
4221
8.92k
  else
4222
8.92k
    RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4223
295k
4224
295k
  RD->setCapturedRecord();
4225
295k
  DC->addDecl(RD);
4226
295k
  RD->setImplicit();
4227
295k
  RD->startDefinition();
4228
295k
4229
295k
  assert(NumParams > 0 && "CapturedStmt requires context parameter");
4230
295k
  CD = CapturedDecl::Create(Context, CurContext, NumParams);
4231
295k
  DC->addDecl(CD);
4232
295k
  return RD;
4233
295k
}
4234
4235
static bool
4236
buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4237
                             SmallVectorImpl<CapturedStmt::Capture> &Captures,
4238
284k
                             SmallVectorImpl<Expr *> &CaptureInits) {
4239
284k
  for (const sema::Capture &Cap : RSI->Captures) {
4240
224k
    if (Cap.isInvalid())
4241
3
      continue;
4242
224k
4243
224k
    // Form the initializer for the capture.
4244
224k
    ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
4245
224k
                                         RSI->CapRegionKind == CR_OpenMP);
4246
224k
4247
224k
    // FIXME: Bail out now if the capture is not used and the initializer has
4248
224k
    // no side-effects.
4249
224k
4250
224k
    // Create a field for this capture.
4251
224k
    FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4252
224k
4253
224k
    // Add the capture to our list of captures.
4254
224k
    if (Cap.isThisCapture()) {
4255
7.31k
      Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4256
7.31k
                                               CapturedStmt::VCK_This));
4257
217k
    } else if (Cap.isVLATypeCapture()) {
4258
5.54k
      Captures.push_back(
4259
5.54k
          CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4260
211k
    } else {
4261
211k
      assert(Cap.isVariableCapture() && "unknown kind of capture");
4262
211k
4263
211k
      if (S.getLangOpts().OpenMP && 
RSI->CapRegionKind == CR_OpenMP211k
)
4264
211k
        S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
4265
211k
4266
211k
      Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4267
211k
                                               Cap.isReferenceCapture()
4268
211k
                                                   ? 
CapturedStmt::VCK_ByRef102k
4269
211k
                                                   : 
CapturedStmt::VCK_ByCopy109k
,
4270
211k
                                               Cap.getVariable()));
4271
211k
    }
4272
224k
    CaptureInits.push_back(Init.get());
4273
224k
  }
4274
284k
  return false;
4275
284k
}
4276
4277
void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4278
                                    CapturedRegionKind Kind,
4279
59
                                    unsigned NumParams) {
4280
59
  CapturedDecl *CD = nullptr;
4281
59
  RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4282
59
4283
59
  // Build the context parameter
4284
59
  DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4285
59
  IdentifierInfo *ParamName = &Context.Idents.get("__context");
4286
59
  QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4287
59
  auto *Param =
4288
59
      ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4289
59
                                ImplicitParamDecl::CapturedContext);
4290
59
  DC->addDecl(Param);
4291
59
4292
59
  CD->setContextParam(0, Param);
4293
59
4294
59
  // Enter the capturing scope for this captured region.
4295
59
  PushCapturedRegionScope(CurScope, CD, RD, Kind);
4296
59
4297
59
  if (CurScope)
4298
59
    PushDeclContext(CurScope, CD);
4299
0
  else
4300
0
    CurContext = CD;
4301
59
4302
59
  PushExpressionEvaluationContext(
4303
59
      ExpressionEvaluationContext::PotentiallyEvaluated);
4304
59
}
4305
4306
void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4307
                                    CapturedRegionKind Kind,
4308
295k
                                    ArrayRef<CapturedParamNameType> Params) {
4309
295k
  CapturedDecl *CD = nullptr;
4310
295k
  RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4311
295k
4312
295k
  // Build the context parameter
4313
295k
  DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4314
295k
  bool ContextIsFound = false;
4315
295k
  unsigned ParamNum = 0;
4316
295k
  for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4317
295k
                                                 E = Params.end();
4318
1.32M
       I != E; 
++I, ++ParamNum1.02M
) {
4319
1.02M
    if (I->second.isNull()) {
4320
295k
      assert(!ContextIsFound &&
4321
295k
             "null type has been found already for '__context' parameter");
4322
295k
      IdentifierInfo *ParamName = &Context.Idents.get("__context");
4323
295k
      QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4324
295k
                               .withConst()
4325
295k
                               .withRestrict();
4326
295k
      auto *Param =
4327
295k
          ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4328
295k
                                    ImplicitParamDecl::CapturedContext);
4329
295k
      DC->addDecl(Param);
4330
295k
      CD->setContextParam(ParamNum, Param);
4331
295k
      ContextIsFound = true;
4332
732k
    } else {
4333
732k
      IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4334
732k
      auto *Param =
4335
732k
          ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4336
732k
                                    ImplicitParamDecl::CapturedContext);
4337
732k
      DC->addDecl(Param);
4338
732k
      CD->setParam(ParamNum, Param);
4339
732k
    }
4340
1.02M
  }
4341
295k
  assert(ContextIsFound && "no null type for '__context' parameter");
4342
295k
  if (!ContextIsFound) {
4343
0
    // Add __context implicitly if it is not specified.
4344
0
    IdentifierInfo *ParamName = &Context.Idents.get("__context");
4345
0
    QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4346
0
    auto *Param =
4347
0
        ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4348
0
                                  ImplicitParamDecl::CapturedContext);
4349
0
    DC->addDecl(Param);
4350
0
    CD->setContextParam(ParamNum, Param);
4351
0
  }
4352
295k
  // Enter the capturing scope for this captured region.
4353
295k
  PushCapturedRegionScope(CurScope, CD, RD, Kind);
4354
295k
4355
295k
  if (CurScope)
4356
195k
    PushDeclContext(CurScope, CD);
4357
99.8k
  else
4358
99.8k
    CurContext = CD;
4359
295k
4360
295k
  PushExpressionEvaluationContext(
4361
295k
      ExpressionEvaluationContext::PotentiallyEvaluated);
4362
295k
}
4363
4364
10.4k
void Sema::ActOnCapturedRegionError() {
4365
10.4k
  DiscardCleanupsInEvaluationContext();
4366
10.4k
  PopExpressionEvaluationContext();
4367
10.4k
  PopDeclContext();
4368
10.4k
  PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4369
10.4k
  CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4370
10.4k
4371
10.4k
  RecordDecl *Record = RSI->TheRecordDecl;
4372
10.4k
  Record->setInvalidDecl();
4373
10.4k
4374
10.4k
  SmallVector<Decl*, 4> Fields(Record->fields());
4375
10.4k
  ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4376
10.4k
              SourceLocation(), SourceLocation(), ParsedAttributesView());
4377
10.4k
}
4378
4379
284k
StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4380
284k
  // Leave the captured scope before we start creating captures in the
4381
284k
  // enclosing scope.
4382
284k
  DiscardCleanupsInEvaluationContext();
4383
284k
  PopExpressionEvaluationContext();
4384
284k
  PopDeclContext();
4385
284k
  PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4386
284k
  CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4387
284k
4388
284k
  SmallVector<CapturedStmt::Capture, 4> Captures;
4389
284k
  SmallVector<Expr *, 4> CaptureInits;
4390
284k
  if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
4391
0
    return StmtError();
4392
284k
4393
284k
  CapturedDecl *CD = RSI->TheCapturedDecl;
4394
284k
  RecordDecl *RD = RSI->TheRecordDecl;
4395
284k
4396
284k
  CapturedStmt *Res = CapturedStmt::Create(
4397
284k
      getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4398
284k
      Captures, CaptureInits, CD, RD);
4399
284k
4400
284k
  CD->setBody(Res->getCapturedStmt());
4401
284k
  RD->completeDefinition();
4402
284k
4403
284k
  return Res;
4404
284k
}