Coverage Report

Created: 2020-09-19 12:23

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