Bug Summary

File:tools/clang/lib/Sema/SemaStmt.cpp
Warning:line 119, column 36
Undefined or garbage value returned to caller

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaStmt.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaStmt.cpp

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaStmt.cpp

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

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h

1//===- TypeLoc.h - Type Source Info Wrapper ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// \brief Defines the clang::TypeLoc interface and its subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_TYPELOC_H
16#define LLVM_CLANG_AST_TYPELOC_H
17
18#include "clang/AST/Decl.h"
19#include "clang/AST/NestedNameSpecifier.h"
20#include "clang/AST/TemplateBase.h"
21#include "clang/AST/Type.h"
22#include "clang/Basic/LLVM.h"
23#include "clang/Basic/SourceLocation.h"
24#include "clang/Basic/Specifiers.h"
25#include "llvm/ADT/ArrayRef.h"
26#include "llvm/Support/Casting.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/MathExtras.h"
29#include <algorithm>
30#include <cassert>
31#include <cstdint>
32#include <cstring>
33
34namespace clang {
35
36class ASTContext;
37class CXXRecordDecl;
38class Expr;
39class ObjCInterfaceDecl;
40class ObjCProtocolDecl;
41class ObjCTypeParamDecl;
42class TemplateTypeParmDecl;
43class UnqualTypeLoc;
44class UnresolvedUsingTypenameDecl;
45
46// Predeclare all the type nodes.
47#define ABSTRACT_TYPELOC(Class, Base)
48#define TYPELOC(Class, Base) \
49 class Class##TypeLoc;
50#include "clang/AST/TypeLocNodes.def"
51
52/// \brief Base wrapper for a particular "section" of type source info.
53///
54/// A client should use the TypeLoc subclasses through castAs()/getAs()
55/// in order to get at the actual information.
56class TypeLoc {
57protected:
58 // The correctness of this relies on the property that, for Type *Ty,
59 // QualType(Ty, 0).getAsOpaquePtr() == (void*) Ty
60 const void *Ty = nullptr;
61 void *Data = nullptr;
62
63public:
64 TypeLoc() = default;
65 TypeLoc(QualType ty, void *opaqueData)
66 : Ty(ty.getAsOpaquePtr()), Data(opaqueData) {}
67 TypeLoc(const Type *ty, void *opaqueData)
68 : Ty(ty), Data(opaqueData) {}
69
70 /// \brief Convert to the specified TypeLoc type, asserting that this TypeLoc
71 /// is of the desired type.
72 ///
73 /// \pre T::isKind(*this)
74 template<typename T>
75 T castAs() const {
76 assert(T::isKind(*this))(static_cast <bool> (T::isKind(*this)) ? void (0) : __assert_fail
("T::isKind(*this)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 76, __extension__ __PRETTY_FUNCTION__))
;
77 T t;
78 TypeLoc& tl = t;
79 tl = *this;
80 return t;
81 }
82
83 /// \brief Convert to the specified TypeLoc type, returning a null TypeLoc if
84 /// this TypeLoc is not of the desired type.
85 template<typename T>
86 T getAs() const {
87 if (!T::isKind(*this))
88 return {};
89 T t;
90 TypeLoc& tl = t;
91 tl = *this;
92 return t;
93 }
94
95 /// \brief Convert to the specified TypeLoc type, returning a null TypeLoc if
96 /// this TypeLock is not of the desired type. It will consider type
97 /// adjustments from a type that wad written as a T to another type that is
98 /// still canonically a T (ignores parens, attributes, elaborated types, etc).
99 template <typename T>
100 T getAsAdjusted() const;
101
102 /// The kinds of TypeLocs. Equivalent to the Type::TypeClass enum,
103 /// except it also defines a Qualified enum that corresponds to the
104 /// QualifiedLoc class.
105 enum TypeLocClass {
106#define ABSTRACT_TYPE(Class, Base)
107#define TYPE(Class, Base) \
108 Class = Type::Class,
109#include "clang/AST/TypeNodes.def"
110 Qualified
111 };
112
113 TypeLocClass getTypeLocClass() const {
114 if (getType().hasLocalQualifiers()) return Qualified;
115 return (TypeLocClass) getType()->getTypeClass();
116 }
117
118 bool isNull() const { return !Ty; }
119 explicit operator bool() const { return Ty; }
19
Undefined or garbage value returned to caller
120
121 /// \brief Returns the size of type source info data block for the given type.
122 static unsigned getFullDataSizeForType(QualType Ty);
123
124 /// \brief Returns the alignment of type source info data block for
125 /// the given type.
126 static unsigned getLocalAlignmentForType(QualType Ty);
127
128 /// \brief Get the type for which this source info wrapper provides
129 /// information.
130 QualType getType() const {
131 return QualType::getFromOpaquePtr(Ty);
132 }
133
134 const Type *getTypePtr() const {
135 return QualType::getFromOpaquePtr(Ty).getTypePtr();
136 }
137
138 /// \brief Get the pointer where source information is stored.
139 void *getOpaqueData() const {
140 return Data;
141 }
142
143 /// \brief Get the begin source location.
144 SourceLocation getBeginLoc() const;
145
146 /// \brief Get the end source location.
147 SourceLocation getEndLoc() const;
148
149 /// \brief Get the full source range.
150 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
151 return SourceRange(getBeginLoc(), getEndLoc());
152 }
153
154 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return getBeginLoc(); }
155 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) { return getEndLoc(); }
156
157 /// \brief Get the local source range.
158 SourceRange getLocalSourceRange() const {
159 return getLocalSourceRangeImpl(*this);
160 }
161
162 /// \brief Returns the size of the type source info data block.
163 unsigned getFullDataSize() const {
164 return getFullDataSizeForType(getType());
165 }
166
167 /// \brief Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the
168 /// TypeLoc is a PointerLoc and next TypeLoc is for "int".
169 TypeLoc getNextTypeLoc() const {
170 return getNextTypeLocImpl(*this);
171 }
172
173 /// \brief Skips past any qualifiers, if this is qualified.
174 UnqualTypeLoc getUnqualifiedLoc() const; // implemented in this header
175
176 TypeLoc IgnoreParens() const;
177
178 /// \brief Find a type with the location of an explicit type qualifier.
179 ///
180 /// The result, if non-null, will be one of:
181 /// QualifiedTypeLoc
182 /// AtomicTypeLoc
183 /// AttributedTypeLoc, for those type attributes that behave as qualifiers
184 TypeLoc findExplicitQualifierLoc() const;
185
186 /// \brief Initializes this to state that every location in this
187 /// type is the given location.
188 ///
189 /// This method exists to provide a simple transition for code that
190 /// relies on location-less types.
191 void initialize(ASTContext &Context, SourceLocation Loc) const {
192 initializeImpl(Context, *this, Loc);
193 }
194
195 /// \brief Initializes this by copying its information from another
196 /// TypeLoc of the same type.
197 void initializeFullCopy(TypeLoc Other) {
198 assert(getType() == Other.getType())(static_cast <bool> (getType() == Other.getType()) ? void
(0) : __assert_fail ("getType() == Other.getType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 198, __extension__ __PRETTY_FUNCTION__))
;
199 copy(Other);
200 }
201
202 /// \brief Initializes this by copying its information from another
203 /// TypeLoc of the same type. The given size must be the full data
204 /// size.
205 void initializeFullCopy(TypeLoc Other, unsigned Size) {
206 assert(getType() == Other.getType())(static_cast <bool> (getType() == Other.getType()) ? void
(0) : __assert_fail ("getType() == Other.getType()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 206, __extension__ __PRETTY_FUNCTION__))
;
207 assert(getFullDataSize() == Size)(static_cast <bool> (getFullDataSize() == Size) ? void (
0) : __assert_fail ("getFullDataSize() == Size", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 207, __extension__ __PRETTY_FUNCTION__))
;
208 copy(Other);
209 }
210
211 /// Copies the other type loc into this one.
212 void copy(TypeLoc other);
213
214 friend bool operator==(const TypeLoc &LHS, const TypeLoc &RHS) {
215 return LHS.Ty == RHS.Ty && LHS.Data == RHS.Data;
216 }
217
218 friend bool operator!=(const TypeLoc &LHS, const TypeLoc &RHS) {
219 return !(LHS == RHS);
220 }
221
222 /// Find the location of the nullability specifier (__nonnull,
223 /// __nullable, or __null_unspecifier), if there is one.
224 SourceLocation findNullabilityLoc() const;
225
226private:
227 static bool isKind(const TypeLoc&) {
228 return true;
229 }
230
231 static void initializeImpl(ASTContext &Context, TypeLoc TL,
232 SourceLocation Loc);
233 static TypeLoc getNextTypeLocImpl(TypeLoc TL);
234 static TypeLoc IgnoreParensImpl(TypeLoc TL);
235 static SourceRange getLocalSourceRangeImpl(TypeLoc TL);
236};
237
238/// \brief Return the TypeLoc for a type source info.
239inline TypeLoc TypeSourceInfo::getTypeLoc() const {
240 // TODO: is this alignment already sufficient?
241 return TypeLoc(Ty, const_cast<void*>(static_cast<const void*>(this + 1)));
242}
243
244/// \brief Wrapper of type source information for a type with
245/// no direct qualifiers.
246class UnqualTypeLoc : public TypeLoc {
247public:
248 UnqualTypeLoc() = default;
249 UnqualTypeLoc(const Type *Ty, void *Data) : TypeLoc(Ty, Data) {}
250
251 const Type *getTypePtr() const {
252 return reinterpret_cast<const Type*>(Ty);
253 }
254
255 TypeLocClass getTypeLocClass() const {
256 return (TypeLocClass) getTypePtr()->getTypeClass();
257 }
258
259private:
260 friend class TypeLoc;
261
262 static bool isKind(const TypeLoc &TL) {
263 return !TL.getType().hasLocalQualifiers();
264 }
265};
266
267/// \brief Wrapper of type source information for a type with
268/// non-trivial direct qualifiers.
269///
270/// Currently, we intentionally do not provide source location for
271/// type qualifiers.
272class QualifiedTypeLoc : public TypeLoc {
273public:
274 SourceRange getLocalSourceRange() const { return {}; }
275
276 UnqualTypeLoc getUnqualifiedLoc() const {
277 unsigned align =
278 TypeLoc::getLocalAlignmentForType(QualType(getTypePtr(), 0));
279 auto dataInt = reinterpret_cast<uintptr_t>(Data);
280 dataInt = llvm::alignTo(dataInt, align);
281 return UnqualTypeLoc(getTypePtr(), reinterpret_cast<void*>(dataInt));
282 }
283
284 /// Initializes the local data of this type source info block to
285 /// provide no information.
286 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
287 // do nothing
288 }
289
290 void copyLocal(TypeLoc other) {
291 // do nothing
292 }
293
294 TypeLoc getNextTypeLoc() const {
295 return getUnqualifiedLoc();
296 }
297
298 /// \brief Returns the size of the type source info data block that is
299 /// specific to this type.
300 unsigned getLocalDataSize() const {
301 // In fact, we don't currently preserve any location information
302 // for qualifiers.
303 return 0;
304 }
305
306 /// \brief Returns the alignment of the type source info data block that is
307 /// specific to this type.
308 unsigned getLocalDataAlignment() const {
309 // We don't preserve any location information.
310 return 1;
311 }
312
313private:
314 friend class TypeLoc;
315
316 static bool isKind(const TypeLoc &TL) {
317 return TL.getType().hasLocalQualifiers();
318 }
319};
320
321inline UnqualTypeLoc TypeLoc::getUnqualifiedLoc() const {
322 if (QualifiedTypeLoc Loc = getAs<QualifiedTypeLoc>())
323 return Loc.getUnqualifiedLoc();
324 return castAs<UnqualTypeLoc>();
325}
326
327/// A metaprogramming base class for TypeLoc classes which correspond
328/// to a particular Type subclass. It is accepted for a single
329/// TypeLoc class to correspond to multiple Type classes.
330///
331/// \tparam Base a class from which to derive
332/// \tparam Derived the class deriving from this one
333/// \tparam TypeClass the concrete Type subclass associated with this
334/// location type
335/// \tparam LocalData the structure type of local location data for
336/// this type
337///
338/// TypeLocs with non-constant amounts of local data should override
339/// getExtraLocalDataSize(); getExtraLocalData() will then point to
340/// this extra memory.
341///
342/// TypeLocs with an inner type should define
343/// QualType getInnerType() const
344/// and getInnerTypeLoc() will then point to this inner type's
345/// location data.
346///
347/// A word about hierarchies: this template is not designed to be
348/// derived from multiple times in a hierarchy. It is also not
349/// designed to be used for classes where subtypes might provide
350/// different amounts of source information. It should be subclassed
351/// only at the deepest portion of the hierarchy where all children
352/// have identical source information; if that's an abstract type,
353/// then further descendents should inherit from
354/// InheritingConcreteTypeLoc instead.
355template <class Base, class Derived, class TypeClass, class LocalData>
356class ConcreteTypeLoc : public Base {
357 friend class TypeLoc;
358
359 const Derived *asDerived() const {
360 return static_cast<const Derived*>(this);
361 }
362
363 static bool isKind(const TypeLoc &TL) {
364 return !TL.getType().hasLocalQualifiers() &&
365 Derived::classofType(TL.getTypePtr());
366 }
367
368 static bool classofType(const Type *Ty) {
369 return TypeClass::classof(Ty);
370 }
371
372public:
373 unsigned getLocalDataAlignment() const {
374 return std::max(unsigned(alignof(LocalData)),
375 asDerived()->getExtraLocalDataAlignment());
376 }
377
378 unsigned getLocalDataSize() const {
379 unsigned size = sizeof(LocalData);
380 unsigned extraAlign = asDerived()->getExtraLocalDataAlignment();
381 size = llvm::alignTo(size, extraAlign);
382 size += asDerived()->getExtraLocalDataSize();
383 return size;
384 }
385
386 void copyLocal(Derived other) {
387 // Some subclasses have no data to copy.
388 if (asDerived()->getLocalDataSize() == 0) return;
389
390 // Copy the fixed-sized local data.
391 memcpy(getLocalData(), other.getLocalData(), sizeof(LocalData));
392
393 // Copy the variable-sized local data. We need to do this
394 // separately because the padding in the source and the padding in
395 // the destination might be different.
396 memcpy(getExtraLocalData(), other.getExtraLocalData(),
397 asDerived()->getExtraLocalDataSize());
398 }
399
400 TypeLoc getNextTypeLoc() const {
401 return getNextTypeLoc(asDerived()->getInnerType());
402 }
403
404 const TypeClass *getTypePtr() const {
405 return cast<TypeClass>(Base::getTypePtr());
406 }
407
408protected:
409 unsigned getExtraLocalDataSize() const {
410 return 0;
411 }
412
413 unsigned getExtraLocalDataAlignment() const {
414 return 1;
415 }
416
417 LocalData *getLocalData() const {
418 return static_cast<LocalData*>(Base::Data);
419 }
420
421 /// Gets a pointer past the Info structure; useful for classes with
422 /// local data that can't be captured in the Info (e.g. because it's
423 /// of variable size).
424 void *getExtraLocalData() const {
425 unsigned size = sizeof(LocalData);
426 unsigned extraAlign = asDerived()->getExtraLocalDataAlignment();
427 size = llvm::alignTo(size, extraAlign);
428 return reinterpret_cast<char*>(Base::Data) + size;
429 }
430
431 void *getNonLocalData() const {
432 auto data = reinterpret_cast<uintptr_t>(Base::Data);
433 data += asDerived()->getLocalDataSize();
434 data = llvm::alignTo(data, getNextTypeAlign());
435 return reinterpret_cast<void*>(data);
436 }
437
438 struct HasNoInnerType {};
439 HasNoInnerType getInnerType() const { return HasNoInnerType(); }
440
441 TypeLoc getInnerTypeLoc() const {
442 return TypeLoc(asDerived()->getInnerType(), getNonLocalData());
443 }
444
445private:
446 unsigned getInnerTypeSize() const {
447 return getInnerTypeSize(asDerived()->getInnerType());
448 }
449
450 unsigned getInnerTypeSize(HasNoInnerType _) const {
451 return 0;
452 }
453
454 unsigned getInnerTypeSize(QualType _) const {
455 return getInnerTypeLoc().getFullDataSize();
456 }
457
458 unsigned getNextTypeAlign() const {
459 return getNextTypeAlign(asDerived()->getInnerType());
460 }
461
462 unsigned getNextTypeAlign(HasNoInnerType _) const {
463 return 1;
464 }
465
466 unsigned getNextTypeAlign(QualType T) const {
467 return TypeLoc::getLocalAlignmentForType(T);
468 }
469
470 TypeLoc getNextTypeLoc(HasNoInnerType _) const { return {}; }
471
472 TypeLoc getNextTypeLoc(QualType T) const {
473 return TypeLoc(T, getNonLocalData());
474 }
475};
476
477/// A metaprogramming class designed for concrete subtypes of abstract
478/// types where all subtypes share equivalently-structured source
479/// information. See the note on ConcreteTypeLoc.
480template <class Base, class Derived, class TypeClass>
481class InheritingConcreteTypeLoc : public Base {
482 friend class TypeLoc;
483
484 static bool classofType(const Type *Ty) {
485 return TypeClass::classof(Ty);
486 }
487
488 static bool isKind(const TypeLoc &TL) {
489 return !TL.getType().hasLocalQualifiers() &&
490 Derived::classofType(TL.getTypePtr());
491 }
492 static bool isKind(const UnqualTypeLoc &TL) {
493 return Derived::classofType(TL.getTypePtr());
494 }
495
496public:
497 const TypeClass *getTypePtr() const {
498 return cast<TypeClass>(Base::getTypePtr());
499 }
500};
501
502struct TypeSpecLocInfo {
503 SourceLocation NameLoc;
504};
505
506/// \brief A reasonable base class for TypeLocs that correspond to
507/// types that are written as a type-specifier.
508class TypeSpecTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
509 TypeSpecTypeLoc,
510 Type,
511 TypeSpecLocInfo> {
512public:
513 enum {
514 LocalDataSize = sizeof(TypeSpecLocInfo),
515 LocalDataAlignment = alignof(TypeSpecLocInfo)
516 };
517
518 SourceLocation getNameLoc() const {
519 return this->getLocalData()->NameLoc;
520 }
521
522 void setNameLoc(SourceLocation Loc) {
523 this->getLocalData()->NameLoc = Loc;
524 }
525
526 SourceRange getLocalSourceRange() const {
527 return SourceRange(getNameLoc(), getNameLoc());
528 }
529
530 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
531 setNameLoc(Loc);
532 }
533
534private:
535 friend class TypeLoc;
536
537 static bool isKind(const TypeLoc &TL);
538};
539
540struct BuiltinLocInfo {
541 SourceRange BuiltinRange;
542};
543
544/// \brief Wrapper for source info for builtin types.
545class BuiltinTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
546 BuiltinTypeLoc,
547 BuiltinType,
548 BuiltinLocInfo> {
549public:
550 SourceLocation getBuiltinLoc() const {
551 return getLocalData()->BuiltinRange.getBegin();
552 }
553
554 void setBuiltinLoc(SourceLocation Loc) {
555 getLocalData()->BuiltinRange = Loc;
556 }
557
558 void expandBuiltinRange(SourceRange Range) {
559 SourceRange &BuiltinRange = getLocalData()->BuiltinRange;
560 if (!BuiltinRange.getBegin().isValid()) {
561 BuiltinRange = Range;
562 } else {
563 BuiltinRange.setBegin(std::min(Range.getBegin(), BuiltinRange.getBegin()));
564 BuiltinRange.setEnd(std::max(Range.getEnd(), BuiltinRange.getEnd()));
565 }
566 }
567
568 SourceLocation getNameLoc() const { return getBuiltinLoc(); }
569
570 WrittenBuiltinSpecs& getWrittenBuiltinSpecs() {
571 return *(static_cast<WrittenBuiltinSpecs*>(getExtraLocalData()));
572 }
573 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
574 return *(static_cast<WrittenBuiltinSpecs*>(getExtraLocalData()));
575 }
576
577 bool needsExtraLocalData() const {
578 BuiltinType::Kind bk = getTypePtr()->getKind();
579 return (bk >= BuiltinType::UShort && bk <= BuiltinType::UInt128)
580 || (bk >= BuiltinType::Short && bk <= BuiltinType::Float128)
581 || bk == BuiltinType::UChar
582 || bk == BuiltinType::SChar;
583 }
584
585 unsigned getExtraLocalDataSize() const {
586 return needsExtraLocalData() ? sizeof(WrittenBuiltinSpecs) : 0;
587 }
588
589 unsigned getExtraLocalDataAlignment() const {
590 return needsExtraLocalData() ? alignof(WrittenBuiltinSpecs) : 1;
591 }
592
593 SourceRange getLocalSourceRange() const {
594 return getLocalData()->BuiltinRange;
595 }
596
597 TypeSpecifierSign getWrittenSignSpec() const {
598 if (needsExtraLocalData())
599 return static_cast<TypeSpecifierSign>(getWrittenBuiltinSpecs().Sign);
600 else
601 return TSS_unspecified;
602 }
603
604 bool hasWrittenSignSpec() const {
605 return getWrittenSignSpec() != TSS_unspecified;
606 }
607
608 void setWrittenSignSpec(TypeSpecifierSign written) {
609 if (needsExtraLocalData())
610 getWrittenBuiltinSpecs().Sign = written;
611 }
612
613 TypeSpecifierWidth getWrittenWidthSpec() const {
614 if (needsExtraLocalData())
615 return static_cast<TypeSpecifierWidth>(getWrittenBuiltinSpecs().Width);
616 else
617 return TSW_unspecified;
618 }
619
620 bool hasWrittenWidthSpec() const {
621 return getWrittenWidthSpec() != TSW_unspecified;
622 }
623
624 void setWrittenWidthSpec(TypeSpecifierWidth written) {
625 if (needsExtraLocalData())
626 getWrittenBuiltinSpecs().Width = written;
627 }
628
629 TypeSpecifierType getWrittenTypeSpec() const;
630
631 bool hasWrittenTypeSpec() const {
632 return getWrittenTypeSpec() != TST_unspecified;
633 }
634
635 void setWrittenTypeSpec(TypeSpecifierType written) {
636 if (needsExtraLocalData())
637 getWrittenBuiltinSpecs().Type = written;
638 }
639
640 bool hasModeAttr() const {
641 if (needsExtraLocalData())
642 return getWrittenBuiltinSpecs().ModeAttr;
643 else
644 return false;
645 }
646
647 void setModeAttr(bool written) {
648 if (needsExtraLocalData())
649 getWrittenBuiltinSpecs().ModeAttr = written;
650 }
651
652 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
653 setBuiltinLoc(Loc);
654 if (needsExtraLocalData()) {
655 WrittenBuiltinSpecs &wbs = getWrittenBuiltinSpecs();
656 wbs.Sign = TSS_unspecified;
657 wbs.Width = TSW_unspecified;
658 wbs.Type = TST_unspecified;
659 wbs.ModeAttr = false;
660 }
661 }
662};
663
664/// \brief Wrapper for source info for typedefs.
665class TypedefTypeLoc : public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
666 TypedefTypeLoc,
667 TypedefType> {
668public:
669 TypedefNameDecl *getTypedefNameDecl() const {
670 return getTypePtr()->getDecl();
671 }
672};
673
674/// \brief Wrapper for source info for injected class names of class
675/// templates.
676class InjectedClassNameTypeLoc :
677 public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
678 InjectedClassNameTypeLoc,
679 InjectedClassNameType> {
680public:
681 CXXRecordDecl *getDecl() const {
682 return getTypePtr()->getDecl();
683 }
684};
685
686/// \brief Wrapper for source info for unresolved typename using decls.
687class UnresolvedUsingTypeLoc :
688 public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
689 UnresolvedUsingTypeLoc,
690 UnresolvedUsingType> {
691public:
692 UnresolvedUsingTypenameDecl *getDecl() const {
693 return getTypePtr()->getDecl();
694 }
695};
696
697/// \brief Wrapper for source info for tag types. Note that this only
698/// records source info for the name itself; a type written 'struct foo'
699/// should be represented as an ElaboratedTypeLoc. We currently
700/// only do that when C++ is enabled because of the expense of
701/// creating an ElaboratedType node for so many type references in C.
702class TagTypeLoc : public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
703 TagTypeLoc,
704 TagType> {
705public:
706 TagDecl *getDecl() const { return getTypePtr()->getDecl(); }
707
708 /// \brief True if the tag was defined in this type specifier.
709 bool isDefinition() const {
710 TagDecl *D = getDecl();
711 return D->isCompleteDefinition() &&
712 (D->getIdentifier() == nullptr || D->getLocation() == getNameLoc());
713 }
714};
715
716/// \brief Wrapper for source info for record types.
717class RecordTypeLoc : public InheritingConcreteTypeLoc<TagTypeLoc,
718 RecordTypeLoc,
719 RecordType> {
720public:
721 RecordDecl *getDecl() const { return getTypePtr()->getDecl(); }
722};
723
724/// \brief Wrapper for source info for enum types.
725class EnumTypeLoc : public InheritingConcreteTypeLoc<TagTypeLoc,
726 EnumTypeLoc,
727 EnumType> {
728public:
729 EnumDecl *getDecl() const { return getTypePtr()->getDecl(); }
730};
731
732/// \brief Wrapper for template type parameters.
733class TemplateTypeParmTypeLoc :
734 public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
735 TemplateTypeParmTypeLoc,
736 TemplateTypeParmType> {
737public:
738 TemplateTypeParmDecl *getDecl() const { return getTypePtr()->getDecl(); }
739};
740
741struct ObjCTypeParamTypeLocInfo {
742 SourceLocation NameLoc;
743};
744
745/// ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for
746/// protocol qualifiers are stored after Info.
747class ObjCTypeParamTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
748 ObjCTypeParamTypeLoc,
749 ObjCTypeParamType,
750 ObjCTypeParamTypeLocInfo> {
751 // SourceLocations are stored after Info, one for each protocol qualifier.
752 SourceLocation *getProtocolLocArray() const {
753 return (SourceLocation*)this->getExtraLocalData() + 2;
754 }
755
756public:
757 ObjCTypeParamDecl *getDecl() const { return getTypePtr()->getDecl(); }
758
759 SourceLocation getNameLoc() const {
760 return this->getLocalData()->NameLoc;
761 }
762
763 void setNameLoc(SourceLocation Loc) {
764 this->getLocalData()->NameLoc = Loc;
765 }
766
767 SourceLocation getProtocolLAngleLoc() const {
768 return getNumProtocols() ?
769 *((SourceLocation*)this->getExtraLocalData()) :
770 SourceLocation();
771 }
772
773 void setProtocolLAngleLoc(SourceLocation Loc) {
774 *((SourceLocation*)this->getExtraLocalData()) = Loc;
775 }
776
777 SourceLocation getProtocolRAngleLoc() const {
778 return getNumProtocols() ?
779 *((SourceLocation*)this->getExtraLocalData() + 1) :
780 SourceLocation();
781 }
782
783 void setProtocolRAngleLoc(SourceLocation Loc) {
784 *((SourceLocation*)this->getExtraLocalData() + 1) = Loc;
785 }
786
787 unsigned getNumProtocols() const {
788 return this->getTypePtr()->getNumProtocols();
789 }
790
791 SourceLocation getProtocolLoc(unsigned i) const {
792 assert(i < getNumProtocols() && "Index is out of bounds!")(static_cast <bool> (i < getNumProtocols() &&
"Index is out of bounds!") ? void (0) : __assert_fail ("i < getNumProtocols() && \"Index is out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 792, __extension__ __PRETTY_FUNCTION__))
;
793 return getProtocolLocArray()[i];
794 }
795
796 void setProtocolLoc(unsigned i, SourceLocation Loc) {
797 assert(i < getNumProtocols() && "Index is out of bounds!")(static_cast <bool> (i < getNumProtocols() &&
"Index is out of bounds!") ? void (0) : __assert_fail ("i < getNumProtocols() && \"Index is out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 797, __extension__ __PRETTY_FUNCTION__))
;
798 getProtocolLocArray()[i] = Loc;
799 }
800
801 ObjCProtocolDecl *getProtocol(unsigned i) const {
802 assert(i < getNumProtocols() && "Index is out of bounds!")(static_cast <bool> (i < getNumProtocols() &&
"Index is out of bounds!") ? void (0) : __assert_fail ("i < getNumProtocols() && \"Index is out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 802, __extension__ __PRETTY_FUNCTION__))
;
803 return *(this->getTypePtr()->qual_begin() + i);
804 }
805
806 ArrayRef<SourceLocation> getProtocolLocs() const {
807 return llvm::makeArrayRef(getProtocolLocArray(), getNumProtocols());
808 }
809
810 void initializeLocal(ASTContext &Context, SourceLocation Loc);
811
812 unsigned getExtraLocalDataSize() const {
813 if (!this->getNumProtocols()) return 0;
814 // When there are protocol qualifers, we have LAngleLoc and RAngleLoc
815 // as well.
816 return (this->getNumProtocols() + 2) * sizeof(SourceLocation) ;
817 }
818
819 unsigned getExtraLocalDataAlignment() const {
820 return alignof(SourceLocation);
821 }
822
823 SourceRange getLocalSourceRange() const {
824 SourceLocation start = getNameLoc();
825 SourceLocation end = getProtocolRAngleLoc();
826 if (end.isInvalid()) return SourceRange(start, start);
827 return SourceRange(start, end);
828 }
829};
830
831/// \brief Wrapper for substituted template type parameters.
832class SubstTemplateTypeParmTypeLoc :
833 public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
834 SubstTemplateTypeParmTypeLoc,
835 SubstTemplateTypeParmType> {
836};
837
838 /// \brief Wrapper for substituted template type parameters.
839class SubstTemplateTypeParmPackTypeLoc :
840 public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
841 SubstTemplateTypeParmPackTypeLoc,
842 SubstTemplateTypeParmPackType> {
843};
844
845struct AttributedLocInfo {
846 union {
847 Expr *ExprOperand;
848
849 /// A raw SourceLocation.
850 unsigned EnumOperandLoc;
851 };
852
853 SourceRange OperandParens;
854
855 SourceLocation AttrLoc;
856};
857
858/// \brief Type source information for an attributed type.
859class AttributedTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
860 AttributedTypeLoc,
861 AttributedType,
862 AttributedLocInfo> {
863public:
864 AttributedType::Kind getAttrKind() const {
865 return getTypePtr()->getAttrKind();
866 }
867
868 bool hasAttrExprOperand() const {
869 return (getAttrKind() >= AttributedType::FirstExprOperandKind &&
870 getAttrKind() <= AttributedType::LastExprOperandKind);
871 }
872
873 bool hasAttrEnumOperand() const {
874 return (getAttrKind() >= AttributedType::FirstEnumOperandKind &&
875 getAttrKind() <= AttributedType::LastEnumOperandKind);
876 }
877
878 bool hasAttrOperand() const {
879 return hasAttrExprOperand() || hasAttrEnumOperand();
880 }
881
882 bool isQualifier() const {
883 return getTypePtr()->isQualifier();
884 }
885
886 /// The modified type, which is generally canonically different from
887 /// the attribute type.
888 /// int main(int, char**) __attribute__((noreturn))
889 /// ~~~ ~~~~~~~~~~~~~
890 TypeLoc getModifiedLoc() const {
891 return getInnerTypeLoc();
892 }
893
894 /// The location of the attribute name, i.e.
895 /// __attribute__((regparm(1000)))
896 /// ^~~~~~~
897 SourceLocation getAttrNameLoc() const {
898 return getLocalData()->AttrLoc;
899 }
900 void setAttrNameLoc(SourceLocation loc) {
901 getLocalData()->AttrLoc = loc;
902 }
903
904 /// The attribute's expression operand, if it has one.
905 /// void *cur_thread __attribute__((address_space(21)))
906 /// ^~
907 Expr *getAttrExprOperand() const {
908 assert(hasAttrExprOperand())(static_cast <bool> (hasAttrExprOperand()) ? void (0) :
__assert_fail ("hasAttrExprOperand()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 908, __extension__ __PRETTY_FUNCTION__))
;
909 return getLocalData()->ExprOperand;
910 }
911 void setAttrExprOperand(Expr *e) {
912 assert(hasAttrExprOperand())(static_cast <bool> (hasAttrExprOperand()) ? void (0) :
__assert_fail ("hasAttrExprOperand()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 912, __extension__ __PRETTY_FUNCTION__))
;
913 getLocalData()->ExprOperand = e;
914 }
915
916 /// The location of the attribute's enumerated operand, if it has one.
917 /// void * __attribute__((objc_gc(weak)))
918 /// ^~~~
919 SourceLocation getAttrEnumOperandLoc() const {
920 assert(hasAttrEnumOperand())(static_cast <bool> (hasAttrEnumOperand()) ? void (0) :
__assert_fail ("hasAttrEnumOperand()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 920, __extension__ __PRETTY_FUNCTION__))
;
921 return SourceLocation::getFromRawEncoding(getLocalData()->EnumOperandLoc);
922 }
923 void setAttrEnumOperandLoc(SourceLocation loc) {
924 assert(hasAttrEnumOperand())(static_cast <bool> (hasAttrEnumOperand()) ? void (0) :
__assert_fail ("hasAttrEnumOperand()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 924, __extension__ __PRETTY_FUNCTION__))
;
925 getLocalData()->EnumOperandLoc = loc.getRawEncoding();
926 }
927
928 /// The location of the parentheses around the operand, if there is
929 /// an operand.
930 /// void * __attribute__((objc_gc(weak)))
931 /// ^ ^
932 SourceRange getAttrOperandParensRange() const {
933 assert(hasAttrOperand())(static_cast <bool> (hasAttrOperand()) ? void (0) : __assert_fail
("hasAttrOperand()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 933, __extension__ __PRETTY_FUNCTION__))
;
934 return getLocalData()->OperandParens;
935 }
936 void setAttrOperandParensRange(SourceRange range) {
937 assert(hasAttrOperand())(static_cast <bool> (hasAttrOperand()) ? void (0) : __assert_fail
("hasAttrOperand()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 937, __extension__ __PRETTY_FUNCTION__))
;
938 getLocalData()->OperandParens = range;
939 }
940
941 SourceRange getLocalSourceRange() const {
942 // Note that this does *not* include the range of the attribute
943 // enclosure, e.g.:
944 // __attribute__((foo(bar)))
945 // ^~~~~~~~~~~~~~~ ~~
946 // or
947 // [[foo(bar)]]
948 // ^~ ~~
949 // That enclosure doesn't necessarily belong to a single attribute
950 // anyway.
951 SourceRange range(getAttrNameLoc());
952 if (hasAttrOperand())
953 range.setEnd(getAttrOperandParensRange().getEnd());
954 return range;
955 }
956
957 void initializeLocal(ASTContext &Context, SourceLocation loc) {
958 setAttrNameLoc(loc);
959 if (hasAttrExprOperand()) {
960 setAttrOperandParensRange(SourceRange(loc));
961 setAttrExprOperand(nullptr);
962 } else if (hasAttrEnumOperand()) {
963 setAttrOperandParensRange(SourceRange(loc));
964 setAttrEnumOperandLoc(loc);
965 }
966 }
967
968 QualType getInnerType() const {
969 return getTypePtr()->getModifiedType();
970 }
971};
972
973struct ObjCObjectTypeLocInfo {
974 SourceLocation TypeArgsLAngleLoc;
975 SourceLocation TypeArgsRAngleLoc;
976 SourceLocation ProtocolLAngleLoc;
977 SourceLocation ProtocolRAngleLoc;
978 bool HasBaseTypeAsWritten;
979};
980
981// A helper class for defining ObjC TypeLocs that can qualified with
982// protocols.
983//
984// TypeClass basically has to be either ObjCInterfaceType or
985// ObjCObjectPointerType.
986class ObjCObjectTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
987 ObjCObjectTypeLoc,
988 ObjCObjectType,
989 ObjCObjectTypeLocInfo> {
990 // TypeSourceInfo*'s are stored after Info, one for each type argument.
991 TypeSourceInfo **getTypeArgLocArray() const {
992 return (TypeSourceInfo**)this->getExtraLocalData();
993 }
994
995 // SourceLocations are stored after the type argument information, one for
996 // each Protocol.
997 SourceLocation *getProtocolLocArray() const {
998 return (SourceLocation*)(getTypeArgLocArray() + getNumTypeArgs());
999 }
1000
1001public:
1002 SourceLocation getTypeArgsLAngleLoc() const {
1003 return this->getLocalData()->TypeArgsLAngleLoc;
1004 }
1005
1006 void setTypeArgsLAngleLoc(SourceLocation Loc) {
1007 this->getLocalData()->TypeArgsLAngleLoc = Loc;
1008 }
1009
1010 SourceLocation getTypeArgsRAngleLoc() const {
1011 return this->getLocalData()->TypeArgsRAngleLoc;
1012 }
1013
1014 void setTypeArgsRAngleLoc(SourceLocation Loc) {
1015 this->getLocalData()->TypeArgsRAngleLoc = Loc;
1016 }
1017
1018 unsigned getNumTypeArgs() const {
1019 return this->getTypePtr()->getTypeArgsAsWritten().size();
1020 }
1021
1022 TypeSourceInfo *getTypeArgTInfo(unsigned i) const {
1023 assert(i < getNumTypeArgs() && "Index is out of bounds!")(static_cast <bool> (i < getNumTypeArgs() &&
"Index is out of bounds!") ? void (0) : __assert_fail ("i < getNumTypeArgs() && \"Index is out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 1023, __extension__ __PRETTY_FUNCTION__))
;
1024 return getTypeArgLocArray()[i];
1025 }
1026
1027 void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo) {
1028 assert(i < getNumTypeArgs() && "Index is out of bounds!")(static_cast <bool> (i < getNumTypeArgs() &&
"Index is out of bounds!") ? void (0) : __assert_fail ("i < getNumTypeArgs() && \"Index is out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 1028, __extension__ __PRETTY_FUNCTION__))
;
1029 getTypeArgLocArray()[i] = TInfo;
1030 }
1031
1032 SourceLocation getProtocolLAngleLoc() const {
1033 return this->getLocalData()->ProtocolLAngleLoc;
1034 }
1035
1036 void setProtocolLAngleLoc(SourceLocation Loc) {
1037 this->getLocalData()->ProtocolLAngleLoc = Loc;
1038 }
1039
1040 SourceLocation getProtocolRAngleLoc() const {
1041 return this->getLocalData()->ProtocolRAngleLoc;
1042 }
1043
1044 void setProtocolRAngleLoc(SourceLocation Loc) {
1045 this->getLocalData()->ProtocolRAngleLoc = Loc;
1046 }
1047
1048 unsigned getNumProtocols() const {
1049 return this->getTypePtr()->getNumProtocols();
1050 }
1051
1052 SourceLocation getProtocolLoc(unsigned i) const {
1053 assert(i < getNumProtocols() && "Index is out of bounds!")(static_cast <bool> (i < getNumProtocols() &&
"Index is out of bounds!") ? void (0) : __assert_fail ("i < getNumProtocols() && \"Index is out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 1053, __extension__ __PRETTY_FUNCTION__))
;
1054 return getProtocolLocArray()[i];
1055 }
1056
1057 void setProtocolLoc(unsigned i, SourceLocation Loc) {
1058 assert(i < getNumProtocols() && "Index is out of bounds!")(static_cast <bool> (i < getNumProtocols() &&
"Index is out of bounds!") ? void (0) : __assert_fail ("i < getNumProtocols() && \"Index is out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 1058, __extension__ __PRETTY_FUNCTION__))
;
1059 getProtocolLocArray()[i] = Loc;
1060 }
1061
1062 ObjCProtocolDecl *getProtocol(unsigned i) const {
1063 assert(i < getNumProtocols() && "Index is out of bounds!")(static_cast <bool> (i < getNumProtocols() &&
"Index is out of bounds!") ? void (0) : __assert_fail ("i < getNumProtocols() && \"Index is out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 1063, __extension__ __PRETTY_FUNCTION__))
;
1064 return *(this->getTypePtr()->qual_begin() + i);
1065 }
1066
1067
1068 ArrayRef<SourceLocation> getProtocolLocs() const {
1069 return llvm::makeArrayRef(getProtocolLocArray(), getNumProtocols());
1070 }
1071
1072 bool hasBaseTypeAsWritten() const {
1073 return getLocalData()->HasBaseTypeAsWritten;
1074 }
1075
1076 void setHasBaseTypeAsWritten(bool HasBaseType) {
1077 getLocalData()->HasBaseTypeAsWritten = HasBaseType;
1078 }
1079
1080 TypeLoc getBaseLoc() const {
1081 return getInnerTypeLoc();
1082 }
1083
1084 SourceRange getLocalSourceRange() const {
1085 SourceLocation start = getTypeArgsLAngleLoc();
1086 if (start.isInvalid())
1087 start = getProtocolLAngleLoc();
1088 SourceLocation end = getProtocolRAngleLoc();
1089 if (end.isInvalid())
1090 end = getTypeArgsRAngleLoc();
1091 return SourceRange(start, end);
1092 }
1093
1094 void initializeLocal(ASTContext &Context, SourceLocation Loc);
1095
1096 unsigned getExtraLocalDataSize() const {
1097 return this->getNumTypeArgs() * sizeof(TypeSourceInfo *)
1098 + this->getNumProtocols() * sizeof(SourceLocation);
1099 }
1100
1101 unsigned getExtraLocalDataAlignment() const {
1102 static_assert(alignof(ObjCObjectTypeLoc) >= alignof(TypeSourceInfo *),
1103 "not enough alignment for tail-allocated data");
1104 return alignof(TypeSourceInfo *);
1105 }
1106
1107 QualType getInnerType() const {
1108 return getTypePtr()->getBaseType();
1109 }
1110};
1111
1112struct ObjCInterfaceLocInfo {
1113 SourceLocation NameLoc;
1114 SourceLocation NameEndLoc;
1115};
1116
1117/// \brief Wrapper for source info for ObjC interfaces.
1118class ObjCInterfaceTypeLoc : public ConcreteTypeLoc<ObjCObjectTypeLoc,
1119 ObjCInterfaceTypeLoc,
1120 ObjCInterfaceType,
1121 ObjCInterfaceLocInfo> {
1122public:
1123 ObjCInterfaceDecl *getIFaceDecl() const {
1124 return getTypePtr()->getDecl();
1125 }
1126
1127 SourceLocation getNameLoc() const {
1128 return getLocalData()->NameLoc;
1129 }
1130
1131 void setNameLoc(SourceLocation Loc) {
1132 getLocalData()->NameLoc = Loc;
1133 }
1134
1135 SourceRange getLocalSourceRange() const {
1136 return SourceRange(getNameLoc(), getNameEndLoc());
1137 }
1138
1139 SourceLocation getNameEndLoc() const {
1140 return getLocalData()->NameEndLoc;
1141 }
1142
1143 void setNameEndLoc(SourceLocation Loc) {
1144 getLocalData()->NameEndLoc = Loc;
1145 }
1146
1147 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1148 setNameLoc(Loc);
1149 setNameEndLoc(Loc);
1150 }
1151};
1152
1153struct ParenLocInfo {
1154 SourceLocation LParenLoc;
1155 SourceLocation RParenLoc;
1156};
1157
1158class ParenTypeLoc
1159 : public ConcreteTypeLoc<UnqualTypeLoc, ParenTypeLoc, ParenType,
1160 ParenLocInfo> {
1161public:
1162 SourceLocation getLParenLoc() const {
1163 return this->getLocalData()->LParenLoc;
1164 }
1165
1166 SourceLocation getRParenLoc() const {
1167 return this->getLocalData()->RParenLoc;
1168 }
1169
1170 void setLParenLoc(SourceLocation Loc) {
1171 this->getLocalData()->LParenLoc = Loc;
1172 }
1173
1174 void setRParenLoc(SourceLocation Loc) {
1175 this->getLocalData()->RParenLoc = Loc;
1176 }
1177
1178 SourceRange getLocalSourceRange() const {
1179 return SourceRange(getLParenLoc(), getRParenLoc());
1180 }
1181
1182 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1183 setLParenLoc(Loc);
1184 setRParenLoc(Loc);
1185 }
1186
1187 TypeLoc getInnerLoc() const {
1188 return getInnerTypeLoc();
1189 }
1190
1191 QualType getInnerType() const {
1192 return this->getTypePtr()->getInnerType();
1193 }
1194};
1195
1196inline TypeLoc TypeLoc::IgnoreParens() const {
1197 if (ParenTypeLoc::isKind(*this))
1198 return IgnoreParensImpl(*this);
1199 return *this;
1200}
1201
1202struct AdjustedLocInfo {}; // Nothing.
1203
1204class AdjustedTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc, AdjustedTypeLoc,
1205 AdjustedType, AdjustedLocInfo> {
1206public:
1207 TypeLoc getOriginalLoc() const {
1208 return getInnerTypeLoc();
1209 }
1210
1211 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1212 // do nothing
1213 }
1214
1215 QualType getInnerType() const {
1216 // The inner type is the undecayed type, since that's what we have source
1217 // location information for.
1218 return getTypePtr()->getOriginalType();
1219 }
1220
1221 SourceRange getLocalSourceRange() const { return {}; }
1222
1223 unsigned getLocalDataSize() const {
1224 // sizeof(AdjustedLocInfo) is 1, but we don't need its address to be unique
1225 // anyway. TypeLocBuilder can't handle data sizes of 1.
1226 return 0; // No data.
1227 }
1228};
1229
1230/// \brief Wrapper for source info for pointers decayed from arrays and
1231/// functions.
1232class DecayedTypeLoc : public InheritingConcreteTypeLoc<
1233 AdjustedTypeLoc, DecayedTypeLoc, DecayedType> {
1234};
1235
1236struct PointerLikeLocInfo {
1237 SourceLocation StarLoc;
1238};
1239
1240/// A base class for
1241template <class Derived, class TypeClass, class LocalData = PointerLikeLocInfo>
1242class PointerLikeTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc, Derived,
1243 TypeClass, LocalData> {
1244public:
1245 SourceLocation getSigilLoc() const {
1246 return this->getLocalData()->StarLoc;
1247 }
1248
1249 void setSigilLoc(SourceLocation Loc) {
1250 this->getLocalData()->StarLoc = Loc;
1251 }
1252
1253 TypeLoc getPointeeLoc() const {
1254 return this->getInnerTypeLoc();
1255 }
1256
1257 SourceRange getLocalSourceRange() const {
1258 return SourceRange(getSigilLoc(), getSigilLoc());
1259 }
1260
1261 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1262 setSigilLoc(Loc);
1263 }
1264
1265 QualType getInnerType() const {
1266 return this->getTypePtr()->getPointeeType();
1267 }
1268};
1269
1270/// \brief Wrapper for source info for pointers.
1271class PointerTypeLoc : public PointerLikeTypeLoc<PointerTypeLoc,
1272 PointerType> {
1273public:
1274 SourceLocation getStarLoc() const {
1275 return getSigilLoc();
1276 }
1277
1278 void setStarLoc(SourceLocation Loc) {
1279 setSigilLoc(Loc);
1280 }
1281};
1282
1283/// \brief Wrapper for source info for block pointers.
1284class BlockPointerTypeLoc : public PointerLikeTypeLoc<BlockPointerTypeLoc,
1285 BlockPointerType> {
1286public:
1287 SourceLocation getCaretLoc() const {
1288 return getSigilLoc();
1289 }
1290
1291 void setCaretLoc(SourceLocation Loc) {
1292 setSigilLoc(Loc);
1293 }
1294};
1295
1296struct MemberPointerLocInfo : public PointerLikeLocInfo {
1297 TypeSourceInfo *ClassTInfo;
1298};
1299
1300/// \brief Wrapper for source info for member pointers.
1301class MemberPointerTypeLoc : public PointerLikeTypeLoc<MemberPointerTypeLoc,
1302 MemberPointerType,
1303 MemberPointerLocInfo> {
1304public:
1305 SourceLocation getStarLoc() const {
1306 return getSigilLoc();
1307 }
1308
1309 void setStarLoc(SourceLocation Loc) {
1310 setSigilLoc(Loc);
1311 }
1312
1313 const Type *getClass() const {
1314 return getTypePtr()->getClass();
1315 }
1316
1317 TypeSourceInfo *getClassTInfo() const {
1318 return getLocalData()->ClassTInfo;
1319 }
1320
1321 void setClassTInfo(TypeSourceInfo* TI) {
1322 getLocalData()->ClassTInfo = TI;
1323 }
1324
1325 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1326 setSigilLoc(Loc);
1327 setClassTInfo(nullptr);
1328 }
1329
1330 SourceRange getLocalSourceRange() const {
1331 if (TypeSourceInfo *TI = getClassTInfo())
1332 return SourceRange(TI->getTypeLoc().getBeginLoc(), getStarLoc());
1333 else
1334 return SourceRange(getStarLoc());
1335 }
1336};
1337
1338/// Wraps an ObjCPointerType with source location information.
1339class ObjCObjectPointerTypeLoc :
1340 public PointerLikeTypeLoc<ObjCObjectPointerTypeLoc,
1341 ObjCObjectPointerType> {
1342public:
1343 SourceLocation getStarLoc() const {
1344 return getSigilLoc();
1345 }
1346
1347 void setStarLoc(SourceLocation Loc) {
1348 setSigilLoc(Loc);
1349 }
1350};
1351
1352class ReferenceTypeLoc : public PointerLikeTypeLoc<ReferenceTypeLoc,
1353 ReferenceType> {
1354public:
1355 QualType getInnerType() const {
1356 return getTypePtr()->getPointeeTypeAsWritten();
1357 }
1358};
1359
1360class LValueReferenceTypeLoc :
1361 public InheritingConcreteTypeLoc<ReferenceTypeLoc,
1362 LValueReferenceTypeLoc,
1363 LValueReferenceType> {
1364public:
1365 SourceLocation getAmpLoc() const {
1366 return getSigilLoc();
1367 }
1368
1369 void setAmpLoc(SourceLocation Loc) {
1370 setSigilLoc(Loc);
1371 }
1372};
1373
1374class RValueReferenceTypeLoc :
1375 public InheritingConcreteTypeLoc<ReferenceTypeLoc,
1376 RValueReferenceTypeLoc,
1377 RValueReferenceType> {
1378public:
1379 SourceLocation getAmpAmpLoc() const {
1380 return getSigilLoc();
1381 }
1382
1383 void setAmpAmpLoc(SourceLocation Loc) {
1384 setSigilLoc(Loc);
1385 }
1386};
1387
1388struct FunctionLocInfo {
1389 SourceLocation LocalRangeBegin;
1390 SourceLocation LParenLoc;
1391 SourceLocation RParenLoc;
1392 SourceLocation LocalRangeEnd;
1393};
1394
1395/// \brief Wrapper for source info for functions.
1396class FunctionTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
1397 FunctionTypeLoc,
1398 FunctionType,
1399 FunctionLocInfo> {
1400 bool hasExceptionSpec() const {
1401 if (auto *FPT = dyn_cast<FunctionProtoType>(getTypePtr())) {
1402 return FPT->hasExceptionSpec();
1403 }
1404 return false;
1405 }
1406
1407 SourceRange *getExceptionSpecRangePtr() const {
1408 assert(hasExceptionSpec() && "No exception spec range")(static_cast <bool> (hasExceptionSpec() && "No exception spec range"
) ? void (0) : __assert_fail ("hasExceptionSpec() && \"No exception spec range\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 1408, __extension__ __PRETTY_FUNCTION__))
;
1409 // After the Info comes the ParmVarDecl array, and after that comes the
1410 // exception specification information.
1411 return (SourceRange *)(getParmArray() + getNumParams());
1412 }
1413
1414public:
1415 SourceLocation getLocalRangeBegin() const {
1416 return getLocalData()->LocalRangeBegin;
1417 }
1418
1419 void setLocalRangeBegin(SourceLocation L) {
1420 getLocalData()->LocalRangeBegin = L;
1421 }
1422
1423 SourceLocation getLocalRangeEnd() const {
1424 return getLocalData()->LocalRangeEnd;
1425 }
1426
1427 void setLocalRangeEnd(SourceLocation L) {
1428 getLocalData()->LocalRangeEnd = L;
1429 }
1430
1431 SourceLocation getLParenLoc() const {
1432 return this->getLocalData()->LParenLoc;
1433 }
1434
1435 void setLParenLoc(SourceLocation Loc) {
1436 this->getLocalData()->LParenLoc = Loc;
1437 }
1438
1439 SourceLocation getRParenLoc() const {
1440 return this->getLocalData()->RParenLoc;
1441 }
1442
1443 void setRParenLoc(SourceLocation Loc) {
1444 this->getLocalData()->RParenLoc = Loc;
1445 }
1446
1447 SourceRange getParensRange() const {
1448 return SourceRange(getLParenLoc(), getRParenLoc());
1449 }
1450
1451 SourceRange getExceptionSpecRange() const {
1452 if (hasExceptionSpec())
1453 return *getExceptionSpecRangePtr();
1454 return {};
1455 }
1456
1457 void setExceptionSpecRange(SourceRange R) {
1458 if (hasExceptionSpec())
1459 *getExceptionSpecRangePtr() = R;
1460 }
1461
1462 ArrayRef<ParmVarDecl *> getParams() const {
1463 return llvm::makeArrayRef(getParmArray(), getNumParams());
1464 }
1465
1466 // ParmVarDecls* are stored after Info, one for each parameter.
1467 ParmVarDecl **getParmArray() const {
1468 return (ParmVarDecl**) getExtraLocalData();
1469 }
1470
1471 unsigned getNumParams() const {
1472 if (isa<FunctionNoProtoType>(getTypePtr()))
1473 return 0;
1474 return cast<FunctionProtoType>(getTypePtr())->getNumParams();
1475 }
1476
1477 ParmVarDecl *getParam(unsigned i) const { return getParmArray()[i]; }
1478 void setParam(unsigned i, ParmVarDecl *VD) { getParmArray()[i] = VD; }
1479
1480 TypeLoc getReturnLoc() const {
1481 return getInnerTypeLoc();
1482 }
1483
1484 SourceRange getLocalSourceRange() const {
1485 return SourceRange(getLocalRangeBegin(), getLocalRangeEnd());
1486 }
1487
1488 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1489 setLocalRangeBegin(Loc);
1490 setLParenLoc(Loc);
1491 setRParenLoc(Loc);
1492 setLocalRangeEnd(Loc);
1493 for (unsigned i = 0, e = getNumParams(); i != e; ++i)
1494 setParam(i, nullptr);
1495 if (hasExceptionSpec())
1496 setExceptionSpecRange(Loc);
1497 }
1498
1499 /// \brief Returns the size of the type source info data block that is
1500 /// specific to this type.
1501 unsigned getExtraLocalDataSize() const {
1502 unsigned ExceptSpecSize = hasExceptionSpec() ? sizeof(SourceRange) : 0;
1503 return (getNumParams() * sizeof(ParmVarDecl *)) + ExceptSpecSize;
1504 }
1505
1506 unsigned getExtraLocalDataAlignment() const { return alignof(ParmVarDecl *); }
1507
1508 QualType getInnerType() const { return getTypePtr()->getReturnType(); }
1509};
1510
1511class FunctionProtoTypeLoc :
1512 public InheritingConcreteTypeLoc<FunctionTypeLoc,
1513 FunctionProtoTypeLoc,
1514 FunctionProtoType> {
1515};
1516
1517class FunctionNoProtoTypeLoc :
1518 public InheritingConcreteTypeLoc<FunctionTypeLoc,
1519 FunctionNoProtoTypeLoc,
1520 FunctionNoProtoType> {
1521};
1522
1523struct ArrayLocInfo {
1524 SourceLocation LBracketLoc, RBracketLoc;
1525 Expr *Size;
1526};
1527
1528/// \brief Wrapper for source info for arrays.
1529class ArrayTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
1530 ArrayTypeLoc,
1531 ArrayType,
1532 ArrayLocInfo> {
1533public:
1534 SourceLocation getLBracketLoc() const {
1535 return getLocalData()->LBracketLoc;
1536 }
1537
1538 void setLBracketLoc(SourceLocation Loc) {
1539 getLocalData()->LBracketLoc = Loc;
1540 }
1541
1542 SourceLocation getRBracketLoc() const {
1543 return getLocalData()->RBracketLoc;
1544 }
1545
1546 void setRBracketLoc(SourceLocation Loc) {
1547 getLocalData()->RBracketLoc = Loc;
1548 }
1549
1550 SourceRange getBracketsRange() const {
1551 return SourceRange(getLBracketLoc(), getRBracketLoc());
1552 }
1553
1554 Expr *getSizeExpr() const {
1555 return getLocalData()->Size;
1556 }
1557
1558 void setSizeExpr(Expr *Size) {
1559 getLocalData()->Size = Size;
1560 }
1561
1562 TypeLoc getElementLoc() const {
1563 return getInnerTypeLoc();
1564 }
1565
1566 SourceRange getLocalSourceRange() const {
1567 return SourceRange(getLBracketLoc(), getRBracketLoc());
1568 }
1569
1570 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1571 setLBracketLoc(Loc);
1572 setRBracketLoc(Loc);
1573 setSizeExpr(nullptr);
1574 }
1575
1576 QualType getInnerType() const { return getTypePtr()->getElementType(); }
1577};
1578
1579class ConstantArrayTypeLoc :
1580 public InheritingConcreteTypeLoc<ArrayTypeLoc,
1581 ConstantArrayTypeLoc,
1582 ConstantArrayType> {
1583};
1584
1585class IncompleteArrayTypeLoc :
1586 public InheritingConcreteTypeLoc<ArrayTypeLoc,
1587 IncompleteArrayTypeLoc,
1588 IncompleteArrayType> {
1589};
1590
1591class DependentSizedArrayTypeLoc :
1592 public InheritingConcreteTypeLoc<ArrayTypeLoc,
1593 DependentSizedArrayTypeLoc,
1594 DependentSizedArrayType> {
1595public:
1596 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1597 ArrayTypeLoc::initializeLocal(Context, Loc);
1598 setSizeExpr(getTypePtr()->getSizeExpr());
1599 }
1600};
1601
1602class VariableArrayTypeLoc :
1603 public InheritingConcreteTypeLoc<ArrayTypeLoc,
1604 VariableArrayTypeLoc,
1605 VariableArrayType> {
1606};
1607
1608// Location information for a TemplateName. Rudimentary for now.
1609struct TemplateNameLocInfo {
1610 SourceLocation NameLoc;
1611};
1612
1613struct TemplateSpecializationLocInfo : TemplateNameLocInfo {
1614 SourceLocation TemplateKWLoc;
1615 SourceLocation LAngleLoc;
1616 SourceLocation RAngleLoc;
1617};
1618
1619class TemplateSpecializationTypeLoc :
1620 public ConcreteTypeLoc<UnqualTypeLoc,
1621 TemplateSpecializationTypeLoc,
1622 TemplateSpecializationType,
1623 TemplateSpecializationLocInfo> {
1624public:
1625 SourceLocation getTemplateKeywordLoc() const {
1626 return getLocalData()->TemplateKWLoc;
1627 }
1628
1629 void setTemplateKeywordLoc(SourceLocation Loc) {
1630 getLocalData()->TemplateKWLoc = Loc;
1631 }
1632
1633 SourceLocation getLAngleLoc() const {
1634 return getLocalData()->LAngleLoc;
1635 }
1636
1637 void setLAngleLoc(SourceLocation Loc) {
1638 getLocalData()->LAngleLoc = Loc;
1639 }
1640
1641 SourceLocation getRAngleLoc() const {
1642 return getLocalData()->RAngleLoc;
1643 }
1644
1645 void setRAngleLoc(SourceLocation Loc) {
1646 getLocalData()->RAngleLoc = Loc;
1647 }
1648
1649 unsigned getNumArgs() const {
1650 return getTypePtr()->getNumArgs();
1651 }
1652
1653 void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI) {
1654 getArgInfos()[i] = AI;
1655 }
1656
1657 TemplateArgumentLocInfo getArgLocInfo(unsigned i) const {
1658 return getArgInfos()[i];
1659 }
1660
1661 TemplateArgumentLoc getArgLoc(unsigned i) const {
1662 return TemplateArgumentLoc(getTypePtr()->getArg(i), getArgLocInfo(i));
1663 }
1664
1665 SourceLocation getTemplateNameLoc() const {
1666 return getLocalData()->NameLoc;
1667 }
1668
1669 void setTemplateNameLoc(SourceLocation Loc) {
1670 getLocalData()->NameLoc = Loc;
1671 }
1672
1673 /// \brief - Copy the location information from the given info.
1674 void copy(TemplateSpecializationTypeLoc Loc) {
1675 unsigned size = getFullDataSize();
1676 assert(size == Loc.getFullDataSize())(static_cast <bool> (size == Loc.getFullDataSize()) ? void
(0) : __assert_fail ("size == Loc.getFullDataSize()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 1676, __extension__ __PRETTY_FUNCTION__))
;
1677
1678 // We're potentially copying Expr references here. We don't
1679 // bother retaining them because TypeSourceInfos live forever, so
1680 // as long as the Expr was retained when originally written into
1681 // the TypeLoc, we're okay.
1682 memcpy(Data, Loc.Data, size);
1683 }
1684
1685 SourceRange getLocalSourceRange() const {
1686 if (getTemplateKeywordLoc().isValid())
1687 return SourceRange(getTemplateKeywordLoc(), getRAngleLoc());
1688 else
1689 return SourceRange(getTemplateNameLoc(), getRAngleLoc());
1690 }
1691
1692 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1693 setTemplateKeywordLoc(Loc);
1694 setTemplateNameLoc(Loc);
1695 setLAngleLoc(Loc);
1696 setRAngleLoc(Loc);
1697 initializeArgLocs(Context, getNumArgs(), getTypePtr()->getArgs(),
1698 getArgInfos(), Loc);
1699 }
1700
1701 static void initializeArgLocs(ASTContext &Context, unsigned NumArgs,
1702 const TemplateArgument *Args,
1703 TemplateArgumentLocInfo *ArgInfos,
1704 SourceLocation Loc);
1705
1706 unsigned getExtraLocalDataSize() const {
1707 return getNumArgs() * sizeof(TemplateArgumentLocInfo);
1708 }
1709
1710 unsigned getExtraLocalDataAlignment() const {
1711 return alignof(TemplateArgumentLocInfo);
1712 }
1713
1714private:
1715 TemplateArgumentLocInfo *getArgInfos() const {
1716 return static_cast<TemplateArgumentLocInfo*>(getExtraLocalData());
1717 }
1718};
1719
1720struct DependentAddressSpaceLocInfo {
1721 Expr *ExprOperand;
1722 SourceRange OperandParens;
1723 SourceLocation AttrLoc;
1724};
1725
1726class DependentAddressSpaceTypeLoc
1727 : public ConcreteTypeLoc<UnqualTypeLoc,
1728 DependentAddressSpaceTypeLoc,
1729 DependentAddressSpaceType,
1730 DependentAddressSpaceLocInfo> {
1731public:
1732 /// The location of the attribute name, i.e.
1733 /// int * __attribute__((address_space(11)))
1734 /// ^~~~~~~~~~~~~
1735 SourceLocation getAttrNameLoc() const {
1736 return getLocalData()->AttrLoc;
1737 }
1738 void setAttrNameLoc(SourceLocation loc) {
1739 getLocalData()->AttrLoc = loc;
1740 }
1741
1742 /// The attribute's expression operand, if it has one.
1743 /// int * __attribute__((address_space(11)))
1744 /// ^~
1745 Expr *getAttrExprOperand() const {
1746 return getLocalData()->ExprOperand;
1747 }
1748 void setAttrExprOperand(Expr *e) {
1749 getLocalData()->ExprOperand = e;
1750 }
1751
1752 /// The location of the parentheses around the operand, if there is
1753 /// an operand.
1754 /// int * __attribute__((address_space(11)))
1755 /// ^ ^
1756 SourceRange getAttrOperandParensRange() const {
1757 return getLocalData()->OperandParens;
1758 }
1759 void setAttrOperandParensRange(SourceRange range) {
1760 getLocalData()->OperandParens = range;
1761 }
1762
1763 SourceRange getLocalSourceRange() const {
1764 SourceRange range(getAttrNameLoc());
1765 range.setEnd(getAttrOperandParensRange().getEnd());
1766 return range;
1767 }
1768
1769 /// Returns the type before the address space attribute application
1770 /// area.
1771 /// int * __attribute__((address_space(11))) *
1772 /// ^ ^
1773 QualType getInnerType() const {
1774 return this->getTypePtr()->getPointeeType();
1775 }
1776
1777 TypeLoc getPointeeTypeLoc() const {
1778 return this->getInnerTypeLoc();
1779 }
1780
1781 void initializeLocal(ASTContext &Context, SourceLocation loc) {
1782 setAttrNameLoc(loc);
1783 setAttrOperandParensRange(SourceRange(loc));
1784 setAttrExprOperand(getTypePtr()->getAddrSpaceExpr());
1785 }
1786};
1787
1788//===----------------------------------------------------------------------===//
1789//
1790// All of these need proper implementations.
1791//
1792//===----------------------------------------------------------------------===//
1793
1794// FIXME: size expression and attribute locations (or keyword if we
1795// ever fully support altivec syntax).
1796class VectorTypeLoc : public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
1797 VectorTypeLoc,
1798 VectorType> {
1799};
1800
1801// FIXME: size expression and attribute locations.
1802class ExtVectorTypeLoc : public InheritingConcreteTypeLoc<VectorTypeLoc,
1803 ExtVectorTypeLoc,
1804 ExtVectorType> {
1805};
1806
1807// FIXME: attribute locations.
1808// For some reason, this isn't a subtype of VectorType.
1809class DependentSizedExtVectorTypeLoc :
1810 public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
1811 DependentSizedExtVectorTypeLoc,
1812 DependentSizedExtVectorType> {
1813};
1814
1815// FIXME: location of the '_Complex' keyword.
1816class ComplexTypeLoc : public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
1817 ComplexTypeLoc,
1818 ComplexType> {
1819};
1820
1821struct TypeofLocInfo {
1822 SourceLocation TypeofLoc;
1823 SourceLocation LParenLoc;
1824 SourceLocation RParenLoc;
1825};
1826
1827struct TypeOfExprTypeLocInfo : public TypeofLocInfo {
1828};
1829
1830struct TypeOfTypeLocInfo : public TypeofLocInfo {
1831 TypeSourceInfo* UnderlyingTInfo;
1832};
1833
1834template <class Derived, class TypeClass, class LocalData = TypeofLocInfo>
1835class TypeofLikeTypeLoc
1836 : public ConcreteTypeLoc<UnqualTypeLoc, Derived, TypeClass, LocalData> {
1837public:
1838 SourceLocation getTypeofLoc() const {
1839 return this->getLocalData()->TypeofLoc;
1840 }
1841
1842 void setTypeofLoc(SourceLocation Loc) {
1843 this->getLocalData()->TypeofLoc = Loc;
1844 }
1845
1846 SourceLocation getLParenLoc() const {
1847 return this->getLocalData()->LParenLoc;
1848 }
1849
1850 void setLParenLoc(SourceLocation Loc) {
1851 this->getLocalData()->LParenLoc = Loc;
1852 }
1853
1854 SourceLocation getRParenLoc() const {
1855 return this->getLocalData()->RParenLoc;
1856 }
1857
1858 void setRParenLoc(SourceLocation Loc) {
1859 this->getLocalData()->RParenLoc = Loc;
1860 }
1861
1862 SourceRange getParensRange() const {
1863 return SourceRange(getLParenLoc(), getRParenLoc());
1864 }
1865
1866 void setParensRange(SourceRange range) {
1867 setLParenLoc(range.getBegin());
1868 setRParenLoc(range.getEnd());
1869 }
1870
1871 SourceRange getLocalSourceRange() const {
1872 return SourceRange(getTypeofLoc(), getRParenLoc());
1873 }
1874
1875 void initializeLocal(ASTContext &Context, SourceLocation Loc) {
1876 setTypeofLoc(Loc);
1877 setLParenLoc(Loc);
1878 setRParenLoc(Loc);
1879 }
1880};
1881
1882class TypeOfExprTypeLoc : public TypeofLikeTypeLoc<TypeOfExprTypeLoc,
1883 TypeOfExprType,
1884 TypeOfExprTypeLocInfo> {
1885public:
1886 Expr* getUnderlyingExpr() const {
1887 return getTypePtr()->getUnderlyingExpr();
1888 }
1889
1890 // Reimplemented to account for GNU/C++ extension
1891 // typeof unary-expression
1892 // where there are no parentheses.
1893 SourceRange getLocalSourceRange() const;
1894};
1895
1896class TypeOfTypeLoc
1897 : public TypeofLikeTypeLoc<TypeOfTypeLoc, TypeOfType, TypeOfTypeLocInfo> {
1898public:
1899 QualType getUnderlyingType() const {
1900 return this->getTypePtr()->getUnderlyingType();
1901 }
1902
1903 TypeSourceInfo* getUnderlyingTInfo() const {
1904 return this->getLocalData()->UnderlyingTInfo;
1905 }
1906
1907 void setUnderlyingTInfo(TypeSourceInfo* TI) const {
1908 this->getLocalData()->UnderlyingTInfo = TI;
1909 }
1910
1911 void initializeLocal(ASTContext &Context, SourceLocation Loc);
1912};
1913
1914// FIXME: location of the 'decltype' and parens.
1915class DecltypeTypeLoc : public InheritingConcreteTypeLoc<TypeSpecTypeLoc,
1916 DecltypeTypeLoc,
1917 DecltypeType> {
1918public:
1919 Expr *getUnderlyingExpr() const { return getTypePtr()->getUnderlyingExpr(); }
1920};
1921
1922struct UnaryTransformTypeLocInfo {
1923 // FIXME: While there's only one unary transform right now, future ones may
1924 // need different representations
1925 SourceLocation KWLoc, LParenLoc, RParenLoc;
1926 TypeSourceInfo *UnderlyingTInfo;
1927};
1928
1929class UnaryTransformTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
1930 UnaryTransformTypeLoc,
1931 UnaryTransformType,
1932 UnaryTransformTypeLocInfo> {
1933public:
1934 SourceLocation getKWLoc() const { return getLocalData()->KWLoc; }
1935 void setKWLoc(SourceLocation Loc) { getLocalData()->KWLoc = Loc; }
1936
1937 SourceLocation getLParenLoc() const { return getLocalData()->LParenLoc; }
1938 void setLParenLoc(SourceLocation Loc) { getLocalData()->LParenLoc = Loc; }
1939
1940 SourceLocation getRParenLoc() const { return getLocalData()->RParenLoc; }
1941 void setRParenLoc(SourceLocation Loc) { getLocalData()->RParenLoc = Loc; }
1942
1943 TypeSourceInfo* getUnderlyingTInfo() const {
1944 return getLocalData()->UnderlyingTInfo;
1945 }
1946
1947 void setUnderlyingTInfo(TypeSourceInfo *TInfo) {
1948 getLocalData()->UnderlyingTInfo = TInfo;
1949 }
1950
1951 SourceRange getLocalSourceRange() const {
1952 return SourceRange(getKWLoc(), getRParenLoc());
1953 }
1954
1955 SourceRange getParensRange() const {
1956 return SourceRange(getLParenLoc(), getRParenLoc());
1957 }
1958
1959 void setParensRange(SourceRange Range) {
1960 setLParenLoc(Range.getBegin());
1961 setRParenLoc(Range.getEnd());
1962 }
1963
1964 void initializeLocal(ASTContext &Context, SourceLocation Loc);
1965};
1966
1967class DeducedTypeLoc
1968 : public InheritingConcreteTypeLoc<TypeSpecTypeLoc, DeducedTypeLoc,
1969 DeducedType> {};
1970
1971class AutoTypeLoc
1972 : public InheritingConcreteTypeLoc<DeducedTypeLoc, AutoTypeLoc, AutoType> {
1973};
1974
1975class DeducedTemplateSpecializationTypeLoc
1976 : public InheritingConcreteTypeLoc<DeducedTypeLoc,
1977 DeducedTemplateSpecializationTypeLoc,
1978 DeducedTemplateSpecializationType> {
1979public:
1980 SourceLocation getTemplateNameLoc() const {
1981 return getNameLoc();
1982 }
1983
1984 void setTemplateNameLoc(SourceLocation Loc) {
1985 setNameLoc(Loc);
1986 }
1987};
1988
1989struct ElaboratedLocInfo {
1990 SourceLocation ElaboratedKWLoc;
1991
1992 /// \brief Data associated with the nested-name-specifier location.
1993 void *QualifierData;
1994};
1995
1996class ElaboratedTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
1997 ElaboratedTypeLoc,
1998 ElaboratedType,
1999 ElaboratedLocInfo> {
2000public:
2001 SourceLocation getElaboratedKeywordLoc() const {
2002 return this->getLocalData()->ElaboratedKWLoc;
2003 }
2004
2005 void setElaboratedKeywordLoc(SourceLocation Loc) {
2006 this->getLocalData()->ElaboratedKWLoc = Loc;
2007 }
2008
2009 NestedNameSpecifierLoc getQualifierLoc() const {
2010 return NestedNameSpecifierLoc(getTypePtr()->getQualifier(),
2011 getLocalData()->QualifierData);
2012 }
2013
2014 void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc) {
2015 assert(QualifierLoc.getNestedNameSpecifier()(static_cast <bool> (QualifierLoc.getNestedNameSpecifier
() == getTypePtr()->getQualifier() && "Inconsistent nested-name-specifier pointer"
) ? void (0) : __assert_fail ("QualifierLoc.getNestedNameSpecifier() == getTypePtr()->getQualifier() && \"Inconsistent nested-name-specifier pointer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 2017, __extension__ __PRETTY_FUNCTION__))
2016 == getTypePtr()->getQualifier() &&(static_cast <bool> (QualifierLoc.getNestedNameSpecifier
() == getTypePtr()->getQualifier() && "Inconsistent nested-name-specifier pointer"
) ? void (0) : __assert_fail ("QualifierLoc.getNestedNameSpecifier() == getTypePtr()->getQualifier() && \"Inconsistent nested-name-specifier pointer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 2017, __extension__ __PRETTY_FUNCTION__))
2017 "Inconsistent nested-name-specifier pointer")(static_cast <bool> (QualifierLoc.getNestedNameSpecifier
() == getTypePtr()->getQualifier() && "Inconsistent nested-name-specifier pointer"
) ? void (0) : __assert_fail ("QualifierLoc.getNestedNameSpecifier() == getTypePtr()->getQualifier() && \"Inconsistent nested-name-specifier pointer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 2017, __extension__ __PRETTY_FUNCTION__))
;
2018 getLocalData()->QualifierData = QualifierLoc.getOpaqueData();
2019 }
2020
2021 SourceRange getLocalSourceRange() const {
2022 if (getElaboratedKeywordLoc().isValid())
2023 if (getQualifierLoc())
2024 return SourceRange(getElaboratedKeywordLoc(),
2025 getQualifierLoc().getEndLoc());
2026 else
2027 return SourceRange(getElaboratedKeywordLoc());
2028 else
2029 return getQualifierLoc().getSourceRange();
2030 }
2031
2032 void initializeLocal(ASTContext &Context, SourceLocation Loc);
2033
2034 TypeLoc getNamedTypeLoc() const {
2035 return getInnerTypeLoc();
2036 }
2037
2038 QualType getInnerType() const {
2039 return getTypePtr()->getNamedType();
2040 }
2041
2042 void copy(ElaboratedTypeLoc Loc) {
2043 unsigned size = getFullDataSize();
2044 assert(size == Loc.getFullDataSize())(static_cast <bool> (size == Loc.getFullDataSize()) ? void
(0) : __assert_fail ("size == Loc.getFullDataSize()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/AST/TypeLoc.h"
, 2044, __extension__ __PRETTY_FUNCTION__))
;
2045 memcpy(Data, Loc.Data, size);
2046 }
2047};
2048
2049// This is exactly the structur