Bug Summary

File:tools/clang/lib/Analysis/BodyFarm.cpp
Warning:line 142, column 19
Called C++ object pointer is null

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 BodyFarm.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~svn337103/build-llvm/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337103/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337103/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn337103/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/lib/gcc/x86_64-linux-gnu/7.3.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~svn337103/build-llvm/tools/clang/lib/Analysis -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-15-073923-5500-1 -x c++ /build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp

/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp

1//== BodyFarm.cpp - Factory for conjuring up fake bodies ----------*- 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// BodyFarm is a factory for creating faux implementations for functions/methods
11// for analysis purposes.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Analysis/BodyFarm.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/Analysis/CodeInjector.h"
24#include "clang/Basic/OperatorKinds.h"
25#include "llvm/ADT/StringSwitch.h"
26#include "llvm/Support/Debug.h"
27
28#define DEBUG_TYPE"body-farm" "body-farm"
29
30using namespace clang;
31
32//===----------------------------------------------------------------------===//
33// Helper creation functions for constructing faux ASTs.
34//===----------------------------------------------------------------------===//
35
36static bool isDispatchBlock(QualType Ty) {
37 // Is it a block pointer?
38 const BlockPointerType *BPT = Ty->getAs<BlockPointerType>();
39 if (!BPT)
40 return false;
41
42 // Check if the block pointer type takes no arguments and
43 // returns void.
44 const FunctionProtoType *FT =
45 BPT->getPointeeType()->getAs<FunctionProtoType>();
46 return FT && FT->getReturnType()->isVoidType() && FT->getNumParams() == 0;
47}
48
49namespace {
50class ASTMaker {
51public:
52 ASTMaker(ASTContext &C) : C(C) {}
53
54 /// Create a new BinaryOperator representing a simple assignment.
55 BinaryOperator *makeAssignment(const Expr *LHS, const Expr *RHS, QualType Ty);
56
57 /// Create a new BinaryOperator representing a comparison.
58 BinaryOperator *makeComparison(const Expr *LHS, const Expr *RHS,
59 BinaryOperator::Opcode Op);
60
61 /// Create a new compound stmt using the provided statements.
62 CompoundStmt *makeCompound(ArrayRef<Stmt*>);
63
64 /// Create a new DeclRefExpr for the referenced variable.
65 DeclRefExpr *makeDeclRefExpr(const VarDecl *D,
66 bool RefersToEnclosingVariableOrCapture = false);
67
68 /// Create a new UnaryOperator representing a dereference.
69 UnaryOperator *makeDereference(const Expr *Arg, QualType Ty);
70
71 /// Create an implicit cast for an integer conversion.
72 Expr *makeIntegralCast(const Expr *Arg, QualType Ty);
73
74 /// Create an implicit cast to a builtin boolean type.
75 ImplicitCastExpr *makeIntegralCastToBoolean(const Expr *Arg);
76
77 /// Create an implicit cast for lvalue-to-rvaluate conversions.
78 ImplicitCastExpr *makeLvalueToRvalue(const Expr *Arg, QualType Ty);
79
80 /// Make RValue out of variable declaration, creating a temporary
81 /// DeclRefExpr in the process.
82 ImplicitCastExpr *
83 makeLvalueToRvalue(const VarDecl *Decl,
84 bool RefersToEnclosingVariableOrCapture = false);
85
86 /// Create an implicit cast of the given type.
87 ImplicitCastExpr *makeImplicitCast(const Expr *Arg, QualType Ty,
88 CastKind CK = CK_LValueToRValue);
89
90 /// Create an Objective-C bool literal.
91 ObjCBoolLiteralExpr *makeObjCBool(bool Val);
92
93 /// Create an Objective-C ivar reference.
94 ObjCIvarRefExpr *makeObjCIvarRef(const Expr *Base, const ObjCIvarDecl *IVar);
95
96 /// Create a Return statement.
97 ReturnStmt *makeReturn(const Expr *RetVal);
98
99 /// Create an integer literal expression of the given type.
100 IntegerLiteral *makeIntegerLiteral(uint64_t Value, QualType Ty);
101
102 /// Create a member expression.
103 MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
104 bool IsArrow = false,
105 ExprValueKind ValueKind = VK_LValue);
106
107 /// Returns a *first* member field of a record declaration with a given name.
108 /// \return an nullptr if no member with such a name exists.
109 ValueDecl *findMemberField(const RecordDecl *RD, StringRef Name);
110
111private:
112 ASTContext &C;
113};
114}
115
116BinaryOperator *ASTMaker::makeAssignment(const Expr *LHS, const Expr *RHS,
117 QualType Ty) {
118 return new (C) BinaryOperator(const_cast<Expr*>(LHS), const_cast<Expr*>(RHS),
119 BO_Assign, Ty, VK_RValue,
120 OK_Ordinary, SourceLocation(), FPOptions());
121}
122
123BinaryOperator *ASTMaker::makeComparison(const Expr *LHS, const Expr *RHS,
124 BinaryOperator::Opcode Op) {
125 assert(BinaryOperator::isLogicalOp(Op) ||(static_cast <bool> (BinaryOperator::isLogicalOp(Op) ||
BinaryOperator::isComparisonOp(Op)) ? void (0) : __assert_fail
("BinaryOperator::isLogicalOp(Op) || BinaryOperator::isComparisonOp(Op)"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp"
, 126, __extension__ __PRETTY_FUNCTION__))
126 BinaryOperator::isComparisonOp(Op))(static_cast <bool> (BinaryOperator::isLogicalOp(Op) ||
BinaryOperator::isComparisonOp(Op)) ? void (0) : __assert_fail
("BinaryOperator::isLogicalOp(Op) || BinaryOperator::isComparisonOp(Op)"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp"
, 126, __extension__ __PRETTY_FUNCTION__))
;
127 return new (C) BinaryOperator(const_cast<Expr*>(LHS),
128 const_cast<Expr*>(RHS),
129 Op,
130 C.getLogicalOperationType(),
131 VK_RValue,
132 OK_Ordinary, SourceLocation(), FPOptions());
133}
134
135CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
136 return CompoundStmt::Create(C, Stmts, SourceLocation(), SourceLocation());
137}
138
139DeclRefExpr *ASTMaker::makeDeclRefExpr(
140 const VarDecl *D,
141 bool RefersToEnclosingVariableOrCapture) {
142 QualType Type = D->getType().getNonReferenceType();
38
Called C++ object pointer is null
143
144 DeclRefExpr *DR = DeclRefExpr::Create(
145 C, NestedNameSpecifierLoc(), SourceLocation(), const_cast<VarDecl *>(D),
146 RefersToEnclosingVariableOrCapture, SourceLocation(), Type, VK_LValue);
147 return DR;
148}
149
150UnaryOperator *ASTMaker::makeDereference(const Expr *Arg, QualType Ty) {
151 return new (C) UnaryOperator(const_cast<Expr*>(Arg), UO_Deref, Ty,
152 VK_LValue, OK_Ordinary, SourceLocation(),
153 /*CanOverflow*/ false);
154}
155
156ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(const Expr *Arg, QualType Ty) {
157 return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
158}
159
160ImplicitCastExpr *
161ASTMaker::makeLvalueToRvalue(const VarDecl *Arg,
162 bool RefersToEnclosingVariableOrCapture) {
163 QualType Type = Arg->getType().getNonReferenceType();
164 return makeLvalueToRvalue(makeDeclRefExpr(Arg,
165 RefersToEnclosingVariableOrCapture),
166 Type);
167}
168
169ImplicitCastExpr *ASTMaker::makeImplicitCast(const Expr *Arg, QualType Ty,
170 CastKind CK) {
171 return ImplicitCastExpr::Create(C, Ty,
172 /* CastKind=*/ CK,
173 /* Expr=*/ const_cast<Expr *>(Arg),
174 /* CXXCastPath=*/ nullptr,
175 /* ExprValueKind=*/ VK_RValue);
176}
177
178Expr *ASTMaker::makeIntegralCast(const Expr *Arg, QualType Ty) {
179 if (Arg->getType() == Ty)
180 return const_cast<Expr*>(Arg);
181
182 return ImplicitCastExpr::Create(C, Ty, CK_IntegralCast,
183 const_cast<Expr*>(Arg), nullptr, VK_RValue);
184}
185
186ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(const Expr *Arg) {
187 return ImplicitCastExpr::Create(C, C.BoolTy, CK_IntegralToBoolean,
188 const_cast<Expr*>(Arg), nullptr, VK_RValue);
189}
190
191ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(bool Val) {
192 QualType Ty = C.getBOOLDecl() ? C.getBOOLType() : C.ObjCBuiltinBoolTy;
193 return new (C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
194}
195
196ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(const Expr *Base,
197 const ObjCIvarDecl *IVar) {
198 return new (C) ObjCIvarRefExpr(const_cast<ObjCIvarDecl*>(IVar),
199 IVar->getType(), SourceLocation(),
200 SourceLocation(), const_cast<Expr*>(Base),
201 /*arrow=*/true, /*free=*/false);
202}
203
204
205ReturnStmt *ASTMaker::makeReturn(const Expr *RetVal) {
206 return new (C) ReturnStmt(SourceLocation(), const_cast<Expr*>(RetVal),
207 nullptr);
208}
209
210IntegerLiteral *ASTMaker::makeIntegerLiteral(uint64_t Value, QualType Ty) {
211 llvm::APInt APValue = llvm::APInt(C.getTypeSize(Ty), Value);
212 return IntegerLiteral::Create(C, APValue, Ty, SourceLocation());
213}
214
215MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
216 bool IsArrow,
217 ExprValueKind ValueKind) {
218
219 DeclAccessPair FoundDecl = DeclAccessPair::make(MemberDecl, AS_public);
220 return MemberExpr::Create(
221 C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
222 SourceLocation(), MemberDecl, FoundDecl,
223 DeclarationNameInfo(MemberDecl->getDeclName(), SourceLocation()),
224 /* TemplateArgumentListInfo=*/ nullptr, MemberDecl->getType(), ValueKind,
225 OK_Ordinary);
226}
227
228ValueDecl *ASTMaker::findMemberField(const RecordDecl *RD, StringRef Name) {
229
230 CXXBasePaths Paths(
231 /* FindAmbiguities=*/false,
232 /* RecordPaths=*/false,
233 /* DetectVirtual=*/ false);
234 const IdentifierInfo &II = C.Idents.get(Name);
235 DeclarationName DeclName = C.DeclarationNames.getIdentifier(&II);
236
237 DeclContextLookupResult Decls = RD->lookup(DeclName);
238 for (NamedDecl *FoundDecl : Decls)
239 if (!FoundDecl->getDeclContext()->isFunctionOrMethod())
240 return cast<ValueDecl>(FoundDecl);
241
242 return nullptr;
243}
244
245//===----------------------------------------------------------------------===//
246// Creation functions for faux ASTs.
247//===----------------------------------------------------------------------===//
248
249typedef Stmt *(*FunctionFarmer)(ASTContext &C, const FunctionDecl *D);
250
251static CallExpr *create_call_once_funcptr_call(ASTContext &C, ASTMaker M,
252 const ParmVarDecl *Callback,
253 ArrayRef<Expr *> CallArgs) {
254
255 QualType Ty = Callback->getType();
256 DeclRefExpr *Call = M.makeDeclRefExpr(Callback);
257 Expr *SubExpr;
258 if (Ty->isRValueReferenceType()) {
259 SubExpr = M.makeImplicitCast(
260 Call, Ty.getNonReferenceType(), CK_LValueToRValue);
261 } else if (Ty->isLValueReferenceType() &&
262 Call->getType()->isFunctionType()) {
263 Ty = C.getPointerType(Ty.getNonReferenceType());
264 SubExpr = M.makeImplicitCast(Call, Ty, CK_FunctionToPointerDecay);
265 } else if (Ty->isLValueReferenceType()
266 && Call->getType()->isPointerType()
267 && Call->getType()->getPointeeType()->isFunctionType()){
268 SubExpr = Call;
269 } else {
270 llvm_unreachable("Unexpected state")::llvm::llvm_unreachable_internal("Unexpected state", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp"
, 270)
;
271 }
272
273 return new (C)
274 CallExpr(C, SubExpr, CallArgs, C.VoidTy, VK_RValue, SourceLocation());
275}
276
277static CallExpr *create_call_once_lambda_call(ASTContext &C, ASTMaker M,
278 const ParmVarDecl *Callback,
279 CXXRecordDecl *CallbackDecl,
280 ArrayRef<Expr *> CallArgs) {
281 assert(CallbackDecl != nullptr)(static_cast <bool> (CallbackDecl != nullptr) ? void (0
) : __assert_fail ("CallbackDecl != nullptr", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp"
, 281, __extension__ __PRETTY_FUNCTION__))
;
282 assert(CallbackDecl->isLambda())(static_cast <bool> (CallbackDecl->isLambda()) ? void
(0) : __assert_fail ("CallbackDecl->isLambda()", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp"
, 282, __extension__ __PRETTY_FUNCTION__))
;
283 FunctionDecl *callOperatorDecl = CallbackDecl->getLambdaCallOperator();
284 assert(callOperatorDecl != nullptr)(static_cast <bool> (callOperatorDecl != nullptr) ? void
(0) : __assert_fail ("callOperatorDecl != nullptr", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp"
, 284, __extension__ __PRETTY_FUNCTION__))
;
285
286 DeclRefExpr *callOperatorDeclRef =
287 DeclRefExpr::Create(/* Ctx =*/ C,
288 /* QualifierLoc =*/ NestedNameSpecifierLoc(),
289 /* TemplateKWLoc =*/ SourceLocation(),
290 const_cast<FunctionDecl *>(callOperatorDecl),
291 /* RefersToEnclosingVariableOrCapture=*/ false,
292 /* NameLoc =*/ SourceLocation(),
293 /* T =*/ callOperatorDecl->getType(),
294 /* VK =*/ VK_LValue);
295
296 return new (C)
297 CXXOperatorCallExpr(/*AstContext=*/C, OO_Call, callOperatorDeclRef,
298 /*args=*/CallArgs,
299 /*QualType=*/C.VoidTy,
300 /*ExprValueType=*/VK_RValue,
301 /*SourceLocation=*/SourceLocation(), FPOptions());
302}
303
304/// Create a fake body for std::call_once.
305/// Emulates the following function body:
306///
307/// \code
308/// typedef struct once_flag_s {
309/// unsigned long __state = 0;
310/// } once_flag;
311/// template<class Callable>
312/// void call_once(once_flag& o, Callable func) {
313/// if (!o.__state) {
314/// func();
315/// }
316/// o.__state = 1;
317/// }
318/// \endcode
319static Stmt *create_call_once(ASTContext &C, const FunctionDecl *D) {
320 LLVM_DEBUG(llvm::dbgs() << "Generating body for call_once\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Generating body for call_once\n"
; } } while (false)
;
321
322 // We need at least two parameters.
323 if (D->param_size() < 2)
14
Assuming the condition is false
15
Taking false branch
324 return nullptr;
325
326 ASTMaker M(C);
327
328 const ParmVarDecl *Flag = D->getParamDecl(0);
329 const ParmVarDecl *Callback = D->getParamDecl(1);
330
331 if (!Callback->getType()->isReferenceType()) {
16
Taking false branch
332 llvm::dbgs() << "libcxx03 std::call_once implementation, skipping.\n";
333 return nullptr;
334 }
335 if (!Flag->getType()->isReferenceType()) {
17
Taking false branch
336 llvm::dbgs() << "unknown std::call_once implementation, skipping.\n";
337 return nullptr;
338 }
339
340 QualType CallbackType = Callback->getType().getNonReferenceType();
341
342 // Nullable pointer, non-null iff function is a CXXRecordDecl.
343 CXXRecordDecl *CallbackRecordDecl = CallbackType->getAsCXXRecordDecl();
344 QualType FlagType = Flag->getType().getNonReferenceType();
345 auto *FlagRecordDecl = dyn_cast_or_null<RecordDecl>(FlagType->getAsTagDecl());
346
347 if (!FlagRecordDecl) {
18
Assuming 'FlagRecordDecl' is non-null
19
Taking false branch
348 LLVM_DEBUG(llvm::dbgs() << "Flag field is not a record: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Flag field is not a record: "
<< "unknown std::call_once implementation, " << "ignoring the call.\n"
; } } while (false)
349 << "unknown std::call_once implementation, "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Flag field is not a record: "
<< "unknown std::call_once implementation, " << "ignoring the call.\n"
; } } while (false)
350 << "ignoring the call.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Flag field is not a record: "
<< "unknown std::call_once implementation, " << "ignoring the call.\n"
; } } while (false)
;
351 return nullptr;
352 }
353
354 // We initially assume libc++ implementation of call_once,
355 // where the once_flag struct has a field `__state_`.
356 ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl, "__state_");
357
358 // Otherwise, try libstdc++ implementation, with a field
359 // `_M_once`
360 if (!FlagFieldDecl) {
20
Assuming 'FlagFieldDecl' is non-null
21
Taking false branch
361 FlagFieldDecl = M.findMemberField(FlagRecordDecl, "_M_once");
362 }
363
364 if (!FlagFieldDecl) {
22
Taking false branch
365 LLVM_DEBUG(llvm::dbgs() << "No field _M_once or __state_ found on "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "No field _M_once or __state_ found on "
<< "std::once_flag struct: unknown std::call_once " <<
"implementation, ignoring the call."; } } while (false)
366 << "std::once_flag struct: unknown std::call_once "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "No field _M_once or __state_ found on "
<< "std::once_flag struct: unknown std::call_once " <<
"implementation, ignoring the call."; } } while (false)
367 << "implementation, ignoring the call.")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "No field _M_once or __state_ found on "
<< "std::once_flag struct: unknown std::call_once " <<
"implementation, ignoring the call."; } } while (false)
;
368 return nullptr;
369 }
370
371 bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->isLambda();
23
Assuming 'CallbackRecordDecl' is null
372 if (CallbackRecordDecl && !isLambdaCall) {
373 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Not supported: synthesizing body for functors when "
<< "body farming std::call_once, ignoring the call."; }
} while (false)
374 << "Not supported: synthesizing body for functors when "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Not supported: synthesizing body for functors when "
<< "body farming std::call_once, ignoring the call."; }
} while (false)
375 << "body farming std::call_once, ignoring the call.")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Not supported: synthesizing body for functors when "
<< "body farming std::call_once, ignoring the call."; }
} while (false)
;
376 return nullptr;
377 }
378
379 SmallVector<Expr *, 5> CallArgs;
380 const FunctionProtoType *CallbackFunctionType;
381 if (isLambdaCall) {
24
Taking false branch
382
383 // Lambda requires callback itself inserted as a first parameter.
384 CallArgs.push_back(
385 M.makeDeclRefExpr(Callback,
386 /* RefersToEnclosingVariableOrCapture=*/ true));
387 CallbackFunctionType = CallbackRecordDecl->getLambdaCallOperator()
388 ->getType()
389 ->getAs<FunctionProtoType>();
390 } else if (!CallbackType->getPointeeType().isNull()) {
25
Taking false branch
391 CallbackFunctionType =
392 CallbackType->getPointeeType()->getAs<FunctionProtoType>();
393 } else {
394 CallbackFunctionType = CallbackType->getAs<FunctionProtoType>();
395 }
396
397 if (!CallbackFunctionType)
26
Taking false branch
398 return nullptr;
399
400 // First two arguments are used for the flag and for the callback.
401 if (D->getNumParams() != CallbackFunctionType->getNumParams() + 2) {
27
Taking false branch
402 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
403 << "params passed to std::call_once, "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
404 << "ignoring the call\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
;
405 return nullptr;
406 }
407
408 // All arguments past first two ones are passed to the callback,
409 // and we turn lvalues into rvalues if the argument is not passed by
410 // reference.
411 for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
28
Assuming the condition is true
29
Loop condition is true. Entering loop body
412 const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
30
Calling 'FunctionDecl::getParamDecl'
32
Returning from 'FunctionDecl::getParamDecl'
33
'PDecl' initialized here
413 if (PDecl &&
34
Assuming 'PDecl' is null
35
Taking false branch
414 CallbackFunctionType->getParamType(ParamIdx - 2)
415 .getNonReferenceType()
416 .getCanonicalType() !=
417 PDecl->getType().getNonReferenceType().getCanonicalType()) {
418 LLVM_DEBUG(llvm::dbgs() << "Types of params of the callback do not match "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
419 << "params passed to std::call_once, "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
420 << "ignoring the call\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("body-farm")) { llvm::dbgs() << "Types of params of the callback do not match "
<< "params passed to std::call_once, " << "ignoring the call\n"
; } } while (false)
;
421 return nullptr;
422 }
423 Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
36
Passing null pointer value via 1st parameter 'D'
37
Calling 'ASTMaker::makeDeclRefExpr'
424 if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
425 QualType PTy = PDecl->getType().getNonReferenceType();
426 ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
427 }
428 CallArgs.push_back(ParamExpr);
429 }
430
431 CallExpr *CallbackCall;
432 if (isLambdaCall) {
433
434 CallbackCall = create_call_once_lambda_call(C, M, Callback,
435 CallbackRecordDecl, CallArgs);
436 } else {
437
438 // Function pointer case.
439 CallbackCall = create_call_once_funcptr_call(C, M, Callback, CallArgs);
440 }
441
442 DeclRefExpr *FlagDecl =
443 M.makeDeclRefExpr(Flag,
444 /* RefersToEnclosingVariableOrCapture=*/true);
445
446
447 MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
448 assert(Deref->isLValue())(static_cast <bool> (Deref->isLValue()) ? void (0) :
__assert_fail ("Deref->isLValue()", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp"
, 448, __extension__ __PRETTY_FUNCTION__))
;
449 QualType DerefType = Deref->getType();
450
451 // Negation predicate.
452 UnaryOperator *FlagCheck = new (C) UnaryOperator(
453 /* input=*/
454 M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
455 CK_IntegralToBoolean),
456 /* opc=*/ UO_LNot,
457 /* QualType=*/ C.IntTy,
458 /* ExprValueKind=*/ VK_RValue,
459 /* ExprObjectKind=*/ OK_Ordinary, SourceLocation(),
460 /* CanOverflow*/ false);
461
462 // Create assignment.
463 BinaryOperator *FlagAssignment = M.makeAssignment(
464 Deref, M.makeIntegralCast(M.makeIntegerLiteral(1, C.IntTy), DerefType),
465 DerefType);
466
467 IfStmt *Out = new (C)
468 IfStmt(C, SourceLocation(),
469 /* IsConstexpr=*/ false,
470 /* init=*/ nullptr,
471 /* var=*/ nullptr,
472 /* cond=*/ FlagCheck,
473 /* then=*/ M.makeCompound({CallbackCall, FlagAssignment}));
474
475 return Out;
476}
477
478/// Create a fake body for dispatch_once.
479static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
480 // Check if we have at least two parameters.
481 if (D->param_size() != 2)
482 return nullptr;
483
484 // Check if the first parameter is a pointer to integer type.
485 const ParmVarDecl *Predicate = D->getParamDecl(0);
486 QualType PredicateQPtrTy = Predicate->getType();
487 const PointerType *PredicatePtrTy = PredicateQPtrTy->getAs<PointerType>();
488 if (!PredicatePtrTy)
489 return nullptr;
490 QualType PredicateTy = PredicatePtrTy->getPointeeType();
491 if (!PredicateTy->isIntegerType())
492 return nullptr;
493
494 // Check if the second parameter is the proper block type.
495 const ParmVarDecl *Block = D->getParamDecl(1);
496 QualType Ty = Block->getType();
497 if (!isDispatchBlock(Ty))
498 return nullptr;
499
500 // Everything checks out. Create a fakse body that checks the predicate,
501 // sets it, and calls the block. Basically, an AST dump of:
502 //
503 // void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) {
504 // if (*predicate != ~0l) {
505 // *predicate = ~0l;
506 // block();
507 // }
508 // }
509
510 ASTMaker M(C);
511
512 // (1) Create the call.
513 CallExpr *CE = new (C) CallExpr(
514 /*ASTContext=*/C,
515 /*StmtClass=*/M.makeLvalueToRvalue(/*Expr=*/Block),
516 /*args=*/None,
517 /*QualType=*/C.VoidTy,
518 /*ExprValueType=*/VK_RValue,
519 /*SourceLocation=*/SourceLocation());
520
521 // (2) Create the assignment to the predicate.
522 Expr *DoneValue =
523 new (C) UnaryOperator(M.makeIntegerLiteral(0, C.LongTy), UO_Not, C.LongTy,
524 VK_RValue, OK_Ordinary, SourceLocation(),
525 /*CanOverflow*/false);
526
527 BinaryOperator *B =
528 M.makeAssignment(
529 M.makeDereference(
530 M.makeLvalueToRvalue(
531 M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
532 PredicateTy),
533 M.makeIntegralCast(DoneValue, PredicateTy),
534 PredicateTy);
535
536 // (3) Create the compound statement.
537 Stmt *Stmts[] = { B, CE };
538 CompoundStmt *CS = M.makeCompound(Stmts);
539
540 // (4) Create the 'if' condition.
541 ImplicitCastExpr *LValToRval =
542 M.makeLvalueToRvalue(
543 M.makeDereference(
544 M.makeLvalueToRvalue(
545 M.makeDeclRefExpr(Predicate),
546 PredicateQPtrTy),
547 PredicateTy),
548 PredicateTy);
549
550 Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
551 // (5) Create the 'if' statement.
552 IfStmt *If = new (C) IfStmt(C, SourceLocation(),
553 /* IsConstexpr=*/ false,
554 /* init=*/ nullptr,
555 /* var=*/ nullptr,
556 /* cond=*/ GuardCondition,
557 /* then=*/ CS);
558 return If;
559}
560
561/// Create a fake body for dispatch_sync.
562static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
563 // Check if we have at least two parameters.
564 if (D->param_size() != 2)
565 return nullptr;
566
567 // Check if the second parameter is a block.
568 const ParmVarDecl *PV = D->getParamDecl(1);
569 QualType Ty = PV->getType();
570 if (!isDispatchBlock(Ty))
571 return nullptr;
572
573 // Everything checks out. Create a fake body that just calls the block.
574 // This is basically just an AST dump of:
575 //
576 // void dispatch_sync(dispatch_queue_t queue, void (^block)(void)) {
577 // block();
578 // }
579 //
580 ASTMaker M(C);
581 DeclRefExpr *DR = M.makeDeclRefExpr(PV);
582 ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
583 CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
584 SourceLocation());
585 return CE;
586}
587
588static Stmt *create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
589{
590 // There are exactly 3 arguments.
591 if (D->param_size() != 3)
592 return nullptr;
593
594 // Signature:
595 // _Bool OSAtomicCompareAndSwapPtr(void *__oldValue,
596 // void *__newValue,
597 // void * volatile *__theValue)
598 // Generate body:
599 // if (oldValue == *theValue) {
600 // *theValue = newValue;
601 // return YES;
602 // }
603 // else return NO;
604
605 QualType ResultTy = D->getReturnType();
606 bool isBoolean = ResultTy->isBooleanType();
607 if (!isBoolean && !ResultTy->isIntegralType(C))
608 return nullptr;
609
610 const ParmVarDecl *OldValue = D->getParamDecl(0);
611 QualType OldValueTy = OldValue->getType();
612
613 const ParmVarDecl *NewValue = D->getParamDecl(1);
614 QualType NewValueTy = NewValue->getType();
615
616 assert(OldValueTy == NewValueTy)(static_cast <bool> (OldValueTy == NewValueTy) ? void (
0) : __assert_fail ("OldValueTy == NewValueTy", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/lib/Analysis/BodyFarm.cpp"
, 616, __extension__ __PRETTY_FUNCTION__))
;
617
618 const ParmVarDecl *TheValue = D->getParamDecl(2);
619 QualType TheValueTy = TheValue->getType();
620 const PointerType *PT = TheValueTy->getAs<PointerType>();
621 if (!PT)
622 return nullptr;
623 QualType PointeeTy = PT->getPointeeType();
624
625 ASTMaker M(C);
626 // Construct the comparison.
627 Expr *Comparison =
628 M.makeComparison(
629 M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
630 M.makeLvalueToRvalue(
631 M.makeDereference(
632 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
633 PointeeTy),
634 PointeeTy),
635 BO_EQ);
636
637 // Construct the body of the IfStmt.
638 Stmt *Stmts[2];
639 Stmts[0] =
640 M.makeAssignment(
641 M.makeDereference(
642 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
643 PointeeTy),
644 M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
645 NewValueTy);
646
647 Expr *BoolVal = M.makeObjCBool(true);
648 Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
649 : M.makeIntegralCast(BoolVal, ResultTy);
650 Stmts[1] = M.makeReturn(RetVal);
651 CompoundStmt *Body = M.makeCompound(Stmts);
652
653 // Construct the else clause.
654 BoolVal = M.makeObjCBool(false);
655 RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
656 : M.makeIntegralCast(BoolVal, ResultTy);
657 Stmt *Else = M.makeReturn(RetVal);
658
659 /// Construct the If.
660 Stmt *If = new (C) IfStmt(C, SourceLocation(), false, nullptr, nullptr,
661 Comparison, Body, SourceLocation(), Else);
662
663 return If;
664}
665
666Stmt *BodyFarm::getBody(const FunctionDecl *D) {
667 D = D->getCanonicalDecl();
668
669 Optional<Stmt *> &Val = Bodies[D];
670 if (Val.hasValue())
1
Assuming the condition is false
2
Taking false branch
671 return Val.getValue();
672
673 Val = nullptr;
674
675 if (D->getIdentifier() == nullptr)
3
Taking false branch
676 return nullptr;
677
678 StringRef Name = D->getName();
679 if (Name.empty())
4
Assuming the condition is false
5
Taking false branch
680 return nullptr;
681
682 FunctionFarmer FF;
683
684 if (Name.startswith("OSAtomicCompareAndSwap") ||
6
Assuming the condition is false
7
Assuming the condition is false
8
Taking false branch
685 Name.startswith("objc_atomicCompareAndSwap")) {
686 FF = create_OSAtomicCompareAndSwap;
687 } else if (Name == "call_once" && D->getDeclContext()->isStdNamespace()) {
9
Assuming the condition is true
10
Assuming the condition is true
11
Taking true branch
688 FF = create_call_once;
689 } else {
690 FF = llvm::StringSwitch<FunctionFarmer>(Name)
691 .Case("dispatch_sync", create_dispatch_sync)
692 .Case("dispatch_once", create_dispatch_once)
693 .Default(nullptr);
694 }
695
696 if (FF) { Val = FF(C, D); }
12
Taking true branch
13
Calling 'create_call_once'
697 else if (Injector) { Val = Injector->getBody(D); }
698 return Val.getValue();
699}
700
701static const ObjCIvarDecl *findBackingIvar(const ObjCPropertyDecl *Prop) {
702 const ObjCIvarDecl *IVar = Prop->getPropertyIvarDecl();
703
704 if (IVar)
705 return IVar;
706
707 // When a readonly property is shadowed in a class extensions with a
708 // a readwrite property, the instance variable belongs to the shadowing
709 // property rather than the shadowed property. If there is no instance
710 // variable on a readonly property, check to see whether the property is
711 // shadowed and if so try to get the instance variable from shadowing
712 // property.
713 if (!Prop->isReadOnly())
714 return nullptr;
715
716 auto *Container = cast<ObjCContainerDecl>(Prop->getDeclContext());
717 const ObjCInterfaceDecl *PrimaryInterface = nullptr;
718 if (auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
719 PrimaryInterface = InterfaceDecl;
720 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
721 PrimaryInterface = CategoryDecl->getClassInterface();
722 } else if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
723 PrimaryInterface = ImplDecl->getClassInterface();
724 } else {
725 return nullptr;
726 }
727
728 // FindPropertyVisibleInPrimaryClass() looks first in class extensions, so it
729 // is guaranteed to find the shadowing property, if it exists, rather than
730 // the shadowed property.
731 auto *ShadowingProp = PrimaryInterface->FindPropertyVisibleInPrimaryClass(
732 Prop->getIdentifier(), Prop->getQueryKind());
733 if (ShadowingProp && ShadowingProp != Prop) {
734 IVar = ShadowingProp->getPropertyIvarDecl();
735 }
736
737 return IVar;
738}
739
740static Stmt *createObjCPropertyGetter(ASTContext &Ctx,
741 const ObjCPropertyDecl *Prop) {
742 // First, find the backing ivar.
743 const ObjCIvarDecl *IVar = findBackingIvar(Prop);
744 if (!IVar)
745 return nullptr;
746
747 // Ignore weak variables, which have special behavior.
748 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
749 return nullptr;
750
751 // Look to see if Sema has synthesized a body for us. This happens in
752 // Objective-C++ because the return value may be a C++ class type with a
753 // non-trivial copy constructor. We can only do this if we can find the
754 // @synthesize for this property, though (or if we know it's been auto-
755 // synthesized).
756 const ObjCImplementationDecl *ImplDecl =
757 IVar->getContainingInterface()->getImplementation();
758 if (ImplDecl) {
759 for (const auto *I : ImplDecl->property_impls()) {
760 if (I->getPropertyDecl() != Prop)
761 continue;
762
763 if (I->getGetterCXXConstructor()) {
764 ASTMaker M(Ctx);
765 return M.makeReturn(I->getGetterCXXConstructor());
766 }
767 }
768 }
769
770 // Sanity check that the property is the same type as the ivar, or a
771 // reference to it, and that it is either an object pointer or trivially
772 // copyable.
773 if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
774 Prop->getType().getNonReferenceType()))
775 return nullptr;
776 if (!IVar->getType()->isObjCLifetimeType() &&
777 !IVar->getType().isTriviallyCopyableType(Ctx))
778 return nullptr;
779
780 // Generate our body:
781 // return self->_ivar;
782 ASTMaker M(Ctx);
783
784 const VarDecl *selfVar = Prop->getGetterMethodDecl()->getSelfDecl();
785 if (!selfVar)
786 return nullptr;
787
788 Expr *loadedIVar =
789 M.makeObjCIvarRef(
790 M.makeLvalueToRvalue(
791 M.makeDeclRefExpr(selfVar),
792 selfVar->getType()),
793 IVar);
794
795 if (!Prop->getType()->isReferenceType())
796 loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->getType());
797
798 return M.makeReturn(loadedIVar);
799}
800
801Stmt *BodyFarm::getBody(const ObjCMethodDecl *D) {
802 // We currently only know how to synthesize property accessors.
803 if (!D->isPropertyAccessor())
804 return nullptr;
805
806 D = D->getCanonicalDecl();
807
808 Optional<Stmt *> &Val = Bodies[D];
809 if (Val.hasValue())
810 return Val.getValue();
811 Val = nullptr;
812
813 const ObjCPropertyDecl *Prop = D->findPropertyDecl();
814 if (!Prop)
815 return nullptr;
816
817 // For now, we only synthesize getters.
818 // Synthesizing setters would cause false negatives in the
819 // RetainCountChecker because the method body would bind the parameter
820 // to an instance variable, causing it to escape. This would prevent
821 // warning in the following common scenario:
822 //
823 // id foo = [[NSObject alloc] init];
824 // self.foo = foo; // We should warn that foo leaks here.
825 //
826 if (D->param_size() != 0)
827 return nullptr;
828
829 Val = createObjCPropertyGetter(C, Prop);
830
831 return Val.getValue();
832}

/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- 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// This file defines the Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECL_H
15#define LLVM_CLANG_AST_DECL_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getStartLoc().print(OS, SrcMgr);
85/// @endcode
86class LLVM_ALIGNAS(8)alignas(8) TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// This represents a decl that may have a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245///
246/// Note that not every NamedDecl is actually named (e.g., a struct might
247/// be anonymous), and not every name is an identifier.
248class NamedDecl : public Decl {
249 /// The name of this declaration, which is typically a normal
250 /// identifier but may also be a special kind of name (C++
251 /// constructor, Objective-C selector, etc.)
252 DeclarationName Name;
253
254 virtual void anchor();
255
256private:
257 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
258
259protected:
260 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
261 : Decl(DK, DC, L), Name(N) {}
262
263public:
264 /// Get the identifier that names this declaration, if there is one.
265 ///
266 /// This will return NULL if this declaration has no name (e.g., for
267 /// an unnamed class) or if the name is a special name (C++ constructor,
268 /// Objective-C selector, etc.).
269 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
270
271 /// Get the name of identifier for this declaration as a StringRef.
272 ///
273 /// This requires that the declaration have a name and that it be a simple
274 /// identifier.
275 StringRef getName() const {
276 assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier"
) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 276, __extension__ __PRETTY_FUNCTION__))
;
277 return getIdentifier() ? getIdentifier()->getName() : "";
278 }
279
280 /// Get a human-readable name for the declaration, even if it is one of the
281 /// special kinds of names (C++ constructor, Objective-C selector, etc).
282 ///
283 /// Creating this name requires expensive string manipulation, so it should
284 /// be called only when performance doesn't matter. For simple declarations,
285 /// getNameAsCString() should suffice.
286 //
287 // FIXME: This function should be renamed to indicate that it is not just an
288 // alternate form of getName(), and clients should move as appropriate.
289 //
290 // FIXME: Deprecated, move clients to getName().
291 std::string getNameAsString() const { return Name.getAsString(); }
292
293 virtual void printName(raw_ostream &os) const;
294
295 /// Get the actual, stored name of the declaration, which may be a special
296 /// name.
297 DeclarationName getDeclName() const { return Name; }
298
299 /// Set the name of this declaration.
300 void setDeclName(DeclarationName N) { Name = N; }
301
302 /// Returns a human-readable qualified name for this declaration, like
303 /// A::B::i, for i being member of namespace A::B.
304 ///
305 /// If the declaration is not a member of context which can be named (record,
306 /// namespace), it will return the same result as printName().
307 ///
308 /// Creating this name is expensive, so it should be called only when
309 /// performance doesn't matter.
310 void printQualifiedName(raw_ostream &OS) const;
311 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
312
313 // FIXME: Remove string version.
314 std::string getQualifiedNameAsString() const;
315
316 /// Appends a human-readable name for this declaration into the given stream.
317 ///
318 /// This is the method invoked by Sema when displaying a NamedDecl
319 /// in a diagnostic. It does not necessarily produce the same
320 /// result as printName(); for example, class template
321 /// specializations are printed with their template arguments.
322 virtual void getNameForDiagnostic(raw_ostream &OS,
323 const PrintingPolicy &Policy,
324 bool Qualified) const;
325
326 /// Determine whether this declaration, if known to be well-formed within
327 /// its context, will replace the declaration OldD if introduced into scope.
328 ///
329 /// A declaration will replace another declaration if, for example, it is
330 /// a redeclaration of the same variable or function, but not if it is a
331 /// declaration of a different kind (function vs. class) or an overloaded
332 /// function.
333 ///
334 /// \param IsKnownNewer \c true if this declaration is known to be newer
335 /// than \p OldD (for instance, if this declaration is newly-created).
336 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
337
338 /// Determine whether this declaration has linkage.
339 bool hasLinkage() const;
340
341 using Decl::isModulePrivate;
342 using Decl::setModulePrivate;
343
344 /// Determine whether this declaration is a C++ class member.
345 bool isCXXClassMember() const {
346 const DeclContext *DC = getDeclContext();
347
348 // C++0x [class.mem]p1:
349 // The enumerators of an unscoped enumeration defined in
350 // the class are members of the class.
351 if (isa<EnumDecl>(DC))
352 DC = DC->getRedeclContext();
353
354 return DC->isRecord();
355 }
356
357 /// Determine whether the given declaration is an instance member of
358 /// a C++ class.
359 bool isCXXInstanceMember() const;
360
361 /// Determine what kind of linkage this entity has.
362 ///
363 /// This is not the linkage as defined by the standard or the codegen notion
364 /// of linkage. It is just an implementation detail that is used to compute
365 /// those.
366 Linkage getLinkageInternal() const;
367
368 /// Get the linkage from a semantic point of view. Entities in
369 /// anonymous namespaces are external (in c++98).
370 Linkage getFormalLinkage() const {
371 return clang::getFormalLinkage(getLinkageInternal());
372 }
373
374 /// True if this decl has external linkage.
375 bool hasExternalFormalLinkage() const {
376 return isExternalFormalLinkage(getLinkageInternal());
377 }
378
379 bool isExternallyVisible() const {
380 return clang::isExternallyVisible(getLinkageInternal());
381 }
382
383 /// Determine whether this declaration can be redeclared in a
384 /// different translation unit.
385 bool isExternallyDeclarable() const {
386 return isExternallyVisible() && !getOwningModuleForLinkage();
387 }
388
389 /// Determines the visibility of this entity.
390 Visibility getVisibility() const {
391 return getLinkageAndVisibility().getVisibility();
392 }
393
394 /// Determines the linkage and visibility of this entity.
395 LinkageInfo getLinkageAndVisibility() const;
396
397 /// Kinds of explicit visibility.
398 enum ExplicitVisibilityKind {
399 /// Do an LV computation for, ultimately, a type.
400 /// Visibility may be restricted by type visibility settings and
401 /// the visibility of template arguments.
402 VisibilityForType,
403
404 /// Do an LV computation for, ultimately, a non-type declaration.
405 /// Visibility may be restricted by value visibility settings and
406 /// the visibility of template arguments.
407 VisibilityForValue
408 };
409
410 /// If visibility was explicitly specified for this
411 /// declaration, return that visibility.
412 Optional<Visibility>
413 getExplicitVisibility(ExplicitVisibilityKind kind) const;
414
415 /// True if the computed linkage is valid. Used for consistency
416 /// checking. Should always return true.
417 bool isLinkageValid() const;
418
419 /// True if something has required us to compute the linkage
420 /// of this declaration.
421 ///
422 /// Language features which can retroactively change linkage (like a
423 /// typedef name for linkage purposes) may need to consider this,
424 /// but hopefully only in transitory ways during parsing.
425 bool hasLinkageBeenComputed() const {
426 return hasCachedLinkage();
427 }
428
429 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
430 /// the underlying named decl.
431 NamedDecl *getUnderlyingDecl() {
432 // Fast-path the common case.
433 if (this->getKind() != UsingShadow &&
434 this->getKind() != ConstructorUsingShadow &&
435 this->getKind() != ObjCCompatibleAlias &&
436 this->getKind() != NamespaceAlias)
437 return this;
438
439 return getUnderlyingDeclImpl();
440 }
441 const NamedDecl *getUnderlyingDecl() const {
442 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
443 }
444
445 NamedDecl *getMostRecentDecl() {
446 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
447 }
448 const NamedDecl *getMostRecentDecl() const {
449 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
450 }
451
452 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
453
454 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
455 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
456};
457
458inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
459 ND.printName(OS);
460 return OS;
461}
462
463/// Represents the declaration of a label. Labels also have a
464/// corresponding LabelStmt, which indicates the position that the label was
465/// defined at. For normal labels, the location of the decl is the same as the
466/// location of the statement. For GNU local labels (__label__), the decl
467/// location is where the __label__ is.
468class LabelDecl : public NamedDecl {
469 LabelStmt *TheStmt;
470 StringRef MSAsmName;
471 bool MSAsmNameResolved = false;
472
473 /// For normal labels, this is the same as the main declaration
474 /// label, i.e., the location of the identifier; for GNU local labels,
475 /// this is the location of the __label__ keyword.
476 SourceLocation LocStart;
477
478 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
479 LabelStmt *S, SourceLocation StartL)
480 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
481
482 void anchor() override;
483
484public:
485 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
486 SourceLocation IdentL, IdentifierInfo *II);
487 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
488 SourceLocation IdentL, IdentifierInfo *II,
489 SourceLocation GnuLabelL);
490 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
491
492 LabelStmt *getStmt() const { return TheStmt; }
493 void setStmt(LabelStmt *T) { TheStmt = T; }
494
495 bool isGnuLocal() const { return LocStart != getLocation(); }
496 void setLocStart(SourceLocation L) { LocStart = L; }
497
498 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
499 return SourceRange(LocStart, getLocation());
500 }
501
502 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
503 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
504 void setMSAsmLabel(StringRef Name);
505 StringRef getMSAsmLabel() const { return MSAsmName; }
506 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
507
508 // Implement isa/cast/dyncast/etc.
509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
510 static bool classofKind(Kind K) { return K == Label; }
511};
512
513/// Represent a C++ namespace.
514class NamespaceDecl : public NamedDecl, public DeclContext,
515 public Redeclarable<NamespaceDecl>
516{
517 /// The starting location of the source range, pointing
518 /// to either the namespace or the inline keyword.
519 SourceLocation LocStart;
520
521 /// The ending location of the source range.
522 SourceLocation RBraceLoc;
523
524 /// A pointer to either the anonymous namespace that lives just inside
525 /// this namespace or to the first namespace in the chain (the latter case
526 /// only when this is not the first in the chain), along with a
527 /// boolean value indicating whether this is an inline namespace.
528 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
529
530 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
531 SourceLocation StartLoc, SourceLocation IdLoc,
532 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
533
534 using redeclarable_base = Redeclarable<NamespaceDecl>;
535
536 NamespaceDecl *getNextRedeclarationImpl() override;
537 NamespaceDecl *getPreviousDeclImpl() override;
538 NamespaceDecl *getMostRecentDeclImpl() override;
539
540public:
541 friend class ASTDeclReader;
542 friend class ASTDeclWriter;
543
544 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
545 bool Inline, SourceLocation StartLoc,
546 SourceLocation IdLoc, IdentifierInfo *Id,
547 NamespaceDecl *PrevDecl);
548
549 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
550
551 using redecl_range = redeclarable_base::redecl_range;
552 using redecl_iterator = redeclarable_base::redecl_iterator;
553
554 using redeclarable_base::redecls_begin;
555 using redeclarable_base::redecls_end;
556 using redeclarable_base::redecls;
557 using redeclarable_base::getPreviousDecl;
558 using redeclarable_base::getMostRecentDecl;
559 using redeclarable_base::isFirstDecl;
560
561 /// Returns true if this is an anonymous namespace declaration.
562 ///
563 /// For example:
564 /// \code
565 /// namespace {
566 /// ...
567 /// };
568 /// \endcode
569 /// q.v. C++ [namespace.unnamed]
570 bool isAnonymousNamespace() const {
571 return !getIdentifier();
572 }
573
574 /// Returns true if this is an inline namespace declaration.
575 bool isInline() const {
576 return AnonOrFirstNamespaceAndInline.getInt();
577 }
578
579 /// Set whether this is an inline namespace declaration.
580 void setInline(bool Inline) {
581 AnonOrFirstNamespaceAndInline.setInt(Inline);
582 }
583
584 /// Get the original (first) namespace declaration.
585 NamespaceDecl *getOriginalNamespace();
586
587 /// Get the original (first) namespace declaration.
588 const NamespaceDecl *getOriginalNamespace() const;
589
590 /// Return true if this declaration is an original (first) declaration
591 /// of the namespace. This is false for non-original (subsequent) namespace
592 /// declarations and anonymous namespaces.
593 bool isOriginalNamespace() const;
594
595 /// Retrieve the anonymous namespace nested inside this namespace,
596 /// if any.
597 NamespaceDecl *getAnonymousNamespace() const {
598 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
599 }
600
601 void setAnonymousNamespace(NamespaceDecl *D) {
602 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
603 }
604
605 /// Retrieves the canonical declaration of this namespace.
606 NamespaceDecl *getCanonicalDecl() override {
607 return getOriginalNamespace();
608 }
609 const NamespaceDecl *getCanonicalDecl() const {
610 return getOriginalNamespace();
611 }
612
613 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
614 return SourceRange(LocStart, RBraceLoc);
615 }
616
617 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
618 SourceLocation getRBraceLoc() const { return RBraceLoc; }
619 void setLocStart(SourceLocation L) { LocStart = L; }
620 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
621
622 // Implement isa/cast/dyncast/etc.
623 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
624 static bool classofKind(Kind K) { return K == Namespace; }
625 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
626 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
627 }
628 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
629 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
630 }
631};
632
633/// Represent the declaration of a variable (in which case it is
634/// an lvalue) a function (in which case it is a function designator) or
635/// an enum constant.
636class ValueDecl : public NamedDecl {
637 QualType DeclType;
638
639 void anchor() override;
640
641protected:
642 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
643 DeclarationName N, QualType T)
644 : NamedDecl(DK, DC, L, N), DeclType(T) {}
645
646public:
647 QualType getType() const { return DeclType; }
648 void setType(QualType newType) { DeclType = newType; }
649
650 /// Determine whether this symbol is weakly-imported,
651 /// or declared with the weak or weak-ref attr.
652 bool isWeak() const;
653
654 // Implement isa/cast/dyncast/etc.
655 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
656 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
657};
658
659/// A struct with extended info about a syntactic
660/// name qualifier, to be used for the case of out-of-line declarations.
661struct QualifierInfo {
662 NestedNameSpecifierLoc QualifierLoc;
663
664 /// The number of "outer" template parameter lists.
665 /// The count includes all of the template parameter lists that were matched
666 /// against the template-ids occurring into the NNS and possibly (in the
667 /// case of an explicit specialization) a final "template <>".
668 unsigned NumTemplParamLists = 0;
669
670 /// A new-allocated array of size NumTemplParamLists,
671 /// containing pointers to the "outer" template parameter lists.
672 /// It includes all of the template parameter lists that were matched
673 /// against the template-ids occurring into the NNS and possibly (in the
674 /// case of an explicit specialization) a final "template <>".
675 TemplateParameterList** TemplParamLists = nullptr;
676
677 QualifierInfo() = default;
678 QualifierInfo(const QualifierInfo &) = delete;
679 QualifierInfo& operator=(const QualifierInfo &) = delete;
680
681 /// Sets info about "outer" template parameter lists.
682 void setTemplateParameterListsInfo(ASTContext &Context,
683 ArrayRef<TemplateParameterList *> TPLists);
684};
685
686/// Represents a ValueDecl that came out of a declarator.
687/// Contains type source information through TypeSourceInfo.
688class DeclaratorDecl : public ValueDecl {
689 // A struct representing both a TInfo and a syntactic qualifier,
690 // to be used for the (uncommon) case of out-of-line declarations.
691 struct ExtInfo : public QualifierInfo {
692 TypeSourceInfo *TInfo;
693 };
694
695 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
696
697 /// The start of the source range for this declaration,
698 /// ignoring outer template declarations.
699 SourceLocation InnerLocStart;
700
701 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
702 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
703 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
704
705protected:
706 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
707 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
708 SourceLocation StartL)
709 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
710
711public:
712 friend class ASTDeclReader;
713 friend class ASTDeclWriter;
714
715 TypeSourceInfo *getTypeSourceInfo() const {
716 return hasExtInfo()
717 ? getExtInfo()->TInfo
718 : DeclInfo.get<TypeSourceInfo*>();
719 }
720
721 void setTypeSourceInfo(TypeSourceInfo *TI) {
722 if (hasExtInfo())
723 getExtInfo()->TInfo = TI;
724 else
725 DeclInfo = TI;
726 }
727
728 /// Return start of source range ignoring outer template declarations.
729 SourceLocation getInnerLocStart() const { return InnerLocStart; }
730 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
731
732 /// Return start of source range taking into account any outer template
733 /// declarations.
734 SourceLocation getOuterLocStart() const;
735
736 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
737
738 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
739 return getOuterLocStart();
740 }
741
742 /// Retrieve the nested-name-specifier that qualifies the name of this
743 /// declaration, if it was present in the source.
744 NestedNameSpecifier *getQualifier() const {
745 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
746 : nullptr;
747 }
748
749 /// Retrieve the nested-name-specifier (with source-location
750 /// information) that qualifies the name of this declaration, if it was
751 /// present in the source.
752 NestedNameSpecifierLoc getQualifierLoc() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc
754 : NestedNameSpecifierLoc();
755 }
756
757 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
758
759 unsigned getNumTemplateParameterLists() const {
760 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
761 }
762
763 TemplateParameterList *getTemplateParameterList(unsigned index) const {
764 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 764, __extension__ __PRETTY_FUNCTION__))
;
765 return getExtInfo()->TemplParamLists[index];
766 }
767
768 void setTemplateParameterListsInfo(ASTContext &Context,
769 ArrayRef<TemplateParameterList *> TPLists);
770
771 SourceLocation getTypeSpecStartLoc() const;
772
773 // Implement isa/cast/dyncast/etc.
774 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
775 static bool classofKind(Kind K) {
776 return K >= firstDeclarator && K <= lastDeclarator;
777 }
778};
779
780/// Structure used to store a statement, the constant value to
781/// which it was evaluated (if any), and whether or not the statement
782/// is an integral constant expression (if known).
783struct EvaluatedStmt {
784 /// Whether this statement was already evaluated.
785 bool WasEvaluated : 1;
786
787 /// Whether this statement is being evaluated.
788 bool IsEvaluating : 1;
789
790 /// Whether we already checked whether this statement was an
791 /// integral constant expression.
792 bool CheckedICE : 1;
793
794 /// Whether we are checking whether this statement is an
795 /// integral constant expression.
796 bool CheckingICE : 1;
797
798 /// Whether this statement is an integral constant expression,
799 /// or in C++11, whether the statement is a constant expression. Only
800 /// valid if CheckedICE is true.
801 bool IsICE : 1;
802
803 Stmt *Value;
804 APValue Evaluated;
805
806 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
807 CheckingICE(false), IsICE(false) {}
808
809};
810
811/// Represents a variable declaration or definition.
812class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
813public:
814 /// Initialization styles.
815 enum InitializationStyle {
816 /// C-style initialization with assignment
817 CInit,
818
819 /// Call-style initialization (C++98)
820 CallInit,
821
822 /// Direct list-initialization (C++11)
823 ListInit
824 };
825
826 /// Kinds of thread-local storage.
827 enum TLSKind {
828 /// Not a TLS variable.
829 TLS_None,
830
831 /// TLS with a known-constant initializer.
832 TLS_Static,
833
834 /// TLS with a dynamic initializer.
835 TLS_Dynamic
836 };
837
838 /// Return the string used to specify the storage class \p SC.
839 ///
840 /// It is illegal to call this function with SC == None.
841 static const char *getStorageClassSpecifierString(StorageClass SC);
842
843protected:
844 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
845 // have allocated the auxiliary struct of information there.
846 //
847 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
848 // this as *many* VarDecls are ParmVarDecls that don't have default
849 // arguments. We could save some space by moving this pointer union to be
850 // allocated in trailing space when necessary.
851 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
852
853 /// The initializer for this variable or, for a ParmVarDecl, the
854 /// C++ default argument.
855 mutable InitType Init;
856
857private:
858 friend class ASTDeclReader;
859 friend class ASTNodeImporter;
860 friend class StmtIteratorBase;
861
862 class VarDeclBitfields {
863 friend class ASTDeclReader;
864 friend class VarDecl;
865
866 unsigned SClass : 3;
867 unsigned TSCSpec : 2;
868 unsigned InitStyle : 2;
869 };
870 enum { NumVarDeclBits = 7 };
871
872protected:
873 enum { NumParameterIndexBits = 8 };
874
875 enum DefaultArgKind {
876 DAK_None,
877 DAK_Unparsed,
878 DAK_Uninstantiated,
879 DAK_Normal
880 };
881
882 class ParmVarDeclBitfields {
883 friend class ASTDeclReader;
884 friend class ParmVarDecl;
885
886 unsigned : NumVarDeclBits;
887
888 /// Whether this parameter inherits a default argument from a
889 /// prior declaration.
890 unsigned HasInheritedDefaultArg : 1;
891
892 /// Describes the kind of default argument for this parameter. By default
893 /// this is none. If this is normal, then the default argument is stored in
894 /// the \c VarDecl initializer expression unless we were unable to parse
895 /// (even an invalid) expression for the default argument.
896 unsigned DefaultArgKind : 2;
897
898 /// Whether this parameter undergoes K&R argument promotion.
899 unsigned IsKNRPromoted : 1;
900
901 /// Whether this parameter is an ObjC method parameter or not.
902 unsigned IsObjCMethodParam : 1;
903
904 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
905 /// Otherwise, the number of function parameter scopes enclosing
906 /// the function parameter scope in which this parameter was
907 /// declared.
908 unsigned ScopeDepthOrObjCQuals : 7;
909
910 /// The number of parameters preceding this parameter in the
911 /// function parameter scope in which it was declared.
912 unsigned ParameterIndex : NumParameterIndexBits;
913 };
914
915 class NonParmVarDeclBitfields {
916 friend class ASTDeclReader;
917 friend class ImplicitParamDecl;
918 friend class VarDecl;
919
920 unsigned : NumVarDeclBits;
921
922 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
923 /// Whether this variable is a definition which was demoted due to
924 /// module merge.
925 unsigned IsThisDeclarationADemotedDefinition : 1;
926
927 /// Whether this variable is the exception variable in a C++ catch
928 /// or an Objective-C @catch statement.
929 unsigned ExceptionVar : 1;
930
931 /// Whether this local variable could be allocated in the return
932 /// slot of its function, enabling the named return value optimization
933 /// (NRVO).
934 unsigned NRVOVariable : 1;
935
936 /// Whether this variable is the for-range-declaration in a C++0x
937 /// for-range statement.
938 unsigned CXXForRangeDecl : 1;
939
940 /// Whether this variable is the for-in loop declaration in Objective-C.
941 unsigned ObjCForDecl : 1;
942
943 /// Whether this variable is an ARC pseudo-__strong
944 /// variable; see isARCPseudoStrong() for details.
945 unsigned ARCPseudoStrong : 1;
946
947 /// Whether this variable is (C++1z) inline.
948 unsigned IsInline : 1;
949
950 /// Whether this variable has (C++1z) inline explicitly specified.
951 unsigned IsInlineSpecified : 1;
952
953 /// Whether this variable is (C++0x) constexpr.
954 unsigned IsConstexpr : 1;
955
956 /// Whether this variable is the implicit variable for a lambda
957 /// init-capture.
958 unsigned IsInitCapture : 1;
959
960 /// Whether this local extern variable's previous declaration was
961 /// declared in the same block scope. This controls whether we should merge
962 /// the type of this declaration with its previous declaration.
963 unsigned PreviousDeclInSameBlockScope : 1;
964
965 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
966 /// something else.
967 unsigned ImplicitParamKind : 3;
968 };
969
970 union {
971 unsigned AllBits;
972 VarDeclBitfields VarDeclBits;
973 ParmVarDeclBitfields ParmVarDeclBits;
974 NonParmVarDeclBitfields NonParmVarDeclBits;
975 };
976
977 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
978 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
979 TypeSourceInfo *TInfo, StorageClass SC);
980
981 using redeclarable_base = Redeclarable<VarDecl>;
982
983 VarDecl *getNextRedeclarationImpl() override {
984 return getNextRedeclaration();
985 }
986
987 VarDecl *getPreviousDeclImpl() override {
988 return getPreviousDecl();
989 }
990
991 VarDecl *getMostRecentDeclImpl() override {
992 return getMostRecentDecl();
993 }
994
995public:
996 using redecl_range = redeclarable_base::redecl_range;
997 using redecl_iterator = redeclarable_base::redecl_iterator;
998
999 using redeclarable_base::redecls_begin;
1000 using redeclarable_base::redecls_end;
1001 using redeclarable_base::redecls;
1002 using redeclarable_base::getPreviousDecl;
1003 using redeclarable_base::getMostRecentDecl;
1004 using redeclarable_base::isFirstDecl;
1005
1006 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1007 SourceLocation StartLoc, SourceLocation IdLoc,
1008 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1009 StorageClass S);
1010
1011 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1012
1013 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1014
1015 /// Returns the storage class as written in the source. For the
1016 /// computed linkage of symbol, see getLinkage.
1017 StorageClass getStorageClass() const {
1018 return (StorageClass) VarDeclBits.SClass;
1019 }
1020 void setStorageClass(StorageClass SC);
1021
1022 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1023 VarDeclBits.TSCSpec = TSC;
1024 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1024, __extension__ __PRETTY_FUNCTION__))
;
1025 }
1026 ThreadStorageClassSpecifier getTSCSpec() const {
1027 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1028 }
1029 TLSKind getTLSKind() const;
1030
1031 /// Returns true if a variable with function scope is a non-static local
1032 /// variable.
1033 bool hasLocalStorage() const {
1034 if (getStorageClass() == SC_None) {
1035 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1036 // used to describe variables allocated in global memory and which are
1037 // accessed inside a kernel(s) as read-only variables. As such, variables
1038 // in constant address space cannot have local storage.
1039 if (getType().getAddressSpace() == LangAS::opencl_constant)
1040 return false;
1041 // Second check is for C++11 [dcl.stc]p4.
1042 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1043 }
1044
1045 // Global Named Register (GNU extension)
1046 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1047 return false;
1048
1049 // Return true for: Auto, Register.
1050 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1051
1052 return getStorageClass() >= SC_Auto;
1053 }
1054
1055 /// Returns true if a variable with function scope is a static local
1056 /// variable.
1057 bool isStaticLocal() const {
1058 return (getStorageClass() == SC_Static ||
1059 // C++11 [dcl.stc]p4
1060 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1061 && !isFileVarDecl();
1062 }
1063
1064 /// Returns true if a variable has extern or __private_extern__
1065 /// storage.
1066 bool hasExternalStorage() const {
1067 return getStorageClass() == SC_Extern ||
1068 getStorageClass() == SC_PrivateExtern;
1069 }
1070
1071 /// Returns true for all variables that do not have local storage.
1072 ///
1073 /// This includes all global variables as well as static variables declared
1074 /// within a function.
1075 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1076
1077 /// Get the storage duration of this variable, per C++ [basic.stc].
1078 StorageDuration getStorageDuration() const {
1079 return hasLocalStorage() ? SD_Automatic :
1080 getTSCSpec() ? SD_Thread : SD_Static;
1081 }
1082
1083 /// Compute the language linkage.
1084 LanguageLinkage getLanguageLinkage() const;
1085
1086 /// Determines whether this variable is a variable with external, C linkage.
1087 bool isExternC() const;
1088
1089 /// Determines whether this variable's context is, or is nested within,
1090 /// a C++ extern "C" linkage spec.
1091 bool isInExternCContext() const;
1092
1093 /// Determines whether this variable's context is, or is nested within,
1094 /// a C++ extern "C++" linkage spec.
1095 bool isInExternCXXContext() const;
1096
1097 /// Returns true for local variable declarations other than parameters.
1098 /// Note that this includes static variables inside of functions. It also
1099 /// includes variables inside blocks.
1100 ///
1101 /// void foo() { int x; static int y; extern int z; }
1102 bool isLocalVarDecl() const {
1103 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1104 return false;
1105 if (const DeclContext *DC = getLexicalDeclContext())
1106 return DC->getRedeclContext()->isFunctionOrMethod();
1107 return false;
1108 }
1109
1110 /// Similar to isLocalVarDecl but also includes parameters.
1111 bool isLocalVarDeclOrParm() const {
1112 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1113 }
1114
1115 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1116 bool isFunctionOrMethodVarDecl() const {
1117 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1118 return false;
1119 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1120 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1121 }
1122
1123 /// Determines whether this is a static data member.
1124 ///
1125 /// This will only be true in C++, and applies to, e.g., the
1126 /// variable 'x' in:
1127 /// \code
1128 /// struct S {
1129 /// static int x;
1130 /// };
1131 /// \endcode
1132 bool isStaticDataMember() const {
1133 // If it wasn't static, it would be a FieldDecl.
1134 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1135 }
1136
1137 VarDecl *getCanonicalDecl() override;
1138 const VarDecl *getCanonicalDecl() const {
1139 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1140 }
1141
1142 enum DefinitionKind {
1143 /// This declaration is only a declaration.
1144 DeclarationOnly,
1145
1146 /// This declaration is a tentative definition.
1147 TentativeDefinition,
1148
1149 /// This declaration is definitely a definition.
1150 Definition
1151 };
1152
1153 /// Check whether this declaration is a definition. If this could be
1154 /// a tentative definition (in C), don't check whether there's an overriding
1155 /// definition.
1156 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1157 DefinitionKind isThisDeclarationADefinition() const {
1158 return isThisDeclarationADefinition(getASTContext());
1159 }
1160
1161 /// Check whether this variable is defined in this translation unit.
1162 DefinitionKind hasDefinition(ASTContext &) const;
1163 DefinitionKind hasDefinition() const {
1164 return hasDefinition(getASTContext());
1165 }
1166
1167 /// Get the tentative definition that acts as the real definition in a TU.
1168 /// Returns null if there is a proper definition available.
1169 VarDecl *getActingDefinition();
1170 const VarDecl *getActingDefinition() const {
1171 return const_cast<VarDecl*>(this)->getActingDefinition();
1172 }
1173
1174 /// Get the real (not just tentative) definition for this declaration.
1175 VarDecl *getDefinition(ASTContext &);
1176 const VarDecl *getDefinition(ASTContext &C) const {
1177 return const_cast<VarDecl*>(this)->getDefinition(C);
1178 }
1179 VarDecl *getDefinition() {
1180 return getDefinition(getASTContext());
1181 }
1182 const VarDecl *getDefinition() const {
1183 return const_cast<VarDecl*>(this)->getDefinition();
1184 }
1185
1186 /// Determine whether this is or was instantiated from an out-of-line
1187 /// definition of a static data member.
1188 bool isOutOfLine() const override;
1189
1190 /// Returns true for file scoped variable declaration.
1191 bool isFileVarDecl() const {
1192 Kind K = getKind();
1193 if (K == ParmVar || K == ImplicitParam)
1194 return false;
1195
1196 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1197 return true;
1198
1199 if (isStaticDataMember())
1200 return true;
1201
1202 return false;
1203 }
1204
1205 /// Get the initializer for this variable, no matter which
1206 /// declaration it is attached to.
1207 const Expr *getAnyInitializer() const {
1208 const VarDecl *D;
1209 return getAnyInitializer(D);
1210 }
1211
1212 /// Get the initializer for this variable, no matter which
1213 /// declaration it is attached to. Also get that declaration.
1214 const Expr *getAnyInitializer(const VarDecl *&D) const;
1215
1216 bool hasInit() const;
1217 const Expr *getInit() const {
1218 return const_cast<VarDecl *>(this)->getInit();
1219 }
1220 Expr *getInit();
1221
1222 /// Retrieve the address of the initializer expression.
1223 Stmt **getInitAddress();
1224
1225 void setInit(Expr *I);
1226
1227 /// Determine whether this variable's value can be used in a
1228 /// constant expression, according to the relevant language standard.
1229 /// This only checks properties of the declaration, and does not check
1230 /// whether the initializer is in fact a constant expression.
1231 bool isUsableInConstantExpressions(ASTContext &C) const;
1232
1233 EvaluatedStmt *ensureEvaluatedStmt() const;
1234
1235 /// Attempt to evaluate the value of the initializer attached to this
1236 /// declaration, and produce notes explaining why it cannot be evaluated or is
1237 /// not a constant expression. Returns a pointer to the value if evaluation
1238 /// succeeded, 0 otherwise.
1239 APValue *evaluateValue() const;
1240 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1241
1242 /// Return the already-evaluated value of this variable's
1243 /// initializer, or NULL if the value is not yet known. Returns pointer
1244 /// to untyped APValue if the value could not be evaluated.
1245 APValue *getEvaluatedValue() const;
1246
1247 /// Determines whether it is already known whether the
1248 /// initializer is an integral constant expression or not.
1249 bool isInitKnownICE() const;
1250
1251 /// Determines whether the initializer is an integral constant
1252 /// expression, or in C++11, whether the initializer is a constant
1253 /// expression.
1254 ///
1255 /// \pre isInitKnownICE()
1256 bool isInitICE() const;
1257
1258 /// Determine whether the value of the initializer attached to this
1259 /// declaration is an integral constant expression.
1260 bool checkInitIsICE() const;
1261
1262 void setInitStyle(InitializationStyle Style) {
1263 VarDeclBits.InitStyle = Style;
1264 }
1265
1266 /// The style of initialization for this declaration.
1267 ///
1268 /// C-style initialization is "int x = 1;". Call-style initialization is
1269 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1270 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1271 /// expression for class types. List-style initialization is C++11 syntax,
1272 /// e.g. "int x{1};". Clients can distinguish between different forms of
1273 /// initialization by checking this value. In particular, "int x = {1};" is
1274 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1275 /// Init expression in all three cases is an InitListExpr.
1276 InitializationStyle getInitStyle() const {
1277 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1278 }
1279
1280 /// Whether the initializer is a direct-initializer (list or call).
1281 bool isDirectInit() const {
1282 return getInitStyle() != CInit;
1283 }
1284
1285 /// If this definition should pretend to be a declaration.
1286 bool isThisDeclarationADemotedDefinition() const {
1287 return isa<ParmVarDecl>(this) ? false :
1288 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1289 }
1290
1291 /// This is a definition which should be demoted to a declaration.
1292 ///
1293 /// In some cases (mostly module merging) we can end up with two visible
1294 /// definitions one of which needs to be demoted to a declaration to keep
1295 /// the AST invariants.
1296 void demoteThisDefinitionToDeclaration() {
1297 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1297, __extension__ __PRETTY_FUNCTION__))
;
1298 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) &&
"Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1298, __extension__ __PRETTY_FUNCTION__))
;
1299 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1300 }
1301
1302 /// Determine whether this variable is the exception variable in a
1303 /// C++ catch statememt or an Objective-C \@catch statement.
1304 bool isExceptionVariable() const {
1305 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1306 }
1307 void setExceptionVariable(bool EV) {
1308 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1308, __extension__ __PRETTY_FUNCTION__))
;
1309 NonParmVarDeclBits.ExceptionVar = EV;
1310 }
1311
1312 /// Determine whether this local variable can be used with the named
1313 /// return value optimization (NRVO).
1314 ///
1315 /// The named return value optimization (NRVO) works by marking certain
1316 /// non-volatile local variables of class type as NRVO objects. These
1317 /// locals can be allocated within the return slot of their containing
1318 /// function, in which case there is no need to copy the object to the
1319 /// return slot when returning from the function. Within the function body,
1320 /// each return that returns the NRVO object will have this variable as its
1321 /// NRVO candidate.
1322 bool isNRVOVariable() const {
1323 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1324 }
1325 void setNRVOVariable(bool NRVO) {
1326 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1326, __extension__ __PRETTY_FUNCTION__))
;
1327 NonParmVarDeclBits.NRVOVariable = NRVO;
1328 }
1329
1330 /// Determine whether this variable is the for-range-declaration in
1331 /// a C++0x for-range statement.
1332 bool isCXXForRangeDecl() const {
1333 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1334 }
1335 void setCXXForRangeDecl(bool FRD) {
1336 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1336, __extension__ __PRETTY_FUNCTION__))
;
1337 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1338 }
1339
1340 /// Determine whether this variable is a for-loop declaration for a
1341 /// for-in statement in Objective-C.
1342 bool isObjCForDecl() const {
1343 return NonParmVarDeclBits.ObjCForDecl;
1344 }
1345
1346 void setObjCForDecl(bool FRD) {
1347 NonParmVarDeclBits.ObjCForDecl = FRD;
1348 }
1349
1350 /// Determine whether this variable is an ARC pseudo-__strong
1351 /// variable. A pseudo-__strong variable has a __strong-qualified
1352 /// type but does not actually retain the object written into it.
1353 /// Generally such variables are also 'const' for safety.
1354 bool isARCPseudoStrong() const {
1355 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1356 }
1357 void setARCPseudoStrong(bool ps) {
1358 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1358, __extension__ __PRETTY_FUNCTION__))
;
1359 NonParmVarDeclBits.ARCPseudoStrong = ps;
1360 }
1361
1362 /// Whether this variable is (C++1z) inline.
1363 bool isInline() const {
1364 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1365 }
1366 bool isInlineSpecified() const {
1367 return isa<ParmVarDecl>(this) ? false
1368 : NonParmVarDeclBits.IsInlineSpecified;
1369 }
1370 void setInlineSpecified() {
1371 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1371, __extension__ __PRETTY_FUNCTION__))
;
1372 NonParmVarDeclBits.IsInline = true;
1373 NonParmVarDeclBits.IsInlineSpecified = true;
1374 }
1375 void setImplicitlyInline() {
1376 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1376, __extension__ __PRETTY_FUNCTION__))
;
1377 NonParmVarDeclBits.IsInline = true;
1378 }
1379
1380 /// Whether this variable is (C++11) constexpr.
1381 bool isConstexpr() const {
1382 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1383 }
1384 void setConstexpr(bool IC) {
1385 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1385, __extension__ __PRETTY_FUNCTION__))
;
1386 NonParmVarDeclBits.IsConstexpr = IC;
1387 }
1388
1389 /// Whether this variable is the implicit variable for a lambda init-capture.
1390 bool isInitCapture() const {
1391 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1392 }
1393 void setInitCapture(bool IC) {
1394 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1394, __extension__ __PRETTY_FUNCTION__))
;
1395 NonParmVarDeclBits.IsInitCapture = IC;
1396 }
1397
1398 /// Whether this local extern variable declaration's previous declaration
1399 /// was declared in the same block scope. Only correct in C++.
1400 bool isPreviousDeclInSameBlockScope() const {
1401 return isa<ParmVarDecl>(this)
1402 ? false
1403 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1404 }
1405 void setPreviousDeclInSameBlockScope(bool Same) {
1406 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1406, __extension__ __PRETTY_FUNCTION__))
;
1407 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1408 }
1409
1410 /// Retrieve the variable declaration from which this variable could
1411 /// be instantiated, if it is an instantiation (rather than a non-template).
1412 VarDecl *getTemplateInstantiationPattern() const;
1413
1414 /// If this variable is an instantiated static data member of a
1415 /// class template specialization, returns the templated static data member
1416 /// from which it was instantiated.
1417 VarDecl *getInstantiatedFromStaticDataMember() const;
1418
1419 /// If this variable is an instantiation of a variable template or a
1420 /// static data member of a class template, determine what kind of
1421 /// template specialization or instantiation this is.
1422 TemplateSpecializationKind getTemplateSpecializationKind() const;
1423
1424 /// If this variable is an instantiation of a variable template or a
1425 /// static data member of a class template, determine its point of
1426 /// instantiation.
1427 SourceLocation getPointOfInstantiation() const;
1428
1429 /// If this variable is an instantiation of a static data member of a
1430 /// class template specialization, retrieves the member specialization
1431 /// information.
1432 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1433
1434 /// For a static data member that was instantiated from a static
1435 /// data member of a class template, set the template specialiation kind.
1436 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1437 SourceLocation PointOfInstantiation = SourceLocation());
1438
1439 /// Specify that this variable is an instantiation of the
1440 /// static data member VD.
1441 void setInstantiationOfStaticDataMember(VarDecl *VD,
1442 TemplateSpecializationKind TSK);
1443
1444 /// Retrieves the variable template that is described by this
1445 /// variable declaration.
1446 ///
1447 /// Every variable template is represented as a VarTemplateDecl and a
1448 /// VarDecl. The former contains template properties (such as
1449 /// the template parameter lists) while the latter contains the
1450 /// actual description of the template's
1451 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1452 /// VarDecl that from a VarTemplateDecl, while
1453 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1454 /// a VarDecl.
1455 VarTemplateDecl *getDescribedVarTemplate() const;
1456
1457 void setDescribedVarTemplate(VarTemplateDecl *Template);
1458
1459 // Is this variable known to have a definition somewhere in the complete
1460 // program? This may be true even if the declaration has internal linkage and
1461 // has no definition within this source file.
1462 bool isKnownToBeDefined() const;
1463
1464 // Implement isa/cast/dyncast/etc.
1465 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1466 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1467};
1468
1469class ImplicitParamDecl : public VarDecl {
1470 void anchor() override;
1471
1472public:
1473 /// Defines the kind of the implicit parameter: is this an implicit parameter
1474 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1475 /// context or something else.
1476 enum ImplicitParamKind : unsigned {
1477 /// Parameter for Objective-C 'self' argument
1478 ObjCSelf,
1479
1480 /// Parameter for Objective-C '_cmd' argument
1481 ObjCCmd,
1482
1483 /// Parameter for C++ 'this' argument
1484 CXXThis,
1485
1486 /// Parameter for C++ virtual table pointers
1487 CXXVTT,
1488
1489 /// Parameter for captured context
1490 CapturedContext,
1491
1492 /// Other implicit parameter
1493 Other,
1494 };
1495
1496 /// Create implicit parameter.
1497 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1498 SourceLocation IdLoc, IdentifierInfo *Id,
1499 QualType T, ImplicitParamKind ParamKind);
1500 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1501 ImplicitParamKind ParamKind);
1502
1503 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1504
1505 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1506 IdentifierInfo *Id, QualType Type,
1507 ImplicitParamKind ParamKind)
1508 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1509 /*TInfo=*/nullptr, SC_None) {
1510 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1511 setImplicit();
1512 }
1513
1514 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1515 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1516 SourceLocation(), /*Id=*/nullptr, Type,
1517 /*TInfo=*/nullptr, SC_None) {
1518 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1519 setImplicit();
1520 }
1521
1522 /// Returns the implicit parameter kind.
1523 ImplicitParamKind getParameterKind() const {
1524 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1525 }
1526
1527 // Implement isa/cast/dyncast/etc.
1528 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1529 static bool classofKind(Kind K) { return K == ImplicitParam; }
1530};
1531
1532/// Represents a parameter to a function.
1533class ParmVarDecl : public VarDecl {
1534public:
1535 enum { MaxFunctionScopeDepth = 255 };
1536 enum { MaxFunctionScopeIndex = 255 };
1537
1538protected:
1539 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1540 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1541 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1542 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1543 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg
== false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1543, __extension__ __PRETTY_FUNCTION__))
;
1544 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None
) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1544, __extension__ __PRETTY_FUNCTION__))
;
1545 assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false
) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1545, __extension__ __PRETTY_FUNCTION__))
;
1546 assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam ==
false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1546, __extension__ __PRETTY_FUNCTION__))
;
1547 setDefaultArg(DefArg);
1548 }
1549
1550public:
1551 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1552 SourceLocation StartLoc,
1553 SourceLocation IdLoc, IdentifierInfo *Id,
1554 QualType T, TypeSourceInfo *TInfo,
1555 StorageClass S, Expr *DefArg);
1556
1557 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1558
1559 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1560
1561 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1562 ParmVarDeclBits.IsObjCMethodParam = true;
1563 setParameterIndex(parameterIndex);
1564 }
1565
1566 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1567 assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam
) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1567, __extension__ __PRETTY_FUNCTION__))
;
1568
1569 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1570 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1571, __extension__ __PRETTY_FUNCTION__))
1571 && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1571, __extension__ __PRETTY_FUNCTION__))
;
1572
1573 setParameterIndex(parameterIndex);
1574 }
1575
1576 bool isObjCMethodParameter() const {
1577 return ParmVarDeclBits.IsObjCMethodParam;
1578 }
1579
1580 unsigned getFunctionScopeDepth() const {
1581 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1582 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1583 }
1584
1585 /// Returns the index of this parameter in its prototype or method scope.
1586 unsigned getFunctionScopeIndex() const {
1587 return getParameterIndex();
1588 }
1589
1590 ObjCDeclQualifier getObjCDeclQualifier() const {
1591 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1592 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1593 }
1594 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1595 assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam)
? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1595, __extension__ __PRETTY_FUNCTION__))
;
1596 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1597 }
1598
1599 /// True if the value passed to this parameter must undergo
1600 /// K&R-style default argument promotion:
1601 ///
1602 /// C99 6.5.2.2.
1603 /// If the expression that denotes the called function has a type
1604 /// that does not include a prototype, the integer promotions are
1605 /// performed on each argument, and arguments that have type float
1606 /// are promoted to double.
1607 bool isKNRPromoted() const {
1608 return ParmVarDeclBits.IsKNRPromoted;
1609 }
1610 void setKNRPromoted(bool promoted) {
1611 ParmVarDeclBits.IsKNRPromoted = promoted;
1612 }
1613
1614 Expr *getDefaultArg();
1615 const Expr *getDefaultArg() const {
1616 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1617 }
1618
1619 void setDefaultArg(Expr *defarg);
1620
1621 /// Retrieve the source range that covers the entire default
1622 /// argument.
1623 SourceRange getDefaultArgRange() const;
1624 void setUninstantiatedDefaultArg(Expr *arg);
1625 Expr *getUninstantiatedDefaultArg();
1626 const Expr *getUninstantiatedDefaultArg() const {
1627 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1628 }
1629
1630 /// Determines whether this parameter has a default argument,
1631 /// either parsed or not.
1632 bool hasDefaultArg() const;
1633
1634 /// Determines whether this parameter has a default argument that has not
1635 /// yet been parsed. This will occur during the processing of a C++ class
1636 /// whose member functions have default arguments, e.g.,
1637 /// @code
1638 /// class X {
1639 /// public:
1640 /// void f(int x = 17); // x has an unparsed default argument now
1641 /// }; // x has a regular default argument now
1642 /// @endcode
1643 bool hasUnparsedDefaultArg() const {
1644 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1645 }
1646
1647 bool hasUninstantiatedDefaultArg() const {
1648 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1649 }
1650
1651 /// Specify that this parameter has an unparsed default argument.
1652 /// The argument will be replaced with a real default argument via
1653 /// setDefaultArg when the class definition enclosing the function
1654 /// declaration that owns this default argument is completed.
1655 void setUnparsedDefaultArg() {
1656 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1657 }
1658
1659 bool hasInheritedDefaultArg() const {
1660 return ParmVarDeclBits.HasInheritedDefaultArg;
1661 }
1662
1663 void setHasInheritedDefaultArg(bool I = true) {
1664 ParmVarDeclBits.HasInheritedDefaultArg = I;
1665 }
1666
1667 QualType getOriginalType() const;
1668
1669 /// Determine whether this parameter is actually a function
1670 /// parameter pack.
1671 bool isParameterPack() const;
1672
1673 /// Sets the function declaration that owns this
1674 /// ParmVarDecl. Since ParmVarDecls are often created before the
1675 /// FunctionDecls that own them, this routine is required to update
1676 /// the DeclContext appropriately.
1677 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1678
1679 // Implement isa/cast/dyncast/etc.
1680 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1681 static bool classofKind(Kind K) { return K == ParmVar; }
1682
1683private:
1684 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1685
1686 void setParameterIndex(unsigned parameterIndex) {
1687 if (parameterIndex >= ParameterIndexSentinel) {
1688 setParameterIndexLarge(parameterIndex);
1689 return;
1690 }
1691
1692 ParmVarDeclBits.ParameterIndex = parameterIndex;
1693 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex
&& "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 1693, __extension__ __PRETTY_FUNCTION__))
;
1694 }
1695 unsigned getParameterIndex() const {
1696 unsigned d = ParmVarDeclBits.ParameterIndex;
1697 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1698 }
1699
1700 void setParameterIndexLarge(unsigned parameterIndex);
1701 unsigned getParameterIndexLarge() const;
1702};
1703
1704/// Represents a function declaration or definition.
1705///
1706/// Since a given function can be declared several times in a program,
1707/// there may be several FunctionDecls that correspond to that
1708/// function. Only one of those FunctionDecls will be found when
1709/// traversing the list of declarations in the context of the
1710/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1711/// contains all of the information known about the function. Other,
1712/// previous declarations of the function are available via the
1713/// getPreviousDecl() chain.
1714class FunctionDecl : public DeclaratorDecl, public DeclContext,
1715 public Redeclarable<FunctionDecl> {
1716public:
1717 /// The kind of templated function a FunctionDecl can be.
1718 enum TemplatedKind {
1719 TK_NonTemplate,
1720 TK_FunctionTemplate,
1721 TK_MemberSpecialization,
1722 TK_FunctionTemplateSpecialization,
1723 TK_DependentFunctionTemplateSpecialization
1724 };
1725
1726private:
1727 /// A new[]'d array of pointers to VarDecls for the formal
1728 /// parameters of this function. This is null if a prototype or if there are
1729 /// no formals.
1730 ParmVarDecl **ParamInfo = nullptr;
1731
1732 LazyDeclStmtPtr Body;
1733
1734 // FIXME: This can be packed into the bitfields in DeclContext.
1735 // NOTE: VC++ packs bitfields poorly if the types differ.
1736 unsigned SClass : 3;
1737 unsigned IsInline : 1;
1738 unsigned IsInlineSpecified : 1;
1739
1740protected:
1741 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1742 // CXXDeductionGuideDecl.
1743 unsigned IsExplicitSpecified : 1;
1744
1745private:
1746 unsigned IsVirtualAsWritten : 1;
1747 unsigned IsPure : 1;
1748 unsigned HasInheritedPrototype : 1;
1749 unsigned HasWrittenPrototype : 1;
1750 unsigned IsDeleted : 1;
1751 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1752
1753 /// This flag indicates whether this function is trivial for the purpose of
1754 /// calls. This is meaningful only when this function is a copy/move
1755 /// constructor or a destructor.
1756 unsigned IsTrivialForCall : 1;
1757
1758 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1759 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1760 unsigned HasImplicitReturnZero : 1;
1761 unsigned IsLateTemplateParsed : 1;
1762 unsigned IsConstexpr : 1;
1763 unsigned InstantiationIsPending : 1;
1764
1765 /// Indicates if the function uses __try.
1766 unsigned UsesSEHTry : 1;
1767
1768 /// Indicates if the function was a definition but its body was
1769 /// skipped.
1770 unsigned HasSkippedBody : 1;
1771
1772 /// Indicates if the function declaration will have a body, once we're done
1773 /// parsing it.
1774 unsigned WillHaveBody : 1;
1775
1776 /// Indicates that this function is a multiversioned function using attribute
1777 /// 'target'.
1778 unsigned IsMultiVersion : 1;
1779
1780protected:
1781 /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid
1782 /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned
1783 /// int as opposed to adding a single bit to FunctionDecl.
1784 /// Indicates that the Deduction Guide is the implicitly generated 'copy
1785 /// deduction candidate' (is used during overload resolution).
1786 unsigned IsCopyDeductionCandidate : 1;
1787
1788private:
1789
1790 /// Store the ODRHash after first calculation.
1791 unsigned HasODRHash : 1;
1792 unsigned ODRHash;
1793
1794 /// End part of this FunctionDecl's source range.
1795 ///
1796 /// We could compute the full range in getSourceRange(). However, when we're
1797 /// dealing with a function definition deserialized from a PCH/AST file,
1798 /// we can only compute the full range once the function body has been
1799 /// de-serialized, so it's far better to have the (sometimes-redundant)
1800 /// EndRangeLoc.
1801 SourceLocation EndRangeLoc;
1802
1803 /// The template or declaration that this declaration
1804 /// describes or was instantiated from, respectively.
1805 ///
1806 /// For non-templates, this value will be NULL. For function
1807 /// declarations that describe a function template, this will be a
1808 /// pointer to a FunctionTemplateDecl. For member functions
1809 /// of class template specializations, this will be a MemberSpecializationInfo
1810 /// pointer containing information about the specialization.
1811 /// For function template specializations, this will be a
1812 /// FunctionTemplateSpecializationInfo, which contains information about
1813 /// the template being specialized and the template arguments involved in
1814 /// that specialization.
1815 llvm::PointerUnion4<FunctionTemplateDecl *,
1816 MemberSpecializationInfo *,
1817 FunctionTemplateSpecializationInfo *,
1818 DependentFunctionTemplateSpecializationInfo *>
1819 TemplateOrSpecialization;
1820
1821 /// Provides source/type location info for the declaration name embedded in
1822 /// the DeclaratorDecl base class.
1823 DeclarationNameLoc DNLoc;
1824
1825 /// Specify that this function declaration is actually a function
1826 /// template specialization.
1827 ///
1828 /// \param C the ASTContext.
1829 ///
1830 /// \param Template the function template that this function template
1831 /// specialization specializes.
1832 ///
1833 /// \param TemplateArgs the template arguments that produced this
1834 /// function template specialization from the template.
1835 ///
1836 /// \param InsertPos If non-NULL, the position in the function template
1837 /// specialization set where the function template specialization data will
1838 /// be inserted.
1839 ///
1840 /// \param TSK the kind of template specialization this is.
1841 ///
1842 /// \param TemplateArgsAsWritten location info of template arguments.
1843 ///
1844 /// \param PointOfInstantiation point at which the function template
1845 /// specialization was first instantiated.
1846 void setFunctionTemplateSpecialization(ASTContext &C,
1847 FunctionTemplateDecl *Template,
1848 const TemplateArgumentList *TemplateArgs,
1849 void *InsertPos,
1850 TemplateSpecializationKind TSK,
1851 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1852 SourceLocation PointOfInstantiation);
1853
1854 /// Specify that this record is an instantiation of the
1855 /// member function FD.
1856 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1857 TemplateSpecializationKind TSK);
1858
1859 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1860
1861protected:
1862 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1863 const DeclarationNameInfo &NameInfo, QualType T,
1864 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1865 bool isConstexprSpecified)
1866 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1867 StartLoc),
1868 DeclContext(DK), redeclarable_base(C), SClass(S),
1869 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1870 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
1871 HasInheritedPrototype(false), HasWrittenPrototype(true),
1872 IsDeleted(false), IsTrivial(false), IsTrivialForCall(false),
1873 IsDefaulted(false),
1874 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1875 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1876 InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false),
1877 WillHaveBody(false), IsMultiVersion(false),
1878 IsCopyDeductionCandidate(false), HasODRHash(false), ODRHash(0),
1879 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {}
1880
1881 using redeclarable_base = Redeclarable<FunctionDecl>;
1882
1883 FunctionDecl *getNextRedeclarationImpl() override {
1884 return getNextRedeclaration();
1885 }
1886
1887 FunctionDecl *getPreviousDeclImpl() override {
1888 return getPreviousDecl();
1889 }
1890
1891 FunctionDecl *getMostRecentDeclImpl() override {
1892 return getMostRecentDecl();
1893 }
1894
1895public:
1896 friend class ASTDeclReader;
1897 friend class ASTDeclWriter;
1898
1899 using redecl_range = redeclarable_base::redecl_range;
1900 using redecl_iterator = redeclarable_base::redecl_iterator;
1901
1902 using redeclarable_base::redecls_begin;
1903 using redeclarable_base::redecls_end;
1904 using redeclarable_base::redecls;
1905 using redeclarable_base::getPreviousDecl;
1906 using redeclarable_base::getMostRecentDecl;
1907 using redeclarable_base::isFirstDecl;
1908
1909 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1910 SourceLocation StartLoc, SourceLocation NLoc,
1911 DeclarationName N, QualType T,
1912 TypeSourceInfo *TInfo,
1913 StorageClass SC,
1914 bool isInlineSpecified = false,
1915 bool hasWrittenPrototype = true,
1916 bool isConstexprSpecified = false) {
1917 DeclarationNameInfo NameInfo(N, NLoc);
1918 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1919 SC,
1920 isInlineSpecified, hasWrittenPrototype,
1921 isConstexprSpecified);
1922 }
1923
1924 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1925 SourceLocation StartLoc,
1926 const DeclarationNameInfo &NameInfo,
1927 QualType T, TypeSourceInfo *TInfo,
1928 StorageClass SC,
1929 bool isInlineSpecified,
1930 bool hasWrittenPrototype,
1931 bool isConstexprSpecified = false);
1932
1933 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1934
1935 DeclarationNameInfo getNameInfo() const {
1936 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1937 }
1938
1939 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1940 bool Qualified) const override;
1941
1942 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1943
1944 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1945
1946 // Function definitions.
1947 //
1948 // A function declaration may be:
1949 // - a non defining declaration,
1950 // - a definition. A function may be defined because:
1951 // - it has a body, or will have it in the case of late parsing.
1952 // - it has an uninstantiated body. The body does not exist because the
1953 // function is not used yet, but the declaration is considered a
1954 // definition and does not allow other definition of this function.
1955 // - it does not have a user specified body, but it does not allow
1956 // redefinition, because it is deleted/defaulted or is defined through
1957 // some other mechanism (alias, ifunc).
1958
1959 /// Returns true if the function has a body.
1960 ///
1961 /// The function body might be in any of the (re-)declarations of this
1962 /// function. The variant that accepts a FunctionDecl pointer will set that
1963 /// function declaration to the actual declaration containing the body (if
1964 /// there is one).
1965 bool hasBody(const FunctionDecl *&Definition) const;
1966
1967 bool hasBody() const override {
1968 const FunctionDecl* Definition;
1969 return hasBody(Definition);
1970 }
1971
1972 /// Returns whether the function has a trivial body that does not require any
1973 /// specific codegen.
1974 bool hasTrivialBody() const;
1975
1976 /// Returns true if the function has a definition that does not need to be
1977 /// instantiated.
1978 ///
1979 /// The variant that accepts a FunctionDecl pointer will set that function
1980 /// declaration to the declaration that is a definition (if there is one).
1981 bool isDefined(const FunctionDecl *&Definition) const;
1982
1983 virtual bool isDefined() const {
1984 const FunctionDecl* Definition;
1985 return isDefined(Definition);
1986 }
1987
1988 /// Get the definition for this declaration.
1989 FunctionDecl *getDefinition() {
1990 const FunctionDecl *Definition;
1991 if (isDefined(Definition))
1992 return const_cast<FunctionDecl *>(Definition);
1993 return nullptr;
1994 }
1995 const FunctionDecl *getDefinition() const {
1996 return const_cast<FunctionDecl *>(this)->getDefinition();
1997 }
1998
1999 /// Retrieve the body (definition) of the function. The function body might be
2000 /// in any of the (re-)declarations of this function. The variant that accepts
2001 /// a FunctionDecl pointer will set that function declaration to the actual
2002 /// declaration containing the body (if there is one).
2003 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
2004 /// unnecessary AST de-serialization of the body.
2005 Stmt *getBody(const FunctionDecl *&Definition) const;
2006
2007 Stmt *getBody() const override {
2008 const FunctionDecl* Definition;
2009 return getBody(Definition);
2010 }
2011
2012 /// Returns whether this specific declaration of the function is also a
2013 /// definition that does not contain uninstantiated body.
2014 ///
2015 /// This does not determine whether the function has been defined (e.g., in a
2016 /// previous definition); for that information, use isDefined.
2017 bool isThisDeclarationADefinition() const {
2018 return IsDeleted || IsDefaulted || Body || HasSkippedBody ||
2019 IsLateTemplateParsed || WillHaveBody || hasDefiningAttr();
2020 }
2021
2022 /// Returns whether this specific declaration of the function has a body.
2023 bool doesThisDeclarationHaveABody() const {
2024 return Body || IsLateTemplateParsed;
2025 }
2026
2027 void setBody(Stmt *B);
2028 void setLazyBody(uint64_t Offset) { Body = Offset; }
2029
2030 /// Whether this function is variadic.
2031 bool isVariadic() const;
2032
2033 /// Whether this function is marked as virtual explicitly.
2034 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
2035 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
2036
2037 /// Whether this virtual function is pure, i.e. makes the containing class
2038 /// abstract.
2039 bool isPure() const { return IsPure; }
2040 void setPure(bool P = true);
2041
2042 /// Whether this templated function will be late parsed.
2043 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
2044 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
2045
2046 /// Whether this function is "trivial" in some specialized C++ senses.
2047 /// Can only be true for default constructors, copy constructors,
2048 /// copy assignment operators, and destructors. Not meaningful until
2049 /// the class has been fully built by Sema.
2050 bool isTrivial() const { return IsTrivial; }
2051 void setTrivial(bool IT) { IsTrivial = IT; }
2052
2053 bool isTrivialForCall() const { return IsTrivialForCall; }
2054 void setTrivialForCall(bool IT) { IsTrivialForCall = IT; }
2055
2056 /// Whether this function is defaulted per C++0x. Only valid for
2057 /// special member functions.
2058 bool isDefaulted() const { return IsDefaulted; }
2059 void setDefaulted(bool D = true) { IsDefaulted = D; }
2060
2061 /// Whether this function is explicitly defaulted per C++0x. Only valid
2062 /// for special member functions.
2063 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
2064 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
2065
2066 /// Whether falling off this function implicitly returns null/zero.
2067 /// If a more specific implicit return value is required, front-ends
2068 /// should synthesize the appropriate return statements.
2069 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
2070 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
2071
2072 /// Whether this function has a prototype, either because one
2073 /// was explicitly written or because it was "inherited" by merging
2074 /// a declaration without a prototype with a declaration that has a
2075 /// prototype.
2076 bool hasPrototype() const {
2077 return HasWrittenPrototype || HasInheritedPrototype;
2078 }
2079
2080 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
2081
2082 /// Whether this function inherited its prototype from a
2083 /// previous declaration.
2084 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
2085 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
2086
2087 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2088 bool isConstexpr() const { return IsConstexpr; }
2089 void setConstexpr(bool IC) { IsConstexpr = IC; }
2090
2091 /// Whether the instantiation of this function is pending.
2092 /// This bit is set when the decision to instantiate this function is made
2093 /// and unset if and when the function body is created. That leaves out
2094 /// cases where instantiation did not happen because the template definition
2095 /// was not seen in this TU. This bit remains set in those cases, under the
2096 /// assumption that the instantiation will happen in some other TU.
2097 bool instantiationIsPending() const { return InstantiationIsPending; }
2098 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
2099
2100 /// Indicates the function uses __try.
2101 bool usesSEHTry() const { return UsesSEHTry; }
2102 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
2103
2104 /// Whether this function has been deleted.
2105 ///
2106 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2107 /// acts like a normal function, except that it cannot actually be
2108 /// called or have its address taken. Deleted functions are
2109 /// typically used in C++ overload resolution to attract arguments
2110 /// whose type or lvalue/rvalue-ness would permit the use of a
2111 /// different overload that would behave incorrectly. For example,
2112 /// one might use deleted functions to ban implicit conversion from
2113 /// a floating-point number to an Integer type:
2114 ///
2115 /// @code
2116 /// struct Integer {
2117 /// Integer(long); // construct from a long
2118 /// Integer(double) = delete; // no construction from float or double
2119 /// Integer(long double) = delete; // no construction from long double
2120 /// };
2121 /// @endcode
2122 // If a function is deleted, its first declaration must be.
2123 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
2124 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
2125 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
2126
2127 /// Determines whether this function is "main", which is the
2128 /// entry point into an executable program.
2129 bool isMain() const;
2130
2131 /// Determines whether this function is a MSVCRT user defined entry
2132 /// point.
2133 bool isMSVCRTEntryPoint() const;
2134
2135 /// Determines whether this operator new or delete is one
2136 /// of the reserved global placement operators:
2137 /// void *operator new(size_t, void *);
2138 /// void *operator new[](size_t, void *);
2139 /// void operator delete(void *, void *);
2140 /// void operator delete[](void *, void *);
2141 /// These functions have special behavior under [new.delete.placement]:
2142 /// These functions are reserved, a C++ program may not define
2143 /// functions that displace the versions in the Standard C++ library.
2144 /// The provisions of [basic.stc.dynamic] do not apply to these
2145 /// reserved placement forms of operator new and operator delete.
2146 ///
2147 /// This function must be an allocation or deallocation function.
2148 bool isReservedGlobalPlacementOperator() const;
2149
2150 /// Determines whether this function is one of the replaceable
2151 /// global allocation functions:
2152 /// void *operator new(size_t);
2153 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2154 /// void *operator new[](size_t);
2155 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2156 /// void operator delete(void *) noexcept;
2157 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2158 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2159 /// void operator delete[](void *) noexcept;
2160 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2161 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2162 /// These functions have special behavior under C++1y [expr.new]:
2163 /// An implementation is allowed to omit a call to a replaceable global
2164 /// allocation function. [...]
2165 ///
2166 /// If this function is an aligned allocation/deallocation function, return
2167 /// true through IsAligned.
2168 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2169
2170 /// Determine whether this is a destroying operator delete.
2171 bool isDestroyingOperatorDelete() const;
2172
2173 /// Compute the language linkage.
2174 LanguageLinkage getLanguageLinkage() const;
2175
2176 /// Determines whether this function is a function with
2177 /// external, C linkage.
2178 bool isExternC() const;
2179
2180 /// Determines whether this function's context is, or is nested within,
2181 /// a C++ extern "C" linkage spec.
2182 bool isInExternCContext() const;
2183
2184 /// Determines whether this function's context is, or is nested within,
2185 /// a C++ extern "C++" linkage spec.
2186 bool isInExternCXXContext() const;
2187
2188 /// Determines whether this is a global function.
2189 bool isGlobal() const;
2190
2191 /// Determines whether this function is known to be 'noreturn', through
2192 /// an attribute on its declaration or its type.
2193 bool isNoReturn() const;
2194
2195 /// True if the function was a definition but its body was skipped.
2196 bool hasSkippedBody() const { return HasSkippedBody; }
2197 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2198
2199 /// True if this function will eventually have a body, once it's fully parsed.
2200 bool willHaveBody() const { return WillHaveBody; }
2201 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2202
2203 /// True if this function is considered a multiversioned function.
2204 bool isMultiVersion() const { return getCanonicalDecl()->IsMultiVersion; }
2205
2206 /// Sets the multiversion state for this declaration and all of its
2207 /// redeclarations.
2208 void setIsMultiVersion(bool V = true) {
2209 getCanonicalDecl()->IsMultiVersion = V;
2210 }
2211
2212 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2213
2214 FunctionDecl *getCanonicalDecl() override;
2215 const FunctionDecl *getCanonicalDecl() const {
2216 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2217 }
2218
2219 unsigned getBuiltinID() const;
2220
2221 // ArrayRef interface to parameters.
2222 ArrayRef<ParmVarDecl *> parameters() const {
2223 return {ParamInfo, getNumParams()};
2224 }
2225 MutableArrayRef<ParmVarDecl *> parameters() {
2226 return {ParamInfo, getNumParams()};
2227 }
2228
2229 // Iterator access to formal parameters.
2230 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2231 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2232
2233 bool param_empty() const { return parameters().empty(); }
2234 param_iterator param_begin() { return parameters().begin(); }
2235 param_iterator param_end() { return parameters().end(); }
2236 param_const_iterator param_begin() const { return parameters().begin(); }
2237 param_const_iterator param_end() const { return parameters().end(); }
2238 size_t param_size() const { return parameters().size(); }
2239
2240 /// Return the number of parameters this function must have based on its
2241 /// FunctionType. This is the length of the ParamInfo array after it has been
2242 /// created.
2243 unsigned getNumParams() const;
2244
2245 const ParmVarDecl *getParamDecl(unsigned i) const {
2246 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2246, __extension__ __PRETTY_FUNCTION__))
;
31
Within the expansion of the macro 'assert':
a
Assuming the condition is true
2247 return ParamInfo[i];
2248 }
2249 ParmVarDecl *getParamDecl(unsigned i) {
2250 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2250, __extension__ __PRETTY_FUNCTION__))
;
2251 return ParamInfo[i];
2252 }
2253 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2254 setParams(getASTContext(), NewParamInfo);
2255 }
2256
2257 /// Returns the minimum number of arguments needed to call this function. This
2258 /// may be fewer than the number of function parameters, if some of the
2259 /// parameters have default arguments (in C++).
2260 unsigned getMinRequiredArguments() const;
2261
2262 QualType getReturnType() const {
2263 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2263, __extension__ __PRETTY_FUNCTION__))
;
2264 return getType()->getAs<FunctionType>()->getReturnType();
2265 }
2266
2267 /// Attempt to compute an informative source range covering the
2268 /// function return type. This may omit qualifiers and other information with
2269 /// limited representation in the AST.
2270 SourceRange getReturnTypeSourceRange() const;
2271
2272 /// Attempt to compute an informative source range covering the
2273 /// function exception specification, if any.
2274 SourceRange getExceptionSpecSourceRange() const;
2275
2276 /// Determine the type of an expression that calls this function.
2277 QualType getCallResultType() const {
2278 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2278, __extension__ __PRETTY_FUNCTION__))
;
2279 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2280 }
2281
2282 /// Returns the WarnUnusedResultAttr that is either declared on this
2283 /// function, or its return type declaration.
2284 const Attr *getUnusedResultAttr() const;
2285
2286 /// Returns true if this function or its return type has the
2287 /// warn_unused_result attribute.
2288 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2289
2290 /// Returns the storage class as written in the source. For the
2291 /// computed linkage of symbol, see getLinkage.
2292 StorageClass getStorageClass() const { return StorageClass(SClass); }
2293
2294 /// Determine whether the "inline" keyword was specified for this
2295 /// function.
2296 bool isInlineSpecified() const { return IsInlineSpecified; }
2297
2298 /// Set whether the "inline" keyword was specified for this function.
2299 void setInlineSpecified(bool I) {
2300 IsInlineSpecified = I;
2301 IsInline = I;
2302 }
2303
2304 /// Flag that this function is implicitly inline.
2305 void setImplicitlyInline() {
2306 IsInline = true;
2307 }
2308
2309 /// Determine whether this function should be inlined, because it is
2310 /// either marked "inline" or "constexpr" or is a member function of a class
2311 /// that was defined in the class body.
2312 bool isInlined() const { return IsInline; }
2313
2314 bool isInlineDefinitionExternallyVisible() const;
2315
2316 bool isMSExternInline() const;
2317
2318 bool doesDeclarationForceExternallyVisibleDefinition() const;
2319
2320 /// Whether this function declaration represents an C++ overloaded
2321 /// operator, e.g., "operator+".
2322 bool isOverloadedOperator() const {
2323 return getOverloadedOperator() != OO_None;
2324 }
2325
2326 OverloadedOperatorKind getOverloadedOperator() const;
2327
2328 const IdentifierInfo *getLiteralIdentifier() const;
2329
2330 /// If this function is an instantiation of a member function
2331 /// of a class template specialization, retrieves the function from
2332 /// which it was instantiated.
2333 ///
2334 /// This routine will return non-NULL for (non-templated) member
2335 /// functions of class templates and for instantiations of function
2336 /// templates. For example, given:
2337 ///
2338 /// \code
2339 /// template<typename T>
2340 /// struct X {
2341 /// void f(T);
2342 /// };
2343 /// \endcode
2344 ///
2345 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2346 /// whose parent is the class template specialization X<int>. For
2347 /// this declaration, getInstantiatedFromFunction() will return
2348 /// the FunctionDecl X<T>::A. When a complete definition of
2349 /// X<int>::A is required, it will be instantiated from the
2350 /// declaration returned by getInstantiatedFromMemberFunction().
2351 FunctionDecl *getInstantiatedFromMemberFunction() const;
2352
2353 /// What kind of templated function this is.
2354 TemplatedKind getTemplatedKind() const;
2355
2356 /// If this function is an instantiation of a member function of a
2357 /// class template specialization, retrieves the member specialization
2358 /// information.
2359 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2360
2361 /// Specify that this record is an instantiation of the
2362 /// member function FD.
2363 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2364 TemplateSpecializationKind TSK) {
2365 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2366 }
2367
2368 /// Retrieves the function template that is described by this
2369 /// function declaration.
2370 ///
2371 /// Every function template is represented as a FunctionTemplateDecl
2372 /// and a FunctionDecl (or something derived from FunctionDecl). The
2373 /// former contains template properties (such as the template
2374 /// parameter lists) while the latter contains the actual
2375 /// description of the template's
2376 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2377 /// FunctionDecl that describes the function template,
2378 /// getDescribedFunctionTemplate() retrieves the
2379 /// FunctionTemplateDecl from a FunctionDecl.
2380 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2381
2382 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2383
2384 /// Determine whether this function is a function template
2385 /// specialization.
2386 bool isFunctionTemplateSpecialization() const {
2387 return getPrimaryTemplate() != nullptr;
2388 }
2389
2390 /// Retrieve the class scope template pattern that this function
2391 /// template specialization is instantiated from.
2392 FunctionDecl *getClassScopeSpecializationPattern() const;
2393
2394 /// If this function is actually a function template specialization,
2395 /// retrieve information about this function template specialization.
2396 /// Otherwise, returns NULL.
2397 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2398
2399 /// Determines whether this function is a function template
2400 /// specialization or a member of a class template specialization that can
2401 /// be implicitly instantiated.
2402 bool isImplicitlyInstantiable() const;
2403
2404 /// Determines if the given function was instantiated from a
2405 /// function template.
2406 bool isTemplateInstantiation() const;
2407
2408 /// Retrieve the function declaration from which this function could
2409 /// be instantiated, if it is an instantiation (rather than a non-template
2410 /// or a specialization, for example).
2411 FunctionDecl *getTemplateInstantiationPattern() const;
2412
2413 /// Retrieve the primary template that this function template
2414 /// specialization either specializes or was instantiated from.
2415 ///
2416 /// If this function declaration is not a function template specialization,
2417 /// returns NULL.
2418 FunctionTemplateDecl *getPrimaryTemplate() const;
2419
2420 /// Retrieve the template arguments used to produce this function
2421 /// template specialization from the primary template.
2422 ///
2423 /// If this function declaration is not a function template specialization,
2424 /// returns NULL.
2425 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2426
2427 /// Retrieve the template argument list as written in the sources,
2428 /// if any.
2429 ///
2430 /// If this function declaration is not a function template specialization
2431 /// or if it had no explicit template argument list, returns NULL.
2432 /// Note that it an explicit template argument list may be written empty,
2433 /// e.g., template<> void foo<>(char* s);
2434 const ASTTemplateArgumentListInfo*
2435 getTemplateSpecializationArgsAsWritten() const;
2436
2437 /// Specify that this function declaration is actually a function
2438 /// template specialization.
2439 ///
2440 /// \param Template the function template that this function template
2441 /// specialization specializes.
2442 ///
2443 /// \param TemplateArgs the template arguments that produced this
2444 /// function template specialization from the template.
2445 ///
2446 /// \param InsertPos If non-NULL, the position in the function template
2447 /// specialization set where the function template specialization data will
2448 /// be inserted.
2449 ///
2450 /// \param TSK the kind of template specialization this is.
2451 ///
2452 /// \param TemplateArgsAsWritten location info of template arguments.
2453 ///
2454 /// \param PointOfInstantiation point at which the function template
2455 /// specialization was first instantiated.
2456 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2457 const TemplateArgumentList *TemplateArgs,
2458 void *InsertPos,
2459 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2460 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2461 SourceLocation PointOfInstantiation = SourceLocation()) {
2462 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2463 InsertPos, TSK, TemplateArgsAsWritten,
2464 PointOfInstantiation);
2465 }
2466
2467 /// Specifies that this function declaration is actually a
2468 /// dependent function template specialization.
2469 void setDependentTemplateSpecialization(ASTContext &Context,
2470 const UnresolvedSetImpl &Templates,
2471 const TemplateArgumentListInfo &TemplateArgs);
2472
2473 DependentFunctionTemplateSpecializationInfo *
2474 getDependentSpecializationInfo() const;
2475
2476 /// Determine what kind of template instantiation this function
2477 /// represents.
2478 TemplateSpecializationKind getTemplateSpecializationKind() const;
2479
2480 /// Determine what kind of template instantiation this function
2481 /// represents.
2482 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2483 SourceLocation PointOfInstantiation = SourceLocation());
2484
2485 /// Retrieve the (first) point of instantiation of a function template
2486 /// specialization or a member of a class template specialization.
2487 ///
2488 /// \returns the first point of instantiation, if this function was
2489 /// instantiated from a template; otherwise, returns an invalid source
2490 /// location.
2491 SourceLocation getPointOfInstantiation() const;
2492
2493 /// Determine whether this is or was instantiated from an out-of-line
2494 /// definition of a member function.
2495 bool isOutOfLine() const override;
2496
2497 /// Identify a memory copying or setting function.
2498 /// If the given function is a memory copy or setting function, returns
2499 /// the corresponding Builtin ID. If the function is not a memory function,
2500 /// returns 0.
2501 unsigned getMemoryFunctionKind() const;
2502
2503 /// Returns ODRHash of the function. This value is calculated and
2504 /// stored on first call, then the stored value returned on the other calls.
2505 unsigned getODRHash();
2506
2507 /// Returns cached ODRHash of the function. This must have been previously
2508 /// computed and stored.
2509 unsigned getODRHash() const;
2510
2511 // Implement isa/cast/dyncast/etc.
2512 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2513 static bool classofKind(Kind K) {
2514 return K >= firstFunction && K <= lastFunction;
2515 }
2516 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2517 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2518 }
2519 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2520 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2521 }
2522};
2523
2524/// Represents a member of a struct/union/class.
2525class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2526 unsigned BitField : 1;
2527 unsigned Mutable : 1;
2528 mutable unsigned CachedFieldIndex : 30;
2529
2530 /// The kinds of value we can store in InitializerOrBitWidth.
2531 ///
2532 /// Note that this is compatible with InClassInitStyle except for
2533 /// ISK_CapturedVLAType.
2534 enum InitStorageKind {
2535 /// If the pointer is null, there's nothing special. Otherwise,
2536 /// this is a bitfield and the pointer is the Expr* storing the
2537 /// bit-width.
2538 ISK_NoInit = (unsigned) ICIS_NoInit,
2539
2540 /// The pointer is an (optional due to delayed parsing) Expr*
2541 /// holding the copy-initializer.
2542 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2543
2544 /// The pointer is an (optional due to delayed parsing) Expr*
2545 /// holding the list-initializer.
2546 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2547
2548 /// The pointer is a VariableArrayType* that's been captured;
2549 /// the enclosing context is a lambda or captured statement.
2550 ISK_CapturedVLAType,
2551 };
2552
2553 /// If this is a bitfield with a default member initializer, this
2554 /// structure is used to represent the two expressions.
2555 struct InitAndBitWidth {
2556 Expr *Init;
2557 Expr *BitWidth;
2558 };
2559
2560 /// Storage for either the bit-width, the in-class initializer, or
2561 /// both (via InitAndBitWidth), or the captured variable length array bound.
2562 ///
2563 /// If the storage kind is ISK_InClassCopyInit or
2564 /// ISK_InClassListInit, but the initializer is null, then this
2565 /// field has an in-class initializer that has not yet been parsed
2566 /// and attached.
2567 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2568 // overwhelmingly common case that we have none of these things.
2569 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2570
2571protected:
2572 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2573 SourceLocation IdLoc, IdentifierInfo *Id,
2574 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2575 InClassInitStyle InitStyle)
2576 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2577 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2578 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2579 if (BW)
2580 setBitWidth(BW);
2581 }
2582
2583public:
2584 friend class ASTDeclReader;
2585 friend class ASTDeclWriter;
2586
2587 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2588 SourceLocation StartLoc, SourceLocation IdLoc,
2589 IdentifierInfo *Id, QualType T,
2590 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2591 InClassInitStyle InitStyle);
2592
2593 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2594
2595 /// Returns the index of this field within its record,
2596 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2597 unsigned getFieldIndex() const;
2598
2599 /// Determines whether this field is mutable (C++ only).
2600 bool isMutable() const { return Mutable; }
2601
2602 /// Determines whether this field is a bitfield.
2603 bool isBitField() const { return BitField; }
2604
2605 /// Determines whether this is an unnamed bitfield.
2606 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2607
2608 /// Determines whether this field is a
2609 /// representative for an anonymous struct or union. Such fields are
2610 /// unnamed and are implicitly generated by the implementation to
2611 /// store the data for the anonymous union or struct.
2612 bool isAnonymousStructOrUnion() const;
2613
2614 Expr *getBitWidth() const {
2615 if (!BitField)
2616 return nullptr;
2617 void *Ptr = InitStorage.getPointer();
2618 if (getInClassInitStyle())
2619 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2620 return static_cast<Expr*>(Ptr);
2621 }
2622
2623 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2624
2625 /// Set the bit-field width for this member.
2626 // Note: used by some clients (i.e., do not remove it).
2627 void setBitWidth(Expr *Width) {
2628 assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2629, __extension__ __PRETTY_FUNCTION__))
2629 "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2629, __extension__ __PRETTY_FUNCTION__))
;
2630 assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified"
) ? void (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2630, __extension__ __PRETTY_FUNCTION__))
;
2631 InitStorage.setPointer(
2632 InitStorage.getInt()
2633 ? new (getASTContext())
2634 InitAndBitWidth{getInClassInitializer(), Width}
2635 : static_cast<void*>(Width));
2636 BitField = true;
2637 }
2638
2639 /// Remove the bit-field width from this member.
2640 // Note: used by some clients (i.e., do not remove it).
2641 void removeBitWidth() {
2642 assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove"
) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2642, __extension__ __PRETTY_FUNCTION__))
;
2643 InitStorage.setPointer(getInClassInitializer());
2644 BitField = false;
2645 }
2646
2647 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2648 /// at all and instead act as a separator between contiguous runs of other
2649 /// bit-fields.
2650 bool isZeroLengthBitField(const ASTContext &Ctx) const;
2651
2652 /// Get the kind of (C++11) default member initializer that this field has.
2653 InClassInitStyle getInClassInitStyle() const {
2654 InitStorageKind storageKind = InitStorage.getInt();
2655 return (storageKind == ISK_CapturedVLAType
2656 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2657 }
2658
2659 /// Determine whether this member has a C++11 default member initializer.
2660 bool hasInClassInitializer() const {
2661 return getInClassInitStyle() != ICIS_NoInit;
2662 }
2663
2664 /// Get the C++11 default member initializer for this member, or null if one
2665 /// has not been set. If a valid declaration has a default member initializer,
2666 /// but this returns null, then we have not parsed and attached it yet.
2667 Expr *getInClassInitializer() const {
2668 if (!hasInClassInitializer())
2669 return nullptr;
2670 void *Ptr = InitStorage.getPointer();
2671 if (BitField)
2672 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2673 return static_cast<Expr*>(Ptr);
2674 }
2675
2676 /// Set the C++11 in-class initializer for this member.
2677 void setInClassInitializer(Expr *Init) {
2678 assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() &&
!getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2678, __extension__ __PRETTY_FUNCTION__))
;
2679 if (BitField)
2680 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2681 else
2682 InitStorage.setPointer(Init);
2683 }
2684
2685 /// Remove the C++11 in-class initializer from this member.
2686 void removeInClassInitializer() {
2687 assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() &&
"no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2687, __extension__ __PRETTY_FUNCTION__))
;
2688 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2689 }
2690
2691 /// Determine whether this member captures the variable length array
2692 /// type.
2693 bool hasCapturedVLAType() const {
2694 return InitStorage.getInt() == ISK_CapturedVLAType;
2695 }
2696
2697 /// Get the captured variable length array type.
2698 const VariableArrayType *getCapturedVLAType() const {
2699 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2700 InitStorage.getPointer())
2701 : nullptr;
2702 }
2703
2704 /// Set the captured variable length array type for this field.
2705 void setCapturedVLAType(const VariableArrayType *VLAType);
2706
2707 /// Returns the parent of this field declaration, which
2708 /// is the struct in which this field is defined.
2709 const RecordDecl *getParent() const {
2710 return cast<RecordDecl>(getDeclContext());
2711 }
2712
2713 RecordDecl *getParent() {
2714 return cast<RecordDecl>(getDeclContext());
2715 }
2716
2717 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2718
2719 /// Retrieves the canonical declaration of this field.
2720 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2721 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2722
2723 // Implement isa/cast/dyncast/etc.
2724 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2725 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2726};
2727
2728/// An instance of this object exists for each enum constant
2729/// that is defined. For example, in "enum X {a,b}", each of a/b are
2730/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2731/// TagType for the X EnumDecl.
2732class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2733 Stmt *Init; // an integer constant expression
2734 llvm::APSInt Val; // The value.
2735
2736protected:
2737 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2738 IdentifierInfo *Id, QualType T, Expr *E,
2739 const llvm::APSInt &V)
2740 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2741
2742public:
2743 friend class StmtIteratorBase;
2744
2745 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2746 SourceLocation L, IdentifierInfo *Id,
2747 QualType T, Expr *E,
2748 const llvm::APSInt &V);
2749 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2750
2751 const Expr *getInitExpr() const { return (const Expr*) Init; }
2752 Expr *getInitExpr() { return (Expr*) Init; }
2753 const llvm::APSInt &getInitVal() const { return Val; }
2754
2755 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2756 void setInitVal(const llvm::APSInt &V) { Val = V; }
2757
2758 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2759
2760 /// Retrieves the canonical declaration of this enumerator.
2761 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2762 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2763
2764 // Implement isa/cast/dyncast/etc.
2765 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2766 static bool classofKind(Kind K) { return K == EnumConstant; }
2767};
2768
2769/// Represents a field injected from an anonymous union/struct into the parent
2770/// scope. These are always implicit.
2771class IndirectFieldDecl : public ValueDecl,
2772 public Mergeable<IndirectFieldDecl> {
2773 NamedDecl **Chaining;
2774 unsigned ChainingSize;
2775
2776 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2777 DeclarationName N, QualType T,
2778 MutableArrayRef<NamedDecl *> CH);
2779
2780 void anchor() override;
2781
2782public:
2783 friend class ASTDeclReader;
2784
2785 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2786 SourceLocation L, IdentifierInfo *Id,
2787 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2788
2789 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2790
2791 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2792
2793 ArrayRef<NamedDecl *> chain() const {
2794 return llvm::makeArrayRef(Chaining, ChainingSize);
2795 }
2796 chain_iterator chain_begin() const { return chain().begin(); }
2797 chain_iterator chain_end() const { return chain().end(); }
2798
2799 unsigned getChainingSize() const { return ChainingSize; }
2800
2801 FieldDecl *getAnonField() const {
2802 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2802, __extension__ __PRETTY_FUNCTION__))
;
2803 return cast<FieldDecl>(chain().back());
2804 }
2805
2806 VarDecl *getVarDecl() const {
2807 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 2807, __extension__ __PRETTY_FUNCTION__))
;
2808 return dyn_cast<VarDecl>(chain().front());
2809 }
2810
2811 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2812 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2813
2814 // Implement isa/cast/dyncast/etc.
2815 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2816 static bool classofKind(Kind K) { return K == IndirectField; }
2817};
2818
2819/// Represents a declaration of a type.
2820class TypeDecl : public NamedDecl {
2821 friend class ASTContext;
2822
2823 /// This indicates the Type object that represents
2824 /// this TypeDecl. It is a cache maintained by
2825 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2826 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2827 mutable const Type *TypeForDecl = nullptr;
2828
2829 /// The start of the source range for this declaration.
2830 SourceLocation LocStart;
2831
2832 void anchor() override;
2833
2834protected:
2835 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2836 SourceLocation StartL = SourceLocation())
2837 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2838
2839public:
2840 // Low-level accessor. If you just want the type defined by this node,
2841 // check out ASTContext::getTypeDeclType or one of
2842 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2843 // already know the specific kind of node this is.
2844 const Type *getTypeForDecl() const { return TypeForDecl; }
2845 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2846
2847 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2848 void setLocStart(SourceLocation L) { LocStart = L; }
2849 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2850 if (LocStart.isValid())
2851 return SourceRange(LocStart, getLocation());
2852 else
2853 return SourceRange(getLocation());
2854 }
2855
2856 // Implement isa/cast/dyncast/etc.
2857 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2858 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2859};
2860
2861/// Base class for declarations which introduce a typedef-name.
2862class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2863 struct LLVM_ALIGNAS(8)alignas(8) ModedTInfo {
2864 TypeSourceInfo *first;
2865 QualType second;
2866 };
2867
2868 /// If int part is 0, we have not computed IsTransparentTag.
2869 /// Otherwise, IsTransparentTag is (getInt() >> 1).
2870 mutable llvm::PointerIntPair<
2871 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
2872 MaybeModedTInfo;
2873
2874 void anchor() override;
2875
2876protected:
2877 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2878 SourceLocation StartLoc, SourceLocation IdLoc,
2879 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2880 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2881 MaybeModedTInfo(TInfo, 0) {}
2882
2883 using redeclarable_base = Redeclarable<TypedefNameDecl>;
2884
2885 TypedefNameDecl *getNextRedeclarationImpl() override {
2886 return getNextRedeclaration();
2887 }
2888
2889 TypedefNameDecl *getPreviousDeclImpl() override {
2890 return getPreviousDecl();
2891 }
2892
2893 TypedefNameDecl *getMostRecentDeclImpl() override {
2894 return getMostRecentDecl();
2895 }
2896
2897public:
2898 using redecl_range = redeclarable_base::redecl_range;
2899 using redecl_iterator = redeclarable_base::redecl_iterator;
2900
2901 using redeclarable_base::redecls_begin;
2902 using redeclarable_base::redecls_end;
2903 using redeclarable_base::redecls;
2904 using redeclarable_base::getPreviousDecl;
2905 using redeclarable_base::getMostRecentDecl;
2906 using redeclarable_base::isFirstDecl;
2907
2908 bool isModed() const {
2909 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
2910 }
2911
2912 TypeSourceInfo *getTypeSourceInfo() const {
2913 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
2914 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
2915 }
2916
2917 QualType getUnderlyingType() const {
2918 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
2919 : MaybeModedTInfo.getPointer()
2920 .get<TypeSourceInfo *>()
2921 ->getType();
2922 }
2923
2924 void setTypeSourceInfo(TypeSourceInfo *newType) {
2925 MaybeModedTInfo.setPointer(newType);
2926 }
2927
2928 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2929 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
2930 ModedTInfo({unmodedTSI, modedTy}));
2931 }
2932
2933 /// Retrieves the canonical declaration of this typedef-name.
2934 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2935 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2936
2937 /// Retrieves the tag declaration for which this is the typedef name for
2938 /// linkage purposes, if any.
2939 ///
2940 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2941 /// this typedef declaration.
2942 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2943
2944 /// Determines if this typedef shares a name and spelling location with its
2945 /// underlying tag type, as is the case with the NS_ENUM macro.
2946 bool isTransparentTag() const {
2947 if (MaybeModedTInfo.getInt())
2948 return MaybeModedTInfo.getInt() & 0x2;
2949 return isTransparentTagSlow();
2950 }
2951
2952 // Implement isa/cast/dyncast/etc.
2953 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2954 static bool classofKind(Kind K) {
2955 return K >= firstTypedefName && K <= lastTypedefName;
2956 }
2957
2958private:
2959 bool isTransparentTagSlow() const;
2960};
2961
2962/// Represents the declaration of a typedef-name via the 'typedef'
2963/// type specifier.
2964class TypedefDecl : public TypedefNameDecl {
2965 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2966 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2967 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2968
2969public:
2970 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2971 SourceLocation StartLoc, SourceLocation IdLoc,
2972 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2973 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2974
2975 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2976
2977 // Implement isa/cast/dyncast/etc.
2978 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2979 static bool classofKind(Kind K) { return K == Typedef; }
2980};
2981
2982/// Represents the declaration of a typedef-name via a C++11
2983/// alias-declaration.
2984class TypeAliasDecl : public TypedefNameDecl {
2985 /// The template for which this is the pattern, if any.
2986 TypeAliasTemplateDecl *Template;
2987
2988 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2989 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2990 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2991 Template(nullptr) {}
2992
2993public:
2994 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2995 SourceLocation StartLoc, SourceLocation IdLoc,
2996 IdentifierInfo *Id, TypeSourceInfo *TInfo);
2997 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2998
2999 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3000
3001 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3002 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3003
3004 // Implement isa/cast/dyncast/etc.
3005 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3006 static bool classofKind(Kind K) { return K == TypeAlias; }
3007};
3008
3009/// Represents the declaration of a struct/union/class/enum.
3010class TagDecl
3011 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
3012public:
3013 // This is really ugly.
3014 using TagKind = TagTypeKind;
3015
3016private:
3017 // FIXME: This can be packed into the bitfields in Decl.
3018 /// The TagKind enum.
3019 unsigned TagDeclKind : 3;
3020
3021 /// True if this is a definition ("struct foo {};"), false if it is a
3022 /// declaration ("struct foo;"). It is not considered a definition
3023 /// until the definition has been fully processed.
3024 unsigned IsCompleteDefinition : 1;
3025
3026protected:
3027 /// True if this is currently being defined.
3028 unsigned IsBeingDefined : 1;
3029
3030private:
3031 /// True if this tag declaration is "embedded" (i.e., defined or declared
3032 /// for the very first time) in the syntax of a declarator.
3033 unsigned IsEmbeddedInDeclarator : 1;
3034
3035 /// True if this tag is free standing, e.g. "struct foo;".
3036 unsigned IsFreeStanding : 1;
3037
3038protected:
3039 // These are used by (and only defined for) EnumDecl.
3040 unsigned NumPositiveBits : 8;
3041 unsigned NumNegativeBits : 8;
3042
3043 /// True if this tag declaration is a scoped enumeration. Only
3044 /// possible in C++11 mode.
3045 unsigned IsScoped : 1;
3046
3047 /// If this tag declaration is a scoped enum,
3048 /// then this is true if the scoped enum was declared using the class
3049 /// tag, false if it was declared with the struct tag. No meaning is
3050 /// associated if this tag declaration is not a scoped enum.
3051 unsigned IsScopedUsingClassTag : 1;
3052
3053 /// True if this is an enumeration with fixed underlying type. Only
3054 /// possible in C++11, Microsoft extensions, or Objective C mode.
3055 unsigned IsFixed : 1;
3056
3057 /// Indicates whether it is possible for declarations of this kind
3058 /// to have an out-of-date definition.
3059 ///
3060 /// This option is only enabled when modules are enabled.
3061 unsigned MayHaveOutOfDateDef : 1;
3062
3063 /// Has the full definition of this type been required by a use somewhere in
3064 /// the TU.
3065 unsigned IsCompleteDefinitionRequired : 1;
3066
3067private:
3068 SourceRange BraceRange;
3069
3070 // A struct representing syntactic qualifier info,
3071 // to be used for the (uncommon) case of out-of-line declarations.
3072 using ExtInfo = QualifierInfo;
3073
3074 /// If the (out-of-line) tag declaration name
3075 /// is qualified, it points to the qualifier info (nns and range);
3076 /// otherwise, if the tag declaration is anonymous and it is part of
3077 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3078 /// otherwise, if the tag declaration is anonymous and it is used as a
3079 /// declaration specifier for variables, it points to the first VarDecl (used
3080 /// for mangling);
3081 /// otherwise, it is a null (TypedefNameDecl) pointer.
3082 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3083
3084 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3085 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3086 const ExtInfo *getExtInfo() const {
3087 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3088 }
3089
3090protected:
3091 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3092 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3093 SourceLocation StartL)
3094 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
3095 TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
3096 IsEmbeddedInDeclarator(false), IsFreeStanding(false),
3097 IsCompleteDefinitionRequired(false),
3098 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
3099 assert((DK != Enum || TK == TTK_Enum) &&(static_cast <bool> ((DK != Enum || TK == TTK_Enum) &&
"EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail
("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 3100, __extension__ __PRETTY_FUNCTION__))
3100 "EnumDecl not matched with TTK_Enum")(static_cast <bool> ((DK != Enum || TK == TTK_Enum) &&
"EnumDecl not matched with TTK_Enum") ? void (0) : __assert_fail
("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 3100, __extension__ __PRETTY_FUNCTION__))
;
3101 setPreviousDecl(PrevDecl);
3102 }
3103
3104 using redeclarable_base = Redeclarable<TagDecl>;
3105
3106 TagDecl *getNextRedeclarationImpl() override {
3107 return getNextRedeclaration();
3108 }
3109
3110 TagDecl *getPreviousDeclImpl() override {
3111 return getPreviousDecl();
3112 }
3113
3114 TagDecl *getMostRecentDeclImpl() override {
3115 return getMostRecentDecl();
3116 }
3117
3118 /// Completes the definition of this tag declaration.
3119 ///
3120 /// This is a helper function for derived classes.
3121 void completeDefinition();
3122
3123public:
3124 friend class ASTDeclReader;
3125 friend class ASTDeclWriter;
3126
3127 using redecl_range = redeclarable_base::redecl_range;
3128 using redecl_iterator = redeclarable_base::redecl_iterator;
3129
3130 using redeclarable_base::redecls_begin;
3131 using redeclarable_base::redecls_end;
3132 using redeclarable_base::redecls;
3133 using redeclarable_base::getPreviousDecl;
3134 using redeclarable_base::getMostRecentDecl;
3135 using redeclarable_base::isFirstDecl;
3136
3137 SourceRange getBraceRange() const { return BraceRange; }
3138 void setBraceRange(SourceRange R) { BraceRange = R; }
3139
3140 /// Return SourceLocation representing start of source
3141 /// range ignoring outer template declarations.
3142 SourceLocation getInnerLocStart() const { return getLocStart(); }
3143
3144 /// Return SourceLocation representing start of source
3145 /// range taking into account any outer template declarations.
3146 SourceLocation getOuterLocStart() const;
3147 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3148
3149 TagDecl *getCanonicalDecl() override;
3150 const TagDecl *getCanonicalDecl() const {
3151 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3152 }
3153
3154 /// Return true if this declaration is a completion definition of the type.
3155 /// Provided for consistency.
3156 bool isThisDeclarationADefinition() const {
3157 return isCompleteDefinition();
3158 }
3159
3160 /// Return true if this decl has its body fully specified.
3161 bool isCompleteDefinition() const {
3162 return IsCompleteDefinition;
3163 }
3164
3165 /// Return true if this complete decl is
3166 /// required to be complete for some existing use.
3167 bool isCompleteDefinitionRequired() const {
3168 return IsCompleteDefinitionRequired;
3169 }
3170
3171 /// Return true if this decl is currently being defined.
3172 bool isBeingDefined() const {
3173 return IsBeingDefined;
3174 }
3175
3176 bool isEmbeddedInDeclarator() const {
3177 return IsEmbeddedInDeclarator;
3178 }
3179 void setEmbeddedInDeclarator(bool isInDeclarator) {
3180 IsEmbeddedInDeclarator = isInDeclarator;
3181 }
3182
3183 bool isFreeStanding() const { return IsFreeStanding; }
3184 void setFreeStanding(bool isFreeStanding = true) {
3185 IsFreeStanding = isFreeStanding;
3186 }
3187
3188 /// Whether this declaration declares a type that is
3189 /// dependent, i.e., a type that somehow depends on template
3190 /// parameters.
3191 bool isDependentType() const { return isDependentContext(); }
3192
3193 /// Starts the definition of this tag declaration.
3194 ///
3195 /// This method should be invoked at the beginning of the definition
3196 /// of this tag declaration. It will set the tag type into a state
3197 /// where it is in the process of being defined.
3198 void startDefinition();
3199
3200 /// Returns the TagDecl that actually defines this
3201 /// struct/union/class/enum. When determining whether or not a
3202 /// struct/union/class/enum has a definition, one should use this
3203 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3204 /// whether or not a specific TagDecl is defining declaration, not
3205 /// whether or not the struct/union/class/enum type is defined.
3206 /// This method returns NULL if there is no TagDecl that defines
3207 /// the struct/union/class/enum.
3208 TagDecl *getDefinition() const;
3209
3210 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
3211
3212 void setCompleteDefinitionRequired(bool V = true) {
3213 IsCompleteDefinitionRequired = V;
3214 }
3215
3216 StringRef getKindName() const {
3217 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3218 }
3219
3220 TagKind getTagKind() const {
3221 return TagKind(TagDeclKind);
3222 }
3223
3224 void setTagKind(TagKind TK) { TagDeclKind = TK; }
3225
3226 bool isStruct() const { return getTagKind() == TTK_Struct; }
3227 bool isInterface() const { return getTagKind() == TTK_Interface; }
3228 bool isClass() const { return getTagKind() == TTK_Class; }
3229 bool isUnion() const { return getTagKind() == TTK_Union; }
3230 bool isEnum() const { return getTagKind() == TTK_Enum; }
3231
3232 /// Is this tag type named, either directly or via being defined in
3233 /// a typedef of this type?
3234 ///
3235 /// C++11 [basic.link]p8:
3236 /// A type is said to have linkage if and only if:
3237 /// - it is a class or enumeration type that is named (or has a
3238 /// name for linkage purposes) and the name has linkage; ...
3239 /// C++11 [dcl.typedef]p9:
3240 /// If the typedef declaration defines an unnamed class (or enum),
3241 /// the first typedef-name declared by the declaration to be that
3242 /// class type (or enum type) is used to denote the class type (or
3243 /// enum type) for linkage purposes only.
3244 ///
3245 /// C does not have an analogous rule, but the same concept is
3246 /// nonetheless useful in some places.
3247 bool hasNameForLinkage() const {
3248 return (getDeclName() || getTypedefNameForAnonDecl());
3249 }
3250
3251 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3252 return hasExtInfo() ? nullptr
3253 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3254 }
3255
3256 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3257
3258 /// Retrieve the nested-name-specifier that qualifies the name of this
3259 /// declaration, if it was present in the source.
3260 NestedNameSpecifier *getQualifier() const {
3261 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3262 : nullptr;
3263 }
3264
3265 /// Retrieve the nested-name-specifier (with source-location
3266 /// information) that qualifies the name of this declaration, if it was
3267 /// present in the source.
3268 NestedNameSpecifierLoc getQualifierLoc() const {
3269 return hasExtInfo() ? getExtInfo()->QualifierLoc
3270 : NestedNameSpecifierLoc();
3271 }
3272
3273 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3274
3275 unsigned getNumTemplateParameterLists() const {
3276 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3277 }
3278
3279 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3280 assert(i < getNumTemplateParameterLists())(static_cast <bool> (i < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 3280, __extension__ __PRETTY_FUNCTION__))
;
3281 return getExtInfo()->TemplParamLists[i];
3282 }
3283
3284 void setTemplateParameterListsInfo(ASTContext &Context,
3285 ArrayRef<TemplateParameterList *> TPLists);
3286
3287 // Implement isa/cast/dyncast/etc.
3288 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3289 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3290
3291 static DeclContext *castToDeclContext(const TagDecl *D) {
3292 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3293 }
3294
3295 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3296 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3297 }
3298};
3299
3300/// Represents an enum. In C++11, enums can be forward-declared
3301/// with a fixed underlying type, and in C we allow them to be forward-declared
3302/// with no underlying type as an extension.
3303class EnumDecl : public TagDecl {
3304 /// This represent the integer type that the enum corresponds
3305 /// to for code generation purposes. Note that the enumerator constants may
3306 /// have a different type than this does.
3307 ///
3308 /// If the underlying integer type was explicitly stated in the source
3309 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3310 /// was automatically deduced somehow, and this is a Type*.
3311 ///
3312 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3313 /// some cases it won't.
3314 ///
3315 /// The underlying type of an enumeration never has any qualifiers, so
3316 /// we can get away with just storing a raw Type*, and thus save an
3317 /// extra pointer when TypeSourceInfo is needed.
3318 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3319
3320 /// The integer type that values of this type should
3321 /// promote to. In C, enumerators are generally of an integer type
3322 /// directly, but gcc-style large enumerators (and all enumerators
3323 /// in C++) are of the enum type instead.
3324 QualType PromotionType;
3325
3326 /// If this enumeration is an instantiation of a member enumeration
3327 /// of a class template specialization, this is the member specialization
3328 /// information.
3329 MemberSpecializationInfo *SpecializationInfo = nullptr;
3330
3331 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3332 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3333 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3334 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3335 assert(Scoped || !ScopedUsingClassTag)(static_cast <bool> (Scoped || !ScopedUsingClassTag) ? void
(0) : __assert_fail ("Scoped || !ScopedUsingClassTag", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 3335, __extension__ __PRETTY_FUNCTION__))
;
3336 IntegerType = (const Type *)nullptr;
3337 NumNegativeBits = 0;
3338 NumPositiveBits = 0;
3339 IsScoped = Scoped;
3340 IsScopedUsingClassTag = ScopedUsingClassTag;
3341 IsFixed = Fixed;
3342 }
3343
3344 void anchor() override;
3345
3346 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3347 TemplateSpecializationKind TSK);
3348public:
3349 friend class ASTDeclReader;
3350
3351 EnumDecl *getCanonicalDecl() override {
3352 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3353 }
3354 const EnumDecl *getCanonicalDecl() const {
3355 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3356 }
3357
3358 EnumDecl *getPreviousDecl() {
3359 return cast_or_null<EnumDecl>(
3360 static_cast<TagDecl *>(this)->getPreviousDecl());
3361 }
3362 const EnumDecl *getPreviousDecl() const {
3363 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3364 }
3365
3366 EnumDecl *getMostRecentDecl() {
3367 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3368 }
3369 const EnumDecl *getMostRecentDecl() const {
3370 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3371 }
3372
3373 EnumDecl *getDefinition() const {
3374 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3375 }
3376
3377 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3378 SourceLocation StartLoc, SourceLocation IdLoc,
3379 IdentifierInfo *Id, EnumDecl *PrevDecl,
3380 bool IsScoped, bool IsScopedUsingClassTag,
3381 bool IsFixed);
3382 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3383
3384 /// When created, the EnumDecl corresponds to a
3385 /// forward-declared enum. This method is used to mark the
3386 /// declaration as being defined; its enumerators have already been
3387 /// added (via DeclContext::addDecl). NewType is the new underlying
3388 /// type of the enumeration type.
3389 void completeDefinition(QualType NewType,
3390 QualType PromotionType,
3391 unsigned NumPositiveBits,
3392 unsigned NumNegativeBits);
3393
3394 // Iterates through the enumerators of this enumeration.
3395 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3396 using enumerator_range =
3397 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3398
3399 enumerator_range enumerators() const {
3400 return enumerator_range(enumerator_begin(), enumerator_end());
3401 }
3402
3403 enumerator_iterator enumerator_begin() const {
3404 const EnumDecl *E = getDefinition();
3405 if (!E)
3406 E = this;
3407 return enumerator_iterator(E->decls_begin());
3408 }
3409
3410 enumerator_iterator enumerator_end() const {
3411 const EnumDecl *E = getDefinition();
3412 if (!E)
3413 E = this;
3414 return enumerator_iterator(E->decls_end());
3415 }
3416
3417 /// Return the integer type that enumerators should promote to.
3418 QualType getPromotionType() const { return PromotionType; }
3419
3420 /// Set the promotion type.
3421 void setPromotionType(QualType T) { PromotionType = T; }
3422
3423 /// Return the integer type this enum decl corresponds to.
3424 /// This returns a null QualType for an enum forward definition with no fixed
3425 /// underlying type.
3426 QualType getIntegerType() const {
3427 if (!IntegerType)
3428 return QualType();
3429 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3430 return QualType(T, 0);
3431 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3432 }
3433
3434 /// Set the underlying integer type.
3435 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3436
3437 /// Set the underlying integer type source info.
3438 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3439
3440 /// Return the type source info for the underlying integer type,
3441 /// if no type source info exists, return 0.
3442 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3443 return IntegerType.dyn_cast<TypeSourceInfo*>();
3444 }
3445
3446 /// Retrieve the source range that covers the underlying type if
3447 /// specified.
3448 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3449
3450 /// Returns the width in bits required to store all the
3451 /// non-negative enumerators of this enum.
3452 unsigned getNumPositiveBits() const {
3453 return NumPositiveBits;
3454 }
3455 void setNumPositiveBits(unsigned Num) {
3456 NumPositiveBits = Num;
3457 assert(NumPositiveBits == Num && "can't store this bitcount")(static_cast <bool> (NumPositiveBits == Num && "can't store this bitcount"
) ? void (0) : __assert_fail ("NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 3457, __extension__ __PRETTY_FUNCTION__))
;
3458 }
3459
3460 /// Returns the width in bits required to store all the
3461 /// negative enumerators of this enum. These widths include
3462 /// the rightmost leading 1; that is:
3463 ///
3464 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3465 /// ------------------------ ------- -----------------
3466 /// -1 1111111 1
3467 /// -10 1110110 5
3468 /// -101 1001011 8
3469 unsigned getNumNegativeBits() const {
3470 return NumNegativeBits;
3471 }
3472 void setNumNegativeBits(unsigned Num) {
3473 NumNegativeBits = Num;
3474 }
3475
3476 /// Returns true if this is a C++11 scoped enumeration.
3477 bool isScoped() const {
3478 return IsScoped;
3479 }
3480
3481 /// Returns true if this is a C++11 scoped enumeration.
3482 bool isScopedUsingClassTag() const {
3483 return IsScopedUsingClassTag;
3484 }
3485
3486 /// Returns true if this is an Objective-C, C++11, or
3487 /// Microsoft-style enumeration with a fixed underlying type.
3488 bool isFixed() const {
3489 return IsFixed;
3490 }
3491
3492 /// Returns true if this can be considered a complete type.
3493 bool isComplete() const {
3494 // IntegerType is set for fixed type enums and non-fixed but implicitly
3495 // int-sized Microsoft enums.
3496 return isCompleteDefinition() || IntegerType;
3497 }
3498
3499 /// Returns true if this enum is either annotated with
3500 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3501 bool isClosed() const;
3502
3503 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3504 /// with enum_extensibility(open).
3505 bool isClosedFlag() const;
3506
3507 /// Returns true if this enum is annotated with neither flag_enum nor
3508 /// enum_extensibility(open).
3509 bool isClosedNonFlag() const;
3510
3511 /// Retrieve the enum definition from which this enumeration could
3512 /// be instantiated, if it is an instantiation (rather than a non-template).
3513 EnumDecl *getTemplateInstantiationPattern() const;
3514
3515 /// Returns the enumeration (declared within the template)
3516 /// from which this enumeration type was instantiated, or NULL if
3517 /// this enumeration was not instantiated from any template.
3518 EnumDecl *getInstantiatedFromMemberEnum() const;
3519
3520 /// If this enumeration is a member of a specialization of a
3521 /// templated class, determine what kind of template specialization
3522 /// or instantiation this is.
3523 TemplateSpecializationKind getTemplateSpecializationKind() const;
3524
3525 /// For an enumeration member that was instantiated from a member
3526 /// enumeration of a templated class, set the template specialiation kind.
3527 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3528 SourceLocation PointOfInstantiation = SourceLocation());
3529
3530 /// If this enumeration is an instantiation of a member enumeration of
3531 /// a class template specialization, retrieves the member specialization
3532 /// information.
3533 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3534 return SpecializationInfo;
3535 }
3536
3537 /// Specify that this enumeration is an instantiation of the
3538 /// member enumeration ED.
3539 void setInstantiationOfMemberEnum(EnumDecl *ED,
3540 TemplateSpecializationKind TSK) {
3541 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3542 }
3543
3544 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3545 static bool classofKind(Kind K) { return K == Enum; }
3546};
3547
3548/// Represents a struct/union/class. For example:
3549/// struct X; // Forward declaration, no "body".
3550/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3551/// This decl will be marked invalid if *any* members are invalid.
3552class RecordDecl : public TagDecl {
3553public:
3554 /// Enum that represents the different ways arguments are passed to and
3555 /// returned from function calls. This takes into account the target-specific
3556 /// and version-specific rules along with the rules determined by the
3557 /// language.
3558 enum ArgPassingKind : unsigned {
3559 /// The argument of this type can be passed directly in registers.
3560 APK_CanPassInRegs,
3561
3562 /// The argument of this type cannot be passed directly in registers.
3563 /// Records containing this type as a subobject are not forced to be passed
3564 /// indirectly. This value is used only in C++. This value is required by
3565 /// C++ because, in uncommon situations, it is possible for a class to have
3566 /// only trivial copy/move constructors even when one of its subobjects has
3567 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3568 /// constructor in the derived class is deleted).
3569 APK_CannotPassInRegs,
3570
3571 /// The argument of this type cannot be passed directly in registers.
3572 /// Records containing this type as a subobject are forced to be passed
3573 /// indirectly.
3574 APK_CanNeverPassInRegs
3575 };
3576
3577private:
3578 friend class DeclContext;
3579
3580 // FIXME: This can be packed into the bitfields in Decl.
3581 /// This is true if this struct ends with a flexible
3582 /// array member (e.g. int X[]) or if this union contains a struct that does.
3583 /// If so, this cannot be contained in arrays or other structs as a member.
3584 unsigned HasFlexibleArrayMember : 1;
3585
3586 /// Whether this is the type of an anonymous struct or union.
3587 unsigned AnonymousStructOrUnion : 1;
3588
3589 /// This is true if this struct has at least one member
3590 /// containing an Objective-C object pointer type.
3591 unsigned HasObjectMember : 1;
3592
3593 /// This is true if struct has at least one member of
3594 /// 'volatile' type.
3595 unsigned HasVolatileMember : 1;
3596
3597 /// Whether the field declarations of this record have been loaded
3598 /// from external storage. To avoid unnecessary deserialization of
3599 /// methods/nested types we allow deserialization of just the fields
3600 /// when needed.
3601 mutable unsigned LoadedFieldsFromExternalStorage : 1;
3602
3603 /// Basic properties of non-trivial C structs.
3604 unsigned NonTrivialToPrimitiveDefaultInitialize : 1;
3605 unsigned NonTrivialToPrimitiveCopy : 1;
3606 unsigned NonTrivialToPrimitiveDestroy : 1;
3607
3608 /// Indicates whether this struct is destroyed in the callee.
3609 ///
3610 /// Please note that MSVC won't merge adjacent bitfields if they don't have
3611 /// the same type.
3612 unsigned ParamDestroyedInCallee : 1;
3613
3614 /// Represents the way this type is passed to a function.
3615 unsigned ArgPassingRestrictions : 2;
3616
3617protected:
3618 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3619 SourceLocation StartLoc, SourceLocation IdLoc,
3620 IdentifierInfo *Id, RecordDecl *PrevDecl);
3621
3622public:
3623 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3624 SourceLocation StartLoc, SourceLocation IdLoc,
3625 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3626 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3627
3628 RecordDecl *getPreviousDecl() {
3629 return cast_or_null<RecordDecl>(
3630 static_cast<TagDecl *>(this)->getPreviousDecl());
3631 }
3632 const RecordDecl *getPreviousDecl() const {
3633 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3634 }
3635
3636 RecordDecl *getMostRecentDecl() {
3637 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3638 }
3639 const RecordDecl *getMostRecentDecl() const {
3640 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3641 }
3642
3643 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3644 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3645
3646 /// Whether this is an anonymous struct or union. To be an anonymous
3647 /// struct or union, it must have been declared without a name and
3648 /// there must be no objects of this type declared, e.g.,
3649 /// @code
3650 /// union { int i; float f; };
3651 /// @endcode
3652 /// is an anonymous union but neither of the following are:
3653 /// @code
3654 /// union X { int i; float f; };
3655 /// union { int i; float f; } obj;
3656 /// @endcode
3657 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3658 void setAnonymousStructOrUnion(bool Anon) {
3659 AnonymousStructOrUnion = Anon;
3660 }
3661
3662 bool hasObjectMember() const { return HasObjectMember; }
3663 void setHasObjectMember (bool val) { HasObjectMember = val; }
3664
3665 bool hasVolatileMember() const { return HasVolatileMember; }
3666 void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3667
3668 bool hasLoadedFieldsFromExternalStorage() const {
3669 return LoadedFieldsFromExternalStorage;
3670 }
3671 void setHasLoadedFieldsFromExternalStorage(bool val) {
3672 LoadedFieldsFromExternalStorage = val;
3673 }
3674
3675 /// Functions to query basic properties of non-trivial C structs.
3676 bool isNonTrivialToPrimitiveDefaultInitialize() const {
3677 return NonTrivialToPrimitiveDefaultInitialize;
3678 }
3679
3680 void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3681 NonTrivialToPrimitiveDefaultInitialize = V;
3682 }
3683
3684 bool isNonTrivialToPrimitiveCopy() const {
3685 return NonTrivialToPrimitiveCopy;
3686 }
3687
3688 void setNonTrivialToPrimitiveCopy(bool V) {
3689 NonTrivialToPrimitiveCopy = V;
3690 }
3691
3692 bool isNonTrivialToPrimitiveDestroy() const {
3693 return NonTrivialToPrimitiveDestroy;
3694 }
3695
3696 void setNonTrivialToPrimitiveDestroy(bool V) {
3697 NonTrivialToPrimitiveDestroy = V;
3698 }
3699
3700 /// Determine whether this class can be passed in registers. In C++ mode,
3701 /// it must have at least one trivial, non-deleted copy or move constructor.
3702 /// FIXME: This should be set as part of completeDefinition.
3703 bool canPassInRegisters() const {
3704 return getArgPassingRestrictions() == APK_CanPassInRegs;
3705 }
3706
3707 ArgPassingKind getArgPassingRestrictions() const {
3708 return static_cast<ArgPassingKind>(ArgPassingRestrictions);
3709 }
3710
3711 void setArgPassingRestrictions(ArgPassingKind Kind) {
3712 ArgPassingRestrictions = static_cast<uint8_t>(Kind);
3713 }
3714
3715 bool isParamDestroyedInCallee() const {
3716 return ParamDestroyedInCallee;
3717 }
3718
3719 void setParamDestroyedInCallee(bool V) {
3720 ParamDestroyedInCallee = V;
3721 }
3722
3723 /// Determines whether this declaration represents the
3724 /// injected class name.
3725 ///
3726 /// The injected class name in C++ is the name of the class that
3727 /// appears inside the class itself. For example:
3728 ///
3729 /// \code
3730 /// struct C {
3731 /// // C is implicitly declared here as a synonym for the class name.
3732 /// };
3733 ///
3734 /// C::C c; // same as "C c;"
3735 /// \endcode
3736 bool isInjectedClassName() const;
3737
3738 /// Determine whether this record is a class describing a lambda
3739 /// function object.
3740 bool isLambda() const;
3741
3742 /// Determine whether this record is a record for captured variables in
3743 /// CapturedStmt construct.
3744 bool isCapturedRecord() const;
3745
3746 /// Mark the record as a record for captured variables in CapturedStmt
3747 /// construct.
3748 void setCapturedRecord();
3749
3750 /// Returns the RecordDecl that actually defines
3751 /// this struct/union/class. When determining whether or not a
3752 /// struct/union/class is completely defined, one should use this
3753 /// method as opposed to 'isCompleteDefinition'.
3754 /// 'isCompleteDefinition' indicates whether or not a specific
3755 /// RecordDecl is a completed definition, not whether or not the
3756 /// record type is defined. This method returns NULL if there is
3757 /// no RecordDecl that defines the struct/union/tag.
3758 RecordDecl *getDefinition() const {
3759 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3760 }
3761
3762 // Iterator access to field members. The field iterator only visits
3763 // the non-static data members of this class, ignoring any static
3764 // data members, functions, constructors, destructors, etc.
3765 using field_iterator = specific_decl_iterator<FieldDecl>;
3766 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3767
3768 field_range fields() const { return field_range(field_begin(), field_end()); }
3769 field_iterator field_begin() const;
3770
3771 field_iterator field_end() const {
3772 return field_iterator(decl_iterator());
3773 }
3774
3775 // Whether there are any fields (non-static data members) in this record.
3776 bool field_empty() const {
3777 return field_begin() == field_end();
3778 }
3779
3780 /// Note that the definition of this type is now complete.
3781 virtual void completeDefinition();
3782
3783 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3784 static bool classofKind(Kind K) {
3785 return K >= firstRecord && K <= lastRecord;
3786 }
3787
3788 /// Get whether or not this is an ms_struct which can
3789 /// be turned on with an attribute, pragma, or -mms-bitfields
3790 /// commandline option.
3791 bool isMsStruct(const ASTContext &C) const;
3792
3793 /// Whether we are allowed to insert extra padding between fields.
3794 /// These padding are added to help AddressSanitizer detect
3795 /// intra-object-overflow bugs.
3796 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3797
3798 /// Finds the first data member which has a name.
3799 /// nullptr is returned if no named data member exists.
3800 const FieldDecl *findFirstNamedDataMember() const;
3801
3802private:
3803 /// Deserialize just the fields.
3804 void LoadFieldsFromExternalStorage() const;
3805};
3806
3807class FileScopeAsmDecl : public Decl {
3808 StringLiteral *AsmString;
3809 SourceLocation RParenLoc;
3810
3811 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3812 SourceLocation StartL, SourceLocation EndL)
3813 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3814
3815 virtual void anchor();
3816
3817public:
3818 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3819 StringLiteral *Str, SourceLocation AsmLoc,
3820 SourceLocation RParenLoc);
3821
3822 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3823
3824 SourceLocation getAsmLoc() const { return getLocation(); }
3825 SourceLocation getRParenLoc() const { return RParenLoc; }
3826 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3827 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3828 return SourceRange(getAsmLoc(), getRParenLoc());
3829 }
3830
3831 const StringLiteral *getAsmString() const { return AsmString; }
3832 StringLiteral *getAsmString() { return AsmString; }
3833 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3834
3835 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3836 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3837};
3838
3839/// Pepresents a block literal declaration, which is like an
3840/// unnamed FunctionDecl. For example:
3841/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3842class BlockDecl : public Decl, public DeclContext {
3843public:
3844 /// A class which contains all the information about a particular
3845 /// captured value.
3846 class Capture {
3847 enum {
3848 flag_isByRef = 0x1,
3849 flag_isNested = 0x2
3850 };
3851
3852 /// The variable being captured.
3853 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3854
3855 /// The copy expression, expressed in terms of a DeclRef (or
3856 /// BlockDeclRef) to the captured variable. Only required if the
3857 /// variable has a C++ class type.
3858 Expr *CopyExpr;
3859
3860 public:
3861 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3862 : VariableAndFlags(variable,
3863 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3864 CopyExpr(copy) {}
3865
3866 /// The variable being captured.
3867 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3868
3869 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3870 /// variable.
3871 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3872
3873 /// Whether this is a nested capture, i.e. the variable captured
3874 /// is not from outside the immediately enclosing function/block.
3875 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3876
3877 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3878 Expr *getCopyExpr() const { return CopyExpr; }
3879 void setCopyExpr(Expr *e) { CopyExpr = e; }
3880 };
3881
3882private:
3883 // FIXME: This can be packed into the bitfields in Decl.
3884 bool IsVariadic : 1;
3885 bool CapturesCXXThis : 1;
3886 bool BlockMissingReturnType : 1;
3887 bool IsConversionFromLambda : 1;
3888
3889 /// A bit that indicates this block is passed directly to a function as a
3890 /// non-escaping parameter.
3891 bool DoesNotEscape : 1;
3892
3893 /// A new[]'d array of pointers to ParmVarDecls for the formal
3894 /// parameters of this function. This is null if a prototype or if there are
3895 /// no formals.
3896 ParmVarDecl **ParamInfo = nullptr;
3897 unsigned NumParams = 0;
3898
3899 Stmt *Body = nullptr;
3900 TypeSourceInfo *SignatureAsWritten = nullptr;
3901
3902 const Capture *Captures = nullptr;
3903 unsigned NumCaptures = 0;
3904
3905 unsigned ManglingNumber = 0;
3906 Decl *ManglingContextDecl = nullptr;
3907
3908protected:
3909 BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3910 : Decl(Block, DC, CaretLoc), DeclContext(Block), IsVariadic(false),
3911 CapturesCXXThis(false), BlockMissingReturnType(true),
3912 IsConversionFromLambda(false), DoesNotEscape(false) {}
3913
3914public:
3915 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3916 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3917
3918 SourceLocation getCaretLocation() const { return getLocation(); }
3919
3920 bool isVariadic() const { return IsVariadic; }
3921 void setIsVariadic(bool value) { IsVariadic = value; }
3922
3923 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3924 Stmt *getBody() const override { return (Stmt*) Body; }
3925 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3926
3927 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3928 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3929
3930 // ArrayRef access to formal parameters.
3931 ArrayRef<ParmVarDecl *> parameters() const {
3932 return {ParamInfo, getNumParams()};
3933 }
3934 MutableArrayRef<ParmVarDecl *> parameters() {
3935 return {ParamInfo, getNumParams()};
3936 }
3937
3938 // Iterator access to formal parameters.
3939 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
3940 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
3941
3942 bool param_empty() const { return parameters().empty(); }
3943 param_iterator param_begin() { return parameters().begin(); }
3944 param_iterator param_end() { return parameters().end(); }
3945 param_const_iterator param_begin() const { return parameters().begin(); }
3946 param_const_iterator param_end() const { return parameters().end(); }
3947 size_t param_size() const { return parameters().size(); }
3948
3949 unsigned getNumParams() const { return NumParams; }
3950
3951 const ParmVarDecl *getParamDecl(unsigned i) const {
3952 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 3952, __extension__ __PRETTY_FUNCTION__))
;
3953 return ParamInfo[i];
3954 }
3955 ParmVarDecl *getParamDecl(unsigned i) {
3956 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 3956, __extension__ __PRETTY_FUNCTION__))
;
3957 return ParamInfo[i];
3958 }
3959
3960 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3961
3962 /// True if this block (or its nested blocks) captures
3963 /// anything of local storage from its enclosing scopes.
3964 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3965
3966 /// Returns the number of captured variables.
3967 /// Does not include an entry for 'this'.
3968 unsigned getNumCaptures() const { return NumCaptures; }
3969
3970 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
3971
3972 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3973
3974 capture_const_iterator capture_begin() const { return captures().begin(); }
3975 capture_const_iterator capture_end() const { return captures().end(); }
3976
3977 bool capturesCXXThis() const { return CapturesCXXThis; }
3978 bool blockMissingReturnType() const { return BlockMissingReturnType; }
3979 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3980
3981 bool isConversionFromLambda() const { return IsConversionFromLambda; }
3982 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3983
3984 bool doesNotEscape() const { return DoesNotEscape; }
3985 void setDoesNotEscape() { DoesNotEscape = true; }
3986
3987 bool capturesVariable(const VarDecl *var) const;
3988
3989 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3990 bool CapturesCXXThis);
3991
3992 unsigned getBlockManglingNumber() const {
3993 return ManglingNumber;
3994 }
3995
3996 Decl *getBlockManglingContextDecl() const {
3997 return ManglingContextDecl;
3998 }
3999
4000 void setBlockMangling(unsigned Number, Decl *Ctx) {
4001 ManglingNumber = Number;
4002 ManglingContextDecl = Ctx;
4003 }
4004
4005 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4006
4007 // Implement isa/cast/dyncast/etc.
4008 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4009 static bool classofKind(Kind K) { return K == Block; }
4010 static DeclContext *castToDeclContext(const BlockDecl *D) {
4011 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4012 }
4013 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4014 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4015 }
4016};
4017
4018/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4019class CapturedDecl final
4020 : public Decl,
4021 public DeclContext,
4022 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4023protected:
4024 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4025 return NumParams;
4026 }
4027
4028private:
4029 /// The number of parameters to the outlined function.
4030 unsigned NumParams;
4031
4032 /// The position of context parameter in list of parameters.
4033 unsigned ContextParam;
4034
4035 /// The body of the outlined function.
4036 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4037
4038 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4039
4040 ImplicitParamDecl *const *getParams() const {
4041 return getTrailingObjects<ImplicitParamDecl *>();
4042 }
4043
4044 ImplicitParamDecl **getParams() {
4045 return getTrailingObjects<ImplicitParamDecl *>();
4046 }
4047
4048public:
4049 friend class ASTDeclReader;
4050 friend class ASTDeclWriter;
4051 friend TrailingObjects;
4052
4053 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4054 unsigned NumParams);
4055 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4056 unsigned NumParams);
4057
4058 Stmt *getBody() const override;
4059 void setBody(Stmt *B);
4060
4061 bool isNothrow() const;
4062 void setNothrow(bool Nothrow = true);
4063
4064 unsigned getNumParams() const { return NumParams; }
4065
4066 ImplicitParamDecl *getParam(unsigned i) const {
4067 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 4067, __extension__ __PRETTY_FUNCTION__))
;
4068 return getParams()[i];
4069 }
4070 void setParam(unsigned i, ImplicitParamDecl *P) {
4071 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 4071, __extension__ __PRETTY_FUNCTION__))
;
4072 getParams()[i] = P;
4073 }
4074
4075 // ArrayRef interface to parameters.
4076 ArrayRef<ImplicitParamDecl *> parameters() const {
4077 return {getParams(), getNumParams()};
4078 }
4079 MutableArrayRef<ImplicitParamDecl *> parameters() {
4080 return {getParams(), getNumParams()};
4081 }
4082
4083 /// Retrieve the parameter containing captured variables.
4084 ImplicitParamDecl *getContextParam() const {
4085 assert(ContextParam < NumParams)(static_cast <bool> (ContextParam < NumParams) ? void
(0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 4085, __extension__ __PRETTY_FUNCTION__))
;
4086 return getParam(ContextParam);
4087 }
4088 void setContextParam(unsigned i, ImplicitParamDecl *P) {
4089 assert(i < NumParams)(static_cast <bool> (i < NumParams) ? void (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 4089, __extension__ __PRETTY_FUNCTION__))
;
4090 ContextParam = i;
4091 setParam(i, P);
4092 }
4093 unsigned getContextParamPosition() const { return ContextParam; }
4094
4095 using param_iterator = ImplicitParamDecl *const *;
4096 using param_range = llvm::iterator_range<param_iterator>;
4097
4098 /// Retrieve an iterator pointing to the first parameter decl.
4099 param_iterator param_begin() const { return getParams(); }
4100 /// Retrieve an iterator one past the last parameter decl.
4101 param_iterator param_end() const { return getParams() + NumParams; }
4102
4103 // Implement isa/cast/dyncast/etc.
4104 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4105 static bool classofKind(Kind K) { return K == Captured; }
4106 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4107 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4108 }
4109 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4110 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4111 }
4112};
4113
4114/// Describes a module import declaration, which makes the contents
4115/// of the named module visible in the current translation unit.
4116///
4117/// An import declaration imports the named module (or submodule). For example:
4118/// \code
4119/// @import std.vector;
4120/// \endcode
4121///
4122/// Import declarations can also be implicitly generated from
4123/// \#include/\#import directives.
4124class ImportDecl final : public Decl,
4125 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4126 friend class ASTContext;
4127 friend class ASTDeclReader;
4128 friend class ASTReader;
4129 friend TrailingObjects;
4130
4131 /// The imported module, along with a bit that indicates whether
4132 /// we have source-location information for each identifier in the module
4133 /// name.
4134 ///
4135 /// When the bit is false, we only have a single source location for the
4136 /// end of the import declaration.
4137 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4138
4139 /// The next import in the list of imports local to the translation
4140 /// unit being parsed (not loaded from an AST file).
4141 ImportDecl *NextLocalImport = nullptr;
4142
4143 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4144 ArrayRef<SourceLocation> IdentifierLocs);
4145
4146 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4147 SourceLocation EndLoc);
4148
4149 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4150
4151public:
4152 /// Create a new module import declaration.
4153 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4154 SourceLocation StartLoc, Module *Imported,
4155 ArrayRef<SourceLocation> IdentifierLocs);
4156
4157 /// Create a new module import declaration for an implicitly-generated
4158 /// import.
4159 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4160 SourceLocation StartLoc, Module *Imported,
4161 SourceLocation EndLoc);
4162
4163 /// Create a new, deserialized module import declaration.
4164 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4165 unsigned NumLocations);
4166
4167 /// Retrieve the module that was imported by the import declaration.
4168 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4169
4170 /// Retrieves the locations of each of the identifiers that make up
4171 /// the complete module name in the import declaration.
4172 ///
4173 /// This will return an empty array if the locations of the individual
4174 /// identifiers aren't available.
4175 ArrayRef<SourceLocation> getIdentifierLocs() const;
4176
4177 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4178
4179 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4180 static bool classofKind(Kind K) { return K == Import; }
4181};
4182
4183/// Represents a C++ Modules TS module export declaration.
4184///
4185/// For example:
4186/// \code
4187/// export void foo();
4188/// \endcode
4189class ExportDecl final : public Decl, public DeclContext {
4190 virtual void anchor();
4191
4192private:
4193 friend class ASTDeclReader;
4194
4195 /// The source location for the right brace (if valid).
4196 SourceLocation RBraceLoc;
4197
4198 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4199 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4200 RBraceLoc(SourceLocation()) {}
4201
4202public:
4203 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4204 SourceLocation ExportLoc);
4205 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4206
4207 SourceLocation getExportLoc() const { return getLocation(); }
4208 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4209 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4210
4211 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
4212 if (RBraceLoc.isValid())
4213 return RBraceLoc;
4214 // No braces: get the end location of the (only) declaration in context
4215 // (if present).
4216 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
4217 }
4218
4219 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4220 return SourceRange(getLocation(), getLocEnd());
4221 }
4222
4223 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4224 static bool classofKind(Kind K) { return K == Export; }
4225 static DeclContext *castToDeclContext(const ExportDecl *D) {
4226 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4227 }
4228 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4229 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4230 }
4231};
4232
4233/// Represents an empty-declaration.
4234class EmptyDecl : public Decl {
4235 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4236
4237 virtual void anchor();
4238
4239public:
4240 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4241 SourceLocation L);
4242 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4243
4244 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4245 static bool classofKind(Kind K) { return K == Empty; }
4246};
4247
4248/// Insertion operator for diagnostics. This allows sending NamedDecl's
4249/// into a diagnostic with <<.
4250inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4251 const NamedDecl* ND) {
4252 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4253 DiagnosticsEngine::ak_nameddecl);
4254 return DB;
4255}
4256inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4257 const NamedDecl* ND) {
4258 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4259 DiagnosticsEngine::ak_nameddecl);
4260 return PD;
4261}
4262
4263template<typename decl_type>
4264void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4265 // Note: This routine is implemented here because we need both NamedDecl
4266 // and Redeclarable to be defined.
4267 assert(RedeclLink.isFirst() &&(static_cast <bool> (RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 4268, __extension__ __PRETTY_FUNCTION__))
4268 "setPreviousDecl on a decl already in a redeclaration chain")(static_cast <bool> (RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? void (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 4268, __extension__ __PRETTY_FUNCTION__))
;
4269
4270 if (PrevDecl) {
4271 // Point to previous. Make sure that this is actually the most recent
4272 // redeclaration, or we can build invalid chains. If the most recent
4273 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4274 First = PrevDecl->getFirstDecl();
4275 assert(First->RedeclLink.isFirst() && "Expected first")(static_cast <bool> (First->RedeclLink.isFirst() &&
"Expected first") ? void (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 4275, __extension__ __PRETTY_FUNCTION__))
;
4276 decl_type *MostRecent = First->getNextRedeclaration();
4277 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4278
4279 // If the declaration was previously visible, a redeclaration of it remains
4280 // visible even if it wouldn't be visible by itself.
4281 static_cast<decl_type*>(this)->IdentifierNamespace |=
4282 MostRecent->getIdentifierNamespace() &
4283 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4284 } else {
4285 // Make this first.
4286 First = static_cast<decl_type*>(this);
4287 }
4288
4289 // First one will point to this one as latest.
4290 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4291
4292 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 4293, __extension__ __PRETTY_FUNCTION__))
4293 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())(static_cast <bool> (!isa<NamedDecl>(static_cast<
decl_type*>(this)) || cast<NamedDecl>(static_cast<
decl_type*>(this))->isLinkageValid()) ? void (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-7~svn337103/tools/clang/include/clang/AST/Decl.h"
, 4293, __extension__ __PRETTY_FUNCTION__))
;
4294}
4295
4296// Inline function definitions.
4297
4298/// Check if the given decl is complete.
4299///
4300/// We use this function to break a cycle between the inline definitions in
4301/// Type.h and Decl.h.
4302inline bool IsEnumDeclComplete(EnumDecl *ED) {
4303 return ED->isComplete();
4304}
4305
4306/// Check if the given decl is scoped.
4307///
4308/// We use this function to break a cycle between the inline definitions in
4309/// Type.h and Decl.h.
4310inline bool IsEnumDeclScoped(EnumDecl *ED) {
4311 return ED->isScoped();
4312}
4313
4314} // namespace clang
4315
4316#endif // LLVM_CLANG_AST_DECL_H