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-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 -analyzer-config-compatibility-mode=true -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-8/lib/clang/8.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -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-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Analysis/BodyFarm.cpp -faddrsig

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

/build/llvm-toolchain-snapshot-8~svn350071/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.getBeginLoc().print(OS, SrcMgr);
85/// @endcode
86class 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")((Name.isIdentifier() && "Name is not a simple identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 276, __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 getBeginLoc() 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 getBeginLoc() 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())((index < getNumTemplateParameterLists()) ? static_cast<
void> (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 764, __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 unsigned EscapingByref : 1;
970 };
971
972 union {
973 unsigned AllBits;
974 VarDeclBitfields VarDeclBits;
975 ParmVarDeclBitfields ParmVarDeclBits;
976 NonParmVarDeclBitfields NonParmVarDeclBits;
977 };
978
979 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
980 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
981 TypeSourceInfo *TInfo, StorageClass SC);
982
983 using redeclarable_base = Redeclarable<VarDecl>;
984
985 VarDecl *getNextRedeclarationImpl() override {
986 return getNextRedeclaration();
987 }
988
989 VarDecl *getPreviousDeclImpl() override {
990 return getPreviousDecl();
991 }
992
993 VarDecl *getMostRecentDeclImpl() override {
994 return getMostRecentDecl();
995 }
996
997public:
998 using redecl_range = redeclarable_base::redecl_range;
999 using redecl_iterator = redeclarable_base::redecl_iterator;
1000
1001 using redeclarable_base::redecls_begin;
1002 using redeclarable_base::redecls_end;
1003 using redeclarable_base::redecls;
1004 using redeclarable_base::getPreviousDecl;
1005 using redeclarable_base::getMostRecentDecl;
1006 using redeclarable_base::isFirstDecl;
1007
1008 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1009 SourceLocation StartLoc, SourceLocation IdLoc,
1010 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1011 StorageClass S);
1012
1013 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1014
1015 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1016
1017 /// Returns the storage class as written in the source. For the
1018 /// computed linkage of symbol, see getLinkage.
1019 StorageClass getStorageClass() const {
1020 return (StorageClass) VarDeclBits.SClass;
1021 }
1022 void setStorageClass(StorageClass SC);
1023
1024 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1025 VarDeclBits.TSCSpec = TSC;
1026 assert(VarDeclBits.TSCSpec == TSC && "truncation")((VarDeclBits.TSCSpec == TSC && "truncation") ? static_cast
<void> (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1026, __PRETTY_FUNCTION__))
;
1027 }
1028 ThreadStorageClassSpecifier getTSCSpec() const {
1029 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1030 }
1031 TLSKind getTLSKind() const;
1032
1033 /// Returns true if a variable with function scope is a non-static local
1034 /// variable.
1035 bool hasLocalStorage() const {
1036 if (getStorageClass() == SC_None) {
1037 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1038 // used to describe variables allocated in global memory and which are
1039 // accessed inside a kernel(s) as read-only variables. As such, variables
1040 // in constant address space cannot have local storage.
1041 if (getType().getAddressSpace() == LangAS::opencl_constant)
1042 return false;
1043 // Second check is for C++11 [dcl.stc]p4.
1044 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1045 }
1046
1047 // Global Named Register (GNU extension)
1048 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1049 return false;
1050
1051 // Return true for: Auto, Register.
1052 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1053
1054 return getStorageClass() >= SC_Auto;
1055 }
1056
1057 /// Returns true if a variable with function scope is a static local
1058 /// variable.
1059 bool isStaticLocal() const {
1060 return (getStorageClass() == SC_Static ||
1061 // C++11 [dcl.stc]p4
1062 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1063 && !isFileVarDecl();
1064 }
1065
1066 /// Returns true if a variable has extern or __private_extern__
1067 /// storage.
1068 bool hasExternalStorage() const {
1069 return getStorageClass() == SC_Extern ||
1070 getStorageClass() == SC_PrivateExtern;
1071 }
1072
1073 /// Returns true for all variables that do not have local storage.
1074 ///
1075 /// This includes all global variables as well as static variables declared
1076 /// within a function.
1077 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1078
1079 /// Get the storage duration of this variable, per C++ [basic.stc].
1080 StorageDuration getStorageDuration() const {
1081 return hasLocalStorage() ? SD_Automatic :
1082 getTSCSpec() ? SD_Thread : SD_Static;
1083 }
1084
1085 /// Compute the language linkage.
1086 LanguageLinkage getLanguageLinkage() const;
1087
1088 /// Determines whether this variable is a variable with external, C linkage.
1089 bool isExternC() const;
1090
1091 /// Determines whether this variable's context is, or is nested within,
1092 /// a C++ extern "C" linkage spec.
1093 bool isInExternCContext() const;
1094
1095 /// Determines whether this variable's context is, or is nested within,
1096 /// a C++ extern "C++" linkage spec.
1097 bool isInExternCXXContext() const;
1098
1099 /// Returns true for local variable declarations other than parameters.
1100 /// Note that this includes static variables inside of functions. It also
1101 /// includes variables inside blocks.
1102 ///
1103 /// void foo() { int x; static int y; extern int z; }
1104 bool isLocalVarDecl() const {
1105 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1106 return false;
1107 if (const DeclContext *DC = getLexicalDeclContext())
1108 return DC->getRedeclContext()->isFunctionOrMethod();
1109 return false;
1110 }
1111
1112 /// Similar to isLocalVarDecl but also includes parameters.
1113 bool isLocalVarDeclOrParm() const {
1114 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1115 }
1116
1117 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1118 bool isFunctionOrMethodVarDecl() const {
1119 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1120 return false;
1121 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1122 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1123 }
1124
1125 /// Determines whether this is a static data member.
1126 ///
1127 /// This will only be true in C++, and applies to, e.g., the
1128 /// variable 'x' in:
1129 /// \code
1130 /// struct S {
1131 /// static int x;
1132 /// };
1133 /// \endcode
1134 bool isStaticDataMember() const {
1135 // If it wasn't static, it would be a FieldDecl.
1136 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1137 }
1138
1139 VarDecl *getCanonicalDecl() override;
1140 const VarDecl *getCanonicalDecl() const {
1141 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1142 }
1143
1144 enum DefinitionKind {
1145 /// This declaration is only a declaration.
1146 DeclarationOnly,
1147
1148 /// This declaration is a tentative definition.
1149 TentativeDefinition,
1150
1151 /// This declaration is definitely a definition.
1152 Definition
1153 };
1154
1155 /// Check whether this declaration is a definition. If this could be
1156 /// a tentative definition (in C), don't check whether there's an overriding
1157 /// definition.
1158 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1159 DefinitionKind isThisDeclarationADefinition() const {
1160 return isThisDeclarationADefinition(getASTContext());
1161 }
1162
1163 /// Check whether this variable is defined in this translation unit.
1164 DefinitionKind hasDefinition(ASTContext &) const;
1165 DefinitionKind hasDefinition() const {
1166 return hasDefinition(getASTContext());
1167 }
1168
1169 /// Get the tentative definition that acts as the real definition in a TU.
1170 /// Returns null if there is a proper definition available.
1171 VarDecl *getActingDefinition();
1172 const VarDecl *getActingDefinition() const {
1173 return const_cast<VarDecl*>(this)->getActingDefinition();
1174 }
1175
1176 /// Get the real (not just tentative) definition for this declaration.
1177 VarDecl *getDefinition(ASTContext &);
1178 const VarDecl *getDefinition(ASTContext &C) const {
1179 return const_cast<VarDecl*>(this)->getDefinition(C);
1180 }
1181 VarDecl *getDefinition() {
1182 return getDefinition(getASTContext());
1183 }
1184 const VarDecl *getDefinition() const {
1185 return const_cast<VarDecl*>(this)->getDefinition();
1186 }
1187
1188 /// Determine whether this is or was instantiated from an out-of-line
1189 /// definition of a static data member.
1190 bool isOutOfLine() const override;
1191
1192 /// Returns true for file scoped variable declaration.
1193 bool isFileVarDecl() const {
1194 Kind K = getKind();
1195 if (K == ParmVar || K == ImplicitParam)
1196 return false;
1197
1198 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1199 return true;
1200
1201 if (isStaticDataMember())
1202 return true;
1203
1204 return false;
1205 }
1206
1207 /// Get the initializer for this variable, no matter which
1208 /// declaration it is attached to.
1209 const Expr *getAnyInitializer() const {
1210 const VarDecl *D;
1211 return getAnyInitializer(D);
1212 }
1213
1214 /// Get the initializer for this variable, no matter which
1215 /// declaration it is attached to. Also get that declaration.
1216 const Expr *getAnyInitializer(const VarDecl *&D) const;
1217
1218 bool hasInit() const;
1219 const Expr *getInit() const {
1220 return const_cast<VarDecl *>(this)->getInit();
1221 }
1222 Expr *getInit();
1223
1224 /// Retrieve the address of the initializer expression.
1225 Stmt **getInitAddress();
1226
1227 void setInit(Expr *I);
1228
1229 /// Determine whether this variable's value can be used in a
1230 /// constant expression, according to the relevant language standard.
1231 /// This only checks properties of the declaration, and does not check
1232 /// whether the initializer is in fact a constant expression.
1233 bool isUsableInConstantExpressions(ASTContext &C) const;
1234
1235 EvaluatedStmt *ensureEvaluatedStmt() const;
1236
1237 /// Attempt to evaluate the value of the initializer attached to this
1238 /// declaration, and produce notes explaining why it cannot be evaluated or is
1239 /// not a constant expression. Returns a pointer to the value if evaluation
1240 /// succeeded, 0 otherwise.
1241 APValue *evaluateValue() const;
1242 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1243
1244 /// Return the already-evaluated value of this variable's
1245 /// initializer, or NULL if the value is not yet known. Returns pointer
1246 /// to untyped APValue if the value could not be evaluated.
1247 APValue *getEvaluatedValue() const;
1248
1249 /// Determines whether it is already known whether the
1250 /// initializer is an integral constant expression or not.
1251 bool isInitKnownICE() const;
1252
1253 /// Determines whether the initializer is an integral constant
1254 /// expression, or in C++11, whether the initializer is a constant
1255 /// expression.
1256 ///
1257 /// \pre isInitKnownICE()
1258 bool isInitICE() const;
1259
1260 /// Determine whether the value of the initializer attached to this
1261 /// declaration is an integral constant expression.
1262 bool checkInitIsICE() const;
1263
1264 void setInitStyle(InitializationStyle Style) {
1265 VarDeclBits.InitStyle = Style;
1266 }
1267
1268 /// The style of initialization for this declaration.
1269 ///
1270 /// C-style initialization is "int x = 1;". Call-style initialization is
1271 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1272 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1273 /// expression for class types. List-style initialization is C++11 syntax,
1274 /// e.g. "int x{1};". Clients can distinguish between different forms of
1275 /// initialization by checking this value. In particular, "int x = {1};" is
1276 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1277 /// Init expression in all three cases is an InitListExpr.
1278 InitializationStyle getInitStyle() const {
1279 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1280 }
1281
1282 /// Whether the initializer is a direct-initializer (list or call).
1283 bool isDirectInit() const {
1284 return getInitStyle() != CInit;
1285 }
1286
1287 /// If this definition should pretend to be a declaration.
1288 bool isThisDeclarationADemotedDefinition() const {
1289 return isa<ParmVarDecl>(this) ? false :
1290 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1291 }
1292
1293 /// This is a definition which should be demoted to a declaration.
1294 ///
1295 /// In some cases (mostly module merging) we can end up with two visible
1296 /// definitions one of which needs to be demoted to a declaration to keep
1297 /// the AST invariants.
1298 void demoteThisDefinitionToDeclaration() {
1299 assert(isThisDeclarationADefinition() && "Not a definition!")((isThisDeclarationADefinition() && "Not a definition!"
) ? static_cast<void> (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1299, __PRETTY_FUNCTION__))
;
1300 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")((!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1300, __PRETTY_FUNCTION__))
;
1301 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1302 }
1303
1304 /// Determine whether this variable is the exception variable in a
1305 /// C++ catch statememt or an Objective-C \@catch statement.
1306 bool isExceptionVariable() const {
1307 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1308 }
1309 void setExceptionVariable(bool EV) {
1310 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1310, __PRETTY_FUNCTION__))
;
1311 NonParmVarDeclBits.ExceptionVar = EV;
1312 }
1313
1314 /// Determine whether this local variable can be used with the named
1315 /// return value optimization (NRVO).
1316 ///
1317 /// The named return value optimization (NRVO) works by marking certain
1318 /// non-volatile local variables of class type as NRVO objects. These
1319 /// locals can be allocated within the return slot of their containing
1320 /// function, in which case there is no need to copy the object to the
1321 /// return slot when returning from the function. Within the function body,
1322 /// each return that returns the NRVO object will have this variable as its
1323 /// NRVO candidate.
1324 bool isNRVOVariable() const {
1325 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1326 }
1327 void setNRVOVariable(bool NRVO) {
1328 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1328, __PRETTY_FUNCTION__))
;
1329 NonParmVarDeclBits.NRVOVariable = NRVO;
1330 }
1331
1332 /// Determine whether this variable is the for-range-declaration in
1333 /// a C++0x for-range statement.
1334 bool isCXXForRangeDecl() const {
1335 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1336 }
1337 void setCXXForRangeDecl(bool FRD) {
1338 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1338, __PRETTY_FUNCTION__))
;
1339 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1340 }
1341
1342 /// Determine whether this variable is a for-loop declaration for a
1343 /// for-in statement in Objective-C.
1344 bool isObjCForDecl() const {
1345 return NonParmVarDeclBits.ObjCForDecl;
1346 }
1347
1348 void setObjCForDecl(bool FRD) {
1349 NonParmVarDeclBits.ObjCForDecl = FRD;
1350 }
1351
1352 /// Determine whether this variable is an ARC pseudo-__strong
1353 /// variable. A pseudo-__strong variable has a __strong-qualified
1354 /// type but does not actually retain the object written into it.
1355 /// Generally such variables are also 'const' for safety.
1356 bool isARCPseudoStrong() const {
1357 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1358 }
1359 void setARCPseudoStrong(bool ps) {
1360 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1360, __PRETTY_FUNCTION__))
;
1361 NonParmVarDeclBits.ARCPseudoStrong = ps;
1362 }
1363
1364 /// Whether this variable is (C++1z) inline.
1365 bool isInline() const {
1366 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1367 }
1368 bool isInlineSpecified() const {
1369 return isa<ParmVarDecl>(this) ? false
1370 : NonParmVarDeclBits.IsInlineSpecified;
1371 }
1372 void setInlineSpecified() {
1373 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1373, __PRETTY_FUNCTION__))
;
1374 NonParmVarDeclBits.IsInline = true;
1375 NonParmVarDeclBits.IsInlineSpecified = true;
1376 }
1377 void setImplicitlyInline() {
1378 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1378, __PRETTY_FUNCTION__))
;
1379 NonParmVarDeclBits.IsInline = true;
1380 }
1381
1382 /// Whether this variable is (C++11) constexpr.
1383 bool isConstexpr() const {
1384 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1385 }
1386 void setConstexpr(bool IC) {
1387 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1387, __PRETTY_FUNCTION__))
;
1388 NonParmVarDeclBits.IsConstexpr = IC;
1389 }
1390
1391 /// Whether this variable is the implicit variable for a lambda init-capture.
1392 bool isInitCapture() const {
1393 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1394 }
1395 void setInitCapture(bool IC) {
1396 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1396, __PRETTY_FUNCTION__))
;
1397 NonParmVarDeclBits.IsInitCapture = IC;
1398 }
1399
1400 /// Whether this local extern variable declaration's previous declaration
1401 /// was declared in the same block scope. Only correct in C++.
1402 bool isPreviousDeclInSameBlockScope() const {
1403 return isa<ParmVarDecl>(this)
1404 ? false
1405 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1406 }
1407 void setPreviousDeclInSameBlockScope(bool Same) {
1408 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1408, __PRETTY_FUNCTION__))
;
1409 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1410 }
1411
1412 /// Indicates the capture is a __block variable that is captured by a block
1413 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1414 /// returns false).
1415 bool isEscapingByref() const;
1416
1417 /// Indicates the capture is a __block variable that is never captured by an
1418 /// escaping block.
1419 bool isNonEscapingByref() const;
1420
1421 void setEscapingByref() {
1422 NonParmVarDeclBits.EscapingByref = true;
1423 }
1424
1425 /// Retrieve the variable declaration from which this variable could
1426 /// be instantiated, if it is an instantiation (rather than a non-template).
1427 VarDecl *getTemplateInstantiationPattern() const;
1428
1429 /// If this variable is an instantiated static data member of a
1430 /// class template specialization, returns the templated static data member
1431 /// from which it was instantiated.
1432 VarDecl *getInstantiatedFromStaticDataMember() const;
1433
1434 /// If this variable is an instantiation of a variable template or a
1435 /// static data member of a class template, determine what kind of
1436 /// template specialization or instantiation this is.
1437 TemplateSpecializationKind getTemplateSpecializationKind() const;
1438
1439 /// If this variable is an instantiation of a variable template or a
1440 /// static data member of a class template, determine its point of
1441 /// instantiation.
1442 SourceLocation getPointOfInstantiation() const;
1443
1444 /// If this variable is an instantiation of a static data member of a
1445 /// class template specialization, retrieves the member specialization
1446 /// information.
1447 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1448
1449 /// For a static data member that was instantiated from a static
1450 /// data member of a class template, set the template specialiation kind.
1451 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1452 SourceLocation PointOfInstantiation = SourceLocation());
1453
1454 /// Specify that this variable is an instantiation of the
1455 /// static data member VD.
1456 void setInstantiationOfStaticDataMember(VarDecl *VD,
1457 TemplateSpecializationKind TSK);
1458
1459 /// Retrieves the variable template that is described by this
1460 /// variable declaration.
1461 ///
1462 /// Every variable template is represented as a VarTemplateDecl and a
1463 /// VarDecl. The former contains template properties (such as
1464 /// the template parameter lists) while the latter contains the
1465 /// actual description of the template's
1466 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1467 /// VarDecl that from a VarTemplateDecl, while
1468 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1469 /// a VarDecl.
1470 VarTemplateDecl *getDescribedVarTemplate() const;
1471
1472 void setDescribedVarTemplate(VarTemplateDecl *Template);
1473
1474 // Is this variable known to have a definition somewhere in the complete
1475 // program? This may be true even if the declaration has internal linkage and
1476 // has no definition within this source file.
1477 bool isKnownToBeDefined() const;
1478
1479 /// Do we need to emit an exit-time destructor for this variable?
1480 bool isNoDestroy(const ASTContext &) const;
1481
1482 // Implement isa/cast/dyncast/etc.
1483 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1484 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1485};
1486
1487class ImplicitParamDecl : public VarDecl {
1488 void anchor() override;
1489
1490public:
1491 /// Defines the kind of the implicit parameter: is this an implicit parameter
1492 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1493 /// context or something else.
1494 enum ImplicitParamKind : unsigned {
1495 /// Parameter for Objective-C 'self' argument
1496 ObjCSelf,
1497
1498 /// Parameter for Objective-C '_cmd' argument
1499 ObjCCmd,
1500
1501 /// Parameter for C++ 'this' argument
1502 CXXThis,
1503
1504 /// Parameter for C++ virtual table pointers
1505 CXXVTT,
1506
1507 /// Parameter for captured context
1508 CapturedContext,
1509
1510 /// Other implicit parameter
1511 Other,
1512 };
1513
1514 /// Create implicit parameter.
1515 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1516 SourceLocation IdLoc, IdentifierInfo *Id,
1517 QualType T, ImplicitParamKind ParamKind);
1518 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1519 ImplicitParamKind ParamKind);
1520
1521 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1522
1523 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1524 IdentifierInfo *Id, QualType Type,
1525 ImplicitParamKind ParamKind)
1526 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1527 /*TInfo=*/nullptr, SC_None) {
1528 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1529 setImplicit();
1530 }
1531
1532 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1533 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1534 SourceLocation(), /*Id=*/nullptr, Type,
1535 /*TInfo=*/nullptr, SC_None) {
1536 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1537 setImplicit();
1538 }
1539
1540 /// Returns the implicit parameter kind.
1541 ImplicitParamKind getParameterKind() const {
1542 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1543 }
1544
1545 // Implement isa/cast/dyncast/etc.
1546 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1547 static bool classofKind(Kind K) { return K == ImplicitParam; }
1548};
1549
1550/// Represents a parameter to a function.
1551class ParmVarDecl : public VarDecl {
1552public:
1553 enum { MaxFunctionScopeDepth = 255 };
1554 enum { MaxFunctionScopeIndex = 255 };
1555
1556protected:
1557 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1558 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1559 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1560 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1561 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)((ParmVarDeclBits.HasInheritedDefaultArg == false) ? static_cast
<void> (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1561, __PRETTY_FUNCTION__))
;
1562 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)((ParmVarDeclBits.DefaultArgKind == DAK_None) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1562, __PRETTY_FUNCTION__))
;
1563 assert(ParmVarDeclBits.IsKNRPromoted == false)((ParmVarDeclBits.IsKNRPromoted == false) ? static_cast<void
> (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1563, __PRETTY_FUNCTION__))
;
1564 assert(ParmVarDeclBits.IsObjCMethodParam == false)((ParmVarDeclBits.IsObjCMethodParam == false) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1564, __PRETTY_FUNCTION__))
;
1565 setDefaultArg(DefArg);
1566 }
1567
1568public:
1569 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1570 SourceLocation StartLoc,
1571 SourceLocation IdLoc, IdentifierInfo *Id,
1572 QualType T, TypeSourceInfo *TInfo,
1573 StorageClass S, Expr *DefArg);
1574
1575 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1576
1577 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1578
1579 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1580 ParmVarDeclBits.IsObjCMethodParam = true;
1581 setParameterIndex(parameterIndex);
1582 }
1583
1584 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1585 assert(!ParmVarDeclBits.IsObjCMethodParam)((!ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1585, __PRETTY_FUNCTION__))
;
1586
1587 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1588 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1589, __PRETTY_FUNCTION__))
1589 && "truncation!")((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1589, __PRETTY_FUNCTION__))
;
1590
1591 setParameterIndex(parameterIndex);
1592 }
1593
1594 bool isObjCMethodParameter() const {
1595 return ParmVarDeclBits.IsObjCMethodParam;
1596 }
1597
1598 unsigned getFunctionScopeDepth() const {
1599 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1600 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1601 }
1602
1603 /// Returns the index of this parameter in its prototype or method scope.
1604 unsigned getFunctionScopeIndex() const {
1605 return getParameterIndex();
1606 }
1607
1608 ObjCDeclQualifier getObjCDeclQualifier() const {
1609 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1610 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1611 }
1612 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1613 assert(ParmVarDeclBits.IsObjCMethodParam)((ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1613, __PRETTY_FUNCTION__))
;
1614 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1615 }
1616
1617 /// True if the value passed to this parameter must undergo
1618 /// K&R-style default argument promotion:
1619 ///
1620 /// C99 6.5.2.2.
1621 /// If the expression that denotes the called function has a type
1622 /// that does not include a prototype, the integer promotions are
1623 /// performed on each argument, and arguments that have type float
1624 /// are promoted to double.
1625 bool isKNRPromoted() const {
1626 return ParmVarDeclBits.IsKNRPromoted;
1627 }
1628 void setKNRPromoted(bool promoted) {
1629 ParmVarDeclBits.IsKNRPromoted = promoted;
1630 }
1631
1632 Expr *getDefaultArg();
1633 const Expr *getDefaultArg() const {
1634 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1635 }
1636
1637 void setDefaultArg(Expr *defarg);
1638
1639 /// Retrieve the source range that covers the entire default
1640 /// argument.
1641 SourceRange getDefaultArgRange() const;
1642 void setUninstantiatedDefaultArg(Expr *arg);
1643 Expr *getUninstantiatedDefaultArg();
1644 const Expr *getUninstantiatedDefaultArg() const {
1645 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1646 }
1647
1648 /// Determines whether this parameter has a default argument,
1649 /// either parsed or not.
1650 bool hasDefaultArg() const;
1651
1652 /// Determines whether this parameter has a default argument that has not
1653 /// yet been parsed. This will occur during the processing of a C++ class
1654 /// whose member functions have default arguments, e.g.,
1655 /// @code
1656 /// class X {
1657 /// public:
1658 /// void f(int x = 17); // x has an unparsed default argument now
1659 /// }; // x has a regular default argument now
1660 /// @endcode
1661 bool hasUnparsedDefaultArg() const {
1662 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1663 }
1664
1665 bool hasUninstantiatedDefaultArg() const {
1666 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1667 }
1668
1669 /// Specify that this parameter has an unparsed default argument.
1670 /// The argument will be replaced with a real default argument via
1671 /// setDefaultArg when the class definition enclosing the function
1672 /// declaration that owns this default argument is completed.
1673 void setUnparsedDefaultArg() {
1674 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1675 }
1676
1677 bool hasInheritedDefaultArg() const {
1678 return ParmVarDeclBits.HasInheritedDefaultArg;
1679 }
1680
1681 void setHasInheritedDefaultArg(bool I = true) {
1682 ParmVarDeclBits.HasInheritedDefaultArg = I;
1683 }
1684
1685 QualType getOriginalType() const;
1686
1687 /// Determine whether this parameter is actually a function
1688 /// parameter pack.
1689 bool isParameterPack() const;
1690
1691 /// Sets the function declaration that owns this
1692 /// ParmVarDecl. Since ParmVarDecls are often created before the
1693 /// FunctionDecls that own them, this routine is required to update
1694 /// the DeclContext appropriately.
1695 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1696
1697 // Implement isa/cast/dyncast/etc.
1698 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1699 static bool classofKind(Kind K) { return K == ParmVar; }
1700
1701private:
1702 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1703
1704 void setParameterIndex(unsigned parameterIndex) {
1705 if (parameterIndex >= ParameterIndexSentinel) {
1706 setParameterIndexLarge(parameterIndex);
1707 return;
1708 }
1709
1710 ParmVarDeclBits.ParameterIndex = parameterIndex;
1711 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")((ParmVarDeclBits.ParameterIndex == parameterIndex &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 1711, __PRETTY_FUNCTION__))
;
1712 }
1713 unsigned getParameterIndex() const {
1714 unsigned d = ParmVarDeclBits.ParameterIndex;
1715 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1716 }
1717
1718 void setParameterIndexLarge(unsigned parameterIndex);
1719 unsigned getParameterIndexLarge() const;
1720};
1721
1722enum class MultiVersionKind {
1723 None,
1724 Target,
1725 CPUSpecific,
1726 CPUDispatch
1727};
1728
1729/// Represents a function declaration or definition.
1730///
1731/// Since a given function can be declared several times in a program,
1732/// there may be several FunctionDecls that correspond to that
1733/// function. Only one of those FunctionDecls will be found when
1734/// traversing the list of declarations in the context of the
1735/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1736/// contains all of the information known about the function. Other,
1737/// previous declarations of the function are available via the
1738/// getPreviousDecl() chain.
1739class FunctionDecl : public DeclaratorDecl,
1740 public DeclContext,
1741 public Redeclarable<FunctionDecl> {
1742 // This class stores some data in DeclContext::FunctionDeclBits
1743 // to save some space. Use the provided accessors to access it.
1744public:
1745 /// The kind of templated function a FunctionDecl can be.
1746 enum TemplatedKind {
1747 TK_NonTemplate,
1748 TK_FunctionTemplate,
1749 TK_MemberSpecialization,
1750 TK_FunctionTemplateSpecialization,
1751 TK_DependentFunctionTemplateSpecialization
1752 };
1753
1754private:
1755 /// A new[]'d array of pointers to VarDecls for the formal
1756 /// parameters of this function. This is null if a prototype or if there are
1757 /// no formals.
1758 ParmVarDecl **ParamInfo = nullptr;
1759
1760 LazyDeclStmtPtr Body;
1761
1762 unsigned ODRHash;
1763
1764 /// End part of this FunctionDecl's source range.
1765 ///
1766 /// We could compute the full range in getSourceRange(). However, when we're
1767 /// dealing with a function definition deserialized from a PCH/AST file,
1768 /// we can only compute the full range once the function body has been
1769 /// de-serialized, so it's far better to have the (sometimes-redundant)
1770 /// EndRangeLoc.
1771 SourceLocation EndRangeLoc;
1772
1773 /// The template or declaration that this declaration
1774 /// describes or was instantiated from, respectively.
1775 ///
1776 /// For non-templates, this value will be NULL. For function
1777 /// declarations that describe a function template, this will be a
1778 /// pointer to a FunctionTemplateDecl. For member functions
1779 /// of class template specializations, this will be a MemberSpecializationInfo
1780 /// pointer containing information about the specialization.
1781 /// For function template specializations, this will be a
1782 /// FunctionTemplateSpecializationInfo, which contains information about
1783 /// the template being specialized and the template arguments involved in
1784 /// that specialization.
1785 llvm::PointerUnion4<FunctionTemplateDecl *,
1786 MemberSpecializationInfo *,
1787 FunctionTemplateSpecializationInfo *,
1788 DependentFunctionTemplateSpecializationInfo *>
1789 TemplateOrSpecialization;
1790
1791 /// Provides source/type location info for the declaration name embedded in
1792 /// the DeclaratorDecl base class.
1793 DeclarationNameLoc DNLoc;
1794
1795 /// Specify that this function declaration is actually a function
1796 /// template specialization.
1797 ///
1798 /// \param C the ASTContext.
1799 ///
1800 /// \param Template the function template that this function template
1801 /// specialization specializes.
1802 ///
1803 /// \param TemplateArgs the template arguments that produced this
1804 /// function template specialization from the template.
1805 ///
1806 /// \param InsertPos If non-NULL, the position in the function template
1807 /// specialization set where the function template specialization data will
1808 /// be inserted.
1809 ///
1810 /// \param TSK the kind of template specialization this is.
1811 ///
1812 /// \param TemplateArgsAsWritten location info of template arguments.
1813 ///
1814 /// \param PointOfInstantiation point at which the function template
1815 /// specialization was first instantiated.
1816 void setFunctionTemplateSpecialization(ASTContext &C,
1817 FunctionTemplateDecl *Template,
1818 const TemplateArgumentList *TemplateArgs,
1819 void *InsertPos,
1820 TemplateSpecializationKind TSK,
1821 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1822 SourceLocation PointOfInstantiation);
1823
1824 /// Specify that this record is an instantiation of the
1825 /// member function FD.
1826 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1827 TemplateSpecializationKind TSK);
1828
1829 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1830
1831 // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
1832 // need to access this bit but we want to avoid making ASTDeclWriter
1833 // a friend of FunctionDeclBitfields just for this.
1834 bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
1835
1836 /// Whether an ODRHash has been stored.
1837 bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
1838
1839 /// State that an ODRHash has been stored.
1840 void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
1841
1842protected:
1843 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1844 const DeclarationNameInfo &NameInfo, QualType T,
1845 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1846 bool isConstexprSpecified);
1847
1848 using redeclarable_base = Redeclarable<FunctionDecl>;
1849
1850 FunctionDecl *getNextRedeclarationImpl() override {
1851 return getNextRedeclaration();
1852 }
1853
1854 FunctionDecl *getPreviousDeclImpl() override {
1855 return getPreviousDecl();
1856 }
1857
1858 FunctionDecl *getMostRecentDeclImpl() override {
1859 return getMostRecentDecl();
1860 }
1861
1862public:
1863 friend class ASTDeclReader;
1864 friend class ASTDeclWriter;
1865
1866 using redecl_range = redeclarable_base::redecl_range;
1867 using redecl_iterator = redeclarable_base::redecl_iterator;
1868
1869 using redeclarable_base::redecls_begin;
1870 using redeclarable_base::redecls_end;
1871 using redeclarable_base::redecls;
1872 using redeclarable_base::getPreviousDecl;
1873 using redeclarable_base::getMostRecentDecl;
1874 using redeclarable_base::isFirstDecl;
1875
1876 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1877 SourceLocation StartLoc, SourceLocation NLoc,
1878 DeclarationName N, QualType T,
1879 TypeSourceInfo *TInfo,
1880 StorageClass SC,
1881 bool isInlineSpecified = false,
1882 bool hasWrittenPrototype = true,
1883 bool isConstexprSpecified = false) {
1884 DeclarationNameInfo NameInfo(N, NLoc);
1885 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1886 SC,
1887 isInlineSpecified, hasWrittenPrototype,
1888 isConstexprSpecified);
1889 }
1890
1891 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1892 SourceLocation StartLoc,
1893 const DeclarationNameInfo &NameInfo,
1894 QualType T, TypeSourceInfo *TInfo,
1895 StorageClass SC,
1896 bool isInlineSpecified,
1897 bool hasWrittenPrototype,
1898 bool isConstexprSpecified = false);
1899
1900 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1901
1902 DeclarationNameInfo getNameInfo() const {
1903 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1904 }
1905
1906 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1907 bool Qualified) const override;
1908
1909 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1910
1911 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1912
1913 // Function definitions.
1914 //
1915 // A function declaration may be:
1916 // - a non defining declaration,
1917 // - a definition. A function may be defined because:
1918 // - it has a body, or will have it in the case of late parsing.
1919 // - it has an uninstantiated body. The body does not exist because the
1920 // function is not used yet, but the declaration is considered a
1921 // definition and does not allow other definition of this function.
1922 // - it does not have a user specified body, but it does not allow
1923 // redefinition, because it is deleted/defaulted or is defined through
1924 // some other mechanism (alias, ifunc).
1925
1926 /// Returns true if the function has a body.
1927 ///
1928 /// The function body might be in any of the (re-)declarations of this
1929 /// function. The variant that accepts a FunctionDecl pointer will set that
1930 /// function declaration to the actual declaration containing the body (if
1931 /// there is one).
1932 bool hasBody(const FunctionDecl *&Definition) const;
1933
1934 bool hasBody() const override {
1935 const FunctionDecl* Definition;
1936 return hasBody(Definition);
1937 }
1938
1939 /// Returns whether the function has a trivial body that does not require any
1940 /// specific codegen.
1941 bool hasTrivialBody() const;
1942
1943 /// Returns true if the function has a definition that does not need to be
1944 /// instantiated.
1945 ///
1946 /// The variant that accepts a FunctionDecl pointer will set that function
1947 /// declaration to the declaration that is a definition (if there is one).
1948 bool isDefined(const FunctionDecl *&Definition) const;
1949
1950 virtual bool isDefined() const {
1951 const FunctionDecl* Definition;
1952 return isDefined(Definition);
1953 }
1954
1955 /// Get the definition for this declaration.
1956 FunctionDecl *getDefinition() {
1957 const FunctionDecl *Definition;
1958 if (isDefined(Definition))
1959 return const_cast<FunctionDecl *>(Definition);
1960 return nullptr;
1961 }
1962 const FunctionDecl *getDefinition() const {
1963 return const_cast<FunctionDecl *>(this)->getDefinition();
1964 }
1965
1966 /// Retrieve the body (definition) of the function. The function body might be
1967 /// in any of the (re-)declarations of this function. The variant that accepts
1968 /// a FunctionDecl pointer will set that function declaration to the actual
1969 /// declaration containing the body (if there is one).
1970 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1971 /// unnecessary AST de-serialization of the body.
1972 Stmt *getBody(const FunctionDecl *&Definition) const;
1973
1974 Stmt *getBody() const override {
1975 const FunctionDecl* Definition;
1976 return getBody(Definition);
1977 }
1978
1979 /// Returns whether this specific declaration of the function is also a
1980 /// definition that does not contain uninstantiated body.
1981 ///
1982 /// This does not determine whether the function has been defined (e.g., in a
1983 /// previous definition); for that information, use isDefined.
1984 bool isThisDeclarationADefinition() const {
1985 return isDeletedAsWritten() || isDefaulted() || Body || hasSkippedBody() ||
1986 isLateTemplateParsed() || willHaveBody() || hasDefiningAttr();
1987 }
1988
1989 /// Returns whether this specific declaration of the function has a body.
1990 bool doesThisDeclarationHaveABody() const {
1991 return Body || isLateTemplateParsed();
1992 }
1993
1994 void setBody(Stmt *B);
1995 void setLazyBody(uint64_t Offset) { Body = Offset; }
1996
1997 /// Whether this function is variadic.
1998 bool isVariadic() const;
1999
2000 /// Whether this function is marked as virtual explicitly.
2001 bool isVirtualAsWritten() const {
2002 return FunctionDeclBits.IsVirtualAsWritten;
2003 }
2004
2005 /// State that this function is marked as virtual explicitly.
2006 void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2007
2008 /// Whether this virtual function is pure, i.e. makes the containing class
2009 /// abstract.
2010 bool isPure() const { return FunctionDeclBits.IsPure; }
2011 void setPure(bool P = true);
2012
2013 /// Whether this templated function will be late parsed.
2014 bool isLateTemplateParsed() const {
2015 return FunctionDeclBits.IsLateTemplateParsed;
2016 }
2017
2018 /// State that this templated function will be late parsed.
2019 void setLateTemplateParsed(bool ILT = true) {
2020 FunctionDeclBits.IsLateTemplateParsed = ILT;
2021 }
2022
2023 /// Whether this function is "trivial" in some specialized C++ senses.
2024 /// Can only be true for default constructors, copy constructors,
2025 /// copy assignment operators, and destructors. Not meaningful until
2026 /// the class has been fully built by Sema.
2027 bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2028 void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2029
2030 bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2031 void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2032
2033 /// Whether this function is defaulted per C++0x. Only valid for
2034 /// special member functions.
2035 bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2036 void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2037
2038 /// Whether this function is explicitly defaulted per C++0x. Only valid
2039 /// for special member functions.
2040 bool isExplicitlyDefaulted() const {
2041 return FunctionDeclBits.IsExplicitlyDefaulted;
2042 }
2043
2044 /// State that this function is explicitly defaulted per C++0x. Only valid
2045 /// for special member functions.
2046 void setExplicitlyDefaulted(bool ED = true) {
2047 FunctionDeclBits.IsExplicitlyDefaulted = ED;
2048 }
2049
2050 /// Whether falling off this function implicitly returns null/zero.
2051 /// If a more specific implicit return value is required, front-ends
2052 /// should synthesize the appropriate return statements.
2053 bool hasImplicitReturnZero() const {
2054 return FunctionDeclBits.HasImplicitReturnZero;
2055 }
2056
2057 /// State that falling off this function implicitly returns null/zero.
2058 /// If a more specific implicit return value is required, front-ends
2059 /// should synthesize the appropriate return statements.
2060 void setHasImplicitReturnZero(bool IRZ) {
2061 FunctionDeclBits.HasImplicitReturnZero = IRZ;
2062 }
2063
2064 /// Whether this function has a prototype, either because one
2065 /// was explicitly written or because it was "inherited" by merging
2066 /// a declaration without a prototype with a declaration that has a
2067 /// prototype.
2068 bool hasPrototype() const {
2069 return hasWrittenPrototype() || hasInheritedPrototype();
2070 }
2071
2072 /// Whether this function has a written prototype.
2073 bool hasWrittenPrototype() const {
2074 return FunctionDeclBits.HasWrittenPrototype;
2075 }
2076
2077 /// State that this function has a written prototype.
2078 void setHasWrittenPrototype(bool P = true) {
2079 FunctionDeclBits.HasWrittenPrototype = P;
2080 }
2081
2082 /// Whether this function inherited its prototype from a
2083 /// previous declaration.
2084 bool hasInheritedPrototype() const {
2085 return FunctionDeclBits.HasInheritedPrototype;
2086 }
2087
2088 /// State that this function inherited its prototype from a
2089 /// previous declaration.
2090 void setHasInheritedPrototype(bool P = true) {
2091 FunctionDeclBits.HasInheritedPrototype = P;
2092 }
2093
2094 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2095 bool isConstexpr() const { return FunctionDeclBits.IsConstexpr; }
2096 void setConstexpr(bool IC) { FunctionDeclBits.IsConstexpr = IC; }
2097
2098 /// Whether the instantiation of this function is pending.
2099 /// This bit is set when the decision to instantiate this function is made
2100 /// and unset if and when the function body is created. That leaves out
2101 /// cases where instantiation did not happen because the template definition
2102 /// was not seen in this TU. This bit remains set in those cases, under the
2103 /// assumption that the instantiation will happen in some other TU.
2104 bool instantiationIsPending() const {
2105 return FunctionDeclBits.InstantiationIsPending;
2106 }
2107
2108 /// State that the instantiation of this function is pending.
2109 /// (see instantiationIsPending)
2110 void setInstantiationIsPending(bool IC) {
2111 FunctionDeclBits.InstantiationIsPending = IC;
2112 }
2113
2114 /// Indicates the function uses __try.
2115 bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2116 void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2117
2118 /// Whether this function has been deleted.
2119 ///
2120 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2121 /// acts like a normal function, except that it cannot actually be
2122 /// called or have its address taken. Deleted functions are
2123 /// typically used in C++ overload resolution to attract arguments
2124 /// whose type or lvalue/rvalue-ness would permit the use of a
2125 /// different overload that would behave incorrectly. For example,
2126 /// one might use deleted functions to ban implicit conversion from
2127 /// a floating-point number to an Integer type:
2128 ///
2129 /// @code
2130 /// struct Integer {
2131 /// Integer(long); // construct from a long
2132 /// Integer(double) = delete; // no construction from float or double
2133 /// Integer(long double) = delete; // no construction from long double
2134 /// };
2135 /// @endcode
2136 // If a function is deleted, its first declaration must be.
2137 bool isDeleted() const {
2138 return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2139 }
2140
2141 bool isDeletedAsWritten() const {
2142 return FunctionDeclBits.IsDeleted && !isDefaulted();
2143 }
2144
2145 void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2146
2147 /// Determines whether this function is "main", which is the
2148 /// entry point into an executable program.
2149 bool isMain() const;
2150
2151 /// Determines whether this function is a MSVCRT user defined entry
2152 /// point.
2153 bool isMSVCRTEntryPoint() const;
2154
2155 /// Determines whether this operator new or delete is one
2156 /// of the reserved global placement operators:
2157 /// void *operator new(size_t, void *);
2158 /// void *operator new[](size_t, void *);
2159 /// void operator delete(void *, void *);
2160 /// void operator delete[](void *, void *);
2161 /// These functions have special behavior under [new.delete.placement]:
2162 /// These functions are reserved, a C++ program may not define
2163 /// functions that displace the versions in the Standard C++ library.
2164 /// The provisions of [basic.stc.dynamic] do not apply to these
2165 /// reserved placement forms of operator new and operator delete.
2166 ///
2167 /// This function must be an allocation or deallocation function.
2168 bool isReservedGlobalPlacementOperator() const;
2169
2170 /// Determines whether this function is one of the replaceable
2171 /// global allocation functions:
2172 /// void *operator new(size_t);
2173 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2174 /// void *operator new[](size_t);
2175 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2176 /// void operator delete(void *) noexcept;
2177 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2178 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2179 /// void operator delete[](void *) noexcept;
2180 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2181 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2182 /// These functions have special behavior under C++1y [expr.new]:
2183 /// An implementation is allowed to omit a call to a replaceable global
2184 /// allocation function. [...]
2185 ///
2186 /// If this function is an aligned allocation/deallocation function, return
2187 /// true through IsAligned.
2188 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2189
2190 /// Determine whether this is a destroying operator delete.
2191 bool isDestroyingOperatorDelete() const;
2192
2193 /// Compute the language linkage.
2194 LanguageLinkage getLanguageLinkage() const;
2195
2196 /// Determines whether this function is a function with
2197 /// external, C linkage.
2198 bool isExternC() const;
2199
2200 /// Determines whether this function's context is, or is nested within,
2201 /// a C++ extern "C" linkage spec.
2202 bool isInExternCContext() const;
2203
2204 /// Determines whether this function's context is, or is nested within,
2205 /// a C++ extern "C++" linkage spec.
2206 bool isInExternCXXContext() const;
2207
2208 /// Determines whether this is a global function.
2209 bool isGlobal() const;
2210
2211 /// Determines whether this function is known to be 'noreturn', through
2212 /// an attribute on its declaration or its type.
2213 bool isNoReturn() const;
2214
2215 /// True if the function was a definition but its body was skipped.
2216 bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2217 void setHasSkippedBody(bool Skipped = true) {
2218 FunctionDeclBits.HasSkippedBody = Skipped;
2219 }
2220
2221 /// True if this function will eventually have a body, once it's fully parsed.
2222 bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2223 void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2224
2225 /// True if this function is considered a multiversioned function.
2226 bool isMultiVersion() const {
2227 return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2228 }
2229
2230 /// Sets the multiversion state for this declaration and all of its
2231 /// redeclarations.
2232 void setIsMultiVersion(bool V = true) {
2233 getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2234 }
2235
2236 /// Gets the kind of multiversioning attribute this declaration has. Note that
2237 /// this can return a value even if the function is not multiversion, such as
2238 /// the case of 'target'.
2239 MultiVersionKind getMultiVersionKind() const;
2240
2241
2242 /// True if this function is a multiversioned dispatch function as a part of
2243 /// the cpu_specific/cpu_dispatch functionality.
2244 bool isCPUDispatchMultiVersion() const;
2245 /// True if this function is a multiversioned processor specific function as a
2246 /// part of the cpu_specific/cpu_dispatch functionality.
2247 bool isCPUSpecificMultiVersion() const;
2248
2249 /// True if this function is a multiversioned dispatch function as a part of
2250 /// the target functionality.
2251 bool isTargetMultiVersion() const;
2252
2253 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2254
2255 FunctionDecl *getCanonicalDecl() override;
2256 const FunctionDecl *getCanonicalDecl() const {
2257 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2258 }
2259
2260 unsigned getBuiltinID() const;
2261
2262 // ArrayRef interface to parameters.
2263 ArrayRef<ParmVarDecl *> parameters() const {
2264 return {ParamInfo, getNumParams()};
2265 }
2266 MutableArrayRef<ParmVarDecl *> parameters() {
2267 return {ParamInfo, getNumParams()};
2268 }
2269
2270 // Iterator access to formal parameters.
2271 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2272 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2273
2274 bool param_empty() const { return parameters().empty(); }
2275 param_iterator param_begin() { return parameters().begin(); }
2276 param_iterator param_end() { return parameters().end(); }
2277 param_const_iterator param_begin() const { return parameters().begin(); }
2278 param_const_iterator param_end() const { return parameters().end(); }
2279 size_t param_size() const { return parameters().size(); }
2280
2281 /// Return the number of parameters this function must have based on its
2282 /// FunctionType. This is the length of the ParamInfo array after it has been
2283 /// created.
2284 unsigned getNumParams() const;
2285
2286 const ParmVarDecl *getParamDecl(unsigned i) const {
2287 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2287, __PRETTY_FUNCTION__))
;
33
Assuming the condition is true
34
'?' condition is true
2288 return ParamInfo[i];
35
Returning pointer
2289 }
2290 ParmVarDecl *getParamDecl(unsigned i) {
2291 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2291, __PRETTY_FUNCTION__))
;
2292 return ParamInfo[i];
2293 }
2294 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2295 setParams(getASTContext(), NewParamInfo);
2296 }
2297
2298 /// Returns the minimum number of arguments needed to call this function. This
2299 /// may be fewer than the number of function parameters, if some of the
2300 /// parameters have default arguments (in C++).
2301 unsigned getMinRequiredArguments() const;
2302
2303 QualType getReturnType() const {
2304 return getType()->castAs<FunctionType>()->getReturnType();
2305 }
2306
2307 /// Attempt to compute an informative source range covering the
2308 /// function return type. This may omit qualifiers and other information with
2309 /// limited representation in the AST.
2310 SourceRange getReturnTypeSourceRange() const;
2311
2312 /// Get the declared return type, which may differ from the actual return
2313 /// type if the return type is deduced.
2314 QualType getDeclaredReturnType() const {
2315 auto *TSI = getTypeSourceInfo();
2316 QualType T = TSI ? TSI->getType() : getType();
2317 return T->castAs<FunctionType>()->getReturnType();
2318 }
2319
2320 /// Attempt to compute an informative source range covering the
2321 /// function exception specification, if any.
2322 SourceRange getExceptionSpecSourceRange() const;
2323
2324 /// Determine the type of an expression that calls this function.
2325 QualType getCallResultType() const {
2326 return getType()->castAs<FunctionType>()->getCallResultType(
2327 getASTContext());
2328 }
2329
2330 /// Returns the WarnUnusedResultAttr that is either declared on this
2331 /// function, or its return type declaration.
2332 const Attr *getUnusedResultAttr() const;
2333
2334 /// Returns true if this function or its return type has the
2335 /// warn_unused_result attribute.
2336 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2337
2338 /// Returns the storage class as written in the source. For the
2339 /// computed linkage of symbol, see getLinkage.
2340 StorageClass getStorageClass() const {
2341 return static_cast<StorageClass>(FunctionDeclBits.SClass);
2342 }
2343
2344 /// Sets the storage class as written in the source.
2345 void setStorageClass(StorageClass SClass) {
2346 FunctionDeclBits.SClass = SClass;
2347 }
2348
2349 /// Determine whether the "inline" keyword was specified for this
2350 /// function.
2351 bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2352
2353 /// Set whether the "inline" keyword was specified for this function.
2354 void setInlineSpecified(bool I) {
2355 FunctionDeclBits.IsInlineSpecified = I;
2356 FunctionDeclBits.IsInline = I;
2357 }
2358
2359 /// Flag that this function is implicitly inline.
2360 void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2361
2362 /// Determine whether this function should be inlined, because it is
2363 /// either marked "inline" or "constexpr" or is a member function of a class
2364 /// that was defined in the class body.
2365 bool isInlined() const { return FunctionDeclBits.IsInline; }
2366
2367 /// Whether this function is marked as explicit explicitly.
2368 bool isExplicitSpecified() const {
2369 return FunctionDeclBits.IsExplicitSpecified;
2370 }
2371
2372 /// State that this function is marked as explicit explicitly.
2373 void setExplicitSpecified(bool ExpSpec = true) {
2374 FunctionDeclBits.IsExplicitSpecified = ExpSpec;
2375 }
2376
2377 bool isInlineDefinitionExternallyVisible() const;
2378
2379 bool isMSExternInline() const;
2380
2381 bool doesDeclarationForceExternallyVisibleDefinition() const;
2382
2383 /// Whether this function declaration represents an C++ overloaded
2384 /// operator, e.g., "operator+".
2385 bool isOverloadedOperator() const {
2386 return getOverloadedOperator() != OO_None;
2387 }
2388
2389 OverloadedOperatorKind getOverloadedOperator() const;
2390
2391 const IdentifierInfo *getLiteralIdentifier() const;
2392
2393 /// If this function is an instantiation of a member function
2394 /// of a class template specialization, retrieves the function from
2395 /// which it was instantiated.
2396 ///
2397 /// This routine will return non-NULL for (non-templated) member
2398 /// functions of class templates and for instantiations of function
2399 /// templates. For example, given:
2400 ///
2401 /// \code
2402 /// template<typename T>
2403 /// struct X {
2404 /// void f(T);
2405 /// };
2406 /// \endcode
2407 ///
2408 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2409 /// whose parent is the class template specialization X<int>. For
2410 /// this declaration, getInstantiatedFromFunction() will return
2411 /// the FunctionDecl X<T>::A. When a complete definition of
2412 /// X<int>::A is required, it will be instantiated from the
2413 /// declaration returned by getInstantiatedFromMemberFunction().
2414 FunctionDecl *getInstantiatedFromMemberFunction() const;
2415
2416 /// What kind of templated function this is.
2417 TemplatedKind getTemplatedKind() const;
2418
2419 /// If this function is an instantiation of a member function of a
2420 /// class template specialization, retrieves the member specialization
2421 /// information.
2422 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2423
2424 /// Specify that this record is an instantiation of the
2425 /// member function FD.
2426 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2427 TemplateSpecializationKind TSK) {
2428 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2429 }
2430
2431 /// Retrieves the function template that is described by this
2432 /// function declaration.
2433 ///
2434 /// Every function template is represented as a FunctionTemplateDecl
2435 /// and a FunctionDecl (or something derived from FunctionDecl). The
2436 /// former contains template properties (such as the template
2437 /// parameter lists) while the latter contains the actual
2438 /// description of the template's
2439 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2440 /// FunctionDecl that describes the function template,
2441 /// getDescribedFunctionTemplate() retrieves the
2442 /// FunctionTemplateDecl from a FunctionDecl.
2443 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2444
2445 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2446
2447 /// Determine whether this function is a function template
2448 /// specialization.
2449 bool isFunctionTemplateSpecialization() const {
2450 return getPrimaryTemplate() != nullptr;
2451 }
2452
2453 /// Retrieve the class scope template pattern that this function
2454 /// template specialization is instantiated from.
2455 FunctionDecl *getClassScopeSpecializationPattern() const;
2456
2457 /// If this function is actually a function template specialization,
2458 /// retrieve information about this function template specialization.
2459 /// Otherwise, returns NULL.
2460 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2461
2462 /// Determines whether this function is a function template
2463 /// specialization or a member of a class template specialization that can
2464 /// be implicitly instantiated.
2465 bool isImplicitlyInstantiable() const;
2466
2467 /// Determines if the given function was instantiated from a
2468 /// function template.
2469 bool isTemplateInstantiation() const;
2470
2471 /// Retrieve the function declaration from which this function could
2472 /// be instantiated, if it is an instantiation (rather than a non-template
2473 /// or a specialization, for example).
2474 FunctionDecl *getTemplateInstantiationPattern() const;
2475
2476 /// Retrieve the primary template that this function template
2477 /// specialization either specializes or was instantiated from.
2478 ///
2479 /// If this function declaration is not a function template specialization,
2480 /// returns NULL.
2481 FunctionTemplateDecl *getPrimaryTemplate() const;
2482
2483 /// Retrieve the template arguments used to produce this function
2484 /// template specialization from the primary template.
2485 ///
2486 /// If this function declaration is not a function template specialization,
2487 /// returns NULL.
2488 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2489
2490 /// Retrieve the template argument list as written in the sources,
2491 /// if any.
2492 ///
2493 /// If this function declaration is not a function template specialization
2494 /// or if it had no explicit template argument list, returns NULL.
2495 /// Note that it an explicit template argument list may be written empty,
2496 /// e.g., template<> void foo<>(char* s);
2497 const ASTTemplateArgumentListInfo*
2498 getTemplateSpecializationArgsAsWritten() const;
2499
2500 /// Specify that this function declaration is actually a function
2501 /// template specialization.
2502 ///
2503 /// \param Template the function template that this function template
2504 /// specialization specializes.
2505 ///
2506 /// \param TemplateArgs the template arguments that produced this
2507 /// function template specialization from the template.
2508 ///
2509 /// \param InsertPos If non-NULL, the position in the function template
2510 /// specialization set where the function template specialization data will
2511 /// be inserted.
2512 ///
2513 /// \param TSK the kind of template specialization this is.
2514 ///
2515 /// \param TemplateArgsAsWritten location info of template arguments.
2516 ///
2517 /// \param PointOfInstantiation point at which the function template
2518 /// specialization was first instantiated.
2519 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2520 const TemplateArgumentList *TemplateArgs,
2521 void *InsertPos,
2522 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2523 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2524 SourceLocation PointOfInstantiation = SourceLocation()) {
2525 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2526 InsertPos, TSK, TemplateArgsAsWritten,
2527 PointOfInstantiation);
2528 }
2529
2530 /// Specifies that this function declaration is actually a
2531 /// dependent function template specialization.
2532 void setDependentTemplateSpecialization(ASTContext &Context,
2533 const UnresolvedSetImpl &Templates,
2534 const TemplateArgumentListInfo &TemplateArgs);
2535
2536 DependentFunctionTemplateSpecializationInfo *
2537 getDependentSpecializationInfo() const;
2538
2539 /// Determine what kind of template instantiation this function
2540 /// represents.
2541 TemplateSpecializationKind getTemplateSpecializationKind() const;
2542
2543 /// Determine what kind of template instantiation this function
2544 /// represents.
2545 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2546 SourceLocation PointOfInstantiation = SourceLocation());
2547
2548 /// Retrieve the (first) point of instantiation of a function template
2549 /// specialization or a member of a class template specialization.
2550 ///
2551 /// \returns the first point of instantiation, if this function was
2552 /// instantiated from a template; otherwise, returns an invalid source
2553 /// location.
2554 SourceLocation getPointOfInstantiation() const;
2555
2556 /// Determine whether this is or was instantiated from an out-of-line
2557 /// definition of a member function.
2558 bool isOutOfLine() const override;
2559
2560 /// Identify a memory copying or setting function.
2561 /// If the given function is a memory copy or setting function, returns
2562 /// the corresponding Builtin ID. If the function is not a memory function,
2563 /// returns 0.
2564 unsigned getMemoryFunctionKind() const;
2565
2566 /// Returns ODRHash of the function. This value is calculated and
2567 /// stored on first call, then the stored value returned on the other calls.
2568 unsigned getODRHash();
2569
2570 /// Returns cached ODRHash of the function. This must have been previously
2571 /// computed and stored.
2572 unsigned getODRHash() const;
2573
2574 // Implement isa/cast/dyncast/etc.
2575 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2576 static bool classofKind(Kind K) {
2577 return K >= firstFunction && K <= lastFunction;
2578 }
2579 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2580 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2581 }
2582 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2583 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2584 }
2585};
2586
2587/// Represents a member of a struct/union/class.
2588class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2589 unsigned BitField : 1;
2590 unsigned Mutable : 1;
2591 mutable unsigned CachedFieldIndex : 30;
2592
2593 /// The kinds of value we can store in InitializerOrBitWidth.
2594 ///
2595 /// Note that this is compatible with InClassInitStyle except for
2596 /// ISK_CapturedVLAType.
2597 enum InitStorageKind {
2598 /// If the pointer is null, there's nothing special. Otherwise,
2599 /// this is a bitfield and the pointer is the Expr* storing the
2600 /// bit-width.
2601 ISK_NoInit = (unsigned) ICIS_NoInit,
2602
2603 /// The pointer is an (optional due to delayed parsing) Expr*
2604 /// holding the copy-initializer.
2605 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2606
2607 /// The pointer is an (optional due to delayed parsing) Expr*
2608 /// holding the list-initializer.
2609 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2610
2611 /// The pointer is a VariableArrayType* that's been captured;
2612 /// the enclosing context is a lambda or captured statement.
2613 ISK_CapturedVLAType,
2614 };
2615
2616 /// If this is a bitfield with a default member initializer, this
2617 /// structure is used to represent the two expressions.
2618 struct InitAndBitWidth {
2619 Expr *Init;
2620 Expr *BitWidth;
2621 };
2622
2623 /// Storage for either the bit-width, the in-class initializer, or
2624 /// both (via InitAndBitWidth), or the captured variable length array bound.
2625 ///
2626 /// If the storage kind is ISK_InClassCopyInit or
2627 /// ISK_InClassListInit, but the initializer is null, then this
2628 /// field has an in-class initializer that has not yet been parsed
2629 /// and attached.
2630 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2631 // overwhelmingly common case that we have none of these things.
2632 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2633
2634protected:
2635 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2636 SourceLocation IdLoc, IdentifierInfo *Id,
2637 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2638 InClassInitStyle InitStyle)
2639 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2640 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2641 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2642 if (BW)
2643 setBitWidth(BW);
2644 }
2645
2646public:
2647 friend class ASTDeclReader;
2648 friend class ASTDeclWriter;
2649
2650 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2651 SourceLocation StartLoc, SourceLocation IdLoc,
2652 IdentifierInfo *Id, QualType T,
2653 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2654 InClassInitStyle InitStyle);
2655
2656 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2657
2658 /// Returns the index of this field within its record,
2659 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2660 unsigned getFieldIndex() const;
2661
2662 /// Determines whether this field is mutable (C++ only).
2663 bool isMutable() const { return Mutable; }
2664
2665 /// Determines whether this field is a bitfield.
2666 bool isBitField() const { return BitField; }
2667
2668 /// Determines whether this is an unnamed bitfield.
2669 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2670
2671 /// Determines whether this field is a
2672 /// representative for an anonymous struct or union. Such fields are
2673 /// unnamed and are implicitly generated by the implementation to
2674 /// store the data for the anonymous union or struct.
2675 bool isAnonymousStructOrUnion() const;
2676
2677 Expr *getBitWidth() const {
2678 if (!BitField)
2679 return nullptr;
2680 void *Ptr = InitStorage.getPointer();
2681 if (getInClassInitStyle())
2682 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2683 return static_cast<Expr*>(Ptr);
2684 }
2685
2686 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2687
2688 /// Set the bit-field width for this member.
2689 // Note: used by some clients (i.e., do not remove it).
2690 void setBitWidth(Expr *Width) {
2691 assert(!hasCapturedVLAType() && !BitField &&((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2692, __PRETTY_FUNCTION__))
2692 "bit width or captured type already set")((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2692, __PRETTY_FUNCTION__))
;
2693 assert(Width && "no bit width specified")((Width && "no bit width specified") ? static_cast<
void> (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2693, __PRETTY_FUNCTION__))
;
2694 InitStorage.setPointer(
2695 InitStorage.getInt()
2696 ? new (getASTContext())
2697 InitAndBitWidth{getInClassInitializer(), Width}
2698 : static_cast<void*>(Width));
2699 BitField = true;
2700 }
2701
2702 /// Remove the bit-field width from this member.
2703 // Note: used by some clients (i.e., do not remove it).
2704 void removeBitWidth() {
2705 assert(isBitField() && "no bitfield width to remove")((isBitField() && "no bitfield width to remove") ? static_cast
<void> (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2705, __PRETTY_FUNCTION__))
;
2706 InitStorage.setPointer(getInClassInitializer());
2707 BitField = false;
2708 }
2709
2710 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2711 /// at all and instead act as a separator between contiguous runs of other
2712 /// bit-fields.
2713 bool isZeroLengthBitField(const ASTContext &Ctx) const;
2714
2715 /// Get the kind of (C++11) default member initializer that this field has.
2716 InClassInitStyle getInClassInitStyle() const {
2717 InitStorageKind storageKind = InitStorage.getInt();
2718 return (storageKind == ISK_CapturedVLAType
2719 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2720 }
2721
2722 /// Determine whether this member has a C++11 default member initializer.
2723 bool hasInClassInitializer() const {
2724 return getInClassInitStyle() != ICIS_NoInit;
2725 }
2726
2727 /// Get the C++11 default member initializer for this member, or null if one
2728 /// has not been set. If a valid declaration has a default member initializer,
2729 /// but this returns null, then we have not parsed and attached it yet.
2730 Expr *getInClassInitializer() const {
2731 if (!hasInClassInitializer())
2732 return nullptr;
2733 void *Ptr = InitStorage.getPointer();
2734 if (BitField)
2735 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2736 return static_cast<Expr*>(Ptr);
2737 }
2738
2739 /// Set the C++11 in-class initializer for this member.
2740 void setInClassInitializer(Expr *Init) {
2741 assert(hasInClassInitializer() && !getInClassInitializer())((hasInClassInitializer() && !getInClassInitializer()
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2741, __PRETTY_FUNCTION__))
;
2742 if (BitField)
2743 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2744 else
2745 InitStorage.setPointer(Init);
2746 }
2747
2748 /// Remove the C++11 in-class initializer from this member.
2749 void removeInClassInitializer() {
2750 assert(hasInClassInitializer() && "no initializer to remove")((hasInClassInitializer() && "no initializer to remove"
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2750, __PRETTY_FUNCTION__))
;
2751 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2752 }
2753
2754 /// Determine whether this member captures the variable length array
2755 /// type.
2756 bool hasCapturedVLAType() const {
2757 return InitStorage.getInt() == ISK_CapturedVLAType;
2758 }
2759
2760 /// Get the captured variable length array type.
2761 const VariableArrayType *getCapturedVLAType() const {
2762 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2763 InitStorage.getPointer())
2764 : nullptr;
2765 }
2766
2767 /// Set the captured variable length array type for this field.
2768 void setCapturedVLAType(const VariableArrayType *VLAType);
2769
2770 /// Returns the parent of this field declaration, which
2771 /// is the struct in which this field is defined.
2772 const RecordDecl *getParent() const {
2773 return cast<RecordDecl>(getDeclContext());
2774 }
2775
2776 RecordDecl *getParent() {
2777 return cast<RecordDecl>(getDeclContext());
2778 }
2779
2780 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2781
2782 /// Retrieves the canonical declaration of this field.
2783 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2784 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2785
2786 // Implement isa/cast/dyncast/etc.
2787 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2788 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2789};
2790
2791/// An instance of this object exists for each enum constant
2792/// that is defined. For example, in "enum X {a,b}", each of a/b are
2793/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2794/// TagType for the X EnumDecl.
2795class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2796 Stmt *Init; // an integer constant expression
2797 llvm::APSInt Val; // The value.
2798
2799protected:
2800 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2801 IdentifierInfo *Id, QualType T, Expr *E,
2802 const llvm::APSInt &V)
2803 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2804
2805public:
2806 friend class StmtIteratorBase;
2807
2808 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2809 SourceLocation L, IdentifierInfo *Id,
2810 QualType T, Expr *E,
2811 const llvm::APSInt &V);
2812 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2813
2814 const Expr *getInitExpr() const { return (const Expr*) Init; }
2815 Expr *getInitExpr() { return (Expr*) Init; }
2816 const llvm::APSInt &getInitVal() const { return Val; }
2817
2818 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2819 void setInitVal(const llvm::APSInt &V) { Val = V; }
2820
2821 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2822
2823 /// Retrieves the canonical declaration of this enumerator.
2824 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2825 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2826
2827 // Implement isa/cast/dyncast/etc.
2828 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2829 static bool classofKind(Kind K) { return K == EnumConstant; }
2830};
2831
2832/// Represents a field injected from an anonymous union/struct into the parent
2833/// scope. These are always implicit.
2834class IndirectFieldDecl : public ValueDecl,
2835 public Mergeable<IndirectFieldDecl> {
2836 NamedDecl **Chaining;
2837 unsigned ChainingSize;
2838
2839 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2840 DeclarationName N, QualType T,
2841 MutableArrayRef<NamedDecl *> CH);
2842
2843 void anchor() override;
2844
2845public:
2846 friend class ASTDeclReader;
2847
2848 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2849 SourceLocation L, IdentifierInfo *Id,
2850 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2851
2852 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2853
2854 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2855
2856 ArrayRef<NamedDecl *> chain() const {
2857 return llvm::makeArrayRef(Chaining, ChainingSize);
2858 }
2859 chain_iterator chain_begin() const { return chain().begin(); }
2860 chain_iterator chain_end() const { return chain().end(); }
2861
2862 unsigned getChainingSize() const { return ChainingSize; }
2863
2864 FieldDecl *getAnonField() const {
2865 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2865, __PRETTY_FUNCTION__))
;
2866 return cast<FieldDecl>(chain().back());
2867 }
2868
2869 VarDecl *getVarDecl() const {
2870 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 2870, __PRETTY_FUNCTION__))
;
2871 return dyn_cast<VarDecl>(chain().front());
2872 }
2873
2874 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2875 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2876
2877 // Implement isa/cast/dyncast/etc.
2878 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2879 static bool classofKind(Kind K) { return K == IndirectField; }
2880};
2881
2882/// Represents a declaration of a type.
2883class TypeDecl : public NamedDecl {
2884 friend class ASTContext;
2885
2886 /// This indicates the Type object that represents
2887 /// this TypeDecl. It is a cache maintained by
2888 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2889 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2890 mutable const Type *TypeForDecl = nullptr;
2891
2892 /// The start of the source range for this declaration.
2893 SourceLocation LocStart;
2894
2895 void anchor() override;
2896
2897protected:
2898 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2899 SourceLocation StartL = SourceLocation())
2900 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2901
2902public:
2903 // Low-level accessor. If you just want the type defined by this node,
2904 // check out ASTContext::getTypeDeclType or one of
2905 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2906 // already know the specific kind of node this is.
2907 const Type *getTypeForDecl() const { return TypeForDecl; }
2908 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2909
2910 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2911 void setLocStart(SourceLocation L) { LocStart = L; }
2912 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2913 if (LocStart.isValid())
2914 return SourceRange(LocStart, getLocation());
2915 else
2916 return SourceRange(getLocation());
2917 }
2918
2919 // Implement isa/cast/dyncast/etc.
2920 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2921 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2922};
2923
2924/// Base class for declarations which introduce a typedef-name.
2925class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2926 struct alignas(8) ModedTInfo {
2927 TypeSourceInfo *first;
2928 QualType second;
2929 };
2930
2931 /// If int part is 0, we have not computed IsTransparentTag.
2932 /// Otherwise, IsTransparentTag is (getInt() >> 1).
2933 mutable llvm::PointerIntPair<
2934 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
2935 MaybeModedTInfo;
2936
2937 void anchor() override;
2938
2939protected:
2940 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2941 SourceLocation StartLoc, SourceLocation IdLoc,
2942 IdentifierInfo *Id, TypeSourceInfo *TInfo)
2943 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2944 MaybeModedTInfo(TInfo, 0) {}
2945
2946 using redeclarable_base = Redeclarable<TypedefNameDecl>;
2947
2948 TypedefNameDecl *getNextRedeclarationImpl() override {
2949 return getNextRedeclaration();
2950 }
2951
2952 TypedefNameDecl *getPreviousDeclImpl() override {
2953 return getPreviousDecl();
2954 }
2955
2956 TypedefNameDecl *getMostRecentDeclImpl() override {
2957 return getMostRecentDecl();
2958 }
2959
2960public:
2961 using redecl_range = redeclarable_base::redecl_range;
2962 using redecl_iterator = redeclarable_base::redecl_iterator;
2963
2964 using redeclarable_base::redecls_begin;
2965 using redeclarable_base::redecls_end;
2966 using redeclarable_base::redecls;
2967 using redeclarable_base::getPreviousDecl;
2968 using redeclarable_base::getMostRecentDecl;
2969 using redeclarable_base::isFirstDecl;
2970
2971 bool isModed() const {
2972 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
2973 }
2974
2975 TypeSourceInfo *getTypeSourceInfo() const {
2976 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
2977 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
2978 }
2979
2980 QualType getUnderlyingType() const {
2981 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
2982 : MaybeModedTInfo.getPointer()
2983 .get<TypeSourceInfo *>()
2984 ->getType();
2985 }
2986
2987 void setTypeSourceInfo(TypeSourceInfo *newType) {
2988 MaybeModedTInfo.setPointer(newType);
2989 }
2990
2991 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2992 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
2993 ModedTInfo({unmodedTSI, modedTy}));
2994 }
2995
2996 /// Retrieves the canonical declaration of this typedef-name.
2997 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2998 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2999
3000 /// Retrieves the tag declaration for which this is the typedef name for
3001 /// linkage purposes, if any.
3002 ///
3003 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
3004 /// this typedef declaration.
3005 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
3006
3007 /// Determines if this typedef shares a name and spelling location with its
3008 /// underlying tag type, as is the case with the NS_ENUM macro.
3009 bool isTransparentTag() const {
3010 if (MaybeModedTInfo.getInt())
3011 return MaybeModedTInfo.getInt() & 0x2;
3012 return isTransparentTagSlow();
3013 }
3014
3015 // Implement isa/cast/dyncast/etc.
3016 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3017 static bool classofKind(Kind K) {
3018 return K >= firstTypedefName && K <= lastTypedefName;
3019 }
3020
3021private:
3022 bool isTransparentTagSlow() const;
3023};
3024
3025/// Represents the declaration of a typedef-name via the 'typedef'
3026/// type specifier.
3027class TypedefDecl : public TypedefNameDecl {
3028 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3029 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3030 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3031
3032public:
3033 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
3034 SourceLocation StartLoc, SourceLocation IdLoc,
3035 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3036 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3037
3038 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3039
3040 // Implement isa/cast/dyncast/etc.
3041 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3042 static bool classofKind(Kind K) { return K == Typedef; }
3043};
3044
3045/// Represents the declaration of a typedef-name via a C++11
3046/// alias-declaration.
3047class TypeAliasDecl : public TypedefNameDecl {
3048 /// The template for which this is the pattern, if any.
3049 TypeAliasTemplateDecl *Template;
3050
3051 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3052 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3053 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3054 Template(nullptr) {}
3055
3056public:
3057 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
3058 SourceLocation StartLoc, SourceLocation IdLoc,
3059 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3060 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3061
3062 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3063
3064 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3065 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3066
3067 // Implement isa/cast/dyncast/etc.
3068 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3069 static bool classofKind(Kind K) { return K == TypeAlias; }
3070};
3071
3072/// Represents the declaration of a struct/union/class/enum.
3073class TagDecl : public TypeDecl,
3074 public DeclContext,
3075 public Redeclarable<TagDecl> {
3076 // This class stores some data in DeclContext::TagDeclBits
3077 // to save some space. Use the provided accessors to access it.
3078public:
3079 // This is really ugly.
3080 using TagKind = TagTypeKind;
3081
3082private:
3083 SourceRange BraceRange;
3084
3085 // A struct representing syntactic qualifier info,
3086 // to be used for the (uncommon) case of out-of-line declarations.
3087 using ExtInfo = QualifierInfo;
3088
3089 /// If the (out-of-line) tag declaration name
3090 /// is qualified, it points to the qualifier info (nns and range);
3091 /// otherwise, if the tag declaration is anonymous and it is part of
3092 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3093 /// otherwise, if the tag declaration is anonymous and it is used as a
3094 /// declaration specifier for variables, it points to the first VarDecl (used
3095 /// for mangling);
3096 /// otherwise, it is a null (TypedefNameDecl) pointer.
3097 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3098
3099 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3100 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3101 const ExtInfo *getExtInfo() const {
3102 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3103 }
3104
3105protected:
3106 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3107 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3108 SourceLocation StartL);
3109
3110 using redeclarable_base = Redeclarable<TagDecl>;
3111
3112 TagDecl *getNextRedeclarationImpl() override {
3113 return getNextRedeclaration();
3114 }
3115
3116 TagDecl *getPreviousDeclImpl() override {
3117 return getPreviousDecl();
3118 }
3119
3120 TagDecl *getMostRecentDeclImpl() override {
3121 return getMostRecentDecl();
3122 }
3123
3124 /// Completes the definition of this tag declaration.
3125 ///
3126 /// This is a helper function for derived classes.
3127 void completeDefinition();
3128
3129 /// True if this decl is currently being defined.
3130 void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3131
3132 /// Indicates whether it is possible for declarations of this kind
3133 /// to have an out-of-date definition.
3134 ///
3135 /// This option is only enabled when modules are enabled.
3136 void setMayHaveOutOfDateDef(bool V = true) {
3137 TagDeclBits.MayHaveOutOfDateDef = V;
3138 }
3139
3140public:
3141 friend class ASTDeclReader;
3142 friend class ASTDeclWriter;
3143
3144 using redecl_range = redeclarable_base::redecl_range;
3145 using redecl_iterator = redeclarable_base::redecl_iterator;
3146
3147 using redeclarable_base::redecls_begin;
3148 using redeclarable_base::redecls_end;
3149 using redeclarable_base::redecls;
3150 using redeclarable_base::getPreviousDecl;
3151 using redeclarable_base::getMostRecentDecl;
3152 using redeclarable_base::isFirstDecl;
3153
3154 SourceRange getBraceRange() const { return BraceRange; }
3155 void setBraceRange(SourceRange R) { BraceRange = R; }
3156
3157 /// Return SourceLocation representing start of source
3158 /// range ignoring outer template declarations.
3159 SourceLocation getInnerLocStart() const { return getBeginLoc(); }
3160
3161 /// Return SourceLocation representing start of source
3162 /// range taking into account any outer template declarations.
3163 SourceLocation getOuterLocStart() const;
3164 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3165
3166 TagDecl *getCanonicalDecl() override;
3167 const TagDecl *getCanonicalDecl() const {
3168 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3169 }
3170
3171 /// Return true if this declaration is a completion definition of the type.
3172 /// Provided for consistency.
3173 bool isThisDeclarationADefinition() const {
3174 return isCompleteDefinition();
3175 }
3176
3177 /// Return true if this decl has its body fully specified.
3178 bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3179
3180 /// True if this decl has its body fully specified.
3181 void setCompleteDefinition(bool V = true) {
3182 TagDeclBits.IsCompleteDefinition = V;
3183 }
3184
3185 /// Return true if this complete decl is
3186 /// required to be complete for some existing use.
3187 bool isCompleteDefinitionRequired() const {
3188 return TagDeclBits.IsCompleteDefinitionRequired;
3189 }
3190
3191 /// True if this complete decl is
3192 /// required to be complete for some existing use.
3193 void setCompleteDefinitionRequired(bool V = true) {
3194 TagDeclBits.IsCompleteDefinitionRequired = V;
3195 }
3196
3197 /// Return true if this decl is currently being defined.
3198 bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3199
3200 /// True if this tag declaration is "embedded" (i.e., defined or declared
3201 /// for the very first time) in the syntax of a declarator.
3202 bool isEmbeddedInDeclarator() const {
3203 return TagDeclBits.IsEmbeddedInDeclarator;
3204 }
3205
3206 /// True if this tag declaration is "embedded" (i.e., defined or declared
3207 /// for the very first time) in the syntax of a declarator.
3208 void setEmbeddedInDeclarator(bool isInDeclarator) {
3209 TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3210 }
3211
3212 /// True if this tag is free standing, e.g. "struct foo;".
3213 bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3214
3215 /// True if this tag is free standing, e.g. "struct foo;".
3216 void setFreeStanding(bool isFreeStanding = true) {
3217 TagDeclBits.IsFreeStanding = isFreeStanding;
3218 }
3219
3220 /// Indicates whether it is possible for declarations of this kind
3221 /// to have an out-of-date definition.
3222 ///
3223 /// This option is only enabled when modules are enabled.
3224 bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3225
3226 /// Whether this declaration declares a type that is
3227 /// dependent, i.e., a type that somehow depends on template
3228 /// parameters.
3229 bool isDependentType() const { return isDependentContext(); }
3230
3231 /// Starts the definition of this tag declaration.
3232 ///
3233 /// This method should be invoked at the beginning of the definition
3234 /// of this tag declaration. It will set the tag type into a state
3235 /// where it is in the process of being defined.
3236 void startDefinition();
3237
3238 /// Returns the TagDecl that actually defines this
3239 /// struct/union/class/enum. When determining whether or not a
3240 /// struct/union/class/enum has a definition, one should use this
3241 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3242 /// whether or not a specific TagDecl is defining declaration, not
3243 /// whether or not the struct/union/class/enum type is defined.
3244 /// This method returns NULL if there is no TagDecl that defines
3245 /// the struct/union/class/enum.
3246 TagDecl *getDefinition() const;
3247
3248 StringRef getKindName() const {
3249 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3250 }
3251
3252 TagKind getTagKind() const {
3253 return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3254 }
3255
3256 void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
3257
3258 bool isStruct() const { return getTagKind() == TTK_Struct; }
3259 bool isInterface() const { return getTagKind() == TTK_Interface; }
3260 bool isClass() const { return getTagKind() == TTK_Class; }
3261 bool isUnion() const { return getTagKind() == TTK_Union; }
3262 bool isEnum() const { return getTagKind() == TTK_Enum; }
3263
3264 /// Is this tag type named, either directly or via being defined in
3265 /// a typedef of this type?
3266 ///
3267 /// C++11 [basic.link]p8:
3268 /// A type is said to have linkage if and only if:
3269 /// - it is a class or enumeration type that is named (or has a
3270 /// name for linkage purposes) and the name has linkage; ...
3271 /// C++11 [dcl.typedef]p9:
3272 /// If the typedef declaration defines an unnamed class (or enum),
3273 /// the first typedef-name declared by the declaration to be that
3274 /// class type (or enum type) is used to denote the class type (or
3275 /// enum type) for linkage purposes only.
3276 ///
3277 /// C does not have an analogous rule, but the same concept is
3278 /// nonetheless useful in some places.
3279 bool hasNameForLinkage() const {
3280 return (getDeclName() || getTypedefNameForAnonDecl());
3281 }
3282
3283 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3284 return hasExtInfo() ? nullptr
3285 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3286 }
3287
3288 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3289
3290 /// Retrieve the nested-name-specifier that qualifies the name of this
3291 /// declaration, if it was present in the source.
3292 NestedNameSpecifier *getQualifier() const {
3293 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3294 : nullptr;
3295 }
3296
3297 /// Retrieve the nested-name-specifier (with source-location
3298 /// information) that qualifies the name of this declaration, if it was
3299 /// present in the source.
3300 NestedNameSpecifierLoc getQualifierLoc() const {
3301 return hasExtInfo() ? getExtInfo()->QualifierLoc
3302 : NestedNameSpecifierLoc();
3303 }
3304
3305 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3306
3307 unsigned getNumTemplateParameterLists() const {
3308 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3309 }
3310
3311 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3312 assert(i < getNumTemplateParameterLists())((i < getNumTemplateParameterLists()) ? static_cast<void
> (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 3312, __PRETTY_FUNCTION__))
;
3313 return getExtInfo()->TemplParamLists[i];
3314 }
3315
3316 void setTemplateParameterListsInfo(ASTContext &Context,
3317 ArrayRef<TemplateParameterList *> TPLists);
3318
3319 // Implement isa/cast/dyncast/etc.
3320 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3321 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3322
3323 static DeclContext *castToDeclContext(const TagDecl *D) {
3324 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3325 }
3326
3327 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3328 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3329 }
3330};
3331
3332/// Represents an enum. In C++11, enums can be forward-declared
3333/// with a fixed underlying type, and in C we allow them to be forward-declared
3334/// with no underlying type as an extension.
3335class EnumDecl : public TagDecl {
3336 // This class stores some data in DeclContext::EnumDeclBits
3337 // to save some space. Use the provided accessors to access it.
3338
3339 /// This represent the integer type that the enum corresponds
3340 /// to for code generation purposes. Note that the enumerator constants may
3341 /// have a different type than this does.
3342 ///
3343 /// If the underlying integer type was explicitly stated in the source
3344 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3345 /// was automatically deduced somehow, and this is a Type*.
3346 ///
3347 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3348 /// some cases it won't.
3349 ///
3350 /// The underlying type of an enumeration never has any qualifiers, so
3351 /// we can get away with just storing a raw Type*, and thus save an
3352 /// extra pointer when TypeSourceInfo is needed.
3353 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3354
3355 /// The integer type that values of this type should
3356 /// promote to. In C, enumerators are generally of an integer type
3357 /// directly, but gcc-style large enumerators (and all enumerators
3358 /// in C++) are of the enum type instead.
3359 QualType PromotionType;
3360
3361 /// If this enumeration is an instantiation of a member enumeration
3362 /// of a class template specialization, this is the member specialization
3363 /// information.
3364 MemberSpecializationInfo *SpecializationInfo = nullptr;
3365
3366 /// Store the ODRHash after first calculation.
3367 /// The corresponding flag HasODRHash is in EnumDeclBits
3368 /// and can be accessed with the provided accessors.
3369 unsigned ODRHash;
3370
3371 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3372 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3373 bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3374
3375 void anchor() override;
3376
3377 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3378 TemplateSpecializationKind TSK);
3379
3380 /// Sets the width in bits required to store all the
3381 /// non-negative enumerators of this enum.
3382 void setNumPositiveBits(unsigned Num) {
3383 EnumDeclBits.NumPositiveBits = Num;
3384 assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount")((EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount"
) ? static_cast<void> (0) : __assert_fail ("EnumDeclBits.NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 3384, __PRETTY_FUNCTION__))
;
3385 }
3386
3387 /// Returns the width in bits required to store all the
3388 /// negative enumerators of this enum. (see getNumNegativeBits)
3389 void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3390
3391 /// True if this tag declaration is a scoped enumeration. Only
3392 /// possible in C++11 mode.
3393 void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3394
3395 /// If this tag declaration is a scoped enum,
3396 /// then this is true if the scoped enum was declared using the class
3397 /// tag, false if it was declared with the struct tag. No meaning is
3398 /// associated if this tag declaration is not a scoped enum.
3399 void setScopedUsingClassTag(bool ScopedUCT = true) {
3400 EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3401 }
3402
3403 /// True if this is an Objective-C, C++11, or
3404 /// Microsoft-style enumeration with a fixed underlying type.
3405 void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3406
3407 /// True if a valid hash is stored in ODRHash.
3408 bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3409 void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3410
3411public:
3412 friend class ASTDeclReader;
3413
3414 EnumDecl *getCanonicalDecl() override {
3415 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3416 }
3417 const EnumDecl *getCanonicalDecl() const {
3418 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3419 }
3420
3421 EnumDecl *getPreviousDecl() {
3422 return cast_or_null<EnumDecl>(
3423 static_cast<TagDecl *>(this)->getPreviousDecl());
3424 }
3425 const EnumDecl *getPreviousDecl() const {
3426 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3427 }
3428
3429 EnumDecl *getMostRecentDecl() {
3430 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3431 }
3432 const EnumDecl *getMostRecentDecl() const {
3433 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3434 }
3435
3436 EnumDecl *getDefinition() const {
3437 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3438 }
3439
3440 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3441 SourceLocation StartLoc, SourceLocation IdLoc,
3442 IdentifierInfo *Id, EnumDecl *PrevDecl,
3443 bool IsScoped, bool IsScopedUsingClassTag,
3444 bool IsFixed);
3445 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3446
3447 /// When created, the EnumDecl corresponds to a
3448 /// forward-declared enum. This method is used to mark the
3449 /// declaration as being defined; its enumerators have already been
3450 /// added (via DeclContext::addDecl). NewType is the new underlying
3451 /// type of the enumeration type.
3452 void completeDefinition(QualType NewType,
3453 QualType PromotionType,
3454 unsigned NumPositiveBits,
3455 unsigned NumNegativeBits);
3456
3457 // Iterates through the enumerators of this enumeration.
3458 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3459 using enumerator_range =
3460 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3461
3462 enumerator_range enumerators() const {
3463 return enumerator_range(enumerator_begin(), enumerator_end());
3464 }
3465
3466 enumerator_iterator enumerator_begin() const {
3467 const EnumDecl *E = getDefinition();
3468 if (!E)
3469 E = this;
3470 return enumerator_iterator(E->decls_begin());
3471 }
3472
3473 enumerator_iterator enumerator_end() const {
3474 const EnumDecl *E = getDefinition();
3475 if (!E)
3476 E = this;
3477 return enumerator_iterator(E->decls_end());
3478 }
3479
3480 /// Return the integer type that enumerators should promote to.
3481 QualType getPromotionType() const { return PromotionType; }
3482
3483 /// Set the promotion type.
3484 void setPromotionType(QualType T) { PromotionType = T; }
3485
3486 /// Return the integer type this enum decl corresponds to.
3487 /// This returns a null QualType for an enum forward definition with no fixed
3488 /// underlying type.
3489 QualType getIntegerType() const {
3490 if (!IntegerType)
3491 return QualType();
3492 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3493 return QualType(T, 0);
3494 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3495 }
3496
3497 /// Set the underlying integer type.
3498 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3499
3500 /// Set the underlying integer type source info.
3501 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3502
3503 /// Return the type source info for the underlying integer type,
3504 /// if no type source info exists, return 0.
3505 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3506 return IntegerType.dyn_cast<TypeSourceInfo*>();
3507 }
3508
3509 /// Retrieve the source range that covers the underlying type if
3510 /// specified.
3511 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3512
3513 /// Returns the width in bits required to store all the
3514 /// non-negative enumerators of this enum.
3515 unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
3516
3517 /// Returns the width in bits required to store all the
3518 /// negative enumerators of this enum. These widths include
3519 /// the rightmost leading 1; that is:
3520 ///
3521 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3522 /// ------------------------ ------- -----------------
3523 /// -1 1111111 1
3524 /// -10 1110110 5
3525 /// -101 1001011 8
3526 unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
3527
3528 /// Returns true if this is a C++11 scoped enumeration.
3529 bool isScoped() const { return EnumDeclBits.IsScoped; }
3530
3531 /// Returns true if this is a C++11 scoped enumeration.
3532 bool isScopedUsingClassTag() const {
3533 return EnumDeclBits.IsScopedUsingClassTag;
3534 }
3535
3536 /// Returns true if this is an Objective-C, C++11, or
3537 /// Microsoft-style enumeration with a fixed underlying type.
3538 bool isFixed() const { return EnumDeclBits.IsFixed; }
3539
3540 unsigned getODRHash();
3541
3542 /// Returns true if this can be considered a complete type.
3543 bool isComplete() const {
3544 // IntegerType is set for fixed type enums and non-fixed but implicitly
3545 // int-sized Microsoft enums.
3546 return isCompleteDefinition() || IntegerType;
3547 }
3548
3549 /// Returns true if this enum is either annotated with
3550 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3551 bool isClosed() const;
3552
3553 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3554 /// with enum_extensibility(open).
3555 bool isClosedFlag() const;
3556
3557 /// Returns true if this enum is annotated with neither flag_enum nor
3558 /// enum_extensibility(open).
3559 bool isClosedNonFlag() const;
3560
3561 /// Retrieve the enum definition from which this enumeration could
3562 /// be instantiated, if it is an instantiation (rather than a non-template).
3563 EnumDecl *getTemplateInstantiationPattern() const;
3564
3565 /// Returns the enumeration (declared within the template)
3566 /// from which this enumeration type was instantiated, or NULL if
3567 /// this enumeration was not instantiated from any template.
3568 EnumDecl *getInstantiatedFromMemberEnum() const;
3569
3570 /// If this enumeration is a member of a specialization of a
3571 /// templated class, determine what kind of template specialization
3572 /// or instantiation this is.
3573 TemplateSpecializationKind getTemplateSpecializationKind() const;
3574
3575 /// For an enumeration member that was instantiated from a member
3576 /// enumeration of a templated class, set the template specialiation kind.
3577 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3578 SourceLocation PointOfInstantiation = SourceLocation());
3579
3580 /// If this enumeration is an instantiation of a member enumeration of
3581 /// a class template specialization, retrieves the member specialization
3582 /// information.
3583 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3584 return SpecializationInfo;
3585 }
3586
3587 /// Specify that this enumeration is an instantiation of the
3588 /// member enumeration ED.
3589 void setInstantiationOfMemberEnum(EnumDecl *ED,
3590 TemplateSpecializationKind TSK) {
3591 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3592 }
3593
3594 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3595 static bool classofKind(Kind K) { return K == Enum; }
3596};
3597
3598/// Represents a struct/union/class. For example:
3599/// struct X; // Forward declaration, no "body".
3600/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3601/// This decl will be marked invalid if *any* members are invalid.
3602class RecordDecl : public TagDecl {
3603 // This class stores some data in DeclContext::RecordDeclBits
3604 // to save some space. Use the provided accessors to access it.
3605public:
3606 friend class DeclContext;
3607 /// Enum that represents the different ways arguments are passed to and
3608 /// returned from function calls. This takes into account the target-specific
3609 /// and version-specific rules along with the rules determined by the
3610 /// language.
3611 enum ArgPassingKind : unsigned {
3612 /// The argument of this type can be passed directly in registers.
3613 APK_CanPassInRegs,
3614
3615 /// The argument of this type cannot be passed directly in registers.
3616 /// Records containing this type as a subobject are not forced to be passed
3617 /// indirectly. This value is used only in C++. This value is required by
3618 /// C++ because, in uncommon situations, it is possible for a class to have
3619 /// only trivial copy/move constructors even when one of its subobjects has
3620 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3621 /// constructor in the derived class is deleted).
3622 APK_CannotPassInRegs,
3623
3624 /// The argument of this type cannot be passed directly in registers.
3625 /// Records containing this type as a subobject are forced to be passed
3626 /// indirectly.
3627 APK_CanNeverPassInRegs
3628 };
3629
3630protected:
3631 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3632 SourceLocation StartLoc, SourceLocation IdLoc,
3633 IdentifierInfo *Id, RecordDecl *PrevDecl);
3634
3635public:
3636 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3637 SourceLocation StartLoc, SourceLocation IdLoc,
3638 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3639 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3640
3641 RecordDecl *getPreviousDecl() {
3642 return cast_or_null<RecordDecl>(
3643 static_cast<TagDecl *>(this)->getPreviousDecl());
3644 }
3645 const RecordDecl *getPreviousDecl() const {
3646 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3647 }
3648
3649 RecordDecl *getMostRecentDecl() {
3650 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3651 }
3652 const RecordDecl *getMostRecentDecl() const {
3653 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3654 }
3655
3656 bool hasFlexibleArrayMember() const {
3657 return RecordDeclBits.HasFlexibleArrayMember;
3658 }
3659
3660 void setHasFlexibleArrayMember(bool V) {
3661 RecordDeclBits.HasFlexibleArrayMember = V;
3662 }
3663
3664 /// Whether this is an anonymous struct or union. To be an anonymous
3665 /// struct or union, it must have been declared without a name and
3666 /// there must be no objects of this type declared, e.g.,
3667 /// @code
3668 /// union { int i; float f; };
3669 /// @endcode
3670 /// is an anonymous union but neither of the following are:
3671 /// @code
3672 /// union X { int i; float f; };
3673 /// union { int i; float f; } obj;
3674 /// @endcode
3675 bool isAnonymousStructOrUnion() const {
3676 return RecordDeclBits.AnonymousStructOrUnion;
3677 }
3678
3679 void setAnonymousStructOrUnion(bool Anon) {
3680 RecordDeclBits.AnonymousStructOrUnion = Anon;
3681 }
3682
3683 bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
3684 void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
3685
3686 bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
3687
3688 void setHasVolatileMember(bool val) {
3689 RecordDeclBits.HasVolatileMember = val;
3690 }
3691
3692 bool hasLoadedFieldsFromExternalStorage() const {
3693 return RecordDeclBits.LoadedFieldsFromExternalStorage;
3694 }
3695
3696 void setHasLoadedFieldsFromExternalStorage(bool val) const {
3697 RecordDeclBits.LoadedFieldsFromExternalStorage = val;
3698 }
3699
3700 /// Functions to query basic properties of non-trivial C structs.
3701 bool isNonTrivialToPrimitiveDefaultInitialize() const {
3702 return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
3703 }
3704
3705 void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3706 RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
3707 }
3708
3709 bool isNonTrivialToPrimitiveCopy() const {
3710 return RecordDeclBits.NonTrivialToPrimitiveCopy;
3711 }
3712
3713 void setNonTrivialToPrimitiveCopy(bool V) {
3714 RecordDeclBits.NonTrivialToPrimitiveCopy = V;
3715 }
3716
3717 bool isNonTrivialToPrimitiveDestroy() const {
3718 return RecordDeclBits.NonTrivialToPrimitiveDestroy;
3719 }
3720
3721 void setNonTrivialToPrimitiveDestroy(bool V) {
3722 RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
3723 }
3724
3725 /// Determine whether this class can be passed in registers. In C++ mode,
3726 /// it must have at least one trivial, non-deleted copy or move constructor.
3727 /// FIXME: This should be set as part of completeDefinition.
3728 bool canPassInRegisters() const {
3729 return getArgPassingRestrictions() == APK_CanPassInRegs;
3730 }
3731
3732 ArgPassingKind getArgPassingRestrictions() const {
3733 return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
3734 }
3735
3736 void setArgPassingRestrictions(ArgPassingKind Kind) {
3737 RecordDeclBits.ArgPassingRestrictions = Kind;
3738 }
3739
3740 bool isParamDestroyedInCallee() const {
3741 return RecordDeclBits.ParamDestroyedInCallee;
3742 }
3743
3744 void setParamDestroyedInCallee(bool V) {
3745 RecordDeclBits.ParamDestroyedInCallee = V;
3746 }
3747
3748 /// Determines whether this declaration represents the
3749 /// injected class name.
3750 ///
3751 /// The injected class name in C++ is the name of the class that
3752 /// appears inside the class itself. For example:
3753 ///
3754 /// \code
3755 /// struct C {
3756 /// // C is implicitly declared here as a synonym for the class name.
3757 /// };
3758 ///
3759 /// C::C c; // same as "C c;"
3760 /// \endcode
3761 bool isInjectedClassName() const;
3762
3763 /// Determine whether this record is a class describing a lambda
3764 /// function object.
3765 bool isLambda() const;
3766
3767 /// Determine whether this record is a record for captured variables in
3768 /// CapturedStmt construct.
3769 bool isCapturedRecord() const;
3770
3771 /// Mark the record as a record for captured variables in CapturedStmt
3772 /// construct.
3773 void setCapturedRecord();
3774
3775 /// Returns the RecordDecl that actually defines
3776 /// this struct/union/class. When determining whether or not a
3777 /// struct/union/class is completely defined, one should use this
3778 /// method as opposed to 'isCompleteDefinition'.
3779 /// 'isCompleteDefinition' indicates whether or not a specific
3780 /// RecordDecl is a completed definition, not whether or not the
3781 /// record type is defined. This method returns NULL if there is
3782 /// no RecordDecl that defines the struct/union/tag.
3783 RecordDecl *getDefinition() const {
3784 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3785 }
3786
3787 // Iterator access to field members. The field iterator only visits
3788 // the non-static data members of this class, ignoring any static
3789 // data members, functions, constructors, destructors, etc.
3790 using field_iterator = specific_decl_iterator<FieldDecl>;
3791 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3792
3793 field_range fields() const { return field_range(field_begin(), field_end()); }
3794 field_iterator field_begin() const;
3795
3796 field_iterator field_end() const {
3797 return field_iterator(decl_iterator());
3798 }
3799
3800 // Whether there are any fields (non-static data members) in this record.
3801 bool field_empty() const {
3802 return field_begin() == field_end();
3803 }
3804
3805 /// Note that the definition of this type is now complete.
3806 virtual void completeDefinition();
3807
3808 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3809 static bool classofKind(Kind K) {
3810 return K >= firstRecord && K <= lastRecord;
3811 }
3812
3813 /// Get whether or not this is an ms_struct which can
3814 /// be turned on with an attribute, pragma, or -mms-bitfields
3815 /// commandline option.
3816 bool isMsStruct(const ASTContext &C) const;
3817
3818 /// Whether we are allowed to insert extra padding between fields.
3819 /// These padding are added to help AddressSanitizer detect
3820 /// intra-object-overflow bugs.
3821 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3822
3823 /// Finds the first data member which has a name.
3824 /// nullptr is returned if no named data member exists.
3825 const FieldDecl *findFirstNamedDataMember() const;
3826
3827private:
3828 /// Deserialize just the fields.
3829 void LoadFieldsFromExternalStorage() const;
3830};
3831
3832class FileScopeAsmDecl : public Decl {
3833 StringLiteral *AsmString;
3834 SourceLocation RParenLoc;
3835
3836 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3837 SourceLocation StartL, SourceLocation EndL)
3838 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3839
3840 virtual void anchor();
3841
3842public:
3843 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3844 StringLiteral *Str, SourceLocation AsmLoc,
3845 SourceLocation RParenLoc);
3846
3847 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3848
3849 SourceLocation getAsmLoc() const { return getLocation(); }
3850 SourceLocation getRParenLoc() const { return RParenLoc; }
3851 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3852 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3853 return SourceRange(getAsmLoc(), getRParenLoc());
3854 }
3855
3856 const StringLiteral *getAsmString() const { return AsmString; }
3857 StringLiteral *getAsmString() { return AsmString; }
3858 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3859
3860 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3861 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3862};
3863
3864/// Pepresents a block literal declaration, which is like an
3865/// unnamed FunctionDecl. For example:
3866/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3867class BlockDecl : public Decl, public DeclContext {
3868 // This class stores some data in DeclContext::BlockDeclBits
3869 // to save some space. Use the provided accessors to access it.
3870public:
3871 /// A class which contains all the information about a particular
3872 /// captured value.
3873 class Capture {
3874 enum {
3875 flag_isByRef = 0x1,
3876 flag_isNested = 0x2
3877 };
3878
3879 /// The variable being captured.
3880 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3881
3882 /// The copy expression, expressed in terms of a DeclRef (or
3883 /// BlockDeclRef) to the captured variable. Only required if the
3884 /// variable has a C++ class type.
3885 Expr *CopyExpr;
3886
3887 public:
3888 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3889 : VariableAndFlags(variable,
3890 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3891 CopyExpr(copy) {}
3892
3893 /// The variable being captured.
3894 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3895
3896 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3897 /// variable.
3898 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3899
3900 bool isEscapingByref() const {
3901 return getVariable()->isEscapingByref();
3902 }
3903
3904 bool isNonEscapingByref() const {
3905 return getVariable()->isNonEscapingByref();
3906 }
3907
3908 /// Whether this is a nested capture, i.e. the variable captured
3909 /// is not from outside the immediately enclosing function/block.
3910 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3911
3912 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3913 Expr *getCopyExpr() const { return CopyExpr; }
3914 void setCopyExpr(Expr *e) { CopyExpr = e; }
3915 };
3916
3917private:
3918 /// A new[]'d array of pointers to ParmVarDecls for the formal
3919 /// parameters of this function. This is null if a prototype or if there are
3920 /// no formals.
3921 ParmVarDecl **ParamInfo = nullptr;
3922 unsigned NumParams = 0;
3923
3924 Stmt *Body = nullptr;
3925 TypeSourceInfo *SignatureAsWritten = nullptr;
3926
3927 const Capture *Captures = nullptr;
3928 unsigned NumCaptures = 0;
3929
3930 unsigned ManglingNumber = 0;
3931 Decl *ManglingContextDecl = nullptr;
3932
3933protected:
3934 BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
3935
3936public:
3937 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
3938 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3939
3940 SourceLocation getCaretLocation() const { return getLocation(); }
3941
3942 bool isVariadic() const { return BlockDeclBits.IsVariadic; }
3943 void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
3944
3945 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3946 Stmt *getBody() const override { return (Stmt*) Body; }
3947 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3948
3949 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3950 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3951
3952 // ArrayRef access to formal parameters.
3953 ArrayRef<ParmVarDecl *> parameters() const {
3954 return {ParamInfo, getNumParams()};
3955 }
3956 MutableArrayRef<ParmVarDecl *> parameters() {
3957 return {ParamInfo, getNumParams()};
3958 }
3959
3960 // Iterator access to formal parameters.
3961 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
3962 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
3963
3964 bool param_empty() const { return parameters().empty(); }
3965 param_iterator param_begin() { return parameters().begin(); }
3966 param_iterator param_end() { return parameters().end(); }
3967 param_const_iterator param_begin() const { return parameters().begin(); }
3968 param_const_iterator param_end() const { return parameters().end(); }
3969 size_t param_size() const { return parameters().size(); }
3970
3971 unsigned getNumParams() const { return NumParams; }
3972
3973 const ParmVarDecl *getParamDecl(unsigned i) const {
3974 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 3974, __PRETTY_FUNCTION__))
;
3975 return ParamInfo[i];
3976 }
3977 ParmVarDecl *getParamDecl(unsigned i) {
3978 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 3978, __PRETTY_FUNCTION__))
;
3979 return ParamInfo[i];
3980 }
3981
3982 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3983
3984 /// True if this block (or its nested blocks) captures
3985 /// anything of local storage from its enclosing scopes.
3986 bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
3987
3988 /// Returns the number of captured variables.
3989 /// Does not include an entry for 'this'.
3990 unsigned getNumCaptures() const { return NumCaptures; }
3991
3992 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
3993
3994 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3995
3996 capture_const_iterator capture_begin() const { return captures().begin(); }
3997 capture_const_iterator capture_end() const { return captures().end(); }
3998
3999 bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
4000 void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
4001
4002 bool blockMissingReturnType() const {
4003 return BlockDeclBits.BlockMissingReturnType;
4004 }
4005
4006 void setBlockMissingReturnType(bool val = true) {
4007 BlockDeclBits.BlockMissingReturnType = val;
4008 }
4009
4010 bool isConversionFromLambda() const {
4011 return BlockDeclBits.IsConversionFromLambda;
4012 }
4013
4014 void setIsConversionFromLambda(bool val = true) {
4015 BlockDeclBits.IsConversionFromLambda = val;
4016 }
4017
4018 bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
4019 void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
4020
4021 bool capturesVariable(const VarDecl *var) const;
4022
4023 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4024 bool CapturesCXXThis);
4025
4026 unsigned getBlockManglingNumber() const {
4027 return ManglingNumber;
4028 }
4029
4030 Decl *getBlockManglingContextDecl() const {
4031 return ManglingContextDecl;
4032 }
4033
4034 void setBlockMangling(unsigned Number, Decl *Ctx) {
4035 ManglingNumber = Number;
4036 ManglingContextDecl = Ctx;
4037 }
4038
4039 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4040
4041 // Implement isa/cast/dyncast/etc.
4042 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4043 static bool classofKind(Kind K) { return K == Block; }
4044 static DeclContext *castToDeclContext(const BlockDecl *D) {
4045 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4046 }
4047 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4048 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4049 }
4050};
4051
4052/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4053class CapturedDecl final
4054 : public Decl,
4055 public DeclContext,
4056 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4057protected:
4058 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4059 return NumParams;
4060 }
4061
4062private:
4063 /// The number of parameters to the outlined function.
4064 unsigned NumParams;
4065
4066 /// The position of context parameter in list of parameters.
4067 unsigned ContextParam;
4068
4069 /// The body of the outlined function.
4070 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4071
4072 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4073
4074 ImplicitParamDecl *const *getParams() const {
4075 return getTrailingObjects<ImplicitParamDecl *>();
4076 }
4077
4078 ImplicitParamDecl **getParams() {
4079 return getTrailingObjects<ImplicitParamDecl *>();
4080 }
4081
4082public:
4083 friend class ASTDeclReader;
4084 friend class ASTDeclWriter;
4085 friend TrailingObjects;
4086
4087 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4088 unsigned NumParams);
4089 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4090 unsigned NumParams);
4091
4092 Stmt *getBody() const override;
4093 void setBody(Stmt *B);
4094
4095 bool isNothrow() const;
4096 void setNothrow(bool Nothrow = true);
4097
4098 unsigned getNumParams() const { return NumParams; }
4099
4100 ImplicitParamDecl *getParam(unsigned i) const {
4101 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 4101, __PRETTY_FUNCTION__))
;
4102 return getParams()[i];
4103 }
4104 void setParam(unsigned i, ImplicitParamDecl *P) {
4105 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 4105, __PRETTY_FUNCTION__))
;
4106 getParams()[i] = P;
4107 }
4108
4109 // ArrayRef interface to parameters.
4110 ArrayRef<ImplicitParamDecl *> parameters() const {
4111 return {getParams(), getNumParams()};
4112 }
4113 MutableArrayRef<ImplicitParamDecl *> parameters() {
4114 return {getParams(), getNumParams()};
4115 }
4116
4117 /// Retrieve the parameter containing captured variables.
4118 ImplicitParamDecl *getContextParam() const {
4119 assert(ContextParam < NumParams)((ContextParam < NumParams) ? static_cast<void> (0) :
__assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 4119, __PRETTY_FUNCTION__))
;
4120 return getParam(ContextParam);
4121 }
4122 void setContextParam(unsigned i, ImplicitParamDecl *P) {
4123 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 4123, __PRETTY_FUNCTION__))
;
4124 ContextParam = i;
4125 setParam(i, P);
4126 }
4127 unsigned getContextParamPosition() const { return ContextParam; }
4128
4129 using param_iterator = ImplicitParamDecl *const *;
4130 using param_range = llvm::iterator_range<param_iterator>;
4131
4132 /// Retrieve an iterator pointing to the first parameter decl.
4133 param_iterator param_begin() const { return getParams(); }
4134 /// Retrieve an iterator one past the last parameter decl.
4135 param_iterator param_end() const { return getParams() + NumParams; }
4136
4137 // Implement isa/cast/dyncast/etc.
4138 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4139 static bool classofKind(Kind K) { return K == Captured; }
4140 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4141 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4142 }
4143 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4144 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4145 }
4146};
4147
4148/// Describes a module import declaration, which makes the contents
4149/// of the named module visible in the current translation unit.
4150///
4151/// An import declaration imports the named module (or submodule). For example:
4152/// \code
4153/// @import std.vector;
4154/// \endcode
4155///
4156/// Import declarations can also be implicitly generated from
4157/// \#include/\#import directives.
4158class ImportDecl final : public Decl,
4159 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4160 friend class ASTContext;
4161 friend class ASTDeclReader;
4162 friend class ASTReader;
4163 friend TrailingObjects;
4164
4165 /// The imported module, along with a bit that indicates whether
4166 /// we have source-location information for each identifier in the module
4167 /// name.
4168 ///
4169 /// When the bit is false, we only have a single source location for the
4170 /// end of the import declaration.
4171 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4172
4173 /// The next import in the list of imports local to the translation
4174 /// unit being parsed (not loaded from an AST file).
4175 ImportDecl *NextLocalImport = nullptr;
4176
4177 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4178 ArrayRef<SourceLocation> IdentifierLocs);
4179
4180 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4181 SourceLocation EndLoc);
4182
4183 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4184
4185public:
4186 /// Create a new module import declaration.
4187 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4188 SourceLocation StartLoc, Module *Imported,
4189 ArrayRef<SourceLocation> IdentifierLocs);
4190
4191 /// Create a new module import declaration for an implicitly-generated
4192 /// import.
4193 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4194 SourceLocation StartLoc, Module *Imported,
4195 SourceLocation EndLoc);
4196
4197 /// Create a new, deserialized module import declaration.
4198 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4199 unsigned NumLocations);
4200
4201 /// Retrieve the module that was imported by the import declaration.
4202 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4203
4204 /// Retrieves the locations of each of the identifiers that make up
4205 /// the complete module name in the import declaration.
4206 ///
4207 /// This will return an empty array if the locations of the individual
4208 /// identifiers aren't available.
4209 ArrayRef<SourceLocation> getIdentifierLocs() const;
4210
4211 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4212
4213 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4214 static bool classofKind(Kind K) { return K == Import; }
4215};
4216
4217/// Represents a C++ Modules TS module export declaration.
4218///
4219/// For example:
4220/// \code
4221/// export void foo();
4222/// \endcode
4223class ExportDecl final : public Decl, public DeclContext {
4224 virtual void anchor();
4225
4226private:
4227 friend class ASTDeclReader;
4228
4229 /// The source location for the right brace (if valid).
4230 SourceLocation RBraceLoc;
4231
4232 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4233 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4234 RBraceLoc(SourceLocation()) {}
4235
4236public:
4237 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4238 SourceLocation ExportLoc);
4239 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4240
4241 SourceLocation getExportLoc() const { return getLocation(); }
4242 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4243 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4244
4245 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4246 if (RBraceLoc.isValid())
4247 return RBraceLoc;
4248 // No braces: get the end location of the (only) declaration in context
4249 // (if present).
4250 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
4251 }
4252
4253 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4254 return SourceRange(getLocation(), getEndLoc());
4255 }
4256
4257 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4258 static bool classofKind(Kind K) { return K == Export; }
4259 static DeclContext *castToDeclContext(const ExportDecl *D) {
4260 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4261 }
4262 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4263 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4264 }
4265};
4266
4267/// Represents an empty-declaration.
4268class EmptyDecl : public Decl {
4269 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4270
4271 virtual void anchor();
4272
4273public:
4274 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4275 SourceLocation L);
4276 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4277
4278 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4279 static bool classofKind(Kind K) { return K == Empty; }
4280};
4281
4282/// Insertion operator for diagnostics. This allows sending NamedDecl's
4283/// into a diagnostic with <<.
4284inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4285 const NamedDecl* ND) {
4286 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4287 DiagnosticsEngine::ak_nameddecl);
4288 return DB;
4289}
4290inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4291 const NamedDecl* ND) {
4292 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4293 DiagnosticsEngine::ak_nameddecl);
4294 return PD;
4295}
4296
4297template<typename decl_type>
4298void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4299 // Note: This routine is implemented here because we need both NamedDecl
4300 // and Redeclarable to be defined.
4301 assert(RedeclLink.isFirst() &&((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 4302, __PRETTY_FUNCTION__))
4302 "setPreviousDecl on a decl already in a redeclaration chain")((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 4302, __PRETTY_FUNCTION__))
;
4303
4304 if (PrevDecl) {
4305 // Point to previous. Make sure that this is actually the most recent
4306 // redeclaration, or we can build invalid chains. If the most recent
4307 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4308 First = PrevDecl->getFirstDecl();
4309 assert(First->RedeclLink.isFirst() && "Expected first")((First->RedeclLink.isFirst() && "Expected first")
? static_cast<void> (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 4309, __PRETTY_FUNCTION__))
;
4310 decl_type *MostRecent = First->getNextRedeclaration();
4311 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4312
4313 // If the declaration was previously visible, a redeclaration of it remains
4314 // visible even if it wouldn't be visible by itself.
4315 static_cast<decl_type*>(this)->IdentifierNamespace |=
4316 MostRecent->getIdentifierNamespace() &
4317 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4318 } else {
4319 // Make this first.
4320 First = static_cast<decl_type*>(this);
4321 }
4322
4323 // First one will point to this one as latest.
4324 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4325
4326 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 4327, __PRETTY_FUNCTION__))
4327 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include/clang/AST/Decl.h"
, 4327, __PRETTY_FUNCTION__))
;
4328}
4329
4330// Inline function definitions.
4331
4332/// Check if the given decl is complete.
4333///
4334/// We use this function to break a cycle between the inline definitions in
4335/// Type.h and Decl.h.
4336inline bool IsEnumDeclComplete(EnumDecl *ED) {
4337 return ED->isComplete();
4338}
4339
4340/// Check if the given decl is scoped.
4341///
4342/// We use this function to break a cycle between the inline definitions in
4343/// Type.h and Decl.h.
4344inline bool IsEnumDeclScoped(EnumDecl *ED) {
4345 return ED->isScoped();
4346}
4347
4348} // namespace clang
4349
4350#endif // LLVM_CLANG_AST_DECL_H