1//===- ScopeInfo.h - Information about a semantic context -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines FunctionScopeInfo and its subclasses, which contain
10// information about a single function, block, lambda, or method body.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SCOPEINFO_H
15#define LLVM_CLANG_SEMA_SCOPEINFO_H
16
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/Type.h"
20#include "clang/Basic/CapturedStmt.h"
21#include "clang/Basic/LLVM.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/SourceLocation.h"
24#include "clang/Sema/CleanupInfo.h"
25#include "clang/Sema/DeclSpec.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/DenseMapInfo.h"
28#include "llvm/ADT/MapVector.h"
29#include "llvm/ADT/PointerIntPair.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/StringSwitch.h"
35#include "llvm/ADT/TinyPtrVector.h"
36#include "llvm/Support/Casting.h"
37#include "llvm/Support/ErrorHandling.h"
38#include <algorithm>
39#include <cassert>
40#include <utility>
41
42namespace clang {
43
44class BlockDecl;
45class CapturedDecl;
46class CXXMethodDecl;
47class CXXRecordDecl;
48class ImplicitParamDecl;
49class NamedDecl;
50class ObjCIvarRefExpr;
51class ObjCMessageExpr;
52class ObjCPropertyDecl;
53class ObjCPropertyRefExpr;
54class ParmVarDecl;
55class RecordDecl;
56class ReturnStmt;
57class Scope;
58class Stmt;
59class SwitchStmt;
60class TemplateParameterList;
61class VarDecl;
62
63namespace sema {
64
65/// Contains information about the compound statement currently being
66/// parsed.
67class CompoundScopeInfo {
68public:
69 /// Whether this compound statement contains `for' or `while' loops
70 /// with empty bodies.
71 bool HasEmptyLoopBodies = false;
72
73 /// Whether this compound statement corresponds to a GNU statement
74 /// expression.
75 bool IsStmtExpr;
76
77 /// FP options at the beginning of the compound statement, prior to
78 /// any pragma.
79 FPOptions InitialFPFeatures;
80
81 CompoundScopeInfo(bool IsStmtExpr, FPOptions FPO)
82 : IsStmtExpr(IsStmtExpr), InitialFPFeatures(FPO) {}
83
84 void setHasEmptyLoopBodies() {
85 HasEmptyLoopBodies = true;
86 }
87};
88
89class PossiblyUnreachableDiag {
90public:
91 PartialDiagnostic PD;
92 SourceLocation Loc;
93 llvm::TinyPtrVector<const Stmt*> Stmts;
94
95 PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
96 ArrayRef<const Stmt *> Stmts)
97 : PD(PD), Loc(Loc), Stmts(Stmts) {}
98};
99
100enum class FirstCoroutineStmtKind { CoReturn, CoAwait, CoYield };
101
102/// Retains information about a function, method, or block that is
103/// currently being parsed.
104class FunctionScopeInfo {
105protected:
106 enum ScopeKind {
107 SK_Function,
108 SK_Block,
109 SK_Lambda,
110 SK_CapturedRegion
111 };
112
113public:
114 /// What kind of scope we are describing.
115 ScopeKind Kind : 3;
116
117 /// Whether this function contains a VLA, \@try, try, C++
118 /// initializer, or anything else that can't be jumped past.
119 bool HasBranchProtectedScope : 1;
120
121 /// Whether this function contains any switches or direct gotos.
122 bool HasBranchIntoScope : 1;
123
124 /// Whether this function contains any indirect gotos.
125 bool HasIndirectGoto : 1;
126
127 /// Whether this function contains any statement marked with
128 /// \c [[clang::musttail]].
129 bool HasMustTail : 1;
130
131 /// Whether a statement was dropped because it was invalid.
132 bool HasDroppedStmt : 1;
133
134 /// True if current scope is for OpenMP declare reduction combiner.
135 bool HasOMPDeclareReductionCombiner : 1;
136
137 /// Whether there is a fallthrough statement in this function.
138 bool HasFallthroughStmt : 1;
139
140 /// Whether this function uses constrained floating point intrinsics
141 bool UsesFPIntrin : 1;
142
143 /// Whether we make reference to a declaration that could be
144 /// unavailable.
145 bool HasPotentialAvailabilityViolations : 1;
146
147 /// A flag that is set when parsing a method that must call super's
148 /// implementation, such as \c -dealloc, \c -finalize, or any method marked
149 /// with \c __attribute__((objc_requires_super)).
150 bool ObjCShouldCallSuper : 1;
151
152 /// True when this is a method marked as a designated initializer.
153 bool ObjCIsDesignatedInit : 1;
154
155 /// This starts true for a method marked as designated initializer and will
156 /// be set to false if there is an invocation to a designated initializer of
157 /// the super class.
158 bool ObjCWarnForNoDesignatedInitChain : 1;
159
160 /// True when this is an initializer method not marked as a designated
161 /// initializer within a class that has at least one initializer marked as a
162 /// designated initializer.
163 bool ObjCIsSecondaryInit : 1;
164
165 /// This starts true for a secondary initializer method and will be set to
166 /// false if there is an invocation of an initializer on 'self'.
167 bool ObjCWarnForNoInitDelegation : 1;
168
169 /// True only when this function has not already built, or attempted
170 /// to build, the initial and final coroutine suspend points
171 bool NeedsCoroutineSuspends : 1;
172
173 /// An enumeration representing the kind of the first coroutine statement
174 /// in the function. One of co_return, co_await, or co_yield.
175 LLVM_PREFERRED_TYPE(FirstCoroutineStmtKind)
176 unsigned char FirstCoroutineStmtKind : 2;
177
178 /// Whether we found an immediate-escalating expression.
179 bool FoundImmediateEscalatingExpression : 1;
180
181 /// First coroutine statement in the current function.
182 /// (ex co_return, co_await, co_yield)
183 SourceLocation FirstCoroutineStmtLoc;
184
185 /// First 'return' statement in the current function.
186 SourceLocation FirstReturnLoc;
187
188 /// First C++ 'try' or ObjC @try statement in the current function.
189 SourceLocation FirstCXXOrObjCTryLoc;
190 enum { TryLocIsCXX, TryLocIsObjC, Unknown } FirstTryType = Unknown;
191
192 /// First SEH '__try' statement in the current function.
193 SourceLocation FirstSEHTryLoc;
194
195 /// First use of a VLA within the current function.
196 SourceLocation FirstVLALoc;
197
198private:
199 /// Used to determine if errors occurred in this function or block.
200 DiagnosticErrorTrap ErrorTrap;
201
202public:
203 /// A SwitchStmt, along with a flag indicating if its list of case statements
204 /// is incomplete (because we dropped an invalid one while parsing).
205 using SwitchInfo = llvm::PointerIntPair<SwitchStmt*, 1, bool>;
206
207 /// SwitchStack - This is the current set of active switch statements in the
208 /// block.
209 SmallVector<SwitchInfo, 8> SwitchStack;
210
211 /// The list of return statements that occur within the function or
212 /// block, if there is any chance of applying the named return value
213 /// optimization, or if we need to infer a return type.
214 SmallVector<ReturnStmt*, 4> Returns;
215
216 /// The promise object for this coroutine, if any.
217 VarDecl *CoroutinePromise = nullptr;
218
219 /// A mapping between the coroutine function parameters that were moved
220 /// to the coroutine frame, and their move statements.
221 llvm::SmallMapVector<ParmVarDecl *, Stmt *, 4> CoroutineParameterMoves;
222
223 /// The initial and final coroutine suspend points.
224 std::pair<Stmt *, Stmt *> CoroutineSuspends;
225
226 /// The stack of currently active compound statement scopes in the
227 /// function.
228 SmallVector<CompoundScopeInfo, 4> CompoundScopes;
229
230 /// The set of blocks that are introduced in this function.
231 llvm::SmallPtrSet<const BlockDecl *, 1> Blocks;
232
233 /// The set of __block variables that are introduced in this function.
234 llvm::TinyPtrVector<VarDecl *> ByrefBlockVars;
235
236 /// A list of PartialDiagnostics created but delayed within the
237 /// current function scope. These diagnostics are vetted for reachability
238 /// prior to being emitted.
239 SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
240
241 /// A list of parameters which have the nonnull attribute and are
242 /// modified in the function.
243 llvm::SmallPtrSet<const ParmVarDecl *, 8> ModifiedNonNullParams;
244
245 /// The set of GNU address of label extension "&&label".
246 llvm::SmallVector<AddrLabelExpr *, 4> AddrLabels;
247
248public:
249 /// Represents a simple identification of a weak object.
250 ///
251 /// Part of the implementation of -Wrepeated-use-of-weak.
252 ///
253 /// This is used to determine if two weak accesses refer to the same object.
254 /// Here are some examples of how various accesses are "profiled":
255 ///
256 /// Access Expression | "Base" Decl | "Property" Decl
257 /// :---------------: | :-----------------: | :------------------------------:
258 /// self.property | self (VarDecl) | property (ObjCPropertyDecl)
259 /// self.implicitProp | self (VarDecl) | -implicitProp (ObjCMethodDecl)
260 /// self->ivar.prop | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
261 /// cxxObj.obj.prop | obj (FieldDecl) | prop (ObjCPropertyDecl)
262 /// [self foo].prop | 0 (unknown) | prop (ObjCPropertyDecl)
263 /// self.prop1.prop2 | prop1 (ObjCPropertyDecl) | prop2 (ObjCPropertyDecl)
264 /// MyClass.prop | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
265 /// MyClass.foo.prop | +foo (ObjCMethodDecl) | -prop (ObjCPropertyDecl)
266 /// weakVar | 0 (known) | weakVar (VarDecl)
267 /// self->weakIvar | self (VarDecl) | weakIvar (ObjCIvarDecl)
268 ///
269 /// Objects are identified with only two Decls to make it reasonably fast to
270 /// compare them.
271 class WeakObjectProfileTy {
272 /// The base object decl, as described in the class documentation.
273 ///
274 /// The extra flag is "true" if the Base and Property are enough to uniquely
275 /// identify the object in memory.
276 ///
277 /// \sa isExactProfile()
278 using BaseInfoTy = llvm::PointerIntPair<const NamedDecl *, 1, bool>;
279 BaseInfoTy Base;
280
281 /// The "property" decl, as described in the class documentation.
282 ///
283 /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
284 /// case of "implicit" properties (regular methods accessed via dot syntax).
285 const NamedDecl *Property = nullptr;
286
287 /// Used to find the proper base profile for a given base expression.
288 static BaseInfoTy getBaseInfo(const Expr *BaseE);
289
290 inline WeakObjectProfileTy();
291 static inline WeakObjectProfileTy getSentinel();
292
293 public:
294 WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
295 WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
296 WeakObjectProfileTy(const DeclRefExpr *RE);
297 WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
298
299 const NamedDecl *getBase() const { return Base.getPointer(); }
300 const NamedDecl *getProperty() const { return Property; }
301
302 /// Returns true if the object base specifies a known object in memory,
303 /// rather than, say, an instance variable or property of another object.
304 ///
305 /// Note that this ignores the effects of aliasing; that is, \c foo.bar is
306 /// considered an exact profile if \c foo is a local variable, even if
307 /// another variable \c foo2 refers to the same object as \c foo.
308 ///
309 /// For increased precision, accesses with base variables that are
310 /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
311 /// be exact, though this is not true for arbitrary variables
312 /// (foo.prop1.prop2).
313 bool isExactProfile() const {
314 return Base.getInt();
315 }
316
317 bool operator==(const WeakObjectProfileTy &Other) const {
318 return Base == Other.Base && Property == Other.Property;
319 }
320
321 // For use in DenseMap.
322 // We can't specialize the usual llvm::DenseMapInfo at the end of the file
323 // because by that point the DenseMap in FunctionScopeInfo has already been
324 // instantiated.
325 class DenseMapInfo {
326 public:
327 static inline WeakObjectProfileTy getEmptyKey() {
328 return WeakObjectProfileTy();
329 }
330
331 static inline WeakObjectProfileTy getTombstoneKey() {
332 return WeakObjectProfileTy::getSentinel();
333 }
334
335 static unsigned getHashValue(const WeakObjectProfileTy &Val) {
336 using Pair = std::pair<BaseInfoTy, const NamedDecl *>;
337
338 return llvm::DenseMapInfo<Pair>::getHashValue(PairVal: Pair(Val.Base,
339 Val.Property));
340 }
341
342 static bool isEqual(const WeakObjectProfileTy &LHS,
343 const WeakObjectProfileTy &RHS) {
344 return LHS == RHS;
345 }
346 };
347 };
348
349 /// Represents a single use of a weak object.
350 ///
351 /// Stores both the expression and whether the access is potentially unsafe
352 /// (i.e. it could potentially be warned about).
353 ///
354 /// Part of the implementation of -Wrepeated-use-of-weak.
355 class WeakUseTy {
356 llvm::PointerIntPair<const Expr *, 1, bool> Rep;
357
358 public:
359 WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
360
361 const Expr *getUseExpr() const { return Rep.getPointer(); }
362 bool isUnsafe() const { return Rep.getInt(); }
363 void markSafe() { Rep.setInt(false); }
364
365 bool operator==(const WeakUseTy &Other) const {
366 return Rep == Other.Rep;
367 }
368 };
369
370 /// Used to collect uses of a particular weak object in a function body.
371 ///
372 /// Part of the implementation of -Wrepeated-use-of-weak.
373 using WeakUseVector = SmallVector<WeakUseTy, 4>;
374
375 /// Used to collect all uses of weak objects in a function body.
376 ///
377 /// Part of the implementation of -Wrepeated-use-of-weak.
378 using WeakObjectUseMap =
379 llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
380 WeakObjectProfileTy::DenseMapInfo>;
381
382private:
383 /// Used to collect all uses of weak objects in this function body.
384 ///
385 /// Part of the implementation of -Wrepeated-use-of-weak.
386 WeakObjectUseMap WeakObjectUses;
387
388protected:
389 FunctionScopeInfo(const FunctionScopeInfo&) = default;
390
391public:
392 FunctionScopeInfo(DiagnosticsEngine &Diag)
393 : Kind(SK_Function), HasBranchProtectedScope(false),
394 HasBranchIntoScope(false), HasIndirectGoto(false), HasMustTail(false),
395 HasDroppedStmt(false), HasOMPDeclareReductionCombiner(false),
396 HasFallthroughStmt(false), UsesFPIntrin(false),
397 HasPotentialAvailabilityViolations(false), ObjCShouldCallSuper(false),
398 ObjCIsDesignatedInit(false), ObjCWarnForNoDesignatedInitChain(false),
399 ObjCIsSecondaryInit(false), ObjCWarnForNoInitDelegation(false),
400 NeedsCoroutineSuspends(true), FoundImmediateEscalatingExpression(false),
401 ErrorTrap(Diag) {}
402
403 virtual ~FunctionScopeInfo();
404
405 /// Determine whether an unrecoverable error has occurred within this
406 /// function. Note that this may return false even if the function body is
407 /// invalid, because the errors may be suppressed if they're caused by prior
408 /// invalid declarations.
409 ///
410 /// FIXME: Migrate the caller of this to use containsErrors() instead once
411 /// it's ready.
412 bool hasUnrecoverableErrorOccurred() const {
413 return ErrorTrap.hasUnrecoverableErrorOccurred();
414 }
415
416 /// Record that a weak object was accessed.
417 ///
418 /// Part of the implementation of -Wrepeated-use-of-weak.
419 template <typename ExprT>
420 inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
421
422 void recordUseOfWeak(const ObjCMessageExpr *Msg,
423 const ObjCPropertyDecl *Prop);
424
425 /// Record that a given expression is a "safe" access of a weak object (e.g.
426 /// assigning it to a strong variable.)
427 ///
428 /// Part of the implementation of -Wrepeated-use-of-weak.
429 void markSafeWeakUse(const Expr *E);
430
431 const WeakObjectUseMap &getWeakObjectUses() const {
432 return WeakObjectUses;
433 }
434
435 void setHasBranchIntoScope() {
436 HasBranchIntoScope = true;
437 }
438
439 void setHasBranchProtectedScope() {
440 HasBranchProtectedScope = true;
441 }
442
443 void setHasIndirectGoto() {
444 HasIndirectGoto = true;
445 }
446
447 void setHasMustTail() { HasMustTail = true; }
448
449 void setHasDroppedStmt() {
450 HasDroppedStmt = true;
451 }
452
453 void setHasOMPDeclareReductionCombiner() {
454 HasOMPDeclareReductionCombiner = true;
455 }
456
457 void setHasFallthroughStmt() {
458 HasFallthroughStmt = true;
459 }
460
461 void setUsesFPIntrin() {
462 UsesFPIntrin = true;
463 }
464
465 void setHasCXXTry(SourceLocation TryLoc) {
466 setHasBranchProtectedScope();
467 FirstCXXOrObjCTryLoc = TryLoc;
468 FirstTryType = TryLocIsCXX;
469 }
470
471 void setHasObjCTry(SourceLocation TryLoc) {
472 setHasBranchProtectedScope();
473 FirstCXXOrObjCTryLoc = TryLoc;
474 FirstTryType = TryLocIsObjC;
475 }
476
477 void setHasSEHTry(SourceLocation TryLoc) {
478 setHasBranchProtectedScope();
479 FirstSEHTryLoc = TryLoc;
480 }
481
482 void setHasVLA(SourceLocation VLALoc) {
483 if (FirstVLALoc.isInvalid())
484 FirstVLALoc = VLALoc;
485 }
486
487 bool NeedsScopeChecking() const {
488 return !HasDroppedStmt && (HasIndirectGoto || HasMustTail ||
489 (HasBranchProtectedScope && HasBranchIntoScope));
490 }
491
492 // Add a block introduced in this function.
493 void addBlock(const BlockDecl *BD) {
494 Blocks.insert(Ptr: BD);
495 }
496
497 // Add a __block variable introduced in this function.
498 void addByrefBlockVar(VarDecl *VD) {
499 ByrefBlockVars.push_back(NewVal: VD);
500 }
501
502 bool isCoroutine() const { return !FirstCoroutineStmtLoc.isInvalid(); }
503
504 void setFirstCoroutineStmt(SourceLocation Loc, StringRef Keyword) {
505 assert(FirstCoroutineStmtLoc.isInvalid() &&
506 "first coroutine statement location already set");
507 FirstCoroutineStmtLoc = Loc;
508 FirstCoroutineStmtKind =
509 llvm::StringSwitch<unsigned char>(Keyword)
510 .Case(S: "co_return",
511 Value: llvm::to_underlying(E: FirstCoroutineStmtKind::CoReturn))
512 .Case(S: "co_await",
513 Value: llvm::to_underlying(E: FirstCoroutineStmtKind::CoAwait))
514 .Case(S: "co_yield",
515 Value: llvm::to_underlying(E: FirstCoroutineStmtKind::CoYield));
516 }
517
518 StringRef getFirstCoroutineStmtKeyword() const {
519 assert(FirstCoroutineStmtLoc.isValid()
520 && "no coroutine statement available");
521 auto Value =
522 static_cast<enum FirstCoroutineStmtKind>(FirstCoroutineStmtKind);
523 switch (Value) {
524 case FirstCoroutineStmtKind::CoReturn:
525 return "co_return";
526 case FirstCoroutineStmtKind::CoAwait:
527 return "co_await";
528 case FirstCoroutineStmtKind::CoYield:
529 return "co_yield";
530 };
531 llvm_unreachable("FirstCoroutineStmtKind has an invalid value");
532 }
533
534 void setNeedsCoroutineSuspends(bool value = true) {
535 assert((!value || CoroutineSuspends.first == nullptr) &&
536 "we already have valid suspend points");
537 NeedsCoroutineSuspends = value;
538 }
539
540 bool hasInvalidCoroutineSuspends() const {
541 return !NeedsCoroutineSuspends && CoroutineSuspends.first == nullptr;
542 }
543
544 void setCoroutineSuspends(Stmt *Initial, Stmt *Final) {
545 assert(Initial && Final && "suspend points cannot be null");
546 assert(CoroutineSuspends.first == nullptr && "suspend points already set");
547 NeedsCoroutineSuspends = false;
548 CoroutineSuspends.first = Initial;
549 CoroutineSuspends.second = Final;
550 }
551
552 /// Clear out the information in this function scope, making it
553 /// suitable for reuse.
554 void Clear();
555
556 bool isPlainFunction() const { return Kind == SK_Function; }
557};
558
559class Capture {
560 // There are three categories of capture: capturing 'this', capturing
561 // local variables, and C++1y initialized captures (which can have an
562 // arbitrary initializer, and don't really capture in the traditional
563 // sense at all).
564 //
565 // There are three ways to capture a local variable:
566 // - capture by copy in the C++11 sense,
567 // - capture by reference in the C++11 sense, and
568 // - __block capture.
569 // Lambdas explicitly specify capture by copy or capture by reference.
570 // For blocks, __block capture applies to variables with that annotation,
571 // variables of reference type are captured by reference, and other
572 // variables are captured by copy.
573 enum CaptureKind {
574 Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_VLA
575 };
576
577 union {
578 /// If Kind == Cap_VLA, the captured type.
579 const VariableArrayType *CapturedVLA;
580
581 /// Otherwise, the captured variable (if any).
582 ValueDecl *CapturedVar;
583 };
584
585 /// The source location at which the first capture occurred.
586 SourceLocation Loc;
587
588 /// The location of the ellipsis that expands a parameter pack.
589 SourceLocation EllipsisLoc;
590
591 /// The type as it was captured, which is the type of the non-static data
592 /// member that would hold the capture.
593 QualType CaptureType;
594
595 /// The CaptureKind of this capture.
596 LLVM_PREFERRED_TYPE(CaptureKind)
597 unsigned Kind : 2;
598
599 /// Whether this is a nested capture (a capture of an enclosing capturing
600 /// scope's capture).
601 LLVM_PREFERRED_TYPE(bool)
602 unsigned Nested : 1;
603
604 /// Whether this is a capture of '*this'.
605 LLVM_PREFERRED_TYPE(bool)
606 unsigned CapturesThis : 1;
607
608 /// Whether an explicit capture has been odr-used in the body of the
609 /// lambda.
610 LLVM_PREFERRED_TYPE(bool)
611 unsigned ODRUsed : 1;
612
613 /// Whether an explicit capture has been non-odr-used in the body of
614 /// the lambda.
615 LLVM_PREFERRED_TYPE(bool)
616 unsigned NonODRUsed : 1;
617
618 /// Whether the capture is invalid (a capture was required but the entity is
619 /// non-capturable).
620 LLVM_PREFERRED_TYPE(bool)
621 unsigned Invalid : 1;
622
623public:
624 Capture(ValueDecl *Var, bool Block, bool ByRef, bool IsNested,
625 SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType,
626 bool Invalid)
627 : CapturedVar(Var), Loc(Loc), EllipsisLoc(EllipsisLoc),
628 CaptureType(CaptureType), Kind(Block ? Cap_Block
629 : ByRef ? Cap_ByRef
630 : Cap_ByCopy),
631 Nested(IsNested), CapturesThis(false), ODRUsed(false),
632 NonODRUsed(false), Invalid(Invalid) {}
633
634 enum IsThisCapture { ThisCapture };
635 Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
636 QualType CaptureType, const bool ByCopy, bool Invalid)
637 : Loc(Loc), CaptureType(CaptureType),
638 Kind(ByCopy ? Cap_ByCopy : Cap_ByRef), Nested(IsNested),
639 CapturesThis(true), ODRUsed(false), NonODRUsed(false),
640 Invalid(Invalid) {}
641
642 enum IsVLACapture { VLACapture };
643 Capture(IsVLACapture, const VariableArrayType *VLA, bool IsNested,
644 SourceLocation Loc, QualType CaptureType)
645 : CapturedVLA(VLA), Loc(Loc), CaptureType(CaptureType), Kind(Cap_VLA),
646 Nested(IsNested), CapturesThis(false), ODRUsed(false),
647 NonODRUsed(false), Invalid(false) {}
648
649 bool isThisCapture() const { return CapturesThis; }
650 bool isVariableCapture() const {
651 return !isThisCapture() && !isVLATypeCapture();
652 }
653
654 bool isCopyCapture() const { return Kind == Cap_ByCopy; }
655 bool isReferenceCapture() const { return Kind == Cap_ByRef; }
656 bool isBlockCapture() const { return Kind == Cap_Block; }
657 bool isVLATypeCapture() const { return Kind == Cap_VLA; }
658
659 bool isNested() const { return Nested; }
660
661 bool isInvalid() const { return Invalid; }
662
663 /// Determine whether this capture is an init-capture.
664 bool isInitCapture() const;
665
666 bool isODRUsed() const { return ODRUsed; }
667 bool isNonODRUsed() const { return NonODRUsed; }
668 void markUsed(bool IsODRUse) {
669 if (IsODRUse)
670 ODRUsed = true;
671 else
672 NonODRUsed = true;
673 }
674
675 ValueDecl *getVariable() const {
676 assert(isVariableCapture());
677 return CapturedVar;
678 }
679
680 const VariableArrayType *getCapturedVLAType() const {
681 assert(isVLATypeCapture());
682 return CapturedVLA;
683 }
684
685 /// Retrieve the location at which this variable was captured.
686 SourceLocation getLocation() const { return Loc; }
687
688 /// Retrieve the source location of the ellipsis, whose presence
689 /// indicates that the capture is a pack expansion.
690 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
691
692 /// Retrieve the capture type for this capture, which is effectively
693 /// the type of the non-static data member in the lambda/block structure
694 /// that would store this capture.
695 QualType getCaptureType() const { return CaptureType; }
696};
697
698class CapturingScopeInfo : public FunctionScopeInfo {
699protected:
700 CapturingScopeInfo(const CapturingScopeInfo&) = default;
701
702public:
703 enum ImplicitCaptureStyle {
704 ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
705 ImpCap_CapturedRegion
706 };
707
708 ImplicitCaptureStyle ImpCaptureStyle;
709
710 CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
711 : FunctionScopeInfo(Diag), ImpCaptureStyle(Style) {}
712
713 /// CaptureMap - A map of captured variables to (index+1) into Captures.
714 llvm::DenseMap<ValueDecl *, unsigned> CaptureMap;
715
716 /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
717 /// zero if 'this' is not captured.
718 unsigned CXXThisCaptureIndex = 0;
719
720 /// Captures - The captures.
721 SmallVector<Capture, 4> Captures;
722
723 /// - Whether the target type of return statements in this context
724 /// is deduced (e.g. a lambda or block with omitted return type).
725 bool HasImplicitReturnType = false;
726
727 /// ReturnType - The target type of return statements in this context,
728 /// or null if unknown.
729 QualType ReturnType;
730
731 void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested,
732 SourceLocation Loc, SourceLocation EllipsisLoc,
733 QualType CaptureType, bool Invalid) {
734 Captures.push_back(Elt: Capture(Var, isBlock, isByref, isNested, Loc,
735 EllipsisLoc, CaptureType, Invalid));
736 CaptureMap[Var] = Captures.size();
737 }
738
739 void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType,
740 QualType CaptureType) {
741 Captures.push_back(Elt: Capture(Capture::VLACapture, VLAType,
742 /*FIXME: IsNested*/ false, Loc, CaptureType));
743 }
744
745 void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType,
746 bool ByCopy);
747
748 /// Determine whether the C++ 'this' is captured.
749 bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
750
751 /// Retrieve the capture of C++ 'this', if it has been captured.
752 Capture &getCXXThisCapture() {
753 assert(isCXXThisCaptured() && "this has not been captured");
754 return Captures[CXXThisCaptureIndex - 1];
755 }
756
757 /// Determine whether the given variable has been captured.
758 bool isCaptured(ValueDecl *Var) const { return CaptureMap.count(Val: Var); }
759
760 /// Determine whether the given variable-array type has been captured.
761 bool isVLATypeCaptured(const VariableArrayType *VAT) const;
762
763 /// Retrieve the capture of the given variable, if it has been
764 /// captured already.
765 Capture &getCapture(ValueDecl *Var) {
766 assert(isCaptured(Var) && "Variable has not been captured");
767 return Captures[CaptureMap[Var] - 1];
768 }
769
770 const Capture &getCapture(ValueDecl *Var) const {
771 llvm::DenseMap<ValueDecl *, unsigned>::const_iterator Known =
772 CaptureMap.find(Val: Var);
773 assert(Known != CaptureMap.end() && "Variable has not been captured");
774 return Captures[Known->second - 1];
775 }
776
777 static bool classof(const FunctionScopeInfo *FSI) {
778 return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda
779 || FSI->Kind == SK_CapturedRegion;
780 }
781};
782
783/// Retains information about a block that is currently being parsed.
784class BlockScopeInfo final : public CapturingScopeInfo {
785public:
786 BlockDecl *TheDecl;
787
788 /// TheScope - This is the scope for the block itself, which contains
789 /// arguments etc.
790 Scope *TheScope;
791
792 /// BlockType - The function type of the block, if one was given.
793 /// Its return type may be BuiltinType::Dependent.
794 QualType FunctionType;
795
796 BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
797 : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
798 TheScope(BlockScope) {
799 Kind = SK_Block;
800 }
801
802 ~BlockScopeInfo() override;
803
804 static bool classof(const FunctionScopeInfo *FSI) {
805 return FSI->Kind == SK_Block;
806 }
807};
808
809/// Retains information about a captured region.
810class CapturedRegionScopeInfo final : public CapturingScopeInfo {
811public:
812 /// The CapturedDecl for this statement.
813 CapturedDecl *TheCapturedDecl;
814
815 /// The captured record type.
816 RecordDecl *TheRecordDecl;
817
818 /// This is the enclosing scope of the captured region.
819 Scope *TheScope;
820
821 /// The implicit parameter for the captured variables.
822 ImplicitParamDecl *ContextParam;
823
824 /// The kind of captured region.
825 unsigned short CapRegionKind;
826
827 unsigned short OpenMPLevel;
828 unsigned short OpenMPCaptureLevel;
829
830 CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
831 RecordDecl *RD, ImplicitParamDecl *Context,
832 CapturedRegionKind K, unsigned OpenMPLevel,
833 unsigned OpenMPCaptureLevel)
834 : CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
835 TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S),
836 ContextParam(Context), CapRegionKind(K), OpenMPLevel(OpenMPLevel),
837 OpenMPCaptureLevel(OpenMPCaptureLevel) {
838 Kind = SK_CapturedRegion;
839 }
840
841 ~CapturedRegionScopeInfo() override;
842
843 /// A descriptive name for the kind of captured region this is.
844 StringRef getRegionName() const {
845 switch (CapRegionKind) {
846 case CR_Default:
847 return "default captured statement";
848 case CR_ObjCAtFinally:
849 return "Objective-C @finally statement";
850 case CR_OpenMP:
851 return "OpenMP region";
852 }
853 llvm_unreachable("Invalid captured region kind!");
854 }
855
856 static bool classof(const FunctionScopeInfo *FSI) {
857 return FSI->Kind == SK_CapturedRegion;
858 }
859};
860
861class LambdaScopeInfo final :
862 public CapturingScopeInfo, public InventedTemplateParameterInfo {
863public:
864 /// The class that describes the lambda.
865 CXXRecordDecl *Lambda = nullptr;
866
867 /// The lambda's compiler-generated \c operator().
868 CXXMethodDecl *CallOperator = nullptr;
869
870 /// Indicate that we parsed the parameter list
871 /// at which point the mutability of the lambda
872 /// is known.
873 bool AfterParameterList = true;
874
875 ParmVarDecl *ExplicitObjectParameter = nullptr;
876
877 /// Source range covering the lambda introducer [...].
878 SourceRange IntroducerRange;
879
880 /// Source location of the '&' or '=' specifying the default capture
881 /// type, if any.
882 SourceLocation CaptureDefaultLoc;
883
884 /// The number of captures in the \c Captures list that are
885 /// explicit captures.
886 unsigned NumExplicitCaptures = 0;
887
888 /// Whether this is a mutable lambda. Until the mutable keyword is parsed,
889 /// we assume the lambda is mutable.
890 bool Mutable = true;
891
892 /// Whether the (empty) parameter list is explicit.
893 bool ExplicitParams = false;
894
895 /// Whether any of the capture expressions requires cleanups.
896 CleanupInfo Cleanup;
897
898 /// Whether the lambda contains an unexpanded parameter pack.
899 bool ContainsUnexpandedParameterPack = false;
900
901 /// Packs introduced by this lambda, if any.
902 SmallVector<NamedDecl*, 4> LocalPacks;
903
904 /// Source range covering the explicit template parameter list (if it exists).
905 SourceRange ExplicitTemplateParamsRange;
906
907 /// The requires-clause immediately following the explicit template parameter
908 /// list, if any. (Note that there may be another requires-clause included as
909 /// part of the lambda-declarator.)
910 ExprResult RequiresClause;
911
912 /// If this is a generic lambda, and the template parameter
913 /// list has been created (from the TemplateParams) then store
914 /// a reference to it (cache it to avoid reconstructing it).
915 TemplateParameterList *GLTemplateParameterList = nullptr;
916
917 /// Contains all variable-referring-expressions (i.e. DeclRefExprs
918 /// or MemberExprs) that refer to local variables in a generic lambda
919 /// or a lambda in a potentially-evaluated-if-used context.
920 ///
921 /// Potentially capturable variables of a nested lambda that might need
922 /// to be captured by the lambda are housed here.
923 /// This is specifically useful for generic lambdas or
924 /// lambdas within a potentially evaluated-if-used context.
925 /// If an enclosing variable is named in an expression of a lambda nested
926 /// within a generic lambda, we don't always know whether the variable
927 /// will truly be odr-used (i.e. need to be captured) by that nested lambda,
928 /// until its instantiation. But we still need to capture it in the
929 /// enclosing lambda if all intervening lambdas can capture the variable.
930 llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs;
931
932 /// Contains all variable-referring-expressions that refer
933 /// to local variables that are usable as constant expressions and
934 /// do not involve an odr-use (they may still need to be captured
935 /// if the enclosing full-expression is instantiation dependent).
936 llvm::SmallSet<Expr *, 8> NonODRUsedCapturingExprs;
937
938 /// A map of explicit capture indices to their introducer source ranges.
939 llvm::DenseMap<unsigned, SourceRange> ExplicitCaptureRanges;
940
941 /// Contains all of the variables defined in this lambda that shadow variables
942 /// that were defined in parent contexts. Used to avoid warnings when the
943 /// shadowed variables are uncaptured by this lambda.
944 struct ShadowedOuterDecl {
945 const NamedDecl *VD;
946 const NamedDecl *ShadowedDecl;
947 };
948 llvm::SmallVector<ShadowedOuterDecl, 4> ShadowingDecls;
949
950 SourceLocation PotentialThisCaptureLocation;
951
952 LambdaScopeInfo(DiagnosticsEngine &Diag)
953 : CapturingScopeInfo(Diag, ImpCap_None) {
954 Kind = SK_Lambda;
955 }
956
957 /// Note when all explicit captures have been added.
958 void finishedExplicitCaptures() {
959 NumExplicitCaptures = Captures.size();
960 }
961
962 static bool classof(const FunctionScopeInfo *FSI) {
963 return FSI->Kind == SK_Lambda;
964 }
965
966 /// Is this scope known to be for a generic lambda? (This will be false until
967 /// we parse a template parameter list or the first 'auto'-typed parameter).
968 bool isGenericLambda() const {
969 return !TemplateParams.empty() || GLTemplateParameterList;
970 }
971
972 /// Add a variable that might potentially be captured by the
973 /// lambda and therefore the enclosing lambdas.
974 ///
975 /// This is also used by enclosing lambda's to speculatively capture
976 /// variables that nested lambda's - depending on their enclosing
977 /// specialization - might need to capture.
978 /// Consider:
979 /// void f(int, int); <-- don't capture
980 /// void f(const int&, double); <-- capture
981 /// void foo() {
982 /// const int x = 10;
983 /// auto L = [=](auto a) { // capture 'x'
984 /// return [=](auto b) {
985 /// f(x, a); // we may or may not need to capture 'x'
986 /// };
987 /// };
988 /// }
989 void addPotentialCapture(Expr *VarExpr) {
990 assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr) ||
991 isa<FunctionParmPackExpr>(VarExpr));
992 PotentiallyCapturingExprs.push_back(Elt: VarExpr);
993 }
994
995 void addPotentialThisCapture(SourceLocation Loc) {
996 PotentialThisCaptureLocation = Loc;
997 }
998
999 bool hasPotentialThisCapture() const {
1000 return PotentialThisCaptureLocation.isValid();
1001 }
1002
1003 /// Mark a variable's reference in a lambda as non-odr using.
1004 ///
1005 /// For generic lambdas, if a variable is named in a potentially evaluated
1006 /// expression, where the enclosing full expression is dependent then we
1007 /// must capture the variable (given a default capture).
1008 /// This is accomplished by recording all references to variables
1009 /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of
1010 /// PotentialCaptures. All such variables have to be captured by that lambda,
1011 /// except for as described below.
1012 /// If that variable is usable as a constant expression and is named in a
1013 /// manner that does not involve its odr-use (e.g. undergoes
1014 /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the
1015 /// act of analyzing the enclosing full expression (ActOnFinishFullExpr)
1016 /// if we can determine that the full expression is not instantiation-
1017 /// dependent, then we can entirely avoid its capture.
1018 ///
1019 /// const int n = 0;
1020 /// [&] (auto x) {
1021 /// (void)+n + x;
1022 /// };
1023 /// Interestingly, this strategy would involve a capture of n, even though
1024 /// it's obviously not odr-used here, because the full-expression is
1025 /// instantiation-dependent. It could be useful to avoid capturing such
1026 /// variables, even when they are referred to in an instantiation-dependent
1027 /// expression, if we can unambiguously determine that they shall never be
1028 /// odr-used. This would involve removal of the variable-referring-expression
1029 /// from the array of PotentialCaptures during the lvalue-to-rvalue
1030 /// conversions. But per the working draft N3797, (post-chicago 2013) we must
1031 /// capture such variables.
1032 /// Before anyone is tempted to implement a strategy for not-capturing 'n',
1033 /// consider the insightful warning in:
1034 /// /cfe-commits/Week-of-Mon-20131104/092596.html
1035 /// "The problem is that the set of captures for a lambda is part of the ABI
1036 /// (since lambda layout can be made visible through inline functions and the
1037 /// like), and there are no guarantees as to which cases we'll manage to build
1038 /// an lvalue-to-rvalue conversion in, when parsing a template -- some
1039 /// seemingly harmless change elsewhere in Sema could cause us to start or stop
1040 /// building such a node. So we need a rule that anyone can implement and get
1041 /// exactly the same result".
1042 void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) {
1043 assert(isa<DeclRefExpr>(CapturingVarExpr) ||
1044 isa<MemberExpr>(CapturingVarExpr) ||
1045 isa<FunctionParmPackExpr>(CapturingVarExpr));
1046 NonODRUsedCapturingExprs.insert(Ptr: CapturingVarExpr);
1047 }
1048 bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const {
1049 assert(isa<DeclRefExpr>(CapturingVarExpr) ||
1050 isa<MemberExpr>(CapturingVarExpr) ||
1051 isa<FunctionParmPackExpr>(CapturingVarExpr));
1052 return NonODRUsedCapturingExprs.count(Ptr: CapturingVarExpr);
1053 }
1054 void removePotentialCapture(Expr *E) {
1055 llvm::erase(C&: PotentiallyCapturingExprs, V: E);
1056 }
1057 void clearPotentialCaptures() {
1058 PotentiallyCapturingExprs.clear();
1059 PotentialThisCaptureLocation = SourceLocation();
1060 }
1061 unsigned getNumPotentialVariableCaptures() const {
1062 return PotentiallyCapturingExprs.size();
1063 }
1064
1065 bool hasPotentialCaptures() const {
1066 return getNumPotentialVariableCaptures() ||
1067 PotentialThisCaptureLocation.isValid();
1068 }
1069
1070 void visitPotentialCaptures(
1071 llvm::function_ref<void(ValueDecl *, Expr *)> Callback) const;
1072
1073 bool lambdaCaptureShouldBeConst() const;
1074};
1075
1076FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
1077 : Base(nullptr, false) {}
1078
1079FunctionScopeInfo::WeakObjectProfileTy
1080FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
1081 FunctionScopeInfo::WeakObjectProfileTy Result;
1082 Result.Base.setInt(true);
1083 return Result;
1084}
1085
1086template <typename ExprT>
1087void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
1088 assert(E);
1089 WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
1090 Uses.push_back(Elt: WeakUseTy(E, IsRead));
1091}
1092
1093inline void CapturingScopeInfo::addThisCapture(bool isNested,
1094 SourceLocation Loc,
1095 QualType CaptureType,
1096 bool ByCopy) {
1097 Captures.push_back(Elt: Capture(Capture::ThisCapture, isNested, Loc, CaptureType,
1098 ByCopy, /*Invalid*/ false));
1099 CXXThisCaptureIndex = Captures.size();
1100}
1101
1102} // namespace sema
1103
1104} // namespace clang
1105
1106#endif // LLVM_CLANG_SEMA_SCOPEINFO_H
1107

source code of clang/include/clang/Sema/ScopeInfo.h